-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuser_agent.rs
More file actions
159 lines (137 loc) · 4.4 KB
/
user_agent.rs
File metadata and controls
159 lines (137 loc) · 4.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use regex::Regex;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq)]
pub struct UserAgentMetadata {
pub raw: String,
pub normalized: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct UserAgentPatternConfig {
pub id: String,
#[serde(
deserialize_with = "deserialize_regex",
serialize_with = "serialize_regex"
)]
pub pattern: Regex,
}
impl PartialEq for UserAgentPatternConfig {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.pattern.as_str() == other.pattern.as_str()
}
}
fn deserialize_regex<'de, D>(deserializer: D) -> Result<Regex, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Regex::new(&s).map_err(serde::de::Error::custom)
}
fn serialize_regex<S>(regex: &Regex, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(regex.as_str())
}
struct UserAgentPattern {
id: String,
regex: Regex,
}
pub struct UserAgentExtractor {
patterns: Vec<UserAgentPattern>,
}
impl std::fmt::Debug for UserAgentExtractor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UserAgentExtractor")
.field("patterns_count", &self.patterns.len())
.finish()
}
}
impl UserAgentExtractor {
pub fn new(extra: Vec<UserAgentPatternConfig>) -> Self {
let mut patterns: Vec<UserAgentPattern> = extra
.into_iter()
.map(|c| UserAgentPattern {
id: c.id,
regex: c.pattern,
})
.collect();
let defaults = vec![
("claude-code", r"(?i)claude[-_]?(code|cli)"),
("claude-app", r"(?i)claude[-_]?app|ClaudeDesktop"),
("cursor", r"(?i)cursor"),
("cline", r"(?i)cline"),
("aider", r"(?i)aider"),
("continue-dev", r"(?i)continue"),
("copilot", r"(?i)copilot"),
];
for (id, pattern) in defaults {
patterns.push(UserAgentPattern {
id: id.to_owned(),
regex: Regex::new(pattern).unwrap(),
});
}
Self { patterns }
}
pub fn extract(&self, raw: &str) -> UserAgentMetadata {
let normalized = self
.patterns
.iter()
.find(|p| p.regex.is_match(raw))
.map(|p| p.id.clone())
.unwrap_or_else(|| "unknown".to_owned());
UserAgentMetadata {
raw: raw.to_owned(),
normalized,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn config(id: &str, pattern: &str) -> UserAgentPatternConfig {
UserAgentPatternConfig {
id: id.to_owned(),
pattern: Regex::new(pattern).unwrap(),
}
}
#[test]
fn test_known_user_agents() {
let extractor = UserAgentExtractor::new(vec![]);
let cases = vec![
("claude-code/1.0.0", "claude-code"),
("claude-cli/2.1.68", "claude-code"),
("ClaudeCode/2.1", "claude-code"),
("ClaudeDesktop/1.0", "claude-app"),
("claude-app/1.0", "claude-app"),
("Cursor/0.45.0", "cursor"),
("cline/3.2.1", "cline"),
("Aider/0.50.0", "aider"),
("Continue-Dev/1.0", "continue-dev"),
("copilot/1.0", "copilot"),
];
for (raw, expected) in cases {
let meta = extractor.extract(raw);
assert_eq!(meta.normalized, expected, "failed for raw={raw}");
assert_eq!(meta.raw, raw);
}
}
#[test]
fn test_unknown_user_agent() {
let extractor = UserAgentExtractor::new(vec![]);
let meta = extractor.extract("Mozilla/5.0");
assert_eq!(meta.normalized, "unknown");
assert_eq!(meta.raw, "Mozilla/5.0");
}
#[test]
fn test_custom_pattern_overrides_default() {
let extractor = UserAgentExtractor::new(vec![config("custom-cursor", r"(?i)cursor")]);
let meta = extractor.extract("Cursor/0.45.0");
assert_eq!(meta.normalized, "custom-cursor");
}
#[test]
fn test_invalid_regex_rejected_at_deserialization() {
let json = r#"{ "id": "bad", "pattern": "[invalid" }"#;
let err = serde_json::from_str::<UserAgentPatternConfig>(json).unwrap_err();
assert!(err.to_string().contains("unclosed character class"));
}
}