@fedify/uri-template 2.3.14 → 2.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/dist/mod.cjs +97 -23
- package/dist/mod.d.cts +18 -2
- package/dist/mod.d.ts +18 -2
- package/dist/mod.js +97 -23
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -148,6 +148,32 @@ Features
|
|
|
148
148
|
- Zero runtime dependencies
|
|
149
149
|
|
|
150
150
|
|
|
151
|
+
HTTP path compatibility
|
|
152
|
+
-----------------------
|
|
153
|
+
|
|
154
|
+
Some HTTP clients, including Mastodon, decode `%3A` to `:` in request paths.
|
|
155
|
+
Pass `{ allowUnencodedColon: true }` to `Router.route()` to accept literal
|
|
156
|
+
colons in variable values where expansion would produce `%3A`:
|
|
157
|
+
|
|
158
|
+
~~~~ typescript
|
|
159
|
+
const router = new Router([["/users/{identifier}", "actor"]]);
|
|
160
|
+
router.route("/users/alice:work", { allowUnencodedColon: true });
|
|
161
|
+
// { name: "actor", template: "/users/{identifier}",
|
|
162
|
+
// values: { identifier: "alice:work" } }
|
|
163
|
+
~~~~
|
|
164
|
+
|
|
165
|
+
Exact matches, including configured trailing-slash retries, take precedence
|
|
166
|
+
over colon-compatible matches. Literal template text still matches exactly,
|
|
167
|
+
and other percent-encoded characters keep their existing matching rules.
|
|
168
|
+
When a template uses colons to separate variables, a decoded colon in a value
|
|
169
|
+
can make the boundary ambiguous; matching follows the existing backtracking
|
|
170
|
+
order.
|
|
171
|
+
|
|
172
|
+
Fedify enables this option for incoming HTTP requests. URI generation and
|
|
173
|
+
`Context.parseUri()` retain their existing behavior. Standalone
|
|
174
|
+
`Template.match()` and `Router.route()` without the option also remain exact.
|
|
175
|
+
|
|
176
|
+
|
|
151
177
|
Route variable constraints
|
|
152
178
|
--------------------------
|
|
153
179
|
|
package/dist/mod.cjs
CHANGED
|
@@ -629,18 +629,81 @@ function reportPrefixModifierError(varSpec, valueType, { report, strict }) {
|
|
|
629
629
|
/**
|
|
630
630
|
* Matches a URI against a parsed URI template and extracts variable bindings.
|
|
631
631
|
*
|
|
632
|
-
*
|
|
633
|
-
*
|
|
634
|
-
* re-expanding the template with that context reproduces the original URI.
|
|
632
|
+
* Recovers variable bindings whose completed context satisfies the caller's
|
|
633
|
+
* roundtrip check. Literal tokens always match the original URI exactly.
|
|
635
634
|
*
|
|
636
635
|
* @param tokens The parsed template tokens to match against.
|
|
637
636
|
* @param uri The concrete URI to decompose.
|
|
638
|
-
* @param
|
|
637
|
+
* @param accept The roundtrip check for a completed variable context.
|
|
638
|
+
* @param equivalent Exact or colon-compatible output comparison, also used by
|
|
639
|
+
* the caller's roundtrip check.
|
|
639
640
|
* @returns The recovered variable context, or `null` if the URI does not match
|
|
640
641
|
* the template under any interpretation.
|
|
641
642
|
*/
|
|
642
|
-
function match(tokens, uri,
|
|
643
|
-
|
|
643
|
+
function match(tokens, uri, accept, equivalent = (left, right) => left === right) {
|
|
644
|
+
if (!canExpandTo(tokens, uri, equivalent)) return null;
|
|
645
|
+
return matchTokens(tokens, uri, accept, 0, 0, {});
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Checks necessary conditions on the whole output, without choosing expression
|
|
649
|
+
* boundaries or bindings. Individual expressions need not round-trip locally:
|
|
650
|
+
* repeated variables can compensate for different consumed lengths elsewhere.
|
|
651
|
+
*/
|
|
652
|
+
function canExpandTo(tokens, uri, equivalent) {
|
|
653
|
+
const specs = /* @__PURE__ */ new Set();
|
|
654
|
+
const counts = /* @__PURE__ */ new Map();
|
|
655
|
+
let namedOrExploded = false;
|
|
656
|
+
let verbatimPercent = false;
|
|
657
|
+
const count = (text, delta) => {
|
|
658
|
+
for (let index = 0; index < text.length; index++) {
|
|
659
|
+
const char = text[index];
|
|
660
|
+
counts.set(char, (counts.get(char) ?? 0) + delta);
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
for (const token of tokens) if (token.kind === "literal") {
|
|
664
|
+
count(token.text, -1);
|
|
665
|
+
verbatimPercent ||= token.text.includes("%");
|
|
666
|
+
} else {
|
|
667
|
+
if (token.vars.some((variable) => variable.prefix != null)) return true;
|
|
668
|
+
const spec = operatorSpecs[token.operator];
|
|
669
|
+
specs.add(spec);
|
|
670
|
+
namedOrExploded ||= spec.named || token.vars.some((variable) => variable.explode);
|
|
671
|
+
verbatimPercent ||= token.vars.some((variable) => variable.name.includes("%"));
|
|
672
|
+
}
|
|
673
|
+
count(uri, 1);
|
|
674
|
+
for (const [char, difference] of counts) {
|
|
675
|
+
if (difference === 0 || char === "%" || char === "," || char === "=" && namedOrExploded) continue;
|
|
676
|
+
if ([...specs].some((spec) => spec.first.includes(char) || spec.sep.includes(char) || equivalent(encodeValue(spec.allowReserved)(char), char))) continue;
|
|
677
|
+
return false;
|
|
678
|
+
}
|
|
679
|
+
return verbatimPercent || hasPossiblePercentEncoding(uri, [...specs].some((spec) => spec.allowReserved));
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* With no percent signs supplied by literals or encoded variable names, every
|
|
683
|
+
* percent sign must come from a value encoder. Reserved expansion preserves
|
|
684
|
+
* triplets; other operators emit canonical UTF-8. Folding %3A only splits runs
|
|
685
|
+
* between complete code points, so canonicality also holds in colon mode.
|
|
686
|
+
*/
|
|
687
|
+
function hasPossiblePercentEncoding(uri, allowReserved) {
|
|
688
|
+
for (let index = 0; index < uri.length;) {
|
|
689
|
+
if (uri[index] !== "%") {
|
|
690
|
+
index++;
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
if (!isPctEncodedAt(uri, index)) return false;
|
|
694
|
+
const start = index;
|
|
695
|
+
do
|
|
696
|
+
index += 3;
|
|
697
|
+
while (isPctEncodedAt(uri, index));
|
|
698
|
+
if (allowReserved) continue;
|
|
699
|
+
const run = uri.slice(start, index);
|
|
700
|
+
try {
|
|
701
|
+
if (encodeValue(false)(decodeURIComponent(run)) !== run) return false;
|
|
702
|
+
} catch {
|
|
703
|
+
return false;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return true;
|
|
644
707
|
}
|
|
645
708
|
/**
|
|
646
709
|
* Walks the token stream and the URI in lockstep, backtracking over every
|
|
@@ -648,26 +711,25 @@ function match(tokens, uri, options) {
|
|
|
648
711
|
*
|
|
649
712
|
* Literal tokens advance deterministically; expression tokens fan out across
|
|
650
713
|
* all viable end positions and value interpretations. When the token stream is
|
|
651
|
-
* exhausted, the accumulated bindings
|
|
652
|
-
*
|
|
653
|
-
* out the spurious interpretations that the permissive parsing stage admits.
|
|
714
|
+
* exhausted, the accumulated bindings must pass the caller's roundtrip check,
|
|
715
|
+
* filtering out spurious interpretations from the permissive parsing stage.
|
|
654
716
|
*
|
|
655
717
|
* @returns The first surviving context, or `null` if every branch fails.
|
|
656
718
|
*/
|
|
657
|
-
function matchTokens(tokens, uri,
|
|
719
|
+
function matchTokens(tokens, uri, accept, tokenIndex, uriIndex, bindings) {
|
|
658
720
|
if (tokenIndex >= tokens.length) {
|
|
659
721
|
if (uriIndex !== uri.length) return null;
|
|
660
722
|
const context = toExpandContext(bindings);
|
|
661
|
-
return
|
|
723
|
+
return accept(context) ? context : null;
|
|
662
724
|
}
|
|
663
725
|
const token = tokens[tokenIndex];
|
|
664
|
-
if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri,
|
|
726
|
+
if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri, accept, tokenIndex + 1, uriIndex + token.text.length, bindings) : null;
|
|
665
727
|
for (const end of expressionEnds(tokens, uri, tokenIndex, uriIndex)) {
|
|
666
728
|
const expression = uri.slice(uriIndex, end);
|
|
667
729
|
for (const expressionBindings of matchExpression(token.vars, token.operator, expression)) {
|
|
668
730
|
const merged = mergeBindings(bindings, expressionBindings);
|
|
669
731
|
if (merged == null) continue;
|
|
670
|
-
const result = matchTokens(tokens, uri,
|
|
732
|
+
const result = matchTokens(tokens, uri, accept, tokenIndex + 1, end, merged);
|
|
671
733
|
if (result != null) return result;
|
|
672
734
|
}
|
|
673
735
|
}
|
|
@@ -1240,7 +1302,7 @@ var Template = class Template {
|
|
|
1240
1302
|
* Matches a URI against this template, returning the variable context if the
|
|
1241
1303
|
* URI matches or `null` if it does not.
|
|
1242
1304
|
*/
|
|
1243
|
-
match = (uri) => match(this.#tokens, uri, this
|
|
1305
|
+
match = (uri) => match(this.#tokens, uri, (context) => this.expand(context) === uri);
|
|
1244
1306
|
toString = () => this.uriTemplate;
|
|
1245
1307
|
};
|
|
1246
1308
|
const freezeTokens = (tokens) => Object.freeze(tokens.map(freezeToken));
|
|
@@ -1584,7 +1646,7 @@ var StateTrie = class {
|
|
|
1584
1646
|
insert = (entry) => fold((node, segment) => isLiteral(segment) ? node.insertLiteral(segment.text) : node.childOrInsertExpression(segment), this.#root, compileSegments(entry.tokens)).insert(entry);
|
|
1585
1647
|
remove = (entry) => foldWhileDefined((node, segment) => isLiteral(segment) ? node.findLiteral(segment.text) : node.childExpression(segment.key), this.#root, compileSegments(entry.tokens)).remove(entry);
|
|
1586
1648
|
*candidates(path) {
|
|
1587
|
-
yield* stateEntries(this.#root, path, 0);
|
|
1649
|
+
yield* stateEntries(this.#root, path, 0, /* @__PURE__ */ new Map());
|
|
1588
1650
|
}
|
|
1589
1651
|
};
|
|
1590
1652
|
function* compileSegments(tokens) {
|
|
@@ -1601,16 +1663,21 @@ const expressionKey = ({ operator, vars: [{ explode, prefix }] }) => [
|
|
|
1601
1663
|
explode ? "*" : "",
|
|
1602
1664
|
prefix ?? ""
|
|
1603
1665
|
].join("\0");
|
|
1604
|
-
function* stateEntries(node, path, index) {
|
|
1666
|
+
function* stateEntries(node, path, index, visited) {
|
|
1667
|
+
let indexes = visited.get(node);
|
|
1668
|
+
if (indexes == null) visited.set(node, indexes = /* @__PURE__ */ new Set());
|
|
1669
|
+
if (indexes.has(index)) return;
|
|
1670
|
+
indexes.add(index);
|
|
1605
1671
|
if (index === path.length) yield* node.entries;
|
|
1606
|
-
for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length);
|
|
1607
|
-
for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index);
|
|
1672
|
+
for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length, visited);
|
|
1673
|
+
for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index, visited);
|
|
1608
1674
|
}
|
|
1609
|
-
function* expressionEntries(edge, path, index) {
|
|
1675
|
+
function* expressionEntries(edge, path, index, visited) {
|
|
1610
1676
|
for (const end of expressionEndIndexes(edge.node, path, index)) {
|
|
1677
|
+
if (visited.get(edge.node)?.has(end)) continue;
|
|
1611
1678
|
const expression = path.slice(index, end);
|
|
1612
1679
|
if (!matchesExpressionShape(edge.operator, expression)) continue;
|
|
1613
|
-
yield* stateEntries(edge.node, path, end);
|
|
1680
|
+
yield* stateEntries(edge.node, path, end, visited);
|
|
1614
1681
|
}
|
|
1615
1682
|
}
|
|
1616
1683
|
function* expressionEndIndexes(node, path, index) {
|
|
@@ -1769,13 +1836,19 @@ var Router = class Router {
|
|
|
1769
1836
|
/**
|
|
1770
1837
|
* Resolves a path name and values from a URI, if any match.
|
|
1771
1838
|
* @param url The URI to resolve.
|
|
1839
|
+
* @param options Options for this lookup only.
|
|
1772
1840
|
* @returns The name of the path and its values, if any match. Otherwise,
|
|
1773
1841
|
* `null`.
|
|
1774
1842
|
*/
|
|
1775
|
-
route = (url
|
|
1776
|
-
|
|
1843
|
+
route = (url, options = {}) => {
|
|
1844
|
+
const strict = this.#route(url) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url)) : null);
|
|
1845
|
+
if (strict != null || !options.allowUnencodedColon || !url.includes(":")) return strict;
|
|
1846
|
+
return this.#route(url, true) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url), true) : null);
|
|
1847
|
+
};
|
|
1848
|
+
#route(url, allowUnencodedColon = false) {
|
|
1777
1849
|
for (const entry of this.#trie.candidates(url)) {
|
|
1778
|
-
const
|
|
1850
|
+
const template = entry.pattern.template;
|
|
1851
|
+
const context = allowUnencodedColon ? match(template.tokens, url, (values) => equalWithUnencodedColon(template.expand(values), url), equalWithUnencodedColon) : template.match(url);
|
|
1779
1852
|
if (context == null) continue;
|
|
1780
1853
|
const values = resolveValues(context, entry);
|
|
1781
1854
|
if (values == null) continue;
|
|
@@ -1808,6 +1881,7 @@ var Router = class Router {
|
|
|
1808
1881
|
entry.options
|
|
1809
1882
|
]);
|
|
1810
1883
|
};
|
|
1884
|
+
const equalWithUnencodedColon = (left, right) => left.replaceAll("%3A", ":") === right.replaceAll("%3A", ":");
|
|
1811
1885
|
const createRouteEntry = ({ index, name, pattern, options }) => ({
|
|
1812
1886
|
index,
|
|
1813
1887
|
name,
|
package/dist/mod.d.cts
CHANGED
|
@@ -517,6 +517,21 @@ interface RouterOptions {
|
|
|
517
517
|
*/
|
|
518
518
|
trailingSlashInsensitive?: boolean;
|
|
519
519
|
}
|
|
520
|
+
/**
|
|
521
|
+
* Options for an individual {@link Router.route} call.
|
|
522
|
+
* @since 2.3.15
|
|
523
|
+
*/
|
|
524
|
+
interface RouterRouteOptions {
|
|
525
|
+
/**
|
|
526
|
+
* Accepts literal colons in variable values where expansion produces `%3A`.
|
|
527
|
+
* Exact matches, including trailing-slash retries, always take precedence.
|
|
528
|
+
* Literal template text remains exact. Defaults to `false`.
|
|
529
|
+
*
|
|
530
|
+
* Intended for inbound HTTP compatibility; identity lookups should keep
|
|
531
|
+
* the default strict matching.
|
|
532
|
+
*/
|
|
533
|
+
readonly allowUnencodedColon?: boolean;
|
|
534
|
+
}
|
|
520
535
|
/**
|
|
521
536
|
* Fully-resolved per-variable matching constraint. Every template variable
|
|
522
537
|
* is constrained even when it is not listed in {@link RouteOptions.variables};
|
|
@@ -753,10 +768,11 @@ declare class Router {
|
|
|
753
768
|
/**
|
|
754
769
|
* Resolves a path name and values from a URI, if any match.
|
|
755
770
|
* @param url The URI to resolve.
|
|
771
|
+
* @param options Options for this lookup only.
|
|
756
772
|
* @returns The name of the path and its values, if any match. Otherwise,
|
|
757
773
|
* `null`.
|
|
758
774
|
*/
|
|
759
|
-
route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path) => RouterRouteResult<TConstraints> | null;
|
|
775
|
+
route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path, options?: RouterRouteOptions) => RouterRouteResult<TConstraints> | null;
|
|
760
776
|
/**
|
|
761
777
|
* Constructs a URL/path from a path name and values.
|
|
762
778
|
* @param name The name of the path.
|
|
@@ -792,4 +808,4 @@ declare const isExpression: <T extends {
|
|
|
792
808
|
declare function isPath(path: string): path is Path;
|
|
793
809
|
declare function assertPath(path: string): asserts path is Path;
|
|
794
810
|
//#endregion
|
|
795
|
-
export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
|
|
811
|
+
export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteOptions, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
|
package/dist/mod.d.ts
CHANGED
|
@@ -517,6 +517,21 @@ interface RouterOptions {
|
|
|
517
517
|
*/
|
|
518
518
|
trailingSlashInsensitive?: boolean;
|
|
519
519
|
}
|
|
520
|
+
/**
|
|
521
|
+
* Options for an individual {@link Router.route} call.
|
|
522
|
+
* @since 2.3.15
|
|
523
|
+
*/
|
|
524
|
+
interface RouterRouteOptions {
|
|
525
|
+
/**
|
|
526
|
+
* Accepts literal colons in variable values where expansion produces `%3A`.
|
|
527
|
+
* Exact matches, including trailing-slash retries, always take precedence.
|
|
528
|
+
* Literal template text remains exact. Defaults to `false`.
|
|
529
|
+
*
|
|
530
|
+
* Intended for inbound HTTP compatibility; identity lookups should keep
|
|
531
|
+
* the default strict matching.
|
|
532
|
+
*/
|
|
533
|
+
readonly allowUnencodedColon?: boolean;
|
|
534
|
+
}
|
|
520
535
|
/**
|
|
521
536
|
* Fully-resolved per-variable matching constraint. Every template variable
|
|
522
537
|
* is constrained even when it is not listed in {@link RouteOptions.variables};
|
|
@@ -753,10 +768,11 @@ declare class Router {
|
|
|
753
768
|
/**
|
|
754
769
|
* Resolves a path name and values from a URI, if any match.
|
|
755
770
|
* @param url The URI to resolve.
|
|
771
|
+
* @param options Options for this lookup only.
|
|
756
772
|
* @returns The name of the path and its values, if any match. Otherwise,
|
|
757
773
|
* `null`.
|
|
758
774
|
*/
|
|
759
|
-
route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path) => RouterRouteResult<TConstraints> | null;
|
|
775
|
+
route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path, options?: RouterRouteOptions) => RouterRouteResult<TConstraints> | null;
|
|
760
776
|
/**
|
|
761
777
|
* Constructs a URL/path from a path name and values.
|
|
762
778
|
* @param name The name of the path.
|
|
@@ -792,4 +808,4 @@ declare const isExpression: <T extends {
|
|
|
792
808
|
declare function isPath(path: string): path is Path;
|
|
793
809
|
declare function assertPath(path: string): asserts path is Path;
|
|
794
810
|
//#endregion
|
|
795
|
-
export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
|
|
811
|
+
export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteOptions, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
|
package/dist/mod.js
CHANGED
|
@@ -628,18 +628,81 @@ function reportPrefixModifierError(varSpec, valueType, { report, strict }) {
|
|
|
628
628
|
/**
|
|
629
629
|
* Matches a URI against a parsed URI template and extracts variable bindings.
|
|
630
630
|
*
|
|
631
|
-
*
|
|
632
|
-
*
|
|
633
|
-
* re-expanding the template with that context reproduces the original URI.
|
|
631
|
+
* Recovers variable bindings whose completed context satisfies the caller's
|
|
632
|
+
* roundtrip check. Literal tokens always match the original URI exactly.
|
|
634
633
|
*
|
|
635
634
|
* @param tokens The parsed template tokens to match against.
|
|
636
635
|
* @param uri The concrete URI to decompose.
|
|
637
|
-
* @param
|
|
636
|
+
* @param accept The roundtrip check for a completed variable context.
|
|
637
|
+
* @param equivalent Exact or colon-compatible output comparison, also used by
|
|
638
|
+
* the caller's roundtrip check.
|
|
638
639
|
* @returns The recovered variable context, or `null` if the URI does not match
|
|
639
640
|
* the template under any interpretation.
|
|
640
641
|
*/
|
|
641
|
-
function match(tokens, uri,
|
|
642
|
-
|
|
642
|
+
function match(tokens, uri, accept, equivalent = (left, right) => left === right) {
|
|
643
|
+
if (!canExpandTo(tokens, uri, equivalent)) return null;
|
|
644
|
+
return matchTokens(tokens, uri, accept, 0, 0, {});
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Checks necessary conditions on the whole output, without choosing expression
|
|
648
|
+
* boundaries or bindings. Individual expressions need not round-trip locally:
|
|
649
|
+
* repeated variables can compensate for different consumed lengths elsewhere.
|
|
650
|
+
*/
|
|
651
|
+
function canExpandTo(tokens, uri, equivalent) {
|
|
652
|
+
const specs = /* @__PURE__ */ new Set();
|
|
653
|
+
const counts = /* @__PURE__ */ new Map();
|
|
654
|
+
let namedOrExploded = false;
|
|
655
|
+
let verbatimPercent = false;
|
|
656
|
+
const count = (text, delta) => {
|
|
657
|
+
for (let index = 0; index < text.length; index++) {
|
|
658
|
+
const char = text[index];
|
|
659
|
+
counts.set(char, (counts.get(char) ?? 0) + delta);
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
for (const token of tokens) if (token.kind === "literal") {
|
|
663
|
+
count(token.text, -1);
|
|
664
|
+
verbatimPercent ||= token.text.includes("%");
|
|
665
|
+
} else {
|
|
666
|
+
if (token.vars.some((variable) => variable.prefix != null)) return true;
|
|
667
|
+
const spec = operatorSpecs[token.operator];
|
|
668
|
+
specs.add(spec);
|
|
669
|
+
namedOrExploded ||= spec.named || token.vars.some((variable) => variable.explode);
|
|
670
|
+
verbatimPercent ||= token.vars.some((variable) => variable.name.includes("%"));
|
|
671
|
+
}
|
|
672
|
+
count(uri, 1);
|
|
673
|
+
for (const [char, difference] of counts) {
|
|
674
|
+
if (difference === 0 || char === "%" || char === "," || char === "=" && namedOrExploded) continue;
|
|
675
|
+
if ([...specs].some((spec) => spec.first.includes(char) || spec.sep.includes(char) || equivalent(encodeValue(spec.allowReserved)(char), char))) continue;
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
return verbatimPercent || hasPossiblePercentEncoding(uri, [...specs].some((spec) => spec.allowReserved));
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* With no percent signs supplied by literals or encoded variable names, every
|
|
682
|
+
* percent sign must come from a value encoder. Reserved expansion preserves
|
|
683
|
+
* triplets; other operators emit canonical UTF-8. Folding %3A only splits runs
|
|
684
|
+
* between complete code points, so canonicality also holds in colon mode.
|
|
685
|
+
*/
|
|
686
|
+
function hasPossiblePercentEncoding(uri, allowReserved) {
|
|
687
|
+
for (let index = 0; index < uri.length;) {
|
|
688
|
+
if (uri[index] !== "%") {
|
|
689
|
+
index++;
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
if (!isPctEncodedAt(uri, index)) return false;
|
|
693
|
+
const start = index;
|
|
694
|
+
do
|
|
695
|
+
index += 3;
|
|
696
|
+
while (isPctEncodedAt(uri, index));
|
|
697
|
+
if (allowReserved) continue;
|
|
698
|
+
const run = uri.slice(start, index);
|
|
699
|
+
try {
|
|
700
|
+
if (encodeValue(false)(decodeURIComponent(run)) !== run) return false;
|
|
701
|
+
} catch {
|
|
702
|
+
return false;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
return true;
|
|
643
706
|
}
|
|
644
707
|
/**
|
|
645
708
|
* Walks the token stream and the URI in lockstep, backtracking over every
|
|
@@ -647,26 +710,25 @@ function match(tokens, uri, options) {
|
|
|
647
710
|
*
|
|
648
711
|
* Literal tokens advance deterministically; expression tokens fan out across
|
|
649
712
|
* all viable end positions and value interpretations. When the token stream is
|
|
650
|
-
* exhausted, the accumulated bindings
|
|
651
|
-
*
|
|
652
|
-
* out the spurious interpretations that the permissive parsing stage admits.
|
|
713
|
+
* exhausted, the accumulated bindings must pass the caller's roundtrip check,
|
|
714
|
+
* filtering out spurious interpretations from the permissive parsing stage.
|
|
653
715
|
*
|
|
654
716
|
* @returns The first surviving context, or `null` if every branch fails.
|
|
655
717
|
*/
|
|
656
|
-
function matchTokens(tokens, uri,
|
|
718
|
+
function matchTokens(tokens, uri, accept, tokenIndex, uriIndex, bindings) {
|
|
657
719
|
if (tokenIndex >= tokens.length) {
|
|
658
720
|
if (uriIndex !== uri.length) return null;
|
|
659
721
|
const context = toExpandContext(bindings);
|
|
660
|
-
return
|
|
722
|
+
return accept(context) ? context : null;
|
|
661
723
|
}
|
|
662
724
|
const token = tokens[tokenIndex];
|
|
663
|
-
if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri,
|
|
725
|
+
if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri, accept, tokenIndex + 1, uriIndex + token.text.length, bindings) : null;
|
|
664
726
|
for (const end of expressionEnds(tokens, uri, tokenIndex, uriIndex)) {
|
|
665
727
|
const expression = uri.slice(uriIndex, end);
|
|
666
728
|
for (const expressionBindings of matchExpression(token.vars, token.operator, expression)) {
|
|
667
729
|
const merged = mergeBindings(bindings, expressionBindings);
|
|
668
730
|
if (merged == null) continue;
|
|
669
|
-
const result = matchTokens(tokens, uri,
|
|
731
|
+
const result = matchTokens(tokens, uri, accept, tokenIndex + 1, end, merged);
|
|
670
732
|
if (result != null) return result;
|
|
671
733
|
}
|
|
672
734
|
}
|
|
@@ -1239,7 +1301,7 @@ var Template = class Template {
|
|
|
1239
1301
|
* Matches a URI against this template, returning the variable context if the
|
|
1240
1302
|
* URI matches or `null` if it does not.
|
|
1241
1303
|
*/
|
|
1242
|
-
match = (uri) => match(this.#tokens, uri, this
|
|
1304
|
+
match = (uri) => match(this.#tokens, uri, (context) => this.expand(context) === uri);
|
|
1243
1305
|
toString = () => this.uriTemplate;
|
|
1244
1306
|
};
|
|
1245
1307
|
const freezeTokens = (tokens) => Object.freeze(tokens.map(freezeToken));
|
|
@@ -1583,7 +1645,7 @@ var StateTrie = class {
|
|
|
1583
1645
|
insert = (entry) => fold((node, segment) => isLiteral(segment) ? node.insertLiteral(segment.text) : node.childOrInsertExpression(segment), this.#root, compileSegments(entry.tokens)).insert(entry);
|
|
1584
1646
|
remove = (entry) => foldWhileDefined((node, segment) => isLiteral(segment) ? node.findLiteral(segment.text) : node.childExpression(segment.key), this.#root, compileSegments(entry.tokens)).remove(entry);
|
|
1585
1647
|
*candidates(path) {
|
|
1586
|
-
yield* stateEntries(this.#root, path, 0);
|
|
1648
|
+
yield* stateEntries(this.#root, path, 0, /* @__PURE__ */ new Map());
|
|
1587
1649
|
}
|
|
1588
1650
|
};
|
|
1589
1651
|
function* compileSegments(tokens) {
|
|
@@ -1600,16 +1662,21 @@ const expressionKey = ({ operator, vars: [{ explode, prefix }] }) => [
|
|
|
1600
1662
|
explode ? "*" : "",
|
|
1601
1663
|
prefix ?? ""
|
|
1602
1664
|
].join("\0");
|
|
1603
|
-
function* stateEntries(node, path, index) {
|
|
1665
|
+
function* stateEntries(node, path, index, visited) {
|
|
1666
|
+
let indexes = visited.get(node);
|
|
1667
|
+
if (indexes == null) visited.set(node, indexes = /* @__PURE__ */ new Set());
|
|
1668
|
+
if (indexes.has(index)) return;
|
|
1669
|
+
indexes.add(index);
|
|
1604
1670
|
if (index === path.length) yield* node.entries;
|
|
1605
|
-
for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length);
|
|
1606
|
-
for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index);
|
|
1671
|
+
for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length, visited);
|
|
1672
|
+
for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index, visited);
|
|
1607
1673
|
}
|
|
1608
|
-
function* expressionEntries(edge, path, index) {
|
|
1674
|
+
function* expressionEntries(edge, path, index, visited) {
|
|
1609
1675
|
for (const end of expressionEndIndexes(edge.node, path, index)) {
|
|
1676
|
+
if (visited.get(edge.node)?.has(end)) continue;
|
|
1610
1677
|
const expression = path.slice(index, end);
|
|
1611
1678
|
if (!matchesExpressionShape(edge.operator, expression)) continue;
|
|
1612
|
-
yield* stateEntries(edge.node, path, end);
|
|
1679
|
+
yield* stateEntries(edge.node, path, end, visited);
|
|
1613
1680
|
}
|
|
1614
1681
|
}
|
|
1615
1682
|
function* expressionEndIndexes(node, path, index) {
|
|
@@ -1768,13 +1835,19 @@ var Router = class Router {
|
|
|
1768
1835
|
/**
|
|
1769
1836
|
* Resolves a path name and values from a URI, if any match.
|
|
1770
1837
|
* @param url The URI to resolve.
|
|
1838
|
+
* @param options Options for this lookup only.
|
|
1771
1839
|
* @returns The name of the path and its values, if any match. Otherwise,
|
|
1772
1840
|
* `null`.
|
|
1773
1841
|
*/
|
|
1774
|
-
route = (url
|
|
1775
|
-
|
|
1842
|
+
route = (url, options = {}) => {
|
|
1843
|
+
const strict = this.#route(url) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url)) : null);
|
|
1844
|
+
if (strict != null || !options.allowUnencodedColon || !url.includes(":")) return strict;
|
|
1845
|
+
return this.#route(url, true) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url), true) : null);
|
|
1846
|
+
};
|
|
1847
|
+
#route(url, allowUnencodedColon = false) {
|
|
1776
1848
|
for (const entry of this.#trie.candidates(url)) {
|
|
1777
|
-
const
|
|
1849
|
+
const template = entry.pattern.template;
|
|
1850
|
+
const context = allowUnencodedColon ? match(template.tokens, url, (values) => equalWithUnencodedColon(template.expand(values), url), equalWithUnencodedColon) : template.match(url);
|
|
1778
1851
|
if (context == null) continue;
|
|
1779
1852
|
const values = resolveValues(context, entry);
|
|
1780
1853
|
if (values == null) continue;
|
|
@@ -1807,6 +1880,7 @@ var Router = class Router {
|
|
|
1807
1880
|
entry.options
|
|
1808
1881
|
]);
|
|
1809
1882
|
};
|
|
1883
|
+
const equalWithUnencodedColon = (left, right) => left.replaceAll("%3A", ":") === right.replaceAll("%3A", ":");
|
|
1810
1884
|
const createRouteEntry = ({ index, name, pattern, options }) => ({
|
|
1811
1885
|
index,
|
|
1812
1886
|
name,
|