Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { processRouteTree } from '../src/process-route-tree'
3import { getMatchedRoutes } from '../src/router'
4import { joinPaths } from '../src'
5import type { RouteLike } from '../src/route'
6β
7type PathOrChildren = string | [string, Array<PathOrChildren>]
8β
9function createRoute(
10 pathOrChildren: Array<PathOrChildren>,
11 parentPath: string,
12): Array<RouteLike> {
13 return pathOrChildren.map((route) => {
14 if (Array.isArray(route)) {
15 const fullPath = joinPaths([parentPath, route[0]])
16 const children = createRoute(route[1], fullPath)
17 const r = {
18 id: fullPath,
19 path: route[0],
20 fullPath,
21 children: children,
22 }
23 children.forEach((child) => {
24 child.parentRoute = r
25 })
26β
27 return r
28 }
29β
30 const fullPath = joinPaths([parentPath, route])
31β
32 return {
33 id: fullPath,
34 path: route,
35 fullPath,
36 }
37 })
38}
39β
40function createRouteTree(pathOrChildren: Array<PathOrChildren>): RouteLike {
41 return {
42 id: '__root__',
43 fullPath: '',
44 isRoot: true,
45 path: undefined,
46 children: createRoute(pathOrChildren, ''),
47 }
48}
49β
50describe('processRouteTree', () => {
51 describe('basic functionality', () => {
52 it('should process a simple route tree', () => {
53 const routeTree = createRouteTree(['/', '/about'])
54β
55 const result = processRouteTree({ routeTree })
56β
57 expect(result.routesById).toHaveProperty('__root__')
58 expect(result.routesById).toHaveProperty('/')
59 expect(result.routesById).toHaveProperty('/about')
60 expect(result.routesByPath).toHaveProperty('/')
61 expect(result.routesByPath).toHaveProperty('/about')
62 expect(result.flatRoutes).toHaveLength(2) // excludes root
63 })
64β
65 it('should assign ranks to routes in flatRoutes', () => {
66 const routeTree = createRouteTree(['/', '/about'])
67β
68 const result = processRouteTree({ routeTree })
69β
70 expect(result.flatRoutes[0]).toHaveProperty('rank', 0)
71 expect(result.flatRoutes[1]).toHaveProperty('rank', 1)
72 })
73 })
74β
75 describe('route ranking - static segments vs params', () => {
76 it('should rank static segments higher than param segments', () => {
77 const routes = ['/users/profile', '/users/$id']
78 const routeTree = createRouteTree(routes)
79β
80 const result = processRouteTree({ routeTree })
81β
82 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
83 expect(result.flatRoutes[0]!.rank).toBe(0)
84 expect(result.flatRoutes[1]!.rank).toBe(1)
85 })
86β
87 it('should rank static segments higher than optional params', () => {
88 const routes = ['/users/settings', '/users/{-$id}']
89 const routeTree = createRouteTree(routes)
90β
91 const result = processRouteTree({ routeTree })
92β
93 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
94 })
95β
96 it('should rank static segments higher than wildcards', () => {
97 const routes = ['/api/v1', '/api/$']
98 const routeTree = createRouteTree(routes)
99β
100 const result = processRouteTree({ routeTree })
101β
102 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
103 })
104 })
105β
106 describe('route ranking - param variations', () => {
107 it('should rank params higher than optional params', () => {
108 const routes = ['/users/$id', '/users/{-$id}']
109 const routeTree = createRouteTree(routes)
110β
111 const result = processRouteTree({ routeTree })
112β
113 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
114 })
115β
116 it('should rank optional params higher than wildcards', () => {
117 const routes = ['/files/{-$path}', '/files/$']
118 const routeTree = createRouteTree(routes)
119β
120 const result = processRouteTree({ routeTree })
121β
122 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
123 })
124 })
125β
126 describe('route ranking - prefix and suffix variations', () => {
127 it('should rank param with prefix and suffix higher than plain param', () => {
128 const routes = ['/user/prefix-{$id}-suffix', '/user/$id']
129 const routeTree = createRouteTree(routes)
130β
131 const result = processRouteTree({ routeTree })
132β
133 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
134 })
135β
136 it('should rank param with prefix higher than plain param', () => {
137 const routes = ['/user/prefix-{$id}', '/user/$id']
138 const routeTree = createRouteTree(routes)
139β
140 const result = processRouteTree({ routeTree })
141β
142 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
143 })
144β
145 it('should rank param with suffix higher than plain param', () => {
146 const routes = ['/user/{$id}-suffix', '/user/$id']
147 const routeTree = createRouteTree(routes)
148β
149 const result = processRouteTree({ routeTree })
150β
151 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
152 })
153 })
154β
155 describe('route ranking - path length priority', () => {
156 it('should rank longer paths higher when segment scores are equal', () => {
157 const routes = ['/api/v1', '/api']
158 const routeTree = createRouteTree(routes)
159β
160 const result = processRouteTree({ routeTree })
161β
162 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
163 })
164β
165 it('should rank longer param paths higher', () => {
166 const routes = ['/users/$id', '/$id']
167 const routeTree = createRouteTree(routes)
168β
169 const result = processRouteTree({ routeTree })
170β
171 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
172 })
173β
174 it('should rank index route higher than root catch-all', () => {
175 const routes = ['/', '/$'] // index route should rank higher than catch-all
176 const routeTree = createRouteTree(routes)
177β
178 const result = processRouteTree({ routeTree })
179β
180 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
181 })
182β
183 it('should rank routes with fewer optional parameters higher (more specific)', () => {
184 const routes = [
185 '/foo', // most specific: exact match only
186 '/foo/{-$p1}', // less specific: matches /foo or /foo/x
187 '/foo/{-$p1}/{-$p2}', // least specific: matches /foo or /foo/x or /foo/x/y
188 ]
189 const routeTree = createRouteTree(routes)
190β
191 const result = processRouteTree({ routeTree })
192β
193 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
194 })
195 })
196β
197 describe('route ranking - alphabetical ordering', () => {
198 it('should sort alphabetically when scores and lengths are equal', () => {
199 const routes = ['/apple', '/middle', '/zebra'] // in expected alphabetical order
200 const routeTree = createRouteTree(routes)
201β
202 const result = processRouteTree({ routeTree })
203β
204 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
205 })
206 })
207β
208 describe('route ranking - original index fallback', () => {
209 it('should use original index when all other criteria are equal', () => {
210 const routes = ['/first', '/second'] // in expected order (original index determines ranking)
211 const routeTree = createRouteTree(routes)
212β
213 const result = processRouteTree({ routeTree })
214β
215 expect(result.flatRoutes.map((r) => r.id)).toEqual(routes)
216 })
217 })
218β
219 describe('complex routing scenarios', () => {
220 it('should correctly rank a complex mix of route types', () => {
221 // Define routes in expected ranking order - createRouteTree will shuffle them to test sorting
222 const expectedOrder = [
223 '/users/profile/settings', // static-deep (longest static path)
224 '/users/profile', // static-medium (medium static path)
225 '/api/user-{$id}', // param-with-prefix (param with prefix has higher score)
226 '/users/$id', // param-simple (plain param)
227 '/posts/{-$slug}', // optional-param (optional param ranks lower than regular param)
228 '/files/$', // wildcard (lowest priority)
229 '/about', // static-shallow (shorter static path)
230 ]
231β
232 const routeTree = createRouteTree(expectedOrder)
233 const result = processRouteTree({ routeTree })
234 const actualOrder = result.flatRoutes.map((r) => r.id)
235β
236 expect(actualOrder).toEqual(expectedOrder)
237 })
238 })
239β
240 describe('route matching with optional parameters', () => {
241 it('should match the most specific route when multiple routes could match', () => {
242 const routes = ['/foo/{-$p}.tsx', '/foo/{-$p}/{-$x}.tsx']
243 const routeTree = createRouteTree(routes)
244 const result = processRouteTree({ routeTree })
245β
246 // Verify the ranking - fewer optional parameters should rank higher
247 expect(result.flatRoutes.map((r) => r.id)).toEqual([
248 '/foo/{-$p}.tsx',
249 '/foo/{-$p}/{-$x}.tsx',
250 ])
251β
252 // The first route in flatRoutes is what will be matched for `/foo`
253 // This demonstrates that `/foo/{-$p}.tsx` will be matched, not `/foo/{-$p}/{-$x}.tsx`
254 const firstMatchingRoute = result.flatRoutes[0]!
255 expect(firstMatchingRoute.id).toBe('/foo/{-$p}.tsx')
256β
257 // This route has 1 optional parameter, making it more specific than the route with 2
258 expect(firstMatchingRoute.fullPath).toBe('/foo/{-$p}.tsx')
259 })
260β
261 it('should demonstrate matching priority for complex optional parameter scenarios', () => {
262 const routes = [
263 '/foo/{-$a}', // 1 optional param
264 '/foo/{-$a}/{-$b}', // 2 optional params
265 '/foo/{-$a}/{-$b}/{-$c}', // 3 optional params
266 '/foo/bar', // static route (should rank highest)
267 '/foo/bar/{-$x}', // static + 1 optional
268 ]
269 const routeTree = createRouteTree(routes)
270 const result = processRouteTree({ routeTree })
271β
272 // Expected ranking from most to least specific:
273 expect(result.flatRoutes.map((r) => r.id)).toEqual([
274 '/foo/bar', // Static route wins
275 '/foo/bar/{-$x}', // Static + optional
276 '/foo/{-$a}', // Fewest optional params (1)
277 '/foo/{-$a}/{-$b}', // More optional params (2)
278 '/foo/{-$a}/{-$b}/{-$c}', // Most optional params (3)
279 ])
280β
281 // For path `/foo/bar` - static route would match
282 // For path `/foo/anything` - `/foo/{-$a}` would match (not the routes with more optional params)
283 // For path `/foo` - `/foo/{-$a}` would match (optional param omitted)
284 })
285β
286 it('should demonstrate actual path matching behavior', () => {
287 const routes = ['/foo/{-$p}.tsx', '/foo/{-$p}/{-$x}.tsx']
288 const routeTree = createRouteTree(routes)
289 const result = processRouteTree({ routeTree })
290β
291 // Test actual path matching for `/foo`
292 const matchResult = getMatchedRoutes({
293 pathname: '/foo',
294 caseSensitive: false,
295 routesByPath: result.routesByPath,
296 routesById: result.routesById,
297 flatRoutes: result.flatRoutes,
298 })
299β
300 // The foundRoute should be the more specific one (fewer optional parameters)
301 expect(matchResult.foundRoute?.id).toBe('/foo/{-$p}.tsx')
302β
303 // The matched route should be included in the route hierarchy
304 expect(matchResult.matchedRoutes.map((r) => r.id)).toContain(
305 '/foo/{-$p}.tsx',
306 )
307β
308 // Parameters should show the optional parameter as undefined when omitted
309 expect(matchResult.routeParams).toEqual({ p: undefined })
310 })
311 })
312β
313 describe('edge cases', () => {
314 it('should handle root route correctly', () => {
315 const routeTree = createRouteTree([])
316β
317 const result = processRouteTree({ routeTree })
318β
319 expect(result.routesById).toHaveProperty('__root__')
320 expect(result.flatRoutes).toHaveLength(0) // root is excluded from flatRoutes
321 })
322β
323 it('should handle routes without paths', () => {
324 // This test case is more complex as it involves layout routes
325 // For now, let's use a simpler approach with createRouteTree
326 const routeTree = createRouteTree(['/layout/child'])
327β
328 const result = processRouteTree({ routeTree })
329β
330 expect(result.routesById).toHaveProperty('/layout/child')
331 expect(result.flatRoutes).toHaveLength(1)
332 expect(result.flatRoutes[0]!.id).toBe('/layout/child')
333 })
334β
335 it('should handle trailing slashes in routesByPath', () => {
336 const routeTree = createRouteTree(['/test', '/test/']) // without slash first
337β
338 const result = processRouteTree({ routeTree })
339β
340 // Route with trailing slash should take precedence in routesByPath
341 expect(result.routesByPath['/test']).toBeDefined()
342 })
343β
344 it('routes with same optional count but different static segments', () => {
345 const routes = [
346 '/a/{-$p1}/b/{-$p1}/{-$p1}/{-$p1}',
347 '/b/{-$p1}/{-$p1}/{-$p1}/{-$p1}',
348 ]
349 const result = processRouteTree({ routeTree: createRouteTree(routes) })
350β
351 // Route with more static segments (/a/{-$p1}/b) should rank higher
352 // than route with fewer static segments (/b)
353 expect(result.flatRoutes.map((r) => r.id)).toEqual([
354 '/a/{-$p1}/b/{-$p1}/{-$p1}/{-$p1}',
355 '/b/{-$p1}/{-$p1}/{-$p1}/{-$p1}',
356 ])
357 })
358β
359 it('routes with different optional counts and different static segments', () => {
360 const routes = [
361 '/foo/{-$p1}/foo/{-$p1}/{-$p1}/{-$p1}',
362 '/foo/{-$p1}/{-$p1}',
363 ]
364 const result = processRouteTree({ routeTree: createRouteTree(routes) })
365β
366 // Both routes share common prefix '/foo/{-$p1}', then differ
367 // Route 1: '/foo/{-$p1}/b/{-$p1}/{-$p1}/{-$p1}' - has static '/b' at position 2, total 4 optional params
368 // Route 2: '/foo/{-$p1}/{-$p1}' - has optional param at position 2, total 2 optional params
369 // Since position 2 differs (static vs optional), static should win
370 expect(result.flatRoutes.map((r) => r.id)).toEqual([
371 '/foo/{-$p1}/foo/{-$p1}/{-$p1}/{-$p1}',
372 '/foo/{-$p1}/{-$p1}',
373 ])
374 })
375β
376 it.each([
377 {
378 routes: ['/foo/{-$p1}/bar', '/foo/{-$p1}', '/foo/$p1', '/foo/$p1/'],
379 expected: ['/foo/{-$p1}/bar', '/foo/$p1/', '/foo/$p1', '/foo/{-$p1}'],
380 },
381 {
382 routes: ['/foo/{-$p1}/{-$p2}/bar', '/foo/$p1/$p2/'],
383 expected: ['/foo/{-$p1}/{-$p2}/bar', '/foo/$p1/$p2/'],
384 },
385 {
386 routes: ['/foo/{-$p1}/$p2/bar', '/foo/$p1/{-$p2}/bar'],
387 expected: ['/foo/$p1/{-$p2}/bar', '/foo/{-$p1}/$p2/bar'],
388 },
389 {
390 routes: [
391 '/foo',
392 '/admin-levels/$adminLevelId/',
393 '/admin-levels/$adminLevelId',
394 '/about',
395 '/admin-levels/{-$adminLevelId}/reports',
396 '/admin-levels/{-$adminLevelId}',
397 '/',
398 ],
399 expected: [
400 '/admin-levels/{-$adminLevelId}/reports',
401 '/admin-levels/$adminLevelId/',
402 '/admin-levels/$adminLevelId',
403 '/about',
404 '/foo',
405 '/admin-levels/{-$adminLevelId}',
406 '/',
407 ],
408 },
409 ])(
410 'static segment after param ranks param higher: $routes',
411 ({ routes, expected }) => {
412 const result = processRouteTree({ routeTree: createRouteTree(routes) })
413 expect(result.flatRoutes.map((r) => r.id)).toEqual(expected)
414 },
415 )
416β
417 it.each([
418 {
419 routes: ['/f{$param}', '/foo{$param}'],
420 expected: ['/foo{$param}', '/f{$param}'],
421 },
422 {
423 routes: ['/{$param}r', '/{$param}bar'],
424 expected: ['/{$param}bar', '/{$param}r'],
425 },
426 {
427 routes: ['/f{$param}bar', '/foo{$param}r'],
428 expected: ['/foo{$param}r', '/f{$param}bar'],
429 },
430 {
431 routes: ['/foo{$param}r', '/f{$param}baaaaaar'], // very long suffix can "override" prefix
432 expected: ['/f{$param}baaaaaar', '/foo{$param}r'],
433 },
434 ])(
435 'length of prefix and suffix are considered in ranking: $routes',
436 ({ routes, expected }) => {
437 const result = processRouteTree({ routeTree: createRouteTree(routes) })
438 expect(result.flatRoutes.map((r) => r.id)).toEqual(expected)
439 },
440 )
441 })
442})