From 3355df08da364a20af350567475ae232546f5ff8 Mon Sep 17 00:00:00 2001 From: Gabriel Halle Date: Sat, 21 Dec 2024 08:38:49 -0500 Subject: [PATCH 1/2] fix(router): 404 for routes starting with an optional parameter --- src/router.ts | 9 +++++++++ src/router_test.ts | 5 +++++ 2 files changed, 14 insertions(+) diff --git a/src/router.ts b/src/router.ts index 34e85bcdbd7..2be7060f2bd 100644 --- a/src/router.ts +++ b/src/router.ts @@ -225,5 +225,14 @@ export function pathToPattern(path: string): string { route = "/"; } + // Handles all cases where an optional parameter is the + // first and only non-group segment + // Case: /[[id]].tsx + // Case: /(group)/[[id]].tsx + // Case: /(group)/[[name]]/(group2)/index.tsx + if (route.startsWith(`{/`) && !/(? { ).toEqual( "/foo{/:name}?/bar{/:bob}?", ); + expect( + pathToPattern("(group)/[[name]]/(group2)/index"), + ).toEqual( + "/{:name}?", + ); }); await t.step("throws on invalid patterns", () => { From cde7062af0640e092bc268a9a2f2d0f2b5265153 Mon Sep 17 00:00:00 2001 From: Gabriel Halle Date: Sat, 21 Dec 2024 09:43:04 -0500 Subject: [PATCH 2/2] avoid using a regex --- src/router.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/router.ts b/src/router.ts index 2be7060f2bd..c3c982b1135 100644 --- a/src/router.ts +++ b/src/router.ts @@ -145,6 +145,7 @@ export function pathToPattern(path: string): string { let route = ""; + let nonOptionalSegments = 0; for (let i = 0; i < parts.length; i++) { const part = parts[i]; @@ -217,7 +218,12 @@ export function pathToPattern(path: string): string { } } - route += (optional ? "" : "/") + pattern; + if (optional) { + route += pattern; + } else { + nonOptionalSegments++; + route += "/" + pattern; + } } // Case: /(group)/index.tsx @@ -225,12 +231,13 @@ export function pathToPattern(path: string): string { route = "/"; } - // Handles all cases where an optional parameter is the - // first and only non-group segment + // Handles all cases where a route starts with + // an optional parameter and does not contain + // any non-group and non-optional segments after // Case: /[[id]].tsx // Case: /(group)/[[id]].tsx // Case: /(group)/[[name]]/(group2)/index.tsx - if (route.startsWith(`{/`) && !/(?