Skip to content

Commit dde56c6

Browse files
committed
fix(router)!: don't prefix / to a pattern that starts with a {/…} group
A leading group is read per expansion, so `{/:a}?/b` is `/:a/b` or `/b` (not `//b`), as in URLPattern.
1 parent 2246fe4 commit dde56c6

19 files changed

Lines changed: 377 additions & 36 deletions

‎.agents/matching.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ Segments after a `**` match from the **end** of the path; the `**` takes what is
5757
`removeRoute` splices entries by the registration identity `_add` stamps on them (`MethodData.route`), never the whole bucket, so same-node siblings survive.
5858

5959
- Plain pattern: identity = the rewritten segment join (static keys via `segmentKey`, suffix included), the same string `ctx.static` is keyed by. Spellings the tree can't distinguish remove each other (`/a/` ≡ `/a`, `\)` ≡ `)`, `/**.md` ≡ `/**/*.md`).
60-
- Expanding pattern (groups, modifiers): every entry gets the pre-expansion text normalized by `expandedRouteId()`, so the `/admin` entry of `/admin/:page?` never collides with a separately registered `/admin`.
60+
- Expanding pattern (groups, modifiers): every entry gets the pre-expansion text normalized by `expandedRouteId()`, so the `/admin` entry of `/admin/:page?` never collides with a separately registered `/admin`. A pattern starting with a group (no `/` in front, see [syntax.md](syntax.md#leading-)) is read after a `/` and marked with a leading `{`, so its `/b` entry (`{a}?/b`) never collides with a plain `/b`, `/{/:a}?/b` or `{x/:a}?/b`.
6161
- All entries with that identity go (duplicates together). An emptied static node deletes its `ctx.static` key via the join accumulated during the walk (no value scan).
6262
- Removal is by registered pattern: `/x/*` does not remove `/x/:id`; `:id(\d+)` and `:x(\d+)` are distinct.
6363
- Suffix routes: `_removeSuffix` walks back from the last segment, prunes empty trie nodes, then `wildcard.suffix`, then the wildcard (`_isEmptyNode` counts `suffix`).

‎.agents/regexp.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ A path matches iff the body matches it with one trailing `/` stripped. The gener
3333

3434
### Optional group inlining (`inlineOptionalGroup`)
3535

36-
The tree expands `{…}?` into two routes, but `routeToRegExp` inlines a single optional group as `(?:…)?` to avoid repeating named groups across alternation branches (PCRE2 and Node 22 reject duplicates). The group must end a segment; both expansions (`routeToRegExpSegments`) must line up as shared head + one differing segment (or added whole segments) + shared tail; with a tail, the head must pass `isFixedSegment()`. When the base segment ends in its only capture, `mergeCapture()` makes it split like the router, whose extended route wins where it matches: a lazy `:name` is emitted as `(?<x>[^/]+?)(?:rest)?` (shortest first with the group before without it finds the router's split, `archive.tar.gz` → `archive` + `tar.gz`). A greedy `*` or a constraint gets a look-ahead instead, unless a `\d`/`\w` run can't take the group's first char. Look-ahead forms are RE2-incompatible and not reversible (`LOOKAHEAD_ROUTES`). An appended part after other captures is inlined only where `appendsCleanly` holds: every capture before it is a lazy `:name` (`/f/:x.a{.a}?/m`), the segment and its extension can't end in the same char (`/*-x{.png}?`), or every capture before it can't match the literal char right after it (`/:id(\d+)-x{.png}?`, `/img/:w(\d+)x:h(\d+){.png}?`), so it splits one way. Falls back to alternation for multi-group routes, non-aligning expansions (an in-segment group followed by optional segments, `/:x{.:e}?/:y?`), a mid-segment optional group after other captures otherwise (`/media/*{.webp}?`, `/*-x{-x}?`), and router-order expansion shapes.
36+
The tree expands `{…}?` into two routes, but `routeToRegExp` inlines a single optional group as `(?:…)?` to avoid repeating named groups across alternation branches (PCRE2 and Node 22 reject duplicates). The group must end a segment; a leading group's full expansion gets the `/` `expandGroupDelimiters` gives it (`{a}?/b` is `(?:\/a)?\/b`), and one with an empty base (`{/:a}?`) falls back; both expansions (`routeToRegExpSegments`) must line up as shared head + one differing segment (or added whole segments) + shared tail; with a tail, the head must pass `isFixedSegment()`. When the base segment ends in its only capture, `mergeCapture()` makes it split like the router, whose extended route wins where it matches: a lazy `:name` is emitted as `(?<x>[^/]+?)(?:rest)?` (shortest first with the group before without it finds the router's split, `archive.tar.gz` → `archive` + `tar.gz`). A greedy `*` or a constraint gets a look-ahead instead, unless a `\d`/`\w` run can't take the group's first char. Look-ahead forms are RE2-incompatible and not reversible (`LOOKAHEAD_ROUTES`). An appended part after other captures is inlined only where `appendsCleanly` holds: every capture before it is a lazy `:name` (`/f/:x.a{.a}?/m`), the segment and its extension can't end in the same char (`/*-x{.png}?`), or every capture before it can't match the literal char right after it (`/:id(\d+)-x{.png}?`, `/img/:w(\d+)x:h(\d+){.png}?`), so it splits one way. Falls back to alternation for multi-group routes, non-aligning expansions (an in-segment group followed by optional segments, `/:x{.:e}?/:y?`), a mid-segment optional group after other captures otherwise (`/media/*{.webp}?`, `/*-x{-x}?`), and router-order expansion shapes.
3737

3838
### Duplicate names
3939

@@ -57,7 +57,7 @@ Inverse of `routeToRegExp`: parses an anchored, PCRE-compatible regex (or source
5757
- **Endings** are normalized structurally, exact shapes only (`ROOT_REPEAT`, `plainBody()` for closed endings, `TRAILING_CATCH_ALL`, `TRAILING_DOT`), then the look-behind suffix, the legacy two-slash suffix or a plain `\/?` is stripped. No generic `.*?` rewrite, so lazy quantifiers inside user constraints survive.
5858
- **Body walk** recognizes `\/` separators, optional units `(?:…)?` / `(?:…)??`, nested optionals, catch-alls (greedy `(?:\/(?<_>[\s\S]*))?` → `**`, a lazy group with a lazy body → `**`, with a greedy body → `{/**}?` (merged; `:_*` where no group can be), `\/(?<x>[\s\S]+)` → `:x+`, root forms, `NESTED_CATCH_ALL`: `:x*` then `*` (`[\s\S]+`; `[\s\S]*` in 0.11, and 0.10's `**` / `:x*` then `:y?`)). `.*` / `.+` read as catch-alls (legacy output), unless the regex has a lazy user-`.` ending.
5959
- **Segments:** `(?<x>[^/]+)`, `[^/]+?` (in a mixed segment) / legacy `[^/]*` → `:x`; `\/(?<x>[\s\S]+)` → `:x+` (legacy `[\s\S]*` too), in an optional unit `:x*` (same route as `{/:x+}?`; 0.11's empty-capable `[\s\S]*` one too, which now needs a value); the closed `**:x` ending `(?:\/\/|(?<x>…)\/?)` → `(?<x>[\s\S]+)` (`REQUIRED_VALUE`, the 0.10 `(?:\/|…)` one → `[\s\S]*`); an in-segment optional lone param comes back as `pre-:x?` (`mergeGroup`); unnamed `[^/]*` → `*`; `(pat)` → `(pat)`; `(?<x>pat)` → `:x(pat)`; route-syntax literals re-escaped; a word char or non-ASCII char after a bare `:name` is escaped (`:x\abc`, `:x\é`; a `-` ends a name, so it stays bare); a constraint body holding a capturing group throws, and so does a `*` right after a `*` (would read as `**`): `addRoute` rejects both. Optional units classify by inner shape into `:x?` / `:x*` / `*` / merged `{…}?` groups. Equivalent outputs come back in one spelling (`/a{/:x+}?` → `/a/:x*`).
60-
- **Unnamed captures** (`(?<_N>…)`) are told apart by the raw group name (`matchNamedGroup`'s `unnamed`, `UNNAMED`), never the decoded one: a param `:_0` is emitted escaped (`__rou3_esc___0`) and decodes to the same `_0`. An optional one stays unnamed: `(?:\/(?<_0>pat))?` → `{/(pat)}?` on the previous segment (`:_0(pat)?` would be a param keyed `_0`, not `0`; with no previous segment, inside a group (`{…}` can't nest), or a body with no constraint form like `[^/]+`, it throws). A `[^/]*` is a bare `*` only where that is optional (ending the route, or with the next optionals nested in its group), else `{/*}?` (`/a{/*}?/b`).
60+
- **Unnamed captures** (`(?<_N>…)`) are told apart by the raw group name (`matchNamedGroup`'s `unnamed`, `UNNAMED`), never the decoded one: a param `:_0` is emitted escaped (`__rou3_esc___0`) and decodes to the same `_0`. An optional one stays unnamed: `(?:\/(?<_0>pat))?` → `{/(pat)}?` on the previous segment, or starting the route with none (`{/(pat)}?/b`, absolute, see [syntax.md](syntax.md#leading-)) (`:_0(pat)?` would be a param keyed `_0`, not `0`; inside a group (`{…}` can't nest), or a body with no constraint form like `[^/]+`, it throws). Other root optionals of whole segments with nothing to merge onto lead the route the same way (`^(?:\/a)?\/b` → `{/a}?/b`); a root in-segment one (`^(?:foo)?`) still throws. A `[^/]*` is a bare `*` only where that is optional (ending the route, or with the next optionals nested in its group), else `{/*}?` (`/a{/*}?/b`).
6161
- **Percent-encoding:** `%XX` comes back as written (`/caf%C3%A9`, never decoded: `%2F`, `%25` would change the route), and `reverseSegment`'s `literal` throws on a char `encodeLiteral` would change (`é`, space, `\{`, `\?`, `\^`): route text is encoded, so no route has it (see [syntax.md](syntax.md#percent-encoding)).
6262
- **Reject by default:** `reverseSegment()` is a whitelist; look-arounds and other `(?…)` constructs, backreferences / metaclass escapes outside a constraint, bare regex operators, constraint bodies with `/`, flags `i`/`m`/`s`/`u`/`v` (`g`/`y`/`d` ignored), unanchored input, and group names that decode to no valid param name all throw. Constraint bodies are opaque and kept verbatim.
6363
- **Legacy inputs** (older look-behind, pre-trailing-slash-change two-slash, 0.9.x `\/?` endings with `.*` / `.+` catch-alls, 0.10's closed endings for an empty-capable `:x` / `**:x`, 0.11's empty-capable `:x*` forms and `ROOT_REPEAT`) are accepted and read as the route they were emitted for, which may now match fewer paths; pinned in `regexp-to-route.test.ts`.

‎.agents/syntax.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
# Pattern syntax
22

3-
`addRoute` pipeline: `checkConstraints` → `expandGroupDelimiters` → `encodeEscapes` / `splitRoute` → `expandModifiers` (`:x+` → `**:x`, `:x*` → `**:x` + the route without it, see [matching.md](matching.md#empty-segments-and-normalization); `pre-:x?` → `pre-:x` + `pre-`, but after a capture it stays for `getParamRegexp`, see [below](#params-sharing-a-segment)) → per segment `segmentKey` (static key) or `getParamRegexp` / `addName`, both percent-encoding literal text (`encodeLiteral`, see [below](#percent-encoding)). Each helper bails early when its trigger is absent (`\`, `�`, `{`, trailing `?`/`+`/`*`, `(`/`{`/`}`, an encode-set char), so plain routes skip the scanners. Keep those guards.
3+
`addRoute` pipeline: `absolutePattern` (see [below](#leading-)) → `checkConstraints` → `expandGroupDelimiters` → `encodeEscapes` / `splitRoute` → `expandModifiers` (`:x+` → `**:x`, `:x*` → `**:x` + the route without it, see [matching.md](matching.md#empty-segments-and-normalization); `pre-:x?` → `pre-:x` + `pre-`, but after a capture it stays for `getParamRegexp`, see [below](#params-sharing-a-segment)) → per segment `segmentKey` (static key) or `getParamRegexp` / `addName`, both percent-encoding literal text (`encodeLiteral`, see [below](#percent-encoding)). Each helper bails early when its trigger is absent (`\`, `�`, `{`, trailing `?`/`+`/`*`, `(`/`{`/`}`, an encode-set char), so plain routes skip the scanners. Keep those guards.
4+
5+
## Leading `/`
6+
7+
A relative pattern gets a `/` (`foo/:id` is `/foo/:id`; URLPattern never matches one on an absolute path). `absolutePattern()` (`operations/_utils.ts`) is the one rule, used by `addRoute`, `removeRoute` and `routeToRegExp`: a pattern starting with `/` or `{` is left alone. A leading `{…}` group can't be prefixed as a whole: `{/:a}?/b` is absolute in URLPattern (WPT gives `{/:foo}bar` as the canonical form of `/:foo\bar`), and a `/` in front would add an empty first segment (`//b`). So `expandGroupDelimiters` applies `absolutePattern` to each expansion of a leading group (`pre === ""`): one starting with `/` is absolute (`/:a/b`), the empty one is the root (`{/:a}?` is `/:a` or `/`, like `/:a?`), any other is relative and gets a `/` (`{a}?/b` is `/a/b` or `/b`, `{/a}?b` is `/ab` or `/b`; URLPattern matches only `/b` / `/ab`, the relative form never), and one starting with `{` is the next group's (`{/a}?{/:b}?/c`). Escaped braces (`\{/a\}`) are literals: relative. `{/…}+` / `{/…}*` throw as anywhere. Insert-time only: lookup is untouched.
8+
9+
- Removal identity: `expandedRouteId` reads a leading-group pattern after a `/` and marks it with a `{` (no other identity starts with one), so `{a}?/b` never shares an identity with a plain `/b`, nor `{/:a}?/b` with `/{/:a}?/b` or `{x/:a}?/b`.
10+
- `routeToRegExp`: `inlineOptionalGroup` builds the full expansion with the same `/` (`{a}?/b` is `(?:\/a)?\/b`); a leading group with nothing after it (`{/:a}?`) has an empty base and falls back to alternation.
11+
- `regExpToRoute`: a root optional of whole segments with no segment to merge onto comes back as a leading group (`^(?:\/(?<_0>\d+))?\/b` → `{/(\d+)}?/b`; `mergeGroup`). Only at the top level and only when the body has no `\/` before it (`/{/a}?` is an empty first segment, then the group).
12+
- Types (`InferRouteParams`) need nothing: they read names, not segments.
413

514
## Escapes
615

‎.agents/testing.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
- Matcher tests compare `findRoute` / `findAllRoutes` with compiled JIT and AOT output; tree and codegen are snapshot-tested.
55
- Paths with empty segments (`/a//`, `/a//b`) must be in every sweep: a `:name` / `**:name` can't take one while `*` / `**` can (`sweepPaths()`, the `overlap.test.ts` / `suffix.test.ts` alphabets hold `""`, and `find.test.ts` "empty segments (compiled parity, sweep)" compares interpreter and compiled on random routers).
66
- Brute-force sweeps (pairs of patterns × short paths) back the hard invariants: `suffix.test.ts` (never pick a strictly broader route), `method-agnostic.test.ts`, `overlap.test.ts`, `route-node-keys.test.ts`, `regexp.test.ts`, `regexp-to-route.test.ts`. Keep them passing with 0 violations; known exceptions live in named, stale-guarded sets (a listed entry that stops differing fails).
7-
- `test/wpt.test.ts`: URLPattern WPT data, vendored verbatim (to sync, copy upstream's `urlpattern/resources/urlpatterntestdata.json` and update the SHA in the file header). Read like WPT's runner (`urlpatterntests.js`): `expected_obj: "error"` must throw `rou3:` (except `ACCEPTED_INVALID_PATTERNS`), `baseURL` / URL-string inputs resolve to their pathname, every input is percent-encoded like `new URL().pathname` (`encodePathname`, checked against the runtime's URLPattern in `PERCENT_ENCODING_CASES`), and entries that are not a lone `pathname` pattern are counted as out of scope. Groups compare with `toStrictEqual` (`null` in the data = an unset group = `undefined`); the one modelled difference is `expectedGroups()`: the tree leaves an unset param out of `params`, so for tree strategies an unset URLPattern group ≡ an absent key (a present `undefined` param still differs). Diffs live in `KNOWN_DIFFS`, `REGEXP_ONLY_KNOWN_DIFFS`, `ROUTER_KNOWN_DIFFS`: maps from label to rou3's exact result (groups, `null` for no match; `split(regexp, router)` where the regex and the tree also differ), each asserted to differ from URLPattern **and** to equal the stored result, so a behaviour PR that changes a listed case must update its entry. Rejected syntax is in `RESERVED_PATTERNS` (asserted to throw); an entry the data no longer reaches fails. Each skip names its reason and checks the exact entry shape that reason describes (anything else throws `wpt: unexpected …`); `--reporter=verbose` prints per-strategy counts. Where the runtime has a global `URLPattern` (not Node 22), "agrees with the runtime's URLPattern" checks every in-scope, non-skipped case (the resolved input, groups as read) against it, as do the `EMPTY_SEGMENT_CASES` / `PERCENT_ENCODING_CASES` side tables.
7+
- `test/wpt.test.ts`: URLPattern WPT data, vendored verbatim (to sync, copy upstream's `urlpattern/resources/urlpatterntestdata.json` and update the SHA in the file header). Read like WPT's runner (`urlpatterntests.js`): `expected_obj: "error"` must throw `rou3:` (except `ACCEPTED_INVALID_PATTERNS`), `baseURL` / URL-string inputs resolve to their pathname, every input is percent-encoded like `new URL().pathname` (`encodePathname`, checked against the runtime's URLPattern in `PERCENT_ENCODING_CASES`), and entries that are not a lone `pathname` pattern are counted as out of scope. Groups compare with `toStrictEqual` (`null` in the data = an unset group = `undefined`); the one modelled difference is `expectedGroups()`: the tree leaves an unset param out of `params`, so for tree strategies an unset URLPattern group ≡ an absent key (a present `undefined` param still differs). Diffs live in `KNOWN_DIFFS`, `REGEXP_ONLY_KNOWN_DIFFS`, `ROUTER_KNOWN_DIFFS`: maps from label to rou3's exact result (groups, `null` for no match; `split(regexp, router)` where the regex and the tree also differ), each asserted to differ from URLPattern **and** to equal the stored result, so a behaviour PR that changes a listed case must update its entry. Rejected syntax is in `RESERVED_PATTERNS` (asserted to throw); an entry the data no longer reaches fails. Each skip names its reason and checks the exact entry shape that reason describes (anything else throws `wpt: unexpected …`); `--reporter=verbose` prints per-strategy counts. Where the runtime has a global `URLPattern` (not Node 22), "agrees with the runtime's URLPattern" checks every in-scope, non-skipped case (the resolved input, groups as read) against it, as do the `EMPTY_SEGMENT_CASES` / `PERCENT_ENCODING_CASES` / `LEADING_GROUP_CASES` side tables (with `EMPTY_SEGMENT_DIFFS` / `LEADING_GROUP_DIFFS`: where rou3 matches and URLPattern doesn't).
88

99
## Regex fixtures and sweeps
1010

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ A route can have only one catch-all. `**`, `**:name`, and a `:name+` / `:name*`
144144

145145
Groups can't be nested or repeated (`{...}+` and `{...}*` throw).
146146

147+
A pattern can start with a group. A group that starts with `/` is part of the path, as in URLPattern: `{/:lang}?/docs` matches `/docs` and `/en/docs`, and `{/:lang}?` matches `/` and `/en`. Write `/{/:lang}?/docs` for a route that starts with an empty segment (`//docs`, `//en/docs`). A pattern that doesn't start with `/` gets one (`users/:id` is `/users/:id`), and so does each form of a leading group without one: `{v2}?/api` matches `/v2/api` and `/api`.
148+
147149
### Escaping
148150

149151
Escape `:`, `*`, `?`, `+`, `(`, `)`, `{` and `}` with a backslash to match them literally (a literal `?`, `{` or `}` is then [percent-encoded](#percent-encoding), like other literal text). Outside a regex constraint, any escaped character is a literal (`\\.` is `.`, `\\\\` is `\`), as in URLPattern. A `\` can't escape `/` or end a segment.
@@ -188,6 +190,7 @@ rou3 matches paths segment by segment in a tree, which leads to a few intentiona
188190
| Path normalization (`.`/`..`) | Resolved in input paths | Opt-in with `{ normalize: true }` |
189191
| Case sensitivity | Can be case-insensitive | Always case-sensitive |
190192
| Non-`/`-prefixed paths | Supported | Paths must start with `/` |
193+
| Patterns without a leading `/` (`users/:id`, `{v2}?/api`) | Never match an absolute path | Get a `/` (`/users/:id`); a leading group, in each form without one (`{v2}?/api` matches `/v2/api` and `/api`) |
191194
| Optional group after a greedy capture in its segment (`/*{.webp}?`, `/*-{:x}?`) | The capture takes what it can (`/a.webp`: `{ 0: "a.webp" }`) | The route with the group wins (`/a.webp`: `{ 0: "a" }`); write `/*-:x?` for URLPattern's split of an optional param |
192195
| Optional segment after `:name+` / `:name*` (`/:a+/:b?`) | The repeated param takes what it can (`/x/y`: `{ a: "x/y" }`) | Segments after a catch-all match from the end (`/x/y`: `{ a: "x", b: "y" }`) |
193196
| Param names | Unicode identifiers | `[A-Za-z_]\w*`; a non-ASCII char or `$` right after one throws |

0 commit comments

Comments
 (0)