Skip to content

Commit 8645b35

Browse files
yangshunclaude
andcommitted
fix(routing): rank overlapping routes segment by segment
Pages sorted dynamic patterns by comparing the whole pattern string, so `[lang]/about` (/:lang/about) registered ahead of `users/[id]` and won /users/about, and `[lang]/[slug]` shadowed every static sibling under `[lang]/`. WebSocket routes sorted by plain string order, so `chat/[room]` shadowed `chat/lobby`. The routes/ comparator ranked by segment but let parameter names break ties, so `[category]/[item]` won /fr/about over `[lang]/about`. Pages, routes/ and WebSocket routes now share one comparator: catch-alls last, fully static routes first, then the first differing segment decides (static, then param, then catch-all). Parameter names never decide. The Pages client matcher classifies segments with the same helper, so ranking and matching agree. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9a6f994 commit 8645b35

10 files changed

Lines changed: 235 additions & 47 deletions

File tree

‎docs/guide/server-routing.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,20 @@ Create route handlers in `routes/` using `.ts`, `.tsx`, `.js`, `.jsx`, `.mts`, o
1414

1515
Dynamic segments use brackets: `[id]` becomes a route parameter and `[...slug]` becomes a catch-all. Prefix files or directories with `_` or `.` to exclude them from routing; `.well-known` remains available for standard discovery endpoints. Directories wrapped in parentheses like `(admin)` are route groups. They help organize files without changing the URL.
1616

17+
### Overlapping routes
18+
19+
When several routes match a URL, the most specific one handles it. Void compares routes segment by segment, from the left, and the first segment that differs decides: a static segment beats `[param]`, and `[param]` beats `[...slug]`. Catch-all routes rank after all other routes.
20+
21+
```
22+
routes/
23+
users/[id].ts → handles /users/about (users beats [lang])
24+
[lang]/about.ts → handles /fr/about (about beats [slug])
25+
[lang]/[slug].ts → handles /fr/contact
26+
[...path].ts → handles URLs no other route matches
27+
```
28+
29+
Parameter names don't affect the order. Routes that differ only in their parameter names, such as `[id].ts` and `[slug].ts`, match the same URLs, so keep only one of them.
30+
1731
### Environment-only routes
1832

1933
Add a `.dev` or `.prod` suffix before the extension to include a route in only one environment:

‎packages/void/src/pages/manifest.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { routeSegmentKind } from '../router/route-order.ts';
12
import { resolveLayoutIds, toLayoutId } from './layout-resolution.ts';
23
import type { PageScanResult } from './types.ts';
34

@@ -106,19 +107,19 @@ const REGEX_SYNTAX = '.*+?^${}()|[]\\';
106107

107108
/** The capture group for `*`, `:name{.+}` and `:name`; other segments match as written. */
108109
function captureGroup(segment: string): string | undefined {
109-
if (segment === '*') {
110-
return '(.*)';
110+
switch (routeSegmentKind(segment)) {
111+
case 'rest':
112+
return segment === '*' ? '(.*)' : '(.+)';
113+
case 'param':
114+
return '([^\\/]+)';
115+
case 'static':
116+
return undefined;
111117
}
112-
if (segment.length < 2 || segment[0] !== ':') {
113-
return undefined;
114-
}
115-
const name = segment.endsWith('{.+}') ? segment.slice(1, -4) : '';
116-
return name && !name.includes('{') && !name.includes('}') ? '(.+)' : '([^\\/]+)';
117118
}
118119

119120
/** Whether `patternToRegex` matches only the pattern's own text. */
120121
function isStaticPattern(pattern: string): boolean {
121-
return pattern.split('/').every((segment) => captureGroup(segment) === undefined);
122+
return pattern.split('/').every((segment) => routeSegmentKind(segment) === 'static');
122123
}
123124

124125
/** The RegExp literal a page pattern matches with, the same on the client and the server. */

‎packages/void/src/pages/scan.ts‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
parseRouteFilename,
1010
type RouteEnvironment,
1111
} from '../router/parse-filename.ts';
12+
import { compareRouteSpecificity } from '../router/route-order.ts';
1213
import { bindingNames } from '../shared/ast-bindings.ts';
1314
import {
1415
isIdentifier,
@@ -407,18 +408,7 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis
407408
});
408409
}
409410

410-
// Sort: static before dynamic, catch-all last
411-
pages.sort((a, b) => {
412-
if (a.catchAll !== b.catchAll) {
413-
return a.catchAll ? 1 : -1;
414-
}
415-
const aDynamic = a.pattern.includes(':');
416-
const bDynamic = b.pattern.includes(':');
417-
if (aDynamic !== bDynamic) {
418-
return aDynamic ? 1 : -1;
419-
}
420-
return a.pattern.localeCompare(b.pattern);
421-
});
411+
pages.sort(compareRouteSpecificity);
422412

423413
if (options?.checkRoutes !== false) {
424414
// At most one page per route in each environment. A scan for every
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/** How a pattern segment matches: as written, one URL segment, or the rest of the path. */
2+
export type RouteSegmentKind = 'static' | 'param' | 'rest';
3+
4+
/**
5+
* Classify one segment of a route pattern. `*` and `:name{.+}` match the rest of the path,
6+
* `:name` matches one segment, and anything else matches as written. Pages match with the
7+
* same rules on the client (see `patternToRegex`), so ranking and matching agree.
8+
*/
9+
export function routeSegmentKind(segment: string): RouteSegmentKind {
10+
if (segment === '*') {
11+
return 'rest';
12+
}
13+
if (segment.length < 2 || segment[0] !== ':') {
14+
return 'static';
15+
}
16+
const name = segment.endsWith('{.+}') ? segment.slice(1, -4) : '';
17+
return name && !name.includes('{') && !name.includes('}') ? 'rest' : 'param';
18+
}
19+
20+
const SEGMENT_RANK: Record<RouteSegmentKind, number> = { static: 0, param: 1, rest: 2 };
21+
22+
/**
23+
* Order routes so that, of any two that match the same URL, the more specific one comes first.
24+
* Hono and the Pages client matcher both use the first match.
25+
*
26+
* Catch-all routes come last and fully static routes first. Otherwise the first segment that
27+
* differs decides: static before `:param` before catch-all. Parameter names never decide, so
28+
* `/:lang/about` ranks ahead of `/:category/:item`. Two different static segments can't match
29+
* the same URL, so their text only keeps the order stable.
30+
*/
31+
export function compareRouteSpecificity(
32+
a: { pattern: string; catchAll: boolean },
33+
b: { pattern: string; catchAll: boolean },
34+
): number {
35+
if (a.catchAll !== b.catchAll) {
36+
return a.catchAll ? 1 : -1;
37+
}
38+
const aSegments = a.pattern.split('/');
39+
const bSegments = b.pattern.split('/');
40+
const aKinds = aSegments.map(routeSegmentKind);
41+
const bKinds = bSegments.map(routeSegmentKind);
42+
// A static route never shares a URL with a more specific one, and Pages looks
43+
// up the leading run of static routes exactly.
44+
const aStatic = aKinds.every((kind) => kind === 'static');
45+
const bStatic = bKinds.every((kind) => kind === 'static');
46+
if (aStatic !== bStatic) {
47+
return aStatic ? -1 : 1;
48+
}
49+
const shared = Math.min(aSegments.length, bSegments.length);
50+
for (let i = 0; i < shared; i++) {
51+
const rank = SEGMENT_RANK[aKinds[i]] - SEGMENT_RANK[bKinds[i]];
52+
if (rank !== 0) {
53+
return rank;
54+
}
55+
if (aKinds[i] === 'static' && aSegments[i] !== bSegments[i]) {
56+
return compareText(aSegments[i], bSegments[i]);
57+
}
58+
}
59+
return aSegments.length - bSegments.length || compareText(a.pattern, b.pattern);
60+
}
61+
62+
function compareText(left: string, right: string): number {
63+
return left < right ? -1 : left > right ? 1 : 0;
64+
}

‎packages/void/src/router/scan.ts‎

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
type RouteDefinition,
1515
type RouteEnvironment,
1616
} from './parse-filename.ts';
17+
import { compareRouteSpecificity } from './route-order.ts';
1718
import { isWebSocketPatternFile, type WebSocketRouteDefinition } from './websocket.ts';
1819

1920
export type ScanResult = {
@@ -47,27 +48,6 @@ function parseMiddlewareDefinitions(files: Array<string>): Array<MiddlewareDefin
4748
.sort((a, b) => a.order - b.order);
4849
}
4950

50-
// Order by specificity (static < dynamic param < catch-all, depth-first); Hono resolves overlap by registration order.
51-
function compareRouteSpecificity(a: RouteDefinition, b: RouteDefinition): number {
52-
if (a.catchAll !== b.catchAll) {
53-
return a.catchAll ? 1 : -1;
54-
}
55-
const aSegments = a.pattern.split('/');
56-
const bSegments = b.pattern.split('/');
57-
const shared = Math.min(aSegments.length, bSegments.length);
58-
for (let i = 0; i < shared; i++) {
59-
const aDynamic = aSegments[i].startsWith(':') || aSegments[i] === '*';
60-
const bDynamic = bSegments[i].startsWith(':') || bSegments[i] === '*';
61-
if (aDynamic !== bDynamic) {
62-
return aDynamic ? 1 : -1;
63-
}
64-
if (aSegments[i] !== bSegments[i]) {
65-
return aSegments[i].localeCompare(bSegments[i]);
66-
}
67-
}
68-
return aSegments.length - bSegments.length;
69-
}
70-
7151
/** Add pages and HTTP methods to the inventories already resolved for this application phase. */
7252
export async function scanRoutes(
7353
root: string,

‎packages/void/src/router/websocket.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
type RouteDefinition,
1919
type RouteEnvironment,
2020
} from './parse-filename.ts';
21+
import { compareRouteSpecificity } from './route-order.ts';
2122

2223
const WEBSOCKET_ROUTE_RE = new RegExp(
2324
`(?:\\.(?:dev|prod))?\\.ws\\.(?:${ROUTE_EXTENSIONS.join('|')})$`,
@@ -148,12 +149,7 @@ function parseWebSocketFiles(
148149
isRouteEnabledForEnvironment(parseWebSocketFilename(filePath), environment),
149150
)
150151
.map((filePath) => buildWebSocketRoute(root, filePath, paths))
151-
.sort((a, b) => {
152-
if (a.catchAll !== b.catchAll) {
153-
return a.catchAll ? 1 : -1;
154-
}
155-
return a.pattern.localeCompare(b.pattern);
156-
});
152+
.sort(compareRouteSpecificity);
157153
const byClass = new Map<string, Array<WebSocketRouteDefinition>>();
158154
for (const route of routes) {
159155
const previous = byClass.get(route.className) ?? [];

‎packages/void/test/unit/pages-scan.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,39 @@ export { handler as action, type actions };`,
364364
expect(patterns.indexOf('/:id')).toBeLessThan(patterns.indexOf('/:slug{.+}'));
365365
});
366366

367+
it('matches overlapping dynamic pages by their first differing segment', async () => {
368+
for (const file of [
369+
'[lang]/about.tsx',
370+
'[lang]/[slug].tsx',
371+
'users/[id].tsx',
372+
'users/[id]/edit.tsx',
373+
'users/new/[tab].tsx',
374+
'docs/[...path].tsx',
375+
'[lang]/[...path].tsx',
376+
]) {
377+
writeFile(file, 'export default function Page() { return null; }');
378+
}
379+
380+
const scan = await scanPages(TMP);
381+
// The server registers pages in this order, and the client matcher keeps it.
382+
const { matchRoute } = new Function(
383+
`${generateComponentManifest(scan, '/project/pages')}\nreturn { matchRoute };`,
384+
)() as { matchRoute: (path: string) => string | null };
385+
expect(
386+
Object.fromEntries(
387+
['/users/about', '/users/new/edit', '/fr/about', '/docs/a/b', '/fr/team/jobs'].map(
388+
(url) => [url, matchRoute(url)],
389+
),
390+
),
391+
).toEqual({
392+
'/users/about': 'users/[id]',
393+
'/users/new/edit': 'users/new/[tab]',
394+
'/fr/about': '[lang]/about',
395+
'/docs/a/b': 'docs/[...path]',
396+
'/fr/team/jobs': '[lang]/[...path]',
397+
});
398+
});
399+
367400
it('handles .tsx components', async () => {
368401
writeFile('dashboard.tsx', 'export default function Dashboard() { return <div />; }');
369402
const result = await scanPages(TMP);
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { describe, expect, it } from 'vite-plus/test';
2+
import { patternToRegex } from '../../src/pages/manifest.ts';
3+
import { compareRouteSpecificity, routeSegmentKind } from '../../src/router/route-order.ts';
4+
5+
function route(pattern: string) {
6+
return {
7+
pattern,
8+
catchAll: pattern.split('/').some((segment) => routeSegmentKind(segment) === 'rest'),
9+
};
10+
}
11+
12+
function matches(pattern: string, url: string): boolean {
13+
return new RegExp(patternToRegex(pattern).slice(1, -1)).test(url);
14+
}
15+
16+
describe('compareRouteSpecificity', () => {
17+
it.each([
18+
// A static segment beats a dynamic one, wherever it is
19+
['/users/:id', '/:lang/about', '/users/about'],
20+
['/users/new/:tab', '/users/:id/edit', '/users/new/edit'],
21+
['/:lang/about', '/:lang/:slug', '/en/about'],
22+
['/about', '/:slug', '/about'],
23+
// Parameter names never decide
24+
['/:lang/about', '/:category/:item', '/fr/about'],
25+
['/:z/about', '/:a/:b', '/fr/about'],
26+
// A plain parameter beats a catch-all, and catch-alls come last
27+
['/docs/:path{.+}', '/:slug{.+}', '/docs/intro'],
28+
['/:lang/:path{.+}', '/:slug{.+}', '/fr/team/jobs'],
29+
['/:lang/:slug', '/docs/:path{.+}', '/docs/intro'],
30+
['/files/:name', '/files/*', '/files/a'],
31+
])('ranks %s ahead of %s, which both match %s', (specific, general, url) => {
32+
expect(matches(specific, url)).toBe(true);
33+
expect(matches(general, url)).toBe(true);
34+
for (const routes of [
35+
[route(specific), route(general)],
36+
[route(general), route(specific)],
37+
]) {
38+
expect(routes.sort(compareRouteSpecificity).map((r) => r.pattern)).toEqual([
39+
specific,
40+
general,
41+
]);
42+
}
43+
});
44+
45+
it('gives the same order for any input order', () => {
46+
const patterns = [
47+
'/',
48+
'/zzz',
49+
'/files/a*b',
50+
'/:lang',
51+
'/:lang/about',
52+
'/:lang/:slug',
53+
'/:category/:item',
54+
'/users/:id',
55+
'/users/:id/edit',
56+
'/users/new/:tab',
57+
'/docs/:path{.+}',
58+
'/:lang/:path{.+}',
59+
'/:slug{.+}',
60+
'/*',
61+
];
62+
const expected = [
63+
// Fully static routes first, so Pages can look them up exactly
64+
'/',
65+
'/files/a*b',
66+
'/zzz',
67+
'/users/new/:tab',
68+
'/users/:id',
69+
'/users/:id/edit',
70+
'/:lang',
71+
'/:lang/about',
72+
'/:category/:item',
73+
'/:lang/:slug',
74+
// Catch-all routes last
75+
'/docs/:path{.+}',
76+
'/:lang/:path{.+}',
77+
'/*',
78+
'/:slug{.+}',
79+
];
80+
for (let shift = 0; shift < patterns.length; shift++) {
81+
const rotated = [...patterns.slice(shift), ...patterns.slice(0, shift)];
82+
expect(rotated.reverse().map(route).sort(compareRouteSpecificity)).toEqual(
83+
expected.map(route),
84+
);
85+
}
86+
});
87+
});

‎packages/void/test/unit/scan.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,19 @@ describe('scanRoutes', () => {
250250
]);
251251
});
252252

253+
it('ranks routes by segment kind, not parameter names', async () => {
254+
createFile('routes/[category]/[item].ts');
255+
createFile('routes/[lang]/about.ts');
256+
createFile('routes/[lang]/[slug].ts');
257+
258+
const result = await scanRoutes(TMP);
259+
expect(result.routes.map((route) => route.pattern)).toEqual([
260+
'/:lang/about',
261+
'/:category/:item',
262+
'/:lang/:slug',
263+
]);
264+
});
265+
253266
it('discovers cron jobs from crons directory', async () => {
254267
createFile('routes/api/hello.ts');
255268
createFile('crons/sync.ts', 'export const cron = "0 * * * *"\nexport default () => {}');

‎packages/void/test/unit/websocket-scan.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,4 +229,14 @@ describe('WebSocket resource names', () => {
229229
expect(() => scanWebSocketRoutesSync(root)).toThrow('duplicate generated name');
230230
expect(scanWebSocketRoutesSync(root, undefined, 'prod')).toHaveLength(1);
231231
});
232+
233+
it('orders a static WebSocket route ahead of a dynamic sibling', () => {
234+
const root = createRoot();
235+
createRoute(root, 'chat/[room].ws.ts', 'export default defineRoom({})');
236+
createRoute(root, 'chat/lobby.ws.ts', 'export default defineRoom({})');
237+
expect(scanWebSocketRoutesSync(root).map((route) => route.pattern)).toEqual([
238+
'/chat/lobby',
239+
'/chat/:room',
240+
]);
241+
});
232242
});

0 commit comments

Comments
 (0)