refactor(router-core): processRouteTree in its own file #5128
main fromrefs/pull/5128/head·merged by Sheraff(GitHub profile, opens in a new tab) - move
processRouteTreeto a separate file because the logic is very self-contained - create a new function
sortRoutesw/ the sorting logic, so it can be tested independently
This PR is a no-op, we're just moving code around, nothing was changed.
Summary by CodeRabbit#
New Features
- Added a public Route type for describing route objects in route trees.
Refactor
- Consolidated route processing into a dedicated module for clearer separation and maintainability.
- Updated public exports for route processing; existing imports may need to be adjusted.
- No runtime behavior changes expected.
Tests
- Updated tests to use the new public Route type and revised import paths.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
View your CI Pipeline Execution ↗ for commit a2a07b469d966251d5899ca1f1ef0606cb220275
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 1m 13s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 3s View ↗
☁️ Nx Cloud last updated this comment at
2025-09-11 16:28:27UTCMore templates
- tanstack-router-solid-example-basic
- tanstack-router-solid-example-basic-devtools-panel
- tanstack-router-solid-example-basic-file-based
- tanstack-router-solid-example-basic-non-nested-devtools
- tanstack-router-solid-example-basic-solid-query
- tanstack-router-solid-example-basic-solid-query-file-based
- tanstack-router-solid-example-basic-ssr-streaming-file-based
- tanstack-router-solid-example-kitchen-sink-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-solid-start-example-bare
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-static
- tanstack-router-react-example-authenticated-routes
- tanstack-router-react-example-authenticated-routes-firebase
- tanstack-router-react-example-basic
- tanstack-router-react-example-basic-default-search-params
- tanstack-router-react-example-basic-devtools-panel
- tanstack-router-react-example-basic-file-based
- tanstack-router-react-example-basic-non-nested-devtools
- tanstack-router-react-example-react-query
- tanstack-router-react-example-basic-react-query-file-based
- tanstack-router-react-example-basic-ssr-file-based
- tanstack-router-react-example-basic-ssr-streaming-file-based
- tanstack-router-react-example-basic-virtual-file-based
- tanstack-router-react-example-basic-virtual-inside-file-based
- tanstack-router-react-example-deferred-data
- tanstack-router-react-example-kitchen-sink
- tanstack-router-react-example-kitchen-sink-file-based
- tanstack-router-react-example-kitchen-sink-react-query
- tanstack-router-react-example-kitchen-sink-react-query-file-based
- tanstack-router-react-example-large-file-based
- tanstack-router-react-example-location-masking
- tanstack-router-react-example-navigation-blocking
- tanstack-router-react-example-quickstart
- tanstack-router-react-example-quickstart-esbuild-file-based
- tanstack-router-react-example-quickstart-file-based
- tanstack-router-react-example-quickstart-rspack-file-based
- tanstack-router-react-example-quickstart-webpack-file-based
- router-monorepo-react-query
- router-mono-simple
- router-mono-simple-lazy
- tanstack-router-react-example-scroll-restoration
- tanstack-search-validator-adapters
- tanstack-start-example-bare
- tanstack-start-example-basic
- tanstack-start-example-basic-auth
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-rsc
- tanstack-start-example-basic-static
- tanstack-start-example-clerk-basic
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-example-supabase-basic
- tanstack-start-tailwind-v4
- tanstack-start-example-trellaux
- tanstack-start-example-workos
- tanstack-router-react-example-view-transitions
- tanstack-router-react-example-with-framer-motion
- tanstack-router-react-example-with-trpc
- tanstack-router-react-example-with-trpc-react-query
@tanstack/arktype-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5128@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5128@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5128@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5128@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5128@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5128@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5128@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5128@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5128@tanstack/react-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@5128@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5128@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5128@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5128@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5128@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5128@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5128@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5128@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5128@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5128@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5128@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5128@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5128@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5128@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5128@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5128@tanstack/solid-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@5128@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5128@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5128@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5128@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5128@tanstack/start-server-functions-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@5128@tanstack/start-server-functions-fetcher
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@5128@tanstack/start-server-functions-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@5128@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5128@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5128@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5128@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5128commit:
a2a07b4Sheraff(GitHub profile, opens in a new tab) closed this
Actionable comments posted: 0
🧹 Nitpick comments (4)
packages/router-core/src/process-route-tree.ts (2)
14-22: Consider documenting the scoring constants.While the constant names are descriptive, adding comments explaining the scoring strategy would help future maintainers understand why these specific values were chosen and how they affect route ranking.
+// Scoring constants for route ranking algorithm +// Higher scores indicate higher priority in route matching const REQUIRED_PARAM_BASE_SCORE = 0.5 const OPTIONAL_PARAM_BASE_SCORE = 0.4 const WILDCARD_PARAM_BASE_SCORE = 0.25 +// Additional bonuses for params with prefixes/suffixes (more specific patterns) const BOTH_PRESENCE_BASE_SCORE = 0.05 const PREFIX_PRESENCE_BASE_SCORE = 0.02 const SUFFIX_PRESENCE_BASE_SCORE = 0.01 +// Length multipliers provide fine-grained differentiation const PREFIX_LENGTH_SCORE_MULTIPLIER = 0.0002 const SUFFIX_LENGTH_SCORE_MULTIPLIER = 0.0001
97-111: Consider extracting the static-after-param detection logic.The nested loop that checks for static segments after parameters could be extracted into a helper function for better readability and testability.
+function hasStaticSegmentAfter(parsed: ReadonlyArray<Segment>, startIndex: number): boolean { + for (let i = startIndex + 1; i < parsed.length; i++) { + const nextSegment = parsed[i]! + if ( + nextSegment.type === SEGMENT_TYPE_PATHNAME && + nextSegment.value !== '/' + ) { + return true + } + } + return false +} if (baseScore) { // if there is any static segment (that is not an index) after a required / optional param, // we will boost this param so it ranks higher than a required/optional param without a static segment after it // JUST FOR SORTING, NOT FOR MATCHING - for (let i = index + 1; i < parsed.length; i++) { - const nextSegment = parsed[i]! - if ( - nextSegment.type === SEGMENT_TYPE_PATHNAME && - nextSegment.value !== '/' - ) { - hasStaticAfter = true - return handleParam(segment, baseScore + 0.2) - } - } + if (hasStaticSegmentAfter(parsed, index)) { + hasStaticAfter = true + return handleParam(segment, baseScore + 0.2) + } return handleParam(segment, baseScore) }packages/router-core/src/router.ts (2)
942-951: Optional: remove downstreamascasts by typing the destructure.Annotate the destructured result with the exported result type to avoid three separate
asassertions.-import { processRouteTree } from './process-route-tree' +import { processRouteTree, type ProcessRouteTreeResult } from './process-route-tree' @@ - const { routesById, routesByPath, flatRoutes } = processRouteTree({ + const { routesById, routesByPath, flatRoutes }: ProcessRouteTreeResult<TRouteTree> = processRouteTree({ routeTree: this.routeTree, initRoute: (route, i) => { route.init({ originalIndex: i, }) }, }) @@ - this.routesById = routesById as RoutesById<TRouteTree> - this.routesByPath = routesByPath as RoutesByPath<TRouteTree> - this.flatRoutes = flatRoutes as Array<AnyRoute> + this.routesById = routesById + this.routesByPath = routesByPath + this.flatRoutes = flatRoutes
959-963: Nit: avoid magic number for not-found route index.Use
Number.MAX_SAFE_INTEGERfor clarity.- notFoundRoute.init({ - originalIndex: 99999999999, - }) + notFoundRoute.init({ + originalIndex: Number.MAX_SAFE_INTEGER, + })📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between e2167659cd251a05cbbbf36e7777f02d0726834b and a2a07b469d966251d5899ca1f1ef0606cb220275.
📒 Files selected for processing (5)
packages/router-core/src/index.ts(1 hunks)packages/router-core/src/process-route-tree.ts(1 hunks)packages/router-core/src/route.ts(1 hunks)packages/router-core/src/router.ts(3 hunks)packages/router-core/tests/processRouteTree.test.ts(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/router-core/src/process-route-tree.ts (2)
packages/router-core/src/route.ts (1)
RouteLike(1753-1764)
packages/router-core/src/path.ts (4)
SEGMENT_TYPE_PARAM(7-7)SEGMENT_TYPE_OPTIONAL_PARAM(9-9)SEGMENT_TYPE_WILDCARD(8-8)SEGMENT_TYPE_PATHNAME(6-6)
packages/router-core/tests/processRouteTree.test.ts (1)
packages/router-core/src/route.ts (1)
RouteLike(1753-1764)
🔇 Additional comments (13)
packages/router-core/src/route.ts (1)
1753-1764: LGTM! Well-structured interface for route-like objects.The
RouteLikeinterface provides a clean abstraction for representing routes with just the essential properties needed for route tree processing. The optional properties are appropriately marked, and the interface is well-placed in the route module.packages/router-core/src/index.ts (1)
197-198: LGTM! Clean re-export from the new module.The exports are correctly updated to re-export from the new
process-route-treemodule, maintaining the same public API while improving code organization.packages/router-core/tests/processRouteTree.test.ts (3)
2-5: LGTM! Imports correctly updated to use the new module structure.The test file properly imports
processRouteTreefrom the new module and uses the publicRouteLiketype, aligning with the refactored code organization.
9-12: LGTM! Return type properly updated to use RouteLike.The function signature correctly uses the
RouteLiketype from the public API.
40-40: LGTM! Consistent type usage throughout test helpers.The
createRouteTreefunction also correctly returns theRouteLiketype, maintaining consistency across all test utilities.packages/router-core/src/process-route-tree.ts (5)
23-50: LGTM! Clean parameter scoring logic.The
handleParamfunction elegantly handles different parameter configurations with appropriate scoring adjustments based on prefix/suffix presence and length.
52-174: Well-structured route sorting implementation with comprehensive ranking criteria.The
sortRoutesfunction implements a sophisticated multi-criteria sorting algorithm that handles various edge cases. The segment-by-segment comparison with multiple tie-breakers ensures predictable and intuitive route matching behavior.
176-180: LGTM! Clean type definition for the processing result.The
ProcessRouteTreeResulttype clearly defines the expected output structure with appropriate generic constraints.
182-228: Well-implemented route tree processing with proper error handling.The
processRouteTreefunction correctly:- Detects duplicate route IDs with clear error messages
- Handles root routes appropriately
- Manages path trimming consistently
- Provides an optional initialization hook for routes
206-213: Confirm/document trailing-slash override behavior.The condition lets index routes (childRoute.fullPath.endsWith('/')) overwrite non-index routes for the same trimmed path — packages/router-core/src/process-route-tree.ts (lines 206–213). The docs describe index-route/trailing-slash semantics and expose a RouterOptions.trailingSlash setting, so this looks intentional. (tanstack.com) There is a reported types vs runtime mismatch around routes-by-path that you may want to address or note in a test/inline comment (#3780). (github.com)
packages/router-core/src/router.ts (3)
32-32: Type-only import is spot on.Keeps runtime clean and tree-shakeable.
56-56: Resolved — RouteLike exposes fullPath, path, parentRoute, and options.caseSensitive. Interface in packages/router-core/src/route.ts includes fullPath, path?, parentRoute?, and options?.caseSensitive.
15-15: Extraction OK — sorting tie-break uses insertion order, not route.originalIndex.sortRoutes (packages/router-core/src/process-route-tree.ts) falls back to
return a.index - b.indexwhereindexis the position in the array passed (fromObject.values(routesById)); processRouteTree buildsroutesByIdvia depth‑firstrecurseRoutes.router.tsstill callsroute.init({ originalIndex: i }), but thatoriginalIndexproperty is not used by the comparator. Confirm the recursion/insertion order matches the pre‑extraction ordering, or change the comparator to useroute.originalIndexif that was the intended tie‑breaker.
Sign in to join this conversation.
Walkthrough#
The route-tree processing logic was extracted from router.ts into a new module process-route-tree.ts, with RouteLike moved to route.ts. Public exports in index.ts now re-export processRouteTree and ProcessRouteTreeResult from the new module. Tests were updated to import from the new paths and use RouteLike.
Changes#
packages/router-core/src/index.tspackages/router-core/src/process-route-tree.tspackages/router-core/src/route.tspackages/router-core/src/router.tspackages/router-core/tests/processRouteTree.test.tsSequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
Suggested reviewers#
Pre-merge checks (2 passed, 1 warning)#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
Poem#
Tip
👮 Agentic pre-merge checks are now available in preview!
Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information.
Example:
Please share your feedback with us on this Discord post.
✨ Finishing touches
🧪 Generate unit tests
Comment `@coderabbitai help` to get the list of available commands and usage tips.