Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 7f0cf73

Browse files
committed
URI Template parser and matcher
1 parent bb28c9b commit 7f0cf73

2 files changed

Lines changed: 396 additions & 0 deletions

File tree

‎src/shared/uriTemplate.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import{UriTemplate}from"./uriTemplate.js";
2+
3+
describe("UriTemplate",()=>{
4+
describe("simple string expansion",()=>{
5+
it("should expand simple string variables",()=>{
6+
consttemplate=newUriTemplate("http://example.com/users/{username}");
7+
expect(template.expand({username: "fred"})).toBe(
8+
"http://example.com/users/fred",
9+
);
10+
});
11+
12+
it("should handle multiple variables",()=>{
13+
consttemplate=newUriTemplate("{x,y}");
14+
expect(template.expand({x: "1024",y: "768"})).toBe("1024,768");
15+
});
16+
17+
it("should encode reserved characters",()=>{
18+
consttemplate=newUriTemplate("{var}");
19+
expect(template.expand({var: "value with spaces"})).toBe(
20+
"value+with+spaces",
21+
);
22+
});
23+
});
24+
25+
describe("reserved expansion",()=>{
26+
it("should not encode reserved characters with + operator",()=>{
27+
consttemplate=newUriTemplate("{+path}/here");
28+
expect(template.expand({path: "/foo/bar"})).toBe("/foo/bar/here");
29+
});
30+
});
31+
32+
describe("fragment expansion",()=>{
33+
it("should add # prefix and not encode reserved chars",()=>{
34+
consttemplate=newUriTemplate("X{#var}");
35+
expect(template.expand({var: "/test"})).toBe("X#/test");
36+
});
37+
});
38+
39+
describe("label expansion",()=>{
40+
it("should add . prefix",()=>{
41+
consttemplate=newUriTemplate("X{.var}");
42+
expect(template.expand({var: "test"})).toBe("X.test");
43+
});
44+
});
45+
46+
describe("path expansion",()=>{
47+
it("should add / prefix",()=>{
48+
consttemplate=newUriTemplate("X{/var}");
49+
expect(template.expand({var: "test"})).toBe("X/test");
50+
});
51+
});
52+
53+
describe("query expansion",()=>{
54+
it("should add ? prefix and name=value format",()=>{
55+
consttemplate=newUriTemplate("X{?var}");
56+
expect(template.expand({var: "test"})).toBe("X?var=test");
57+
});
58+
});
59+
60+
describe("form continuation expansion",()=>{
61+
it("should add & prefix and name=value format",()=>{
62+
consttemplate=newUriTemplate("X{&var}");
63+
expect(template.expand({var: "test"})).toBe("X&var=test");
64+
});
65+
});
66+
67+
describe("matching",()=>{
68+
it("should match simple strings and extract variables",()=>{
69+
consttemplate=newUriTemplate("http://example.com/users/{username}");
70+
constmatch=template.match("http://example.com/users/fred");
71+
expect(match).toEqual({username: "fred"});
72+
});
73+
74+
it("should match multiple variables",()=>{
75+
consttemplate=newUriTemplate("/users/{username}/posts/{postId}");
76+
constmatch=template.match("/users/fred/posts/123");
77+
expect(match).toEqual({username: "fred",postId: "123"});
78+
});
79+
80+
it("should return null for non-matching URIs",()=>{
81+
consttemplate=newUriTemplate("/users/{username}");
82+
constmatch=template.match("/posts/123");
83+
expect(match).toBeNull();
84+
});
85+
86+
it("should handle exploded arrays",()=>{
87+
consttemplate=newUriTemplate("{/list*}");
88+
constmatch=template.match("/red,green,blue");
89+
expect(match).toEqual({list: ["red","green","blue"]});
90+
});
91+
});
92+
93+
describe("edge cases",()=>{
94+
it("should handle empty variables",()=>{
95+
consttemplate=newUriTemplate("{empty}");
96+
expect(template.expand({})).toBe("");
97+
expect(template.expand({empty: ""})).toBe("");
98+
});
99+
100+
it("should handle undefined variables",()=>{
101+
consttemplate=newUriTemplate("{a}{b}{c}");
102+
expect(template.expand({b: "2"})).toBe("2");
103+
});
104+
105+
it("should handle special characters in variable names",()=>{
106+
consttemplate=newUriTemplate("{$var_name}");
107+
expect(template.expand({"$var_name": "value"})).toBe("value");
108+
});
109+
});
110+
111+
describe("complex patterns",()=>{
112+
it("should handle nested path segments",()=>{
113+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
114+
expect(template.expand({
115+
version: "v1",
116+
resource: "users",
117+
id: "123"
118+
})).toBe("/api/v1/users/123");
119+
});
120+
121+
it("should handle query parameters with arrays",()=>{
122+
consttemplate=newUriTemplate("/search{?tags*}");
123+
expect(template.expand({
124+
tags: ["nodejs","typescript","testing"]
125+
})).toBe("/search?tags=nodejs,typescript,testing");
126+
});
127+
128+
it("should handle multiple query parameters",()=>{
129+
consttemplate=newUriTemplate("/search{?q,page,limit}");
130+
expect(template.expand({
131+
q: "test",
132+
page: "1",
133+
limit: "10"
134+
})).toBe("/search?q=test&page=1&limit=10");
135+
});
136+
});
137+
138+
describe("matching complex patterns",()=>{
139+
it("should match nested path segments",()=>{
140+
consttemplate=newUriTemplate("/api/{version}/{resource}/{id}");
141+
constmatch=template.match("/api/v1/users/123");
142+
expect(match).toEqual({
143+
version: "v1",
144+
resource: "users",
145+
id: "123"
146+
});
147+
});
148+
149+
it("should match query parameters",()=>{
150+
consttemplate=newUriTemplate("/search{?q}");
151+
constmatch=template.match("/search?q=test");
152+
expect(match).toEqual({q: "test"});
153+
});
154+
155+
it("should match multiple query parameters",()=>{
156+
consttemplate=newUriTemplate("/search{?q,page}");
157+
constmatch=template.match("/search?q=test&page=1");
158+
expect(match).toEqual({q: "test",page: "1"});
159+
});
160+
161+
it("should handle partial matches correctly",()=>{
162+
consttemplate=newUriTemplate("/users/{id}");
163+
expect(template.match("/users/123/extra")).toBeNull();
164+
expect(template.match("/users")).toBeNull();
165+
});
166+
});
167+
});

‎src/shared/uriTemplate.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Claude-authored implementation of RFC 6570 URI Templates
2+
3+
typeVariables=Record<string,string|string[]>;
4+
5+
exportclassUriTemplate{
6+
privatereadonlyparts: Array<
7+
|string
8+
|{name: string;operator: string;names: string[];exploded: boolean}
9+
>;
10+
11+
constructor(template: string){
12+
this.parts=this.parse(template);
13+
}
14+
15+
privateparse(
16+
template: string,
17+
): Array<
18+
|string
19+
|{name: string;operator: string;names: string[];exploded: boolean}
20+
>{
21+
constparts: Array<
22+
|string
23+
|{name: string;operator: string;names: string[];exploded: boolean}
24+
>=[];
25+
letcurrentText="";
26+
leti=0;
27+
28+
while(i<template.length){
29+
if(template[i]==="{"){
30+
if(currentText){
31+
parts.push(currentText);
32+
currentText="";
33+
}
34+
constend=template.indexOf("}",i);
35+
if(end===-1)thrownewError("Unclosed template expression");
36+
37+
constexpr=template.slice(i+1,end);
38+
constoperator=this.getOperator(expr);
39+
constexploded=expr.includes("*");
40+
constnames=this.getNames(expr);
41+
constname=names[0];
42+
parts.push({ name, operator, names, exploded });
43+
i=end+1;
44+
}else{
45+
currentText+=template[i];
46+
i++;
47+
}
48+
}
49+
50+
if(currentText){
51+
parts.push(currentText);
52+
}
53+
54+
returnparts;
55+
}
56+
57+
privategetOperator(expr: string): string{
58+
constoperators=["+","#",".","/","?","&"];
59+
returnoperators.find((op)=>expr.startsWith(op))||"";
60+
}
61+
62+
privategetNames(expr: string): string[]{
63+
constoperator=this.getOperator(expr);
64+
returnexpr
65+
.slice(operator.length)
66+
.split(",")
67+
.map((name)=>name.replace("*","").trim())
68+
.filter((name)=>name.length>0);
69+
}
70+
71+
privateencodeValue(value: string,operator: string): string{
72+
if(operator==="+"||operator==="#"){
73+
returnencodeURI(value);
74+
}
75+
returnencodeURIComponent(value).replace(/%20/g,"+");
76+
}
77+
78+
privateexpandPart(
79+
part: {
80+
name: string;
81+
operator: string;
82+
names: string[];
83+
exploded: boolean;
84+
},
85+
variables: Variables,
86+
): string{
87+
if(part.operator==="?"||part.operator==="&"){
88+
constpairs=part.names
89+
.map((name)=>{
90+
constvalue=variables[name];
91+
if(value===undefined)return"";
92+
constencoded=Array.isArray(value)
93+
? value.map((v)=>this.encodeValue(v,part.operator)).join(",")
94+
: this.encodeValue(value.toString(),part.operator);
95+
return`${name}=${encoded}`;
96+
})
97+
.filter((pair)=>pair.length>0);
98+
99+
if(pairs.length===0)return"";
100+
constseparator=part.operator==="?" ? "?" : "&";
101+
returnseparator+pairs.join("&");
102+
}
103+
104+
if(part.names.length>1){
105+
constvalues=part.names
106+
.map((name)=>variables[name])
107+
.filter((v)=>v!==undefined);
108+
if(values.length===0)return"";
109+
returnvalues.map((v)=>(Array.isArray(v) ? v[0] : v)).join(",");
110+
}
111+
112+
constvalue=variables[part.name];
113+
if(value===undefined)return"";
114+
115+
constvalues=Array.isArray(value) ? value : [value];
116+
constencoded=values.map((v)=>this.encodeValue(v,part.operator));
117+
118+
switch(part.operator){
119+
case"":
120+
returnencoded.join(",");
121+
case"+":
122+
returnencoded.join(",");
123+
case"#":
124+
return"#"+encoded.join(",");
125+
case".":
126+
return"."+encoded.join(".");
127+
case"/":
128+
return"/"+encoded.join("/");
129+
default:
130+
returnencoded.join(",");
131+
}
132+
}
133+
134+
expand(variables: Variables): string{
135+
returnthis.parts
136+
.map((part)=>{
137+
if(typeofpart==="string")returnpart;
138+
returnthis.expandPart(part,variables);
139+
})
140+
.join("");
141+
}
142+
143+
privateescapeRegExp(str: string): string{
144+
returnstr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
145+
}
146+
147+
privatepartToRegExp(part: {
148+
name: string;
149+
operator: string;
150+
names: string[];
151+
exploded: boolean;
152+
}): Array<{pattern: string;name: string}>{
153+
constpatterns: Array<{pattern: string;name: string}>=[];
154+
155+
if(part.operator==="?"||part.operator==="&"){
156+
for(leti=0;i<part.names.length;i++){
157+
constname=part.names[i];
158+
constprefix=i===0 ? "\\"+part.operator : "&";
159+
patterns.push({
160+
pattern: prefix+this.escapeRegExp(name)+"=([^&]+)",
161+
name,
162+
});
163+
}
164+
returnpatterns;
165+
}
166+
167+
letpattern: string;
168+
constname=part.name;
169+
170+
switch(part.operator){
171+
case"":
172+
pattern=part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
173+
break;
174+
case"+":
175+
case"#":
176+
pattern="(.+)";
177+
break;
178+
case".":
179+
pattern="\\.([^/,]+)";
180+
break;
181+
case"/":
182+
pattern="/"+(part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
183+
break;
184+
default:
185+
pattern="([^/]+)";
186+
}
187+
188+
patterns.push({ pattern, name });
189+
returnpatterns;
190+
}
191+
192+
match(uri: string): Variables|null{
193+
letpattern="^";
194+
constnames: Array<{name: string;exploded: boolean}>=[];
195+
196+
for(constpartofthis.parts){
197+
if(typeofpart==="string"){
198+
pattern+=this.escapeRegExp(part);
199+
}else{
200+
constpatterns=this.partToRegExp(part);
201+
for(const{pattern: partPattern, name }ofpatterns){
202+
pattern+=partPattern;
203+
names.push({ name,exploded: part.exploded});
204+
}
205+
}
206+
}
207+
208+
pattern+="$";
209+
constregex=newRegExp(pattern);
210+
constmatch=uri.match(regex);
211+
212+
if(!match)returnnull;
213+
214+
constresult: Variables={};
215+
for(leti=0;i<names.length;i++){
216+
const{ name, exploded }=names[i];
217+
constvalue=match[i+1];
218+
constcleanName=name.replace("*","");
219+
220+
if(exploded&&value.includes(",")){
221+
result[cleanName]=value.split(",");
222+
}else{
223+
result[cleanName]=value;
224+
}
225+
}
226+
227+
returnresult;
228+
}
229+
}

0 commit comments

Comments
 (0)