Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

processRouteTree.test.ts

442 lines15.4 KB

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 })
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 }
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})