Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/loud-women-end.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/router-core': patch
---

wildcard nodes have the same priority rules as other nodes in route matching
98 changes: 58 additions & 40 deletions packages/router-core/src/new-process-route-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,7 @@ type MatchStackFrame<T extends RouteLike> = {
* If we really really need to support more than 32 segments we can switch to using a `BigInt` here. It's about 2x slower in worst case scenarios.
*/
skipped: number
/** Positional bitmasks tracking which consumed URL segments matched each segment kind. */
statics: number
dynamics: number
optionals: number
Expand Down Expand Up @@ -1066,13 +1067,12 @@ function getNodeMatch<T extends RouteLike>(
index: 1,
skipped: 0,
depth: 1,
statics: 1,
statics: 0,
dynamics: 0,
optionals: 0,
},
]

let wildcardMatch: Frame | null = null
let bestFuzzy: Frame | null = null
let bestMatch: Frame | null = null

Expand All @@ -1081,6 +1081,18 @@ function getNodeMatch<T extends RouteLike>(
const { node, index, skipped, depth, statics, dynamics, optionals } = frame
let { extract, rawParams, parsedParams } = frame

// Wildcard candidates are pushed speculatively as fallbacks in case a
// higher-priority wildcard later fails params.parse. If a better wildcard
// has already validated and become bestMatch, lower-priority wildcard
// fallbacks cannot win anymore and should not run params.parse.
if (
node.kind === SEGMENT_TYPE_WILDCARD &&
node.route &&
!isFrameMoreSpecific(bestMatch, frame)
) {
continue
}

if (node.skipOnParamError) {
const result = validateMatchParams(path, parts, frame)
if (!result) continue
Expand All @@ -1101,7 +1113,13 @@ function getNodeMatch<T extends RouteLike>(

const isBeyondPath = index === partsLength
if (isBeyondPath) {
if (node.route && !pathIsIndex && isFrameMoreSpecific(bestMatch, frame)) {
if (
node.route &&
(!pathIsIndex ||
node.kind === SEGMENT_TYPE_INDEX ||
node.kind === SEGMENT_TYPE_WILDCARD) &&
isFrameMoreSpecific(bestMatch, frame)
) {
bestMatch = frame
}
// beyond the length of the path parts, only some segment types can match
Expand Down Expand Up @@ -1134,7 +1152,12 @@ function getNodeMatch<T extends RouteLike>(
if (indexValid) {
// perfect match, no need to continue
// this is an optimization, algorithm should work correctly without this block
if (statics === partsLength && !dynamics && !optionals && !skipped) {
if (
!dynamics &&
!optionals &&
!skipped &&
isPerfectStaticMatch(statics, partsLength)
) {
return indexFrame
}
if (isFrameMoreSpecific(bestMatch, indexFrame)) {
Expand All @@ -1145,8 +1168,9 @@ function getNodeMatch<T extends RouteLike>(
}

// 5. Try wildcard match
if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) {
for (const segment of node.wildcard) {
if (node.wildcard) {
for (let i = node.wildcard.length - 1; i >= 0; i--) {
const segment = node.wildcard[i]!
const { prefix, suffix } = segment
if (prefix) {
if (isBeyondPath) continue
Expand All @@ -1161,26 +1185,20 @@ function getNodeMatch<T extends RouteLike>(
const casePart = segment.caseSensitive ? end : end.toLowerCase()
if (casePart !== suffix) continue
}
// the first wildcard match is the highest priority one
// wildcard matches skip the stack because they cannot have children
const frame = {
// wildcard matches consume the rest of the URL and cannot have children
const consumed = partsLength - index
stack.push({
node: segment,
index: partsLength,
skipped,
depth,
statics,
dynamics,
optionals,
depth: depth + 1,
statics: shiftScore(statics, consumed),
dynamics: shiftScore(dynamics, consumed),
optionals: shiftScore(optionals, consumed),
extract,
rawParams,
parsedParams,
}
if (segment.skipOnParamError) {
const result = validateMatchParams(path, parts, frame)
if (!result) continue
}
wildcardMatch = frame
break
})
}
}

Expand Down Expand Up @@ -1220,9 +1238,9 @@ function getNodeMatch<T extends RouteLike>(
index: index + 1,
skipped,
depth: nextDepth,
statics,
dynamics,
optionals: optionals + 1,
statics: shiftScore(statics),
dynamics: shiftScore(dynamics),
optionals: shiftScore(optionals) + 1,
extract,
rawParams,
parsedParams,
Expand All @@ -1248,9 +1266,9 @@ function getNodeMatch<T extends RouteLike>(
index: index + 1,
skipped,
depth: depth + 1,
statics,
dynamics: dynamics + 1,
optionals,
statics: shiftScore(statics),
dynamics: shiftScore(dynamics) + 1,
optionals: shiftScore(optionals),
extract,
rawParams,
parsedParams,
Expand All @@ -1269,9 +1287,9 @@ function getNodeMatch<T extends RouteLike>(
index: index + 1,
skipped,
depth: depth + 1,
statics: statics + 1,
dynamics,
optionals,
statics: shiftScore(statics) + 1,
dynamics: shiftScore(dynamics),
optionals: shiftScore(optionals),
extract,
rawParams,
parsedParams,
Expand All @@ -1288,9 +1306,9 @@ function getNodeMatch<T extends RouteLike>(
index: index + 1,
skipped,
depth: depth + 1,
statics: statics + 1,
dynamics,
optionals,
statics: shiftScore(statics) + 1,
dynamics: shiftScore(dynamics),
optionals: shiftScore(optionals),
extract,
rawParams,
parsedParams,
Expand Down Expand Up @@ -1319,16 +1337,8 @@ function getNodeMatch<T extends RouteLike>(
}
}

if (bestMatch && wildcardMatch) {
return isFrameMoreSpecific(wildcardMatch, bestMatch)
? bestMatch
: wildcardMatch
}

if (bestMatch) return bestMatch

if (wildcardMatch) return wildcardMatch

if (fuzzy && bestFuzzy) {
let sliceIndex = bestFuzzy.index
for (let i = 0; i < bestFuzzy.index; i++) {
Expand All @@ -1343,6 +1353,14 @@ function getNodeMatch<T extends RouteLike>(
return null
}

function shiftScore(score: number, amount = 1): number {
return score * 2 ** amount
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid precision loss in positional specificity scoring

Using number bitmasks for statics/dynamics/optionals means scores stop being exact once a match consumes ~54 path segments (values exceed Number.MAX_SAFE_INTEGER). In that range, distinct specificity patterns can collapse to the same numeric value (for example 2**53 and 2**53 + 1), so isFrameMoreSpecific can pick the wrong route. This is a functional regression from the previous count-based scoring and affects very deep route trees/URLs.

Useful? React with 👍 / 👎.


function isPerfectStaticMatch(statics: number, partsLength: number): boolean {
return statics === 2 ** (partsLength - 1) - 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cd packages/router-core/src && head -c 200000 new-process-route-tree.ts | tail -c 100000 | grep -n "function shiftScore\|function isPerfectStaticMatch\|MatchStackFrame\|statics.*number\|dynamics.*number" -A 5 -B 2

Repository: TanStack/router

Length of output: 2204


🏁 Script executed:

# First, check the exact lines mentioned (1350-1355)
sed -n '1345,1360p' packages/router-core/src/new-process-route-tree.ts

# Then check the MatchStackFrame definition (1026-1030)
sed -n '1020,1035p' packages/router-core/src/new-process-route-tree.ts

# Check the isFrameMoreSpecific function to understand how scores are used
rg "isFrameMoreSpecific" packages/router-core/src/new-process-route-tree.ts -A 10 -B 2

Repository: TanStack/router

Length of output: 2561


🏁 Script executed:

# Search for any depth limits or safeguards
rg "MAX.*DEPTH|MAX.*SEGMENT|53|Number.MAX_SAFE" packages/router-core/src/new-process-route-tree.ts -B 2 -A 2

# Check if there are tests for deep routes
find . -path "*/test*" -name "*.test.*" -o -name "*.spec.*" | head -20 | xargs grep -l "deep\|depth.*segment\|53.*segment" 2>/dev/null | head -5

# Check for any comments about the bitmasking approach and limitations
rg "BigInt|bitmask|precision|safe.*integer" packages/router-core/src/new-process-route-tree.ts -B 1 -A 1

Repository: TanStack/router

Length of output: 658


🏁 Script executed:

# Check if there are practical limits preventing deep routes
rg "partsLength|\.length.*parts" packages/router-core/src/new-process-route-tree.ts | head -20

# Look for any validation or limits on route depth
rg "throw.*depth|throw.*segment|validate.*path.*length" packages/router-core/src/new-process-route-tree.ts -B 2 -A 2

# Check how shiftScore is actually used - see the caller context
rg "shiftScore\(" packages/router-core/src/new-process-route-tree.ts -B 3 -A 3

Repository: TanStack/router

Length of output: 1934


Bitmask precision loss breaks route specificity comparison on deep paths.

Lines 1350-1355 use JavaScript number bitmasks to track route specificity. The shiftScore() helper multiplies scores by powers of two for each consumed segment, and isFrameMoreSpecific() relies on direct numeric comparison of these masks. Once a path exceeds ~53 segments, statics, dynamics, and optionals lose precision beyond JavaScript's Number.MAX_SAFE_INTEGER, causing incorrect route ordering and incorrect results from isPerfectStaticMatch(). While the codebase acknowledges this risk for the skipped field (with a comment suggesting BigInt as fallback), the positional score fields face the same vulnerability and require the same mitigation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/router-core/src/new-process-route-tree.ts` around lines 1350 - 1355,
The numeric bitmask operations lose precision for deep paths; update shiftScore
and isPerfectStaticMatch (and any comparisons in isFrameMoreSpecific) to use
BigInt for bit shifting and masks instead of Number so masks remain exact beyond
53 bits: change shiftScore to perform BigInt shifts (e.g., 1n << BigInt(amount)
or use multiplication with BigInt), ensure statics/dynamics/optionals are
stored/compared as BigInt, and update isPerfectStaticMatch to compute
2**(partsLength-1)-1 using BigInt (or bit-shift) so route specificity
comparisons remain correct for long paths. Ensure callers that pass numbers
coerce to BigInt consistently and maintain interop where necessary.

}

function validateMatchParams<T extends RouteLike>(
path: string,
parts: Array<string>,
Expand Down
Loading
Loading