refactor(router-core): more stable url decoding #5663
main fromrefs/pull/5663/head·merged by nlynzaad(GitHub profile, opens in a new tab) This PR addresses the issue filed in #3962 and follows on from #5534 and #3987. As mentioned in #3987 we should ideally find a better solution to deal with this, however these will bring changes to users and ideally, we should leave these for the next major, this solution attempts to deal with this problem without breaking current use cases.
when backslashes are used in a path param the decoded value \ is removed from the pathname. we should not be decoding %5C to \ when decoding the various path segments. We already do this for %25 (percentage signs) and a more complete solution is needed for these special characters that should not be decoded.
This PR adds a new utility function decodePathSegment that will decode the path segment ignoring a defined array of encoded values. As a default we are not decoding \, % and /. In addition to these, the defined list of special characters that can be allowed to not be encoded has also been added here.
While working on this PR it also came to fore that when navigating to a path that contains special characters these are shown in the URL in encoded form, however when refreshing the page or browsing to the path directly these are shown in decoded form. In addition to the above we are also now standardizing this to show the decoded form on navigation similar as to when browsing directly to the path.
This PR also adds tests for the new utility function as well updates the solid-router and react-router e2e tests to test the functionality.
Summary by CodeRabbit#
Bug Fixes
- Improved decoding of escaped characters in URL segments (backslashes, percent-encodings, emoji) for more accurate route matching and displayed params.
New Features
- Added example links and new wildcard route variants demonstrating complex escaped parameter values, including non‑ASCII tokens and escaped splats.
Tests
- Expanded test coverage for encoded, escaped, and Unicode path scenarios (wildcard, prefix, suffix, and link navigation).
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
View your CI Pipeline Execution ↗ for commit ba624dd29c00fcacc2127f57f8d8e42fc2536617
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded <1s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 2s View ↗
☁️ Nx Cloud last updated this comment at
2025-10-28 21:32:48UTCMore 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-kitchen-sink-solid-query
- tanstack-router-solid-example-kitchen-sink-solid-query-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-solid-start-example-bare
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-auth
- tanstack-solid-start-example-basic-cloudflare
- tanstack-solid-start-example-basic-netlify
- tanstack-solid-start-example-basic-nitro
- tanstack-start-example-basic-solid-query
- 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-i18n-paraglide
- 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-cloudflare
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-static
- tanstack-start-bun-hosting
- tanstack-start-example-clerk-basic
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-i18n-paraglide
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-streaming-data-from-server-functions
- 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@5663@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5663@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5663@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5663@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5663@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5663@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5663@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5663@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5663@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5663@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5663@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5663@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5663@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5663@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5663@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5663@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5663@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5663@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5663@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5663@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5663@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5663@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5663@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@5663@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5663@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5663@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5663@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5663@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5663@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5663@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5663@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5663@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5663@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5663@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5663commit:
ba624ddActionable comments posted: 2
🧹 Nitpick comments (4)
packages/router-core/src/utils.ts (3)
528-541: Consider edge cases in recursive splitting logic.The recursive decoding splits by ignored characters and processes subparts, but there are potential edge cases:
Adjacent delimiters: If the input contains adjacent ignored characters (e.g.,
%25%5C), splitting by%25produces an empty string between delimiters. Empty strings are handled at line 526, but verify this doesn't cause issues.Ordering dependency: The function processes
decodeIgnorearray sequentially withstartIndex. This means the order of characters inDECODE_IGNORE_LISTaffects which character is used to split first. Document this behavior or consider if order matters for correctness.Performance: Deeply nested encoded sequences could cause many recursive calls. For typical URL segments this should be fine, but consider if there's a risk with pathological inputs.
492-504: Document why specific characters are in the ignore list.DECODE_IGNORE_LISTincludes various special characters (%, \, /, ;, :, @, &, =, +, $, ,) but the rationale isn't immediately clear. Based on the PR objectives,%,\, and/are explicitly mentioned, but the others appear to be reserved URI characters from RFC 3986.Consider adding a comment explaining:
- Why each character or category is included
- The relationship to RFC 3986 reserved characters
- How this aligns with the PR's goal to prevent incorrect decoding of backslashes
Example:
+// Characters that should remain encoded in path segments: +// - % : percent itself to avoid double-decoding +// - \ : backslash (issue #3962) +// - / : path separator +// - Other reserved URI characters per RFC 3986: ; : @ & = + $ , const DECODE_IGNORE_LIST = [ '%', '\\',
526-526: Consider using stricter RFC 3986-compliant hex pattern for clarity.The regex
/%../gat line 525 (and line 516) is technically non-compliant with RFC 3986 percent-encoding, which requires two hexadecimal digits. As confirmed, it matches invalid sequences like%ggand%...However, the current implementation is functionally safe: invalid matches are caught by
decodeURIComponent()in the fallback (line 516), which throws and returns malformed sequences unchanged. The comment "leaving the malformed tags in place" suggests this resilient behavior is intentional.Recommendation: Either use the stricter pattern
/%[0-9A-Fa-f]{2}/gto enforce RFC 3986 compliance and improve clarity, or add a comment explaining why the permissive pattern is used for resilience. This will make the design choice explicit to future maintainers.All existing tests use valid hex sequences and pass; there is no test coverage for invalid sequences like
%gg.packages/router-core/tests/utils.test.ts (1)
502-511: Consider using actual path segments in test cases.While the test logic is correct, the function is named
decodePathSegmentbut tests use full URLs with query parameters. Consider using actual path segment examples (e.g.,/path/to/%D1%88%D0%B5%D0%BB%D0%BB%D1%8B) for better alignment with the function's intended use case.📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between e2be32a9b5a9e0a3a58d8abcf4b9663588b4aeae and 547268173ebd6bafc350acc3de6e274f20b0548f.
📒 Files selected for processing (9)
e2e/react-router/basic-file-based/src/routes/params-ps/index.tsx(1 hunks)e2e/react-router/basic-file-based/tests/params.spec.ts(1 hunks)e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsx(1 hunks)e2e/solid-router/basic-file-based/tests/params.spec.ts(1 hunks)packages/router-core/src/path.ts(2 hunks)packages/router-core/src/router.ts(2 hunks)packages/router-core/src/utils.ts(1 hunks)packages/router-core/tests/path.test.ts(1 hunks)packages/router-core/tests/utils.test.ts(2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/router-core/src/path.tse2e/solid-router/basic-file-based/src/routes/params-ps/index.tsxe2e/solid-router/basic-file-based/tests/params.spec.tse2e/react-router/basic-file-based/tests/params.spec.tspackages/router-core/src/router.tspackages/router-core/tests/path.test.tspackages/router-core/src/utils.tspackages/router-core/tests/utils.test.tse2e/react-router/basic-file-based/src/routes/params-ps/index.tsx
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/tests/path.test.tspackages/router-core/src/utils.tspackages/router-core/tests/utils.test.ts
**/src/routes/**
📄 CodeRabbit inference engine (AGENTS.md)
Place file-based routes under src/routes/ directories
Files:
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsxe2e/react-router/basic-file-based/src/routes/params-ps/index.tsx
e2e/**
📄 CodeRabbit inference engine (AGENTS.md)
Store end-to-end tests under the e2e/ directory
Files:
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsxe2e/solid-router/basic-file-based/tests/params.spec.tse2e/react-router/basic-file-based/tests/params.spec.tse2e/react-router/basic-file-based/src/routes/params-ps/index.tsx
🧠 Learnings (1)
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad PR: TanStack/router#5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Applied to files:
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsxe2e/react-router/basic-file-based/src/routes/params-ps/index.tsx
🧬 Code graph analysis (4)
packages/router-core/src/path.ts (1)
packages/router-core/src/utils.ts (1)
decodePathSegment(506-544)
packages/router-core/src/router.ts (2)
packages/router-core/src/utils.ts (1)
decodePathSegment(506-544)
packages/router-core/src/path.ts (1)
interpolatePath(403-517)
packages/router-core/tests/path.test.ts (1)
packages/router-core/src/path.ts (1)
SEGMENT_TYPE_PATHNAME(6-6)
packages/router-core/tests/utils.test.ts (1)
packages/router-core/src/utils.ts (1)
decodePathSegment(506-544)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (11)
e2e/react-router/basic-file-based/src/routes/params-ps/index.tsx (1)
52-60: Good test coverage for escaped characters in wildcard parameters.The new link tests escaped sequences including backslashes, forward slashes, percent signs, and an emoji. This aligns well with the PR's goal of handling backslashes correctly in path parameters.
Note: The string literal
'test[s\\/.\\/parameter%!🚀]'correctly escapes backslashes for JavaScript string syntax. The\\/sequence becomes a single backslash followed by a forward slash in the runtime string value.e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsx (1)
52-60: Consistent test coverage across frameworks.The test case matches the React Router implementation, ensuring consistent behavior for escaped wildcard parameters across both frameworks.
e2e/react-router/basic-file-based/tests/params.spec.ts (1)
293-301: Same verification needed for React Router tests.The test case is identical to the Solid Router version. See the comment on
e2e/solid-router/basic-file-based/tests/params.spec.tslines 368-376 for verification of the expected pathname encoding.packages/router-core/tests/path.test.ts (1)
835-842: Test correctly validates the new decoding behavior.The test case verifies that:
%25(percent) is preserved as%25after one decode pass%5C(backslash) is preserved as%5C- Cyrillic characters
%D1%88%D0%B5and%D0%BB%D0%BB%D1%8Bcorrectly decode toшеandллы
This aligns with the PR objective to prevent incorrect decoding of backslashes and percent signs while allowing normal character decoding.
packages/router-core/src/path.ts (2)
1-1: Import change consolidates decoding logic.The addition of
decodePathSegmentto the imports from./utilsenables the centralized decoding behavior introduced in this PR.
361-361: All verification points confirmed—no issues found.The control flow is correct:
- Parameter segments (lines 338-346) return early with
SEGMENT_TYPE_PARAMand are not decoded here - Wildcard segments (lines 349-356) return early with
SEGMENT_TYPE_WILDCARDand are not decoded here - Only the final return (lines 360-363) applies
decodePathSegment(), exclusively forSEGMENT_TYPE_PATHNAMEsegments - Parameters are decoded separately during matching (confirmed at lines 719, 775 in
matchByPath)
packages/router-core/src/router.ts (2)
5-5: Import enables decoding in buildLocation.The import of
decodePathSegmentsupports applying the new decoding logic to interpolated paths in thebuildLocationmethod.
1674-1685: Review concern about double-encoding/decoding appears unfounded after code verification.The encoding/decoding flow is intentional and coordinated, not problematic:
encodePathParam(path.ts:519) usesencodeURIComponentthen selectively reverses encoding based ondecodeCharMapduring interpolation- The result still contains partially-encoded characters (those not in
decodeCharMap) decodePathSegment(utils.ts:506) performs final fulldecodeURIComponenton the interpolated path
This is a controlled pattern where
decodeCharMappreserves specific encoded characters through interpolation (e.g., keeping "/" encoded for certain parameter types), thendecodePathSegmentdecodes the final result. No double-encoding occurs.e2e/solid-router/basic-file-based/tests/params.spec.ts (1)
368-376: Test expectation is correct—no issues found.The selective encoding in the test pathname is intentional. The code uses
encodeURI()for wildcard/splat params (lines 438–446 in path.ts), which preserves URI structural characters like/,[,],., and!, while still encoding special characters like backslashes (\), percent signs (%), and Unicode. This is the correct encoding strategy for wildcard parameters to preserve path structure while safely encoding dangerous characters.packages/router-core/tests/utils.test.ts (2)
2-7: LGTM!The import statement correctly includes the new
decodePathSegmentfunction alongside existing utilities.
513-569: Test coverage for ignore list behavior looks solid.These tests effectively validate that the function correctly preserves specified encoded characters while decoding others. The multiple test scenarios cover different combinations well.
@@ -494,0 +560,21 @@560+ it('should decode a path segment with multiple ignored characters and multiple ignored items existing', () => {561+ const itemsToCheck = ['%25', '%5C']562+ const stringToCheck =563+ 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B'564+ const expectedResult = 'https://mozilla.org/?x=%25ше%5Cллы'565+566+ const result = decodePathSegment(stringToCheck, itemsToCheck)567+568+ expect(result).toBe(expectedResult)569+ })570+571+ it('should decode a path segment, ignoring `%` and `\\` by default, with multiple ignored items existing', () => {572+ const stringToCheck =573+ 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B'574+ const expectedResult = 'https://mozilla.org/?x=%25ше%5Cллы'575+576+ const result = decodePathSegment(stringToCheck)577+578+ expect(result).toBe(expectedResult)579+ })580+})🛠️ Refactor suggestion | 🟠 Major
Expand test coverage for edge cases and malformed encodings.
The implementation includes fallback handling for malformed percent-encodings, but there are no tests validating this critical behavior. Consider adding tests for:
- Malformed encodings:
%ZZ,%1,%%, incomplete sequences - Edge cases: empty string, strings without any percent-encoding
- Boundary conditions: ignored characters at the beginning or end of the string
- Consecutive ignored characters:
%25%25,%5C%5C
These scenarios are important to test given the implementation's recursive splitting logic and error handling.
Example test cases:
it('should handle malformed percent-encodings gracefully', () => { const stringToCheck = 'path%ZZ%D1%88test%1end' // Malformed sequences should remain as-is, valid ones decoded const result = decodePathSegment(stringToCheck) expect(result).toContain('%ZZ') // Malformed should remain expect(result).toContain('%1') // Incomplete should remain }) it('should return empty string unchanged', () => { expect(decodePathSegment('')).toBe('') }) it('should return strings without encoding unchanged', () => { const stringToCheck = 'plain-text-path' expect(decodePathSegment(stringToCheck)).toBe(stringToCheck) }) it('should handle consecutive ignored characters', () => { const stringToCheck = 'test%25%25end' const expectedResult = 'test%25%25end' expect(decodePathSegment(stringToCheck)).toBe(expectedResult) })🤖 Prompt for AI Agents
In packages/router-core/tests/utils.test.ts around lines 501 to 580, the current decodePathSegment tests miss coverage for malformed percent-encodings, empty/no-encoding inputs, boundary ignored characters, and consecutive ignored characters; add new unit tests in this describe block that assert malformed sequences like '%ZZ', '%1', '%%' remain un-decoded while valid sequences decode, that '' returns '' unchanged, that strings without percent-encoding return unchanged, that ignored characters at start/end are handled (e.g. '%25foo' and 'foo%25'), and that consecutive ignored items like '%25%25' and '%5C%5C' preserve the expected escaped representation so the function’s fallback logic is validated.Resolvedby nlynzaad(GitHub profile, opens in a new tab)@@ -494,0 +559,21 @@559+560+ it('should decode a path segment with multiple ignored characters and multiple ignored items existing', () => {561+ const itemsToCheck = ['%25', '%5C']562+ const stringToCheck =563+ 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B'564+ const expectedResult = 'https://mozilla.org/?x=%25ше%5Cллы'565+566+ const result = decodePathSegment(stringToCheck, itemsToCheck)567+568+ expect(result).toBe(expectedResult)569+ })570+571+ it('should decode a path segment, ignoring `%` and `\\` by default, with multiple ignored items existing', () => {572+ const stringToCheck =573+ 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B'574+ const expectedResult = 'https://mozilla.org/?x=%25ше%5Cллы'575+576+ const result = decodePathSegment(stringToCheck)577+578+ expect(result).toBe(expectedResult)579+ })⚠️ Potential issue | 🟡 Minor
Add test coverage for %2F (slash) in default ignore list.
The PR description states that %2F (slash) should be ignored by default alongside %25 (percent) and %5C (backslash), but there's no test validating this behavior. Please add a test case to verify that %2F remains encoded when using the default ignore list.
Example test case:
+ it('should decode a path segment, ignoring `%`, `\\`, and `/` by default', () => { + const stringToCheck = 'path%2Fto%2F%D1%88%D0%B5%D0%BB%D0%BB%D1%8B' + const expectedResult = 'path%2Fto%2Fшеллы' + + const result = decodePathSegment(stringToCheck) + + expect(result).toBe(expectedResult) + })📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('should decode a path segment, ignoring `%` and `\\` by default, with multiple ignored items existing', () => { const stringToCheck = 'https://mozilla.org/?x=%25%D1%88%D0%B5%D0%BB%D0%BB%D1%8B' const expectedResult = 'https://mozilla.org/?x=%25ше%5Cллы' const result = decodePathSegment(stringToCheck) expect(result).toBe(expectedResult) }) it('should decode a path segment, ignoring `%`, `\\`, and `/` by default', () => { const stringToCheck = 'path%2Fto%2F%D1%88%D0%B5%D0%BB%D0%BB%D1%8B' const expectedResult = 'path%2Fto%2Fшеллы' const result = decodePathSegment(stringToCheck) expect(result).toBe(expectedResult) })🤖 Prompt for AI Agents
In packages/router-core/tests/utils.test.ts around lines 571 to 579, the existing test verifies that %25 and %5C are left encoded but omits %2F (slash) which should also be ignored by default; add a new test (or extend this one) that includes a %2F sequence in the input URL and assert that the output still contains the encoded %2F (i.e., remains %2F) while other decoded sequences are decoded, so the test confirms the default ignore list includes slash.SeanCassiere reviewed
@@ -488,3 +488,5 @@488488 }489489 return undefined490490 }491+492+const DECODE_IGNORE_LIST = [Although it'll be negligible, could we precompute this into a
Set? Perhaps even have them in their encoded form already?@@ -490,0 +506,21 @@506+export function decodePathSegment(507+ part: string,508+ decodeIgnore: Array<string> = DECODE_IGNORE_LIST,509+ startIndex = 0,510+) {511+ function decode(part: string) {512+ try {513+ return decodeURIComponent(part)514+ } catch {515+ // if the decoding fails, try to decode the various parts leaving the malformed tags in place516+ return part.replaceAll(/%../g, (match) => {517+ try {518+ return decodeURIComponent(match)519+ } catch {520+ return match521+ }522+ })523+ }524+ }525+526+ if (part === '' || !part.match(/%../g)) return partComment from here to end of the block please, for future adventurers.
Resolvedby nlynzaad(GitHub profile, opens in a new tab)@@ -1670,13 +1671,4 @@16701671 }16711672 }167216731673- const nextPathname = interpolatePath({1674- // Use the original template path for interpolation1675- // This preserves the original parameter syntax including optional parameters1676- path: nextTo,1677- params: nextParams,1678- leaveWildcards: false,1679- leaveParams: opts.leaveParams,1680- decodeCharMap: this.pathParamsDecodeCharMap,1681- parseCache: this.parsePathnameCache,1682- }).interpolatedPath1674+ const nextPathname = decodePathSegment(How does this play with the prefix and suffix groups?
For the most part I think it should be fine, since the common characters are in the
DECODE_IGNORE_LIST.Rather I just want to make sure our testing covers it too.
I'll add some test cases to the e2e test similar to the one for splats
okay think we are testing all of the impacted areas now.
I'll add some test cases to the e2e test similar to the one for splats
Actionable comments posted: 1
♻️ Duplicate comments (2)
packages/router-core/src/utils.ts (2)
492-504: Previous optimization suggestion still applicable.The past review comment about using a
SetforDECODE_IGNORE_LISTremains valid and would improve lookup performance in line 531. Since this feedback was already provided, I'm flagging this as duplicate.
526-544: Previous comment request still applicable.The past review comment requesting explanatory comments for this algorithm remains valid. The recursive splitting logic with
startIndexis clever but not immediately obvious to future maintainers.Additionally, a minor observation: the null-check
char &&on line 531 is unnecessary since array access within the loop bounds is always defined. However, this is defensive programming and harmless.📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 547268173ebd6bafc350acc3de6e274f20b0548f and 50e7cb21d88a72818604a8d703850a6eec5fd894.
📒 Files selected for processing (2)
packages/router-core/src/utils.ts(1 hunks)packages/router-core/tests/utils.test.ts(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/router-core/tests/utils.test.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/router-core/src/utils.ts
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/src/utils.ts
🧬 Code graph analysis (1)
packages/router-core/src/utils.ts (1)
packages/router-core/src/index.ts (1)
decode(109-109)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (1)
packages/router-core/src/utils.ts (1)
511-524: Well-designed error-tolerant decoding.The fallback mechanism that decodes individual percent-encoded sequences is a robust approach for handling malformed input. This ensures the function doesn't fail on partially invalid encodings.
@@ -490 +490,21 @@490490 }491+492+const DECODE_IGNORE_LIST = [493+ '%',494+ '\\',495+ '/',496+ ';',497+ ':',498+ '@',499+ '&',500+ '=',501+ '+',502+ '$',503+ ',',504+].map((c) => encodeURIComponent(c))505+506+export function decodePathSegment(507+ part: string,508+ decodeIgnore: Array<string> = DECODE_IGNORE_LIST,509+ startIndex = 0,510+) {🛠️ Refactor suggestion | 🟠 Major
Add explicit return type annotation for exported function.
The function is part of the public API but lacks an explicit return type. This is especially important in strict TypeScript mode to ensure type safety and prevent accidental API changes.
Apply this diff:
export function decodePathSegment( part: string, decodeIgnore: Array<string> = DECODE_IGNORE_LIST, startIndex = 0, -) { +): string {📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export function decodePathSegment( part: string, decodeIgnore: Array<string> = DECODE_IGNORE_LIST, startIndex = 0, ): string {🤖 Prompt for AI Agents
In packages/router-core/src/utils.ts around lines 506 to 510, the exported function decodePathSegment lacks an explicit return type; update its signature to include the correct return type (e.g., string) — e.g., change the function declaration to explicitly return string (or the appropriate union type if the implementation can return other types), and update any internal code to ensure all return paths match that explicit type.✅ Addressed in commit e2cbaf9
Actionable comments posted: 0
♻️ Duplicate comments (1)
packages/router-core/src/utils.ts (1)
506-510: Add explicit return type annotation for type safety.The exported function lacks an explicit return type annotation, which reduces type safety in strict TypeScript mode and makes the public API contract less clear.
Apply this diff:
export function decodePathSegment( part: string, decodeIgnore: Array<string> = Array.from(DECODE_IGNORE_LIST.values()), startIndex = 0, -) { +): string {🧹 Nitpick comments (2)
packages/router-core/src/utils.ts (2)
492-504: Precompute the default ignore list to avoid repeated allocations.The default parameter in
decodePathSegmentcallsArray.from(DECODE_IGNORE_LIST.values())every time the function is invoked without an explicitdecodeIgnoreargument, creating unnecessary array allocations.Apply this diff to precompute the array:
const DECODE_IGNORE_LIST = new Map([ ['%', '%25'], ['\\', '%5C'], ['/', '%2F'], [';', '%3B'], [':', '%3A'], ['@', '%40'], ['&', '%26'], ['=', '%3D'], ['+', '%2B'], ['$', '%24'], [',', '%2C'], ]) + +const DECODE_IGNORE_ARRAY = Array.from(DECODE_IGNORE_LIST.values())Then update the function signature:
export function decodePathSegment( part: string, - decodeIgnore: Array<string> = Array.from(DECODE_IGNORE_LIST.values()), + decodeIgnore: Array<string> = DECODE_IGNORE_ARRAY, startIndex = 0, ): string {
511-527: Add return type to internal helper for consistency.The internal
decodehelper function should have an explicit return type annotation for consistency with strict TypeScript practices.Apply this diff:
- function decode(part: string) { + function decode(part: string): string { try {📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 50e7cb21d88a72818604a8d703850a6eec5fd894 and e2cbaf96827bd601bb65febceb1b8df5779d184b.
📒 Files selected for processing (1)
packages/router-core/src/utils.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/router-core/src/utils.ts
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/src/utils.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Test
- GitHub Check: Preview
🔇 Additional comments (1)
packages/router-core/src/utils.ts (1)
529-558: Well-structured recursive decoding algorithm.The implementation correctly handles the recursive decoding logic:
- Splits on ignore characters
- Recursively processes each segment with incremented index
- Rejoins with the original delimiter preserved
- Falls back to full decode when no more ignore characters are found
The comments effectively explain the algorithm's approach.
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/react-router/tests/link.test.tsx (1)
6556-6569: Fix component naming convention.The function
pathRouteComponentshould follow React naming conventions and bePathRouteComponent(PascalCase). This aligns with the pattern used throughout this file (e.g.,IndexComponent,PostsComponent,PostsIndexComponent).Apply this diff:
- function pathRouteComponent() { + function PathRouteComponent() { const params = pathRoute.useParams() return ( <div>e2e/react-router/basic-file-based/tests/params.spec.ts (1)
293-319: Align emoji encoding with Solid Router tests for consistency.The React test uses a hardcoded
%F0%9F%9A%80for the emoji (line 295), while the Solid Router equivalent uses`${encodeURIComponent('🚀')}`(Solid line 370). Both produce the same result, but usingencodeURIComponentis more explicit and maintainable.Apply this diff to align with the Solid approach:
{ id: 'l-to-wildcard-escaped', - pathname: `/params-ps/wildcard/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80]`, + pathname: `/params-ps/wildcard/test[s%5C/.%5C/parameter%25!${encodeURIComponent('🚀')}]`, params: { _splat: 'test[s\\/.\\/parameter%!🚀]', '*': 'test[s\\/.\\/parameter%!🚀]', }, destHeadingId: 'ParamsWildcardSplat', },📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between e2cbaf96827bd601bb65febceb1b8df5779d184b and d37ecc8f4800255c3cc950aa42554ef33e3290fa.
📒 Files selected for processing (13)
e2e/react-router/basic-file-based/src/routeTree.gen.ts(13 hunks)e2e/react-router/basic-file-based/src/routes/params-ps/index.tsx(3 hunks)e2e/react-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsx(1 hunks)e2e/react-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsx(1 hunks)e2e/react-router/basic-file-based/tests/params.spec.ts(1 hunks)e2e/solid-router/basic-file-based/src/routeTree.gen.ts(13 hunks)e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsx(3 hunks)e2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsx(1 hunks)e2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsx(1 hunks)e2e/solid-router/basic-file-based/tests/params.spec.ts(1 hunks)packages/react-router/tests/link.test.tsx(1 hunks)packages/router-core/src/utils.ts(1 hunks)packages/solid-router/tests/link.test.tsx(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/router-core/src/utils.ts
- e2e/react-router/basic-file-based/src/routes/params-ps/index.tsx
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsxe2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsxe2e/react-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsxe2e/react-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsxe2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsxpackages/solid-router/tests/link.test.tsxe2e/react-router/basic-file-based/tests/params.spec.tse2e/solid-router/basic-file-based/tests/params.spec.tspackages/react-router/tests/link.test.tsxe2e/react-router/basic-file-based/src/routeTree.gen.tse2e/solid-router/basic-file-based/src/routeTree.gen.ts
**/src/routes/**
📄 CodeRabbit inference engine (AGENTS.md)
Place file-based routes under src/routes/ directories
Files:
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsxe2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsxe2e/react-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsxe2e/react-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsxe2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsx
e2e/**
📄 CodeRabbit inference engine (AGENTS.md)
Store end-to-end tests under the e2e/ directory
Files:
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsxe2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsxe2e/react-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsxe2e/react-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsxe2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsxe2e/react-router/basic-file-based/tests/params.spec.tse2e/solid-router/basic-file-based/tests/params.spec.tse2e/react-router/basic-file-based/src/routeTree.gen.tse2e/solid-router/basic-file-based/src/routeTree.gen.ts
packages/{react-router,solid-router}/**
📄 CodeRabbit inference engine (AGENTS.md)
Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/
Files:
packages/solid-router/tests/link.test.tsxpackages/react-router/tests/link.test.tsx
🧠 Learnings (1)
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad PR: TanStack/router#5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Applied to files:
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsx
🧬 Code graph analysis (2)
packages/solid-router/tests/link.test.tsx (1)
packages/react-router/src/link.tsx (1)
Link(567-598)
packages/react-router/tests/link.test.tsx (1)
packages/react-router/src/link.tsx (1)
Link(567-598)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (12)
packages/react-router/tests/link.test.tsx (1)
6483-6527: Excellent test coverage for encoded and unicode paths.The test cases comprehensively cover different path patterns (prefix, suffix, wildcard, path param) with encoded characters, unicode, and special characters. The approach of testing both direct navigation (via
history.replaceState) and Link component navigation ensures the decoding behavior works correctly in both scenarios.packages/solid-router/tests/link.test.tsx (1)
6480-6598: LGTM! Comprehensive test coverage for encoded and unicode paths.The test suite effectively validates the PR's objectives:
- Tests preservation of special characters (backslash, percent, slash) in encoded form
- Covers multiple route patterns (splat with prefix/suffix, plain splat, path params)
- Validates both direct browser navigation and link-based navigation
- Verifies that unicode characters (emoji 🚀, Korean 대) are properly percent-encoded in URLs while params are correctly decoded
The test flow is thorough: it validates the href attribute on links, then actual navigation behavior, ensuring consistency between link generation and route matching.
Note: Ensure the different encoding behavior between splat params (where
/can appear unescaped as\/) vs path params (where/must be%2F) is intentional per the decodePathSegment implementation.e2e/react-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsx (1)
1-15: React suffix@대 route OK.Route path, useParams, and test output are correct and consistent with other wildcard routes.
e2e/react-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsx (1)
1-15: React prefix@대{$} route OK.Matches conventions; parameters surfaced for tests via data-testid.
e2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/prefix@대{$}.tsx (1)
1-15: Solid prefix@대{$} route OK.Correct use of Route.useParams() accessor (p()) and test hook.
e2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/{$}suffix@대.tsx (1)
1-15: Solid {$}suffix@대 route OK.Accessor usage and test output are consistent; no issues.
e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsx (3)
88-96: Code snippet verified and consistent.The code at lines 88-96 matches the provided snippet exactly. Test cases at
e2e/solid-router/basic-file-based/tests/params.spec.ts:387and corresponding react-router tests validate the expected URL encoding behavior. The suffix variant follows established patterns.
52-60: Test coverage confirmed for escaped wildcard link.The data-testid
l-to-wildcard-escapedis properly referenced in both solid-router and react-router test suites (params.spec.tslines 369 and 294 respectively), with matching URL-encoded pathname expectations that align with the source code_splatvalue.
70-78: Wildcard prefix variant verified and consistent.The source code at lines 70–78 correctly implements the
prefix@대{$}route prefix with properly escaped_splatparameter. Path and label match, and the test expectations confirm correct URL encoding of the prefix and parameter values across both test suites.e2e/solid-router/basic-file-based/src/routeTree.gen.ts (1)
58-62: Route tree wiring for both new wildcard paths is confirmed and consistent.Both
/params-ps/wildcard/prefix@대{$}and/params-ps/wildcard/{$}suffix@대are present and properly wired across all sections: imports (lines 58, 61), consts (lines 339–343, 356–361), FileRoutesByFullPath/To/Id types (lines 616, 696, 787), module augmentation (line 1482, 1457–1460), and RootRouteChildren (lines 2114–2115). The file is auto-generated and no manual edits are required.e2e/solid-router/basic-file-based/tests/params.spec.ts (1)
368-394: LGTM! Comprehensive test coverage for escaped characters.The three new test cases properly validate the preservation of backslashes and other special characters in path parameters. The expected params correctly show decoded values with backslashes intact (
test[s\\/.\\/parameter%!🚀]), while the pathnames remain URL-encoded, which aligns with the PR's objectives.e2e/react-router/basic-file-based/src/routeTree.gen.ts (1)
59-62: Generated route imports look correct.The auto-generated imports for the new Korean wildcard routes follow the established naming convention and are properly integrated into the route tree.
@@ -40,3 +40,4 @@4040 sleep,4141 } from './utils'4242 import type { RouterHistory } from '../src'43+import React from 'react'⚠️ Potential issue | 🔴 Critical
Remove the incorrect React import.
This is a Solid.js test file and React is not used anywhere. This import should be removed.
Apply this diff:
-import React from 'react'📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
🤖 Prompt for AI Agents
In packages/solid-router/tests/link.test.tsx at line 43, remove the unused and incorrect "import React from 'react'" — this is a Solid.js test and React is not used; delete that import line and ensure no other React-specific imports remain in the file.✅ Addressed in commit 145dde3
Actionable comments posted: 0
🧹 Nitpick comments (3)
packages/react-router/tests/link.test.tsx (3)
6529-6531: Prefertest.each(testCases)overObject.values(testCases).testCasesis already an array;Object.valuesis redundant and discards type info, reducing strictness.Apply this diff:
- test.each(Object.values(testCases))( + test.each(testCases)(
6484-6527: Strengthen typing fortestCases(strict TS).Give
testCasesa readonly, explicit shape to preserve inference and catch mistakes early, while accommodating heterogeneousparamskeys (_splat,*,id).Apply this diff:
- const testCases = [ + const testCases = [ { name: 'with prefix', path: '/foo/prefix대{$}', browsePath: '/foo/prefix대test[s%5C/.%5C/parameter%25!🚀]', expectedPath: '/foo/prefix%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80]', params: { _splat: 'test[s\\/.\\/parameter%!🚀]', '*': 'test[s\\/.\\/parameter%!🚀]', }, }, { name: 'with suffix', path: '/foo/{$}대suffix', browsePath: '/foo/test[s%5C/.%5C/parameter%25!🚀]대suffix', expectedPath: '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80]%EB%8C%80suffix', params: { _splat: 'test[s\\/.\\/parameter%!🚀]', '*': 'test[s\\/.\\/parameter%!🚀]', }, }, { name: 'with wildcard', path: '/foo/$', browsePath: '/foo/test[s%5C/.%5C/parameter%25!🚀]', expectedPath: '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80]', params: { _splat: 'test[s\\/.\\/parameter%!🚀]', '*': 'test[s\\/.\\/parameter%!🚀]', }, }, // '/' is left as is with splat params but encoded with normal params { name: 'with path param', path: `/foo/$id`, browsePath: '/foo/test[s%5C%2F.%5C%2Fparameter%25!🚀]', expectedPath: '/foo/test[s%5C%2F.%5C%2Fparameter%25!%F0%9F%9A%80]', params: { id: 'test[s\\/.\\/parameter%!🚀]', }, }, - ] + ] as const satisfies ReadonlyArray<{ + name: string + path: string + browsePath: string + expectedPath: string + // Allow either splat or id cases. '*' included for assertions. + params: Record<string, string> + }>
6556-6570: Avoid TDZ-style cross-reference between component and route for clarity.PathRouteComponentreadspathRoute.useParams()whilepathRouteis declared later. It works (function body runs after assignment), but the order can confuse readers. Consider relying on function hoisting or using the genericuseParamsto decouple.Option A — move the function below (uses hoisting, no behavior change):
- function PathRouteComponent() { - const params = pathRoute.useParams() - return ( - <div> - <h1>Path Route</h1> - <p> - params:{' '} - <span data-testid="params-to-validate"> - {JSON.stringify(params)} - </span> - </p> - </div> - ) - } - const pathRoute = createRoute({ getParentRoute: () => rootRoute, path, component: PathRouteComponent, }) + + function PathRouteComponent() { + const params = pathRoute.useParams() + return ( + <div> + <h1>Path Route</h1> + <p> + params:{' '} + <span data-testid="params-to-validate"> + {JSON.stringify(params)} + </span> + </p> + </div> + ) + }Option B — decouple with generic hook (if you don’t need route‑typed params here):
- function PathRouteComponent() { - const params = pathRoute.useParams() + function PathRouteComponent() { + const params = useParams({ strict: false }) ... }Also applies to: 6571-6575
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 145dde323087f5038424d003446110d1f0bf30dd and 0faa289be5b905ea816b70179e703f5eb86af664.
📒 Files selected for processing (2)
e2e/solid-router/basic-file-based/tests/params.spec.ts(1 hunks)packages/react-router/tests/link.test.tsx(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- e2e/solid-router/basic-file-based/tests/params.spec.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/react-router/tests/link.test.tsx
packages/{react-router,solid-router}/**
📄 CodeRabbit inference engine (AGENTS.md)
Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/
Files:
packages/react-router/tests/link.test.tsx
🧬 Code graph analysis (1)
packages/react-router/tests/link.test.tsx (1)
packages/react-router/src/link.tsx (1)
Link(567-598)
🔇 Additional comments (1)
packages/react-router/tests/link.test.tsx (1)
6483-6599: Great coverage; behavior matches PR intent.Solid end-to-end verification for mixed encoded/Unicode segments, splat vs. param slash handling, and href generation. Nothing blocking.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 0faa289be5b905ea816b70179e703f5eb86af664 and ce1f225657694d9bef65b7dd7cbea92f094f50cc.
📒 Files selected for processing (2)
packages/react-router/tests/link.test.tsx(1 hunks)packages/solid-router/tests/link.test.tsx(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/solid-router/tests/link.test.tsxpackages/react-router/tests/link.test.tsx
packages/{react-router,solid-router}/**
📄 CodeRabbit inference engine (AGENTS.md)
Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/
Files:
packages/solid-router/tests/link.test.tsxpackages/react-router/tests/link.test.tsx
🧠 Learnings (1)
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR PR: TanStack/router#0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{react-router,solid-router}/** : Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/Applied to files:
packages/solid-router/tests/link.test.tsx
🧬 Code graph analysis (1)
packages/react-router/tests/link.test.tsx (1)
packages/react-router/src/link.tsx (1)
Link(567-598)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (3)
packages/solid-router/tests/link.test.tsx (1)
6575-6584: The review comment is incorrect. This is the established test pattern throughout the file.The
validate()function (lines 6531-6537) usesawait waitFor()to asynchronously poll and wait for the router state to update after the URL change, which is the appropriate mechanism for handling this scenario. This exact pattern—render the router, then callwindow.history.replaceState, then validate—is used consistently across 13+ tests in this file (at lines 5286, 5306, 5326, 5347, 5366, 5387, 5406, 5427, 5447, 5462, 5478, 5497, and 6582), indicating it's the established convention for this codebase. The browser history integration appears to support this pattern, and the tests are functioning as designed.Likely an incorrect or invalid review comment.
packages/react-router/tests/link.test.tsx (2)
6483-6599: Duplication concern is unsubstantiated.The verification script found only a single occurrence of the "encoded and unicode paths" describe block at line 6483—not multiple. The review comment's primary concern about duplicate test suites does not reflect the actual state of the code.
Likely an incorrect or invalid review comment.
6484-6527: The{$}syntax is valid and correct for splat routes with prefix/suffix.After searching the codebase,
{$}is the correct and intentional syntax for splat routes that include prefix or suffix text. This is evident from multiple route definitions inroute.test-d.tsx:path: 'prefix{$}suffix'path: 'docs/$docId/before{$}after/detail{-$detailId}/file-{$myFile}.pdf'
The syntax pattern is: braces are required when combining literal text with a parameter or splat. Standalone sплat uses bare
$(as in your "with wildcard" test case), but splat with surrounding text requires{$}. Optional variants use{-$}.The test cases at lines 6487 and 6498 are syntactically correct.
Likely an incorrect or invalid review comment.
@@ -6481,0 +6566,21 @@6566+ <h1>Path Route</h1>6567+ <p>6568+ params:{' '}6569+ <span data-testid="params-to-validate">6570+ {JSON.stringify(params)}6571+ </span>6572+ </p>6573+ </div>6574+ )6575+ }6576+6577+ const router = createRouter({6578+ routeTree: rootRoute.addChildren([indexRoute, pathRoute]),6579+ history,6580+ })6581+6582+ render(<RouterProvider router={router} />)6583+6584+ await act(() => window.history.replaceState(null, 'root', browsePath))6585+6586+ await validate()⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
Verify that direct
window.history.replaceStatetriggers router updates.Line 6584 directly manipulates the browser history using
window.history.replaceState, then immediately validates that the router has parsed the path parameters. However, the router is using ahistoryobject (created viacreateBrowserHistory()on line 57), not directly monitoringwindow.history.window.history.replaceState()does not triggerpopstateevents, so the router may not be notified of the location change, which could cause this test to fail or behave unpredictably.Consider using the router's history object instead:
-await act(() => window.history.replaceState(null, 'root', browsePath)) +await act(() => history.replace(browsePath))Or verify that the router implementation correctly handles direct
window.historymanipulations through polling or other mechanisms.
I'll verify this test concern by examining the codebase structure and understanding how the router handles history changes.
🏁 Script executed:
#!/bin/bash # First, locate and examine the test file around the problematic lines fd 'link.test.tsx' --type f | head -5Length of output: 83
🏁 Script executed:
#!/bin/bash # Check if the file exists and get line count if [ -f "packages/react-router/tests/link.test.tsx" ]; then wc -l packages/react-router/tests/link.test.tsx fiLength of output: 46
🏁 Script executed:
#!/bin/bash # Extract context around lines 6584-6586 and the history initialization at line 57 echo "=== Lines around 6584-6586 (test code) ===" sed -n '6575,6598p' packages/react-router/tests/link.test.tsx echo "" echo "=== Lines around 57 (history initialization) ===" sed -n '50,70p' packages/react-router/tests/link.test.tsxLength of output: 1086
🏁 Script executed:
#!/bin/bash # Search for other uses of window.history in tests to see if this pattern is common rg 'window\.history\.' packages/react-router/tests/link.test.tsx -n -C 2 | head -50Length of output: 1110
🏁 Script executed:
#!/bin/bash # Search for history.replace or history.push patterns to understand the recommended approach rg 'history\.(replace|push)' packages/react-router/tests/link.test.tsx -n -C 2 | head -50Length of output: 1458
🏁 Script executed:
#!/bin/bash # Look at the validate function to understand what it checks rg -n 'const validate|function validate' packages/react-router/tests/link.test.tsx -A 5 | head -30Length of output: 290
🏁 Script executed:
#!/bin/bash # Examine the router implementation to see how it handles history changes fd 'index.ts' packages/react-router/src --type f | xargs grep -l 'createBrowserHistory\|history' | head -3Length of output: 35
🏁 Script executed:
#!/bin/bash # Look for BrowserHistory or similar implementation to understand event listeners rg 'popstate\|hashchange\|addEventListener' packages/react-router/src -n -C 2 | head -40Length of output: 0
--- 🏁 Script executed: ```shell #!/bin/bash # Search for how the router accesses/syncs current location rg 'window\.location|location\.pathname' packages/react-router/src -n -C 2 | head -60Length of output: 1913
🏁 Script executed:
#!/bin/bash # Check if there's a history listener or location sync mechanism rg 'addEventListener|on\(' packages/react-router/src -n | grep -i 'popstate\|hashchange\|history\|location' | head -20Length of output: 851
🏁 Script executed:
#!/bin/bash # Look at a working test that uses window.history.replaceState before render+validate sed -n '4528,4545p' packages/react-router/tests/link.test.tsxLength of output: 655
🏁 Script executed:
#!/bin/bash # Check how the validate function in the problematic test is structured sed -n '6529,6600p' packages/react-router/tests/link.test.tsxLength of output: 1904
🏁 Script executed:
#!/bin/bash # Search for listener subscriptions or effect hooks that sync router state rg 'useLayoutEffect|useEffect|subscribe|listener' packages/react-router/src -n | head -30Length of output: 1475
🏁 Script executed:
#!/bin/bash # Check history library - look for how createBrowserHistory integrates with window.history rg 'createBrowserHistory' packages -A 10 -B 2 | head -40Length of output: 2640
🌐 Web query:
Does createBrowserHistory() from history library listen to window.history.replaceState events?💡 Result:
Short answer: No.
createBrowserHistory listens for popstate and uses the HTML5 history API when your app calls history.push / history.replace, but it does not automatically detect external calls to window.history.replaceState made by other code — those calls do not fire a popstate event and the history library doesn't monkey‑patch replaceState for you. See the history README and the MDN popstate/replaceState behavior. [1][2]
Sources:
- history README (createBrowserHistory uses pushState/replaceState and listens via popstate). [1]
- MDN: replaceState / popstate behavior (pushState/replaceState do not trigger popstate). [2]
🌐 Web query:
Does history.replaceState() fire popstate events in modern browsers?💡 Result:
No — calling history.replaceState() does not fire a popstate event. popstate is fired when the active history entry changes (e.g., back/forward or history.back()/history.forward()), not by pushState()/replaceState() themselves. [1][2]
References:
- MDN: Window: popstate event. [1]
- MDN: NavigationCurrentEntryChangeEvent (Navigation API) — newer event for entry changes including replace. [2]
Use
history.replace()instead ofwindow.history.replaceState()to trigger router updates.Line 6584 uses
window.history.replaceState()to change the browser location, but this does not fire apopstateevent. Since the router's history object only listens forpopstateevents (and uses thehistorylibrary's subscription mechanism), the router is never notified of the location change. The router state remains stale, and the subsequentvalidate()call expecting parsed parameters will fail.The test file uses
history.push()successfully in other places (e.g., lines 5299, 5321) as the correct pattern. Replace the directwindow.history.replaceState()calls with the router's history object:-await act(() => window.history.replaceState(null, 'root', browsePath)) +await act(() => history.replace(browsePath))Also apply the same fix to line 6588.
🤖 Prompt for AI Agents
In packages/react-router/tests/link.test.tsx around lines 6584-6588 the test uses window.history.replaceState() which doesn't emit a popstate event so the router's history subscription isn't notified; replace those direct DOM history calls with the router history API (call history.replace(browsePath) on the history object used by the test) so the router receives the update and the subsequent validate() sees the new location; make the same replacement for the other occurrence referenced at line 6588.okay think we are testing all of the impacted areas now.
SeanCassiere approved these changes
SeanCassiere changed the title
nlynzaad(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Walkthrough#
Adds a tolerant path-segment decoder (
decodePathSegment) used in path parsing and location building; introduces escaped/unicode wildcard e2e routes and tests for React and Solid; updates generated route trees and expands link tests for encoded/Unicode path handling.Changes#
packages/router-core/src/utils.ts,packages/router-core/tests/utils.test.tsDECODE_IGNORE_LISTand exporteddecodePathSegment(part: string, decodeIgnore?: string[], startIndex?: number)implementing tolerant, recursive decoding; add unit tests covering ignore-lists, malformed encodings, and edge cases.packages/router-core/src/path.ts,packages/router-core/src/router.ts,packages/router-core/tests/path.test.tsdecodePathSegment(part)in path parsing and applydecodePathSegmentto interpolated paths inbuildLocation; add path parsing test for preserving/decoding percent/backslash sequences.e2e/react-router/basic-file-based/src/routes/params-ps/index.tsx,e2e/react-router/basic-file-based/tests/params.spec.ts,e2e/react-router/basic-file-based/src/routeTree.gen.ts,e2e/react-router/basic-file-based/src/routes/params-ps/wildcard/*e2e/solid-router/basic-file-based/src/routes/params-ps/index.tsx,e2e/solid-router/basic-file-based/tests/params.spec.ts,e2e/solid-router/basic-file-based/src/routeTree.gen.ts,e2e/solid-router/basic-file-based/src/routes/params-ps/wildcard/*packages/react-router/tests/link.test.tsx,packages/solid-router/tests/link.test.tsxSequence Diagram(s)#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~25 minutes
decodePathSegment.path.tsandrouter.ts.routeTree.gen.tschanges and new route filenames; check duplicated test blocks inlink.test.tsxfor intentional duplication.Possibly related PRs#
buildLocation/interpolation logic inrouter.ts; closely related to the decode step added here.decodePathSegmentintegration.Suggested reviewers#
Poem#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
decodePathSegmentutility function inpackages/router-core/src/utils.ts, replacing manual decoding inpath.ts, and applying it to path interpolation inrouter.ts. These changes collectively make URL decoding more stable and robust by handling special characters (backslash, percent, slash) in a configurable manner. The title is specific and clear enough that a developer reviewing the history would understand the focus is on improving URL decoding stability, even though it doesn't explicitly mention the underlying bug fix (incorrect backslash decoding in path parameters).✨ Finishing touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.