diff --git a/e2e/react-router/basic-file-based/src/routeTree.gen.ts b/e2e/react-router/basic-file-based/src/routeTree.gen.ts index 28197e4d98..2d99238033 100644 --- a/e2e/react-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based/src/routeTree.gen.ts @@ -20,16 +20,21 @@ import { Route as ComponentTypesTestRouteImport } from './routes/component-types import { Route as AnchorRouteImport } from './routes/anchor' import { Route as LayoutRouteImport } from './routes/_layout' import { Route as Char45824Char54620Char48124Char44397RouteRouteImport } from './routes/대한민국/route' +import { Route as SkipOnParseErrorRouteRouteImport } from './routes/skip-on-parse-error/route' import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' import { Route as PathlessLayoutRouteRouteImport } from './routes/pathless-layout/route' import { Route as NonNestedRouteRouteImport } from './routes/non-nested/route' import { Route as IndexRouteImport } from './routes/index' +import { Route as SkipOnParseErrorIndexRouteImport } from './routes/skip-on-parse-error/index' import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' import { Route as RelativeIndexRouteImport } from './routes/relative/index' import { Route as RedirectIndexRouteImport } from './routes/redirect/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as ParamsPsIndexRouteImport } from './routes/params-ps/index' import { Route as StructuralSharingEnabledRouteImport } from './routes/structural-sharing.$enabled' +import { Route as SkipOnParseErrorUuidRouteImport } from './routes/skip-on-parse-error/$uuid' +import { Route as SkipOnParseErrorSlugRouteImport } from './routes/skip-on-parse-error/$slug' +import { Route as SkipOnParseErrorNumRouteImport } from './routes/skip-on-parse-error/$num' import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' @@ -173,6 +178,11 @@ const Char45824Char54620Char48124Char44397RouteRoute = path: '/대한민국', getParentRoute: () => rootRouteImport, } as any) +const SkipOnParseErrorRouteRoute = SkipOnParseErrorRouteRouteImport.update({ + id: '/skip-on-parse-error', + path: '/skip-on-parse-error', + getParentRoute: () => rootRouteImport, +} as any) const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ id: '/search-params', path: '/search-params', @@ -193,6 +203,11 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) +const SkipOnParseErrorIndexRoute = SkipOnParseErrorIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ id: '/', path: '/', @@ -224,6 +239,21 @@ const StructuralSharingEnabledRoute = path: '/structural-sharing/$enabled', getParentRoute: () => rootRouteImport, } as any) +const SkipOnParseErrorUuidRoute = SkipOnParseErrorUuidRouteImport.update({ + id: '/$uuid', + path: '/$uuid', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) +const SkipOnParseErrorSlugRoute = SkipOnParseErrorSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) +const SkipOnParseErrorNumRoute = SkipOnParseErrorNumRouteImport.update({ + id: '/$num', + path: '/$num', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ id: '/default', path: '/default', @@ -705,6 +735,7 @@ export interface FileRoutesByFullPath { '/non-nested': typeof NonNestedRouteRouteWithChildren '/pathless-layout': typeof PathlessLayoutLayoutRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/skip-on-parse-error': typeof SkipOnParseErrorRouteRouteWithChildren '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute @@ -729,12 +760,16 @@ export interface FileRoutesByFullPath { '/posts/$postId': typeof PostsPostIdRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute + '/skip-on-parse-error/$num': typeof SkipOnParseErrorNumRoute + '/skip-on-parse-error/$slug': typeof SkipOnParseErrorSlugRoute + '/skip-on-parse-error/$uuid': typeof SkipOnParseErrorUuidRoute '/structural-sharing/$enabled': typeof StructuralSharingEnabledRoute '/params-ps': typeof ParamsPsIndexRoute '/posts/': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute '/relative': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute + '/skip-on-parse-error/': typeof SkipOnParseErrorIndexRoute '/non-nested/deep/$baz': typeof NonNestedDeepBazRouteRouteWithChildren '/non-nested/named/$baz': typeof NonNestedNamedBazRouteRouteWithChildren '/non-nested/path/baz': typeof NonNestedPathBazRouteRouteWithChildren @@ -832,12 +867,16 @@ export interface FileRoutesByTo { '/lazyinside': typeof groupLazyinsideRoute '/posts/$postId': typeof PostsPostIdRoute '/search-params/default': typeof SearchParamsDefaultRoute + '/skip-on-parse-error/$num': typeof SkipOnParseErrorNumRoute + '/skip-on-parse-error/$slug': typeof SkipOnParseErrorSlugRoute + '/skip-on-parse-error/$uuid': typeof SkipOnParseErrorUuidRoute '/structural-sharing/$enabled': typeof StructuralSharingEnabledRoute '/params-ps': typeof ParamsPsIndexRoute '/posts': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute '/relative': typeof RelativeIndexRoute '/search-params': typeof SearchParamsIndexRoute + '/skip-on-parse-error': typeof SkipOnParseErrorIndexRoute '/params-ps/named/$foo': typeof ParamsPsNamedFooRouteRouteWithChildren '/params-ps/non-nested/$foo': typeof ParamsPsNonNestedFooRouteRouteWithChildren '/insidelayout': typeof groupLayoutInsidelayoutRoute @@ -907,6 +946,7 @@ export interface FileRoutesById { '/non-nested': typeof NonNestedRouteRouteWithChildren '/pathless-layout': typeof PathlessLayoutRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/skip-on-parse-error': typeof SkipOnParseErrorRouteRouteWithChildren '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren '/anchor': typeof AnchorRoute @@ -935,12 +975,16 @@ export interface FileRoutesById { '/posts/$postId': typeof PostsPostIdRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute + '/skip-on-parse-error/$num': typeof SkipOnParseErrorNumRoute + '/skip-on-parse-error/$slug': typeof SkipOnParseErrorSlugRoute + '/skip-on-parse-error/$uuid': typeof SkipOnParseErrorUuidRoute '/structural-sharing/$enabled': typeof StructuralSharingEnabledRoute '/params-ps/': typeof ParamsPsIndexRoute '/posts/': typeof PostsIndexRoute '/redirect/': typeof RedirectIndexRoute '/relative/': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute + '/skip-on-parse-error/': typeof SkipOnParseErrorIndexRoute '/non-nested/deep/$baz': typeof NonNestedDeepBazRouteRouteWithChildren '/non-nested/named/$baz': typeof NonNestedNamedBazRouteRouteWithChildren '/non-nested/path/baz': typeof NonNestedPathBazRouteRouteWithChildren @@ -1019,6 +1063,7 @@ export interface FileRouteTypes { | '/non-nested' | '/pathless-layout' | '/search-params' + | '/skip-on-parse-error' | '/대한민국' | '/anchor' | '/component-types-test' @@ -1043,12 +1088,16 @@ export interface FileRouteTypes { | '/posts/$postId' | '/redirect/$target' | '/search-params/default' + | '/skip-on-parse-error/$num' + | '/skip-on-parse-error/$slug' + | '/skip-on-parse-error/$uuid' | '/structural-sharing/$enabled' | '/params-ps' | '/posts/' | '/redirect' | '/relative' | '/search-params/' + | '/skip-on-parse-error/' | '/non-nested/deep/$baz' | '/non-nested/named/$baz' | '/non-nested/path/baz' @@ -1146,12 +1195,16 @@ export interface FileRouteTypes { | '/lazyinside' | '/posts/$postId' | '/search-params/default' + | '/skip-on-parse-error/$num' + | '/skip-on-parse-error/$slug' + | '/skip-on-parse-error/$uuid' | '/structural-sharing/$enabled' | '/params-ps' | '/posts' | '/redirect' | '/relative' | '/search-params' + | '/skip-on-parse-error' | '/params-ps/named/$foo' | '/params-ps/non-nested/$foo' | '/insidelayout' @@ -1220,6 +1273,7 @@ export interface FileRouteTypes { | '/non-nested' | '/pathless-layout' | '/search-params' + | '/skip-on-parse-error' | '/대한민국' | '/_layout' | '/anchor' @@ -1248,12 +1302,16 @@ export interface FileRouteTypes { | '/posts/$postId' | '/redirect/$target' | '/search-params/default' + | '/skip-on-parse-error/$num' + | '/skip-on-parse-error/$slug' + | '/skip-on-parse-error/$uuid' | '/structural-sharing/$enabled' | '/params-ps/' | '/posts/' | '/redirect/' | '/relative/' | '/search-params/' + | '/skip-on-parse-error/' | '/non-nested/deep/$baz' | '/non-nested/named/$baz' | '/non-nested/path/baz' @@ -1331,6 +1389,7 @@ export interface RootRouteChildren { NonNestedRouteRoute: typeof NonNestedRouteRouteWithChildren PathlessLayoutRouteRoute: typeof PathlessLayoutRouteRouteWithChildren SearchParamsRouteRoute: typeof SearchParamsRouteRouteWithChildren + SkipOnParseErrorRouteRoute: typeof SkipOnParseErrorRouteRouteWithChildren Char45824Char54620Char48124Char44397RouteRoute: typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren AnchorRoute: typeof AnchorRoute @@ -1451,6 +1510,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteRouteImport parentRoute: typeof rootRouteImport } + '/skip-on-parse-error': { + id: '/skip-on-parse-error' + path: '/skip-on-parse-error' + fullPath: '/skip-on-parse-error' + preLoaderRoute: typeof SkipOnParseErrorRouteRouteImport + parentRoute: typeof rootRouteImport + } '/search-params': { id: '/search-params' path: '/search-params' @@ -1479,6 +1545,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/skip-on-parse-error/': { + id: '/skip-on-parse-error/' + path: '/' + fullPath: '/skip-on-parse-error/' + preLoaderRoute: typeof SkipOnParseErrorIndexRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } '/search-params/': { id: '/search-params/' path: '/' @@ -1521,6 +1594,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof StructuralSharingEnabledRouteImport parentRoute: typeof rootRouteImport } + '/skip-on-parse-error/$uuid': { + id: '/skip-on-parse-error/$uuid' + path: '/$uuid' + fullPath: '/skip-on-parse-error/$uuid' + preLoaderRoute: typeof SkipOnParseErrorUuidRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } + '/skip-on-parse-error/$slug': { + id: '/skip-on-parse-error/$slug' + path: '/$slug' + fullPath: '/skip-on-parse-error/$slug' + preLoaderRoute: typeof SkipOnParseErrorSlugRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } + '/skip-on-parse-error/$num': { + id: '/skip-on-parse-error/$num' + path: '/$num' + fullPath: '/skip-on-parse-error/$num' + preLoaderRoute: typeof SkipOnParseErrorNumRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } '/search-params/default': { id: '/search-params/default' path: '/default' @@ -2377,6 +2471,25 @@ const SearchParamsRouteRouteChildren: SearchParamsRouteRouteChildren = { const SearchParamsRouteRouteWithChildren = SearchParamsRouteRoute._addFileChildren(SearchParamsRouteRouteChildren) +interface SkipOnParseErrorRouteRouteChildren { + SkipOnParseErrorNumRoute: typeof SkipOnParseErrorNumRoute + SkipOnParseErrorSlugRoute: typeof SkipOnParseErrorSlugRoute + SkipOnParseErrorUuidRoute: typeof SkipOnParseErrorUuidRoute + SkipOnParseErrorIndexRoute: typeof SkipOnParseErrorIndexRoute +} + +const SkipOnParseErrorRouteRouteChildren: SkipOnParseErrorRouteRouteChildren = { + SkipOnParseErrorNumRoute: SkipOnParseErrorNumRoute, + SkipOnParseErrorSlugRoute: SkipOnParseErrorSlugRoute, + SkipOnParseErrorUuidRoute: SkipOnParseErrorUuidRoute, + SkipOnParseErrorIndexRoute: SkipOnParseErrorIndexRoute, +} + +const SkipOnParseErrorRouteRouteWithChildren = + SkipOnParseErrorRouteRoute._addFileChildren( + SkipOnParseErrorRouteRouteChildren, + ) + interface Char45824Char54620Char48124Char44397RouteRouteChildren { Char45824Char54620Char48124Char44397WildcardSplatRoute: typeof Char45824Char54620Char48124Char44397WildcardSplatRoute Char45824Char54620Char48124Char44397Char55357Char56960IdRoute: typeof Char45824Char54620Char48124Char44397Char55357Char56960IdRoute @@ -2586,6 +2699,7 @@ const rootRouteChildren: RootRouteChildren = { NonNestedRouteRoute: NonNestedRouteRouteWithChildren, PathlessLayoutRouteRoute: PathlessLayoutRouteRouteWithChildren, SearchParamsRouteRoute: SearchParamsRouteRouteWithChildren, + SkipOnParseErrorRouteRoute: SkipOnParseErrorRouteRouteWithChildren, Char45824Char54620Char48124Char44397RouteRoute: Char45824Char54620Char48124Char44397RouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$num.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$num.tsx new file mode 100644 index 0000000000..6e235f8f72 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$num.tsx @@ -0,0 +1,31 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error/$num')({ + params: { + parse: (params) => { + const num = parseInt(params.num, 10) + if (isNaN(num) || num.toString() !== params.num) { + throw new Error('Invalid numeric format') + } + return { num } + }, + stringify: (params) => ({ num: String(params.num) }), + }, + skipRouteOnParseError: true, + component: NumericRouteComponent, +}) + +function NumericRouteComponent() { + const { num } = Route.useParams() + + return ( +
+

Numeric Route

+

{num}

+

Type: {typeof num}

+

+ This route matched because the param is a valid number. +

+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$slug.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$slug.tsx new file mode 100644 index 0000000000..35691a5504 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$slug.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error/$slug')({ + // No params.parse - this is the catch-all fallback + // Still has skipRouteOnParseError to participate in the competition + skipRouteOnParseError: true, + component: CatchallRouteComponent, +}) + +function CatchallRouteComponent() { + const { slug } = Route.useParams() + + return ( +
+

Catch-all Route

+

{slug}

+

+ This route matches any string that doesn't match UUID or Numeric + patterns. +

+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$uuid.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$uuid.tsx new file mode 100644 index 0000000000..2f08f064d2 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$uuid.tsx @@ -0,0 +1,33 @@ +import { createFileRoute } from '@tanstack/react-router' + +// UUID validation regex +const UUID_REGEX = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i + +export const Route = createFileRoute('/skip-on-parse-error/$uuid')({ + params: { + parse: (params) => { + if (!UUID_REGEX.test(params.uuid)) { + throw new Error('Invalid UUID format') + } + return { uuid: params.uuid } + }, + stringify: (params) => ({ uuid: params.uuid }), + }, + skipRouteOnParseError: true, + component: UuidRouteComponent, +}) + +function UuidRouteComponent() { + const { uuid } = Route.useParams() + + return ( +
+

UUID Route

+

{uuid}

+

+ This route matched because the param is a valid UUID. +

+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/index.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/index.tsx new file mode 100644 index 0000000000..78c825a40e --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/index.tsx @@ -0,0 +1,70 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error/')({ + component: SkipOnParseErrorIndex, +}) + +function SkipOnParseErrorIndex() { + const uuidValue = '123e4567-e89b-12d3-a456-426614174000' + const numericValue = 12345 + const stringValue = 'hello-world' + + return ( +
+

Test Links

+ +
+

UUID Route Tests

+
+ + Navigate to UUID: {uuidValue.slice(0, 8)}... + +
+
+ +
+

Numeric Route Tests

+
+ + Navigate to Numeric: {numericValue} + +
+
+ +
+

String Route Tests (Catch-all)

+
+ + Navigate to String: {stringValue} + +
+
+ +
+

+ Expected behavior: +

+ +
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/route.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/route.tsx new file mode 100644 index 0000000000..85aac5d1ac --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/route.tsx @@ -0,0 +1,20 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error')({ + component: SkipOnParseErrorLayout, +}) + +function SkipOnParseErrorLayout() { + return ( +
+

+ Skip Route on Parse Error Tests (File-Based) +

+

+ This tests the skipRouteOnParseError feature with multiple competing + routes that have different param validators. +

+ +
+ ) +} diff --git a/e2e/react-router/basic-file-based/tests/skip-on-parse-error.spec.ts b/e2e/react-router/basic-file-based/tests/skip-on-parse-error.spec.ts new file mode 100644 index 0000000000..e49c05fe6a --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/skip-on-parse-error.spec.ts @@ -0,0 +1,180 @@ +import { expect, test } from '@playwright/test' + +test.describe('skipRouteOnParseError (file-based)', () => { + const UUID_VALUE = '123e4567-e89b-12d3-a456-426614174000' + const NUMERIC_VALUE = '12345' + const STRING_VALUE = 'hello-world' + + test.describe('direct URL navigation', () => { + test('navigating to UUID value matches UUID route', async ({ page }) => { + await page.goto(`/skip-on-parse-error/${UUID_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('navigating to numeric value matches Numeric route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${NUMERIC_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + + // Verify the param was parsed as a number + const paramType = page.getByTestId('param-type') + await expect(paramType).toHaveText('Type: number') + }) + + test('navigating to string value matches Catch-all route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${STRING_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + + test('navigating to another UUID matches UUID route', async ({ page }) => { + const anotherUuid = 'a1b2c3d4-e5f6-1234-89ab-cdef01234567' + await page.goto(`/skip-on-parse-error/${anotherUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + }) + + test('navigating to zero matches Numeric route', async ({ page }) => { + await page.goto('/skip-on-parse-error/0') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText('0') + }) + + test('navigating to negative number matches Numeric route', async ({ + page, + }) => { + // -123 parses to -123, and "-123" === "-123" check passes + await page.goto('/skip-on-parse-error/-123') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + }) + + test('navigating to float matches Catch-all route', async ({ page }) => { + // 123.45 won't match numeric because parseInt("123.45") === 123, and "123" !== "123.45" + await page.goto('/skip-on-parse-error/123.45') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + + test('navigating to UUID-like but invalid format matches Catch-all', async ({ + page, + }) => { + // Invalid UUID (wrong version digit) + const invalidUuid = '123e4567-e89b-9999-a456-426614174000' + await page.goto(`/skip-on-parse-error/${invalidUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + }) + + test.describe('client-side navigation via Link', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('clicking UUID link navigates to UUID route', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('clicking Numeric link navigates to Numeric route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-numeric') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + }) + + test('clicking String link navigates to Catch-all route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-string') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + }) + + test.describe('Link href generation', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('UUID link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${UUID_VALUE}`, + ) + }) + + test('Numeric link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-numeric') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${NUMERIC_VALUE}`, + ) + }) + + test('String link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-string') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${STRING_VALUE}`, + ) + }) + }) +}) diff --git a/e2e/react-router/basic/src/main.tsx b/e2e/react-router/basic/src/main.tsx index 36e5106654..10aeb78efe 100644 --- a/e2e/react-router/basic/src/main.tsx +++ b/e2e/react-router/basic/src/main.tsx @@ -409,6 +409,179 @@ const paramsPsWildcardSplatSuffixRoute = createRoute({ }, }) +// skipRouteOnParseError test routes +// These routes demonstrate competing routes at the same path level with different validators +const UUID_REGEX = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i + +const skipOnParseErrorRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/skip-on-parse-error', + component: function SkipOnParseErrorLayout() { + return ( +
+

+ Skip Route on Parse Error Tests +

+

+ This tests the skipRouteOnParseError feature with multiple competing + routes that have different param validators. +

+ +
+ ) + }, +}) + +const skipOnParseErrorIndexRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '/', + component: function SkipOnParseErrorIndex() { + const uuidValue = '123e4567-e89b-12d3-a456-426614174000' + const numericValue = '12345' + const stringValue = 'hello-world' + + return ( +
+

Test Links

+ +
+

UUID Route Tests

+
+ + Navigate to UUID: {uuidValue.slice(0, 8)}... + +
+
+ +
+

Numeric Route Tests

+
+ + Navigate to Numeric: {numericValue} + +
+
+ +
+

String Route Tests (Catch-all)

+
+ + Navigate to String: {stringValue} + +
+
+ +
+

+ Expected behavior: +

+ +
+
+ ) + }, +}) + +// UUID route - has highest priority due to skipRouteOnParseError + specific validation +const skipOnParseErrorUuidRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '$uuid', + params: { + parse: (params: { uuid: string }) => { + if (!UUID_REGEX.test(params.uuid)) { + throw new Error('Invalid UUID format') + } + return { uuid: params.uuid } + }, + stringify: (params: { uuid: string }) => ({ uuid: params.uuid }), + }, + skipRouteOnParseError: true, + component: function UuidRouteComponent() { + const { uuid } = skipOnParseErrorUuidRoute.useParams() + + return ( +
+

UUID Route

+

{uuid}

+

+ This route matched because the param is a valid UUID. +

+
+ ) + }, +}) + +// Numeric route - has priority over catch-all due to skipRouteOnParseError + validation +const skipOnParseErrorNumericRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '$num', + params: { + parse: (params: { num: string }) => { + const num = parseInt(params.num, 10) + if (isNaN(num) || num.toString() !== params.num) { + throw new Error('Invalid numeric format') + } + return { num } + }, + stringify: (params: { num: number }) => ({ num: String(params.num) }), + }, + skipRouteOnParseError: true, + component: function NumericRouteComponent() { + const { num } = skipOnParseErrorNumericRoute.useParams() + + return ( +
+

Numeric Route

+

{num}

+

Type: {typeof num}

+

+ This route matched because the param is a valid number. +

+
+ ) + }, +}) + +// Catch-all route - lowest priority, matches any string that doesn't match UUID or Numeric +const skipOnParseErrorCatchallRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '$slug', + component: function CatchallRouteComponent() { + const { slug } = skipOnParseErrorCatchallRoute.useParams() + + return ( +
+

Catch-all Route

+

{slug}

+

+ This route matches any string that doesn't match UUID or Numeric + patterns. +

+
+ ) + }, +}) + const routeTree = rootRoute.addChildren([ postsRoute.addChildren([postRoute, postsIndexRoute]), layoutRoute.addChildren([ @@ -429,6 +602,14 @@ const routeTree = rootRoute.addChildren([ ]), paramsPsIndexRoute, ]), + // skipRouteOnParseError routes - order matters for priority: + // UUID route (most specific validator) -> Numeric route -> Catch-all (no validator) + skipOnParseErrorRoute.addChildren([ + skipOnParseErrorIndexRoute, + skipOnParseErrorUuidRoute, + skipOnParseErrorNumericRoute, + skipOnParseErrorCatchallRoute, + ]), indexRoute, ]) diff --git a/e2e/react-router/basic/tests/skip-on-parse-error.spec.ts b/e2e/react-router/basic/tests/skip-on-parse-error.spec.ts new file mode 100644 index 0000000000..8f16a73f0f --- /dev/null +++ b/e2e/react-router/basic/tests/skip-on-parse-error.spec.ts @@ -0,0 +1,181 @@ +import { expect, test } from '@playwright/test' + +test.describe('skipRouteOnParseError', () => { + const UUID_VALUE = '123e4567-e89b-12d3-a456-426614174000' + const NUMERIC_VALUE = '12345' + const STRING_VALUE = 'hello-world' + + test.describe('direct URL navigation', () => { + test('navigating to UUID value matches UUID route', async ({ page }) => { + await page.goto(`/skip-on-parse-error/${UUID_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('navigating to numeric value matches Numeric route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${NUMERIC_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + + // Verify the param was parsed as a number + const paramType = page.getByTestId('param-type') + await expect(paramType).toHaveText('Type: number') + }) + + test('navigating to string value matches Catch-all route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${STRING_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + + test('navigating to another UUID matches UUID route', async ({ page }) => { + const anotherUuid = 'a1b2c3d4-e5f6-1234-89ab-cdef01234567' + await page.goto(`/skip-on-parse-error/${anotherUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + }) + + test('navigating to zero matches Numeric route', async ({ page }) => { + await page.goto('/skip-on-parse-error/0') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText('0') + }) + + test('navigating to negative number matches Catch-all (not valid integer parse)', async ({ + page, + }) => { + // Our numeric parser requires the string representation to match exactly + // -123 parses to -123, but "-123" !== "-123" check passes, so this should match numeric + await page.goto('/skip-on-parse-error/-123') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + }) + + test('navigating to float matches Catch-all route', async ({ page }) => { + // 123.45 won't match numeric because parseInt("123.45") === 123, and "123" !== "123.45" + await page.goto('/skip-on-parse-error/123.45') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + + test('navigating to UUID-like but invalid format matches Catch-all', async ({ + page, + }) => { + // Invalid UUID (wrong version digit) + const invalidUuid = '123e4567-e89b-9999-a456-426614174000' + await page.goto(`/skip-on-parse-error/${invalidUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + }) + + test.describe('client-side navigation via Link', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('clicking UUID link navigates to UUID route', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('clicking Numeric link navigates to Numeric route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-numeric') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + }) + + test('clicking String link navigates to Catch-all route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-string') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + }) + + test.describe('Link href generation', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('UUID link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${UUID_VALUE}`, + ) + }) + + test('Numeric link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-numeric') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${NUMERIC_VALUE}`, + ) + }) + + test('String link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-string') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${STRING_VALUE}`, + ) + }) + }) +}) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 1cfcc8aa53..653241e0f3 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -8,6 +8,7 @@ export const SEGMENT_TYPE_PARAM = 1 export const SEGMENT_TYPE_WILDCARD = 2 export const SEGMENT_TYPE_OPTIONAL_PARAM = 3 const SEGMENT_TYPE_INDEX = 4 +const SEGMENT_TYPE_PATHLESS = 5 // only used in matching to represent pathless routes that need to carry more information /** * All the kinds of segments that can be present in a route path. @@ -21,7 +22,10 @@ export type SegmentKind = /** * All the kinds of segments that can be present in the segment tree. */ -type ExtendedSegmentKind = SegmentKind | typeof SEGMENT_TYPE_INDEX +type ExtendedSegmentKind = + | SegmentKind + | typeof SEGMENT_TYPE_INDEX + | typeof SEGMENT_TYPE_PATHLESS const PARAM_W_CURLY_BRACES_RE = /^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/ // prefix{$paramName}suffix @@ -183,6 +187,8 @@ function parseSegments( const path = route.fullPath ?? route.from const length = path.length const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive + const parse = route.options?.params?.parse ?? null + const skipRouteOnParseError = !!route.options?.skipRouteOnParseError while (cursor < length) { const segment = parseSegment(path, cursor, data) let nextNode: AnySegmentNode @@ -241,12 +247,15 @@ function parseSegments( : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase() - const existingNode = node.dynamic?.find( - (s) => - s.caseSensitive === actuallyCaseSensitive && - s.prefix === prefix && - s.suffix === suffix, - ) + const existingNode = + (!parse || !skipRouteOnParseError) && + node.dynamic?.find( + (s) => + (!s.parse || !s.skipRouteOnParseError) && + s.caseSensitive === actuallyCaseSensitive && + s.prefix === prefix && + s.suffix === suffix, + ) if (existingNode) { nextNode = existingNode } else { @@ -280,12 +289,15 @@ function parseSegments( : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase() - const existingNode = node.optional?.find( - (s) => - s.caseSensitive === actuallyCaseSensitive && - s.prefix === prefix && - s.suffix === suffix, - ) + const existingNode = + (!parse || !skipRouteOnParseError) && + node.optional?.find( + (s) => + (!s.parse || !s.skipRouteOnParseError) && + s.caseSensitive === actuallyCaseSensitive && + s.prefix === prefix && + s.suffix === suffix, + ) if (existingNode) { nextNode = existingNode } else { @@ -336,8 +348,28 @@ function parseSegments( node = nextNode } - const isLeaf = (route.path || !route.children) && !route.isRoot + // create pathless node + if ( + parse && + skipRouteOnParseError && + route.children && + !route.isRoot && + route.id && + route.id.charCodeAt(route.id.lastIndexOf('/') + 1) === 95 /* '_' */ + ) { + const pathlessNode = createStaticNode( + route.fullPath ?? route.from, + ) + pathlessNode.kind = SEGMENT_TYPE_PATHLESS + pathlessNode.parent = node + depth++ + pathlessNode.depth = depth + node.pathless ??= [] + node.pathless.push(pathlessNode) + node = pathlessNode + } + const isLeaf = (route.path || !route.children) && !route.isRoot // create index node if (isLeaf && path.endsWith('/')) { const indexNode = createStaticNode( @@ -351,6 +383,9 @@ function parseSegments( node = indexNode } + node.parse = parse + node.skipRouteOnParseError = skipRouteOnParseError + // make node "matchable" if (isLeaf && !node.route) { node.route = route @@ -372,9 +407,33 @@ function parseSegments( } function sortDynamic( - a: { prefix?: string; suffix?: string; caseSensitive: boolean }, - b: { prefix?: string; suffix?: string; caseSensitive: boolean }, + a: { + prefix?: string + suffix?: string + caseSensitive: boolean + parse: null | ((params: Record) => any) + skipRouteOnParseError: boolean + }, + b: { + prefix?: string + suffix?: string + caseSensitive: boolean + parse: null | ((params: Record) => any) + skipRouteOnParseError: boolean + }, ) { + if ( + a.parse && + a.skipRouteOnParseError && + (!b.parse || !b.skipRouteOnParseError) + ) + return -1 + if ( + (!a.parse || !a.skipRouteOnParseError) && + b.parse && + b.skipRouteOnParseError + ) + return 1 if (a.prefix && b.prefix && a.prefix !== b.prefix) { if (a.prefix.startsWith(b.prefix)) return -1 if (b.prefix.startsWith(a.prefix)) return 1 @@ -396,6 +455,11 @@ function sortDynamic( } function sortTreeNodes(node: SegmentNode) { + if (node.pathless) { + for (const child of node.pathless) { + sortTreeNodes(child) + } + } if (node.static) { for (const child of node.static.values()) { sortTreeNodes(child) @@ -432,6 +496,7 @@ function createStaticNode( return { kind: SEGMENT_TYPE_PATHNAME, depth: 0, + pathless: null, index: null, static: null, staticInsensitive: null, @@ -441,6 +506,8 @@ function createStaticNode( route: null, fullPath, parent: null, + parse: null, + skipRouteOnParseError: false, } } @@ -461,6 +528,7 @@ function createDynamicNode( return { kind, depth: 0, + pathless: null, index: null, static: null, staticInsensitive: null, @@ -470,6 +538,8 @@ function createDynamicNode( route: null, fullPath, parent: null, + parse: null, + skipRouteOnParseError: false, caseSensitive, prefix, suffix, @@ -477,7 +547,10 @@ function createDynamicNode( } type StaticSegmentNode = SegmentNode & { - kind: typeof SEGMENT_TYPE_PATHNAME | typeof SEGMENT_TYPE_INDEX + kind: + | typeof SEGMENT_TYPE_PATHNAME + | typeof SEGMENT_TYPE_PATHLESS + | typeof SEGMENT_TYPE_INDEX } type DynamicSegmentNode = SegmentNode & { @@ -497,6 +570,8 @@ type AnySegmentNode = type SegmentNode = { kind: ExtendedSegmentKind + pathless: Array> | null + /** Exact index segment (highest priority) */ index: StaticSegmentNode | null @@ -524,15 +599,26 @@ type SegmentNode = { parent: AnySegmentNode | null depth: number + + /** route.options.params.parse function, set on the last node of the route */ + parse: null | ((params: Record) => any) + + /** If true, errors thrown during parsing will cause this route to be ignored as a match candidate */ + skipRouteOnParseError: boolean } type RouteLike = { + id?: string path?: string // relative path from the parent, children?: Array // child routes, parentRoute?: RouteLike // parent route, isRoot?: boolean options?: { + skipRouteOnParseError?: boolean caseSensitive?: boolean + params?: { + parse?: (params: Record) => any + } } } & // router tree @@ -623,6 +709,12 @@ type RouteMatch> = { route: T params: Record branch: ReadonlyArray + /** + * For routes with `skipRouteOnParseError`, this contains the already-parsed params + * from the parse function that was validated during matching. + * This allows `matchRoutesInternal` to avoid re-parsing these params. + */ + parsedParams?: Record } export function findRouteMatch< @@ -718,32 +810,75 @@ function findMatch( path: string, segmentTree: AnySegmentNode, fuzzy = false, -): { route: T; params: Record } | null { +): { + route: T + params: Record + parsedParams?: Record +} | null { const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null - const params = extractParams(path, parts, leaf) - if ('**' in leaf) params['**'] = leaf['**']! + // Check if this was a skipRouteOnParseError route that already ran parse + const routeHadSkipParseError = + 'skipRouteOnParseError' in leaf.node && + leaf.node.skipRouteOnParseError && + 'parse' in leaf.node && + leaf.node.parse + // If skipRouteOnParseError was used, leaf.params contains the PARSED params. + // Otherwise (e.g., fuzzy matching), leaf.params may contain raw string params like '**'. + const parsedParams = routeHadSkipParseError + ? 'params' in leaf + ? leaf.params + : undefined + : undefined + // extractParams needs to run from the beginning to get raw string params. + // For fuzzy matches, we need to preserve the '**' param that was computed. + const [params] = extractParams(path, parts, { + node: leaf.node, + skipped: leaf.skipped, + // Don't pass extract state - we want to extract from the beginning + // For non-skipRouteOnParseError routes, pass through params (e.g., fuzzy '**') + params: routeHadSkipParseError + ? undefined + : 'params' in leaf + ? leaf.params + : undefined, + }) const route = leaf.node.route! return { route, params, + parsedParams, } } +/** + * This function is "resumable": + * - the `leaf` input can contain `extract` and `params` properties from a previous `extractParams` call + * - the returned `state` can be passed back as `extract` in a future call to continue extracting params from where we left off + * + * Inputs are *not* mutated. + */ function extractParams( path: string, parts: Array, - leaf: { node: AnySegmentNode; skipped: number }, -) { + leaf: { + node: AnySegmentNode + skipped: number + extract?: { part: number; node: number; path: number } + params?: Record + }, +): [ + params: Record, + state: { part: number; node: number; path: number }, +] { const list = buildBranch(leaf.node) let nodeParts: Array | null = null const params: Record = {} - for ( - let partIndex = 0, nodeIndex = 0, pathIndex = 0; - nodeIndex < list.length; - partIndex++, nodeIndex++, pathIndex++ - ) { + let partIndex = leaf.extract?.part ?? 0 + let nodeIndex = leaf.extract?.node ?? 0 + let pathIndex = leaf.extract?.path ?? 0 + for (; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++) { const node = list[nodeIndex]! const part = parts[partIndex] const currentPathIndex = pathIndex @@ -798,7 +933,8 @@ function extractParams( break } } - return params + if (leaf.params) Object.assign(params, leaf.params) + return [params, { part: partIndex, node: nodeIndex, path: pathIndex }] } function buildRouteBranch(route: T) { @@ -836,6 +972,12 @@ type MatchStackFrame = { statics: number dynamics: number optionals: number + /** intermediary state for param extraction */ + extract?: { part: number; node: number; path: number } + /** intermediary params from param extraction */ + // TODO: I'm not sure, but I think we need both the raw strings for `interpolatePath` and the parsed values for the final match object + // I think they can still be accumulated (separately) in a single object (each) because `interpolatePath` returns the `usedParams` anyway + params?: Record } function getNodeMatch( @@ -880,8 +1022,15 @@ function getNodeMatch( while (stack.length) { const frame = stack.pop()! - // eslint-disable-next-line prefer-const - let { node, index, skipped, depth, statics, dynamics, optionals } = frame + const { node, index, skipped, depth, statics, dynamics, optionals } = frame + let { extract, params } = frame + + if (node.skipRouteOnParseError && node.parse) { + const result = validateMatchParams(path, parts, frame) + if (!result) continue + params = result[0] + extract = result[1] + } // In fuzzy mode, track the best partial match we've found so far if ( @@ -898,8 +1047,9 @@ function getNodeMatch( if (node.route && !pathIsIndex && isFrameMoreSpecific(bestMatch, frame)) { bestMatch = frame } - // beyond the length of the path parts, only index segments, or skipped optional segments, or wildcard segments can match - if (!node.optional && !node.wildcard && !node.index) continue + // beyond the length of the path parts, only index segments, skipped optional segments, wildcard segments, or pathless segments can match + if (!node.optional && !node.wildcard && !node.index && !node.pathless) + continue } const part = isBeyondPath ? undefined : parts[index]! @@ -915,6 +1065,12 @@ function getNodeMatch( statics, dynamics, optionals, + extract, + params, + } + if (node.index.skipRouteOnParseError && node.index.parse) { + const result = validateMatchParams(path, parts, indexFrame) + if (!result) continue } // perfect match, no need to continue // this is an optimization, algorithm should work correctly without this block @@ -946,7 +1102,7 @@ function getNodeMatch( } // the first wildcard match is the highest priority one // wildcard matches skip the stack because they cannot have children - wildcardMatch = { + const frame = { node: segment, index: partsLength, skipped, @@ -954,7 +1110,14 @@ function getNodeMatch( statics, dynamics, optionals, + extract, + params, } + if (segment.skipRouteOnParseError && segment.parse) { + const result = validateMatchParams(path, parts, frame) + if (!result) continue + } + wildcardMatch = frame break } } @@ -974,6 +1137,8 @@ function getNodeMatch( statics, dynamics, optionals, + extract, + params, }) // enqueue skipping the optional } if (!isBeyondPath) { @@ -995,6 +1160,8 @@ function getNodeMatch( statics, dynamics, optionals: optionals + 1, + extract, + params, }) } } @@ -1020,6 +1187,8 @@ function getNodeMatch( statics, dynamics: dynamics + 1, optionals, + extract, + params, }) } } @@ -1038,6 +1207,8 @@ function getNodeMatch( statics: statics + 1, dynamics, optionals, + extract, + params, }) } } @@ -1054,6 +1225,27 @@ function getNodeMatch( statics: statics + 1, dynamics, optionals, + extract, + params, + }) + } + } + + // 0. Try pathless match + if (node.pathless) { + const nextDepth = depth + 1 + for (let i = node.pathless.length - 1; i >= 0; i--) { + const segment = node.pathless[i]! + stack.push({ + node: segment, + index, + skipped, + depth: nextDepth, + statics, + dynamics, + optionals, + extract, + params, }) } } @@ -1075,16 +1267,31 @@ function getNodeMatch( sliceIndex += parts[i]!.length } const splat = sliceIndex === path.length ? '/' : path.slice(sliceIndex) - return { - node: bestFuzzy.node, - skipped: bestFuzzy.skipped, - '**': decodeURIComponent(splat), - } + bestFuzzy.params ??= {} + bestFuzzy.params['**'] = decodeURIComponent(splat) + return bestFuzzy } return null } +function validateMatchParams( + path: string, + parts: Array, + frame: MatchStackFrame, +) { + try { + const result = extractParams(path, parts, frame) + frame.params = result[0] + frame.extract = result[1] + result[0] = frame.node.parse!(result[0]) + frame.params = result[0] + return result + } catch { + return null + } +} + function isFrameMoreSpecific( // the stack frame previously saved as "best match" prev: MatchStackFrame | null, diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 53d726ef05..b87b657da6 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -1188,6 +1188,8 @@ export interface UpdatableRouteOptions< in out TBeforeLoadFn, > extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions { + /** If true, this route will be skipped during matching if a parse error occurs, and we'll look for another match */ + skipRouteOnParseError?: boolean // If true, this route will be matched as case-sensitive caseSensitive?: boolean // If true, this route will be forcefully wrapped in a suspense boundary diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 54da83a33e..3a2773ffd5 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -700,6 +700,12 @@ export type GetMatchRoutesFn = (pathname: string) => { matchedRoutes: ReadonlyArray routeParams: Record foundRoute: AnyRoute | undefined + parseError?: unknown + /** + * For routes with `skipRouteOnParseError`, this contains the already-parsed params + * from the parse function that was validated during matching. + */ + parsedParams?: Record } export type EmitFn = (routerEvent: RouterEvent) => void @@ -1248,7 +1254,7 @@ export class RouterCore< opts?: MatchRoutesOpts, ): Array { const matchedRoutesResult = this.getMatchedRoutes(next.pathname) - const { foundRoute, routeParams } = matchedRoutesResult + const { foundRoute, routeParams, parsedParams } = matchedRoutesResult let { matchedRoutes } = matchedRoutesResult let isGlobalNotFound = false @@ -1393,22 +1399,32 @@ export class RouterCore< route.options.params?.parse ?? route.options.parseParams if (strictParseParams) { - try { - Object.assign( - strictParams, - strictParseParams(strictParams as Record), - ) - } catch (err: any) { - if (isNotFound(err) || isRedirect(err)) { - paramsError = err - } else { - paramsError = new PathParamError(err.message, { - cause: err, - }) - } + // If this route used skipRouteOnParseError, the parse was already called + // during matching and the result is in parsedParams. Skip re-parsing. + const alreadyParsed = + route.options.skipRouteOnParseError && parsedParams - if (opts?.throwOnError) { - throw paramsError + if (alreadyParsed) { + // Use the pre-parsed params from the matching phase + Object.assign(strictParams, parsedParams) + } else { + try { + Object.assign( + strictParams, + strictParseParams(strictParams as Record), + ) + } catch (err: any) { + if (isNotFound(err) || isRedirect(err)) { + paramsError = err + } else { + paramsError = new PathParamError(err.message, { + cause: err, + }) + } + + if (opts?.throwOnError) { + throw paramsError + } } } } @@ -2692,15 +2708,17 @@ export function getMatchedRoutes({ const trimmedPath = trimPathRight(pathname) let foundRoute: TRouteLike | undefined = undefined + let parsedParams: Record | undefined = undefined const match = findRouteMatch(trimmedPath, processedTree, true) if (match) { foundRoute = match.route Object.assign(routeParams, match.params) // Copy params, because they're cached + parsedParams = match.parsedParams } const matchedRoutes = match?.branch || [routesById[rootRouteId]!] - return { matchedRoutes, routeParams, foundRoute } + return { matchedRoutes, routeParams, foundRoute, parsedParams } } function applySearchMiddleware({ diff --git a/packages/router-core/tests/new-process-route-tree.test.ts b/packages/router-core/tests/new-process-route-tree.test.ts index 47083567e2..9e724a70e2 100644 --- a/packages/router-core/tests/new-process-route-tree.test.ts +++ b/packages/router-core/tests/new-process-route-tree.test.ts @@ -863,6 +863,991 @@ describe('findRouteMatch', () => { }) }) }) + describe('pathless routes', () => { + it('builds segment tree correctly', () => { + const tree = { + path: '/', + isRoot: true, + id: '__root__', + fullPath: '/', + children: [ + { + path: '/', + id: '/', + fullPath: '/', + options: {}, + }, + { + id: '/$foo/_layout', + path: '$foo', + fullPath: '/$foo', + options: { + params: { parse: () => {} }, + skipRouteOnParseError: true, + }, + children: [ + { + id: '/$foo/_layout/bar', + path: 'bar', + fullPath: '/$foo/bar', + options: {}, + }, + { + id: '/$foo/_layout/', + path: '/', + fullPath: '/$foo/', + options: {}, + }, + ], + }, + { + id: '/$foo/hello', + path: '$foo/hello', + fullPath: '/$foo/hello', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + expect(processedTree.segmentTree).toMatchInlineSnapshot(` + { + "depth": 0, + "dynamic": [ + { + "caseSensitive": false, + "depth": 1, + "dynamic": null, + "fullPath": "/$foo", + "index": null, + "kind": 1, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": [ + { + "depth": 2, + "dynamic": null, + "fullPath": "/$foo", + "index": { + "depth": 3, + "dynamic": null, + "fullPath": "/$foo/", + "index": null, + "kind": 4, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/$foo/", + "id": "/$foo/_layout/", + "options": {}, + "path": "/", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + "kind": 5, + "optional": null, + "parent": [Circular], + "parse": [Function], + "pathless": null, + "route": { + "children": [ + { + "fullPath": "/$foo/bar", + "id": "/$foo/_layout/bar", + "options": {}, + "path": "bar", + }, + { + "fullPath": "/$foo/", + "id": "/$foo/_layout/", + "options": {}, + "path": "/", + }, + ], + "fullPath": "/$foo", + "id": "/$foo/_layout", + "options": { + "params": { + "parse": [Function], + }, + "skipRouteOnParseError": true, + }, + "path": "$foo", + }, + "skipRouteOnParseError": true, + "static": null, + "staticInsensitive": Map { + "bar" => { + "depth": 3, + "dynamic": null, + "fullPath": "/$foo/bar", + "index": null, + "kind": 0, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/$foo/bar", + "id": "/$foo/_layout/bar", + "options": {}, + "path": "bar", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + }, + "wildcard": null, + }, + ], + "prefix": undefined, + "route": null, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": Map { + "hello" => { + "depth": 2, + "dynamic": null, + "fullPath": "/$foo/hello", + "index": null, + "kind": 0, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/$foo/hello", + "id": "/$foo/hello", + "options": {}, + "path": "$foo/hello", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + }, + "suffix": undefined, + "wildcard": null, + }, + ], + "fullPath": "/", + "index": { + "depth": 1, + "dynamic": null, + "fullPath": "/", + "index": null, + "kind": 4, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/", + "id": "/", + "options": {}, + "path": "/", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + "kind": 0, + "optional": null, + "parent": null, + "parse": null, + "pathless": null, + "route": null, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + } + `) + }) + }) + + describe('skipRouteOnParseError', () => { + describe('basic matching with parse validation', () => { + it('matches route when parse succeeds', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => ({ + id: parseInt(params.id!, 10), + }), + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + // params contains raw string values for interpolatePath + expect(result?.params).toEqual({ id: '123' }) + // parsedParams contains the transformed values from parse + expect(result?.parsedParams).toEqual({ id: 123 }) + }) + + it('skips route when parse throws and finds no alternative', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/abc', processedTree) + expect(result).toBeNull() + }) + + it('skips route when parse throws and finds alternative match', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + // numeric should match the validated route + const numericResult = findRouteMatch('/123', processedTree) + expect(numericResult?.route.id).toBe('/$id') + // params contains raw string values for interpolatePath + expect(numericResult?.params).toEqual({ id: '123' }) + // parsedParams contains the transformed values from parse + expect(numericResult?.parsedParams).toEqual({ id: 123 }) + + // non-numeric should fall through to the non-validated route + const slugResult = findRouteMatch('/hello-world', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + expect(slugResult?.params).toEqual({ slug: 'hello-world' }) + }) + }) + + describe('priority: validated routes take precedence', () => { + it('validated dynamic route has priority over non-validated dynamic route', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + // validated route should be tried first + const numericResult = findRouteMatch('/123', processedTree) + expect(numericResult?.route.id).toBe('/$id') + }) + + it('static route still has priority over validated dynamic route', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/settings', + fullPath: '/settings', + path: 'settings', + options: {}, + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/settings', processedTree) + expect(result?.route.id).toBe('/settings') + }) + }) + + describe('regex-like validation patterns', () => { + it('uuid validation pattern', () => { + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: (params: Record) => { + if (!uuidRegex.test(params.uuid!)) + throw new Error('Not a UUID') + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const uuidResult = findRouteMatch( + '/550e8400-e29b-41d4-a716-446655440000', + processedTree, + ) + expect(uuidResult?.route.id).toBe('/$uuid') + + const slugResult = findRouteMatch('/my-blog-post', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + }) + + it('date validation pattern (YYYY-MM-DD)', () => { + const dateRegex = /^\d{4}-\d{2}-\d{2}$/ + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/posts/$date', + fullPath: '/posts/$date', + path: 'posts/$date', + options: { + params: { + parse: (params: Record) => { + if (!dateRegex.test(params.date!)) + throw new Error('Not a date') + return { date: new Date(params.date!) } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/posts/$slug', + fullPath: '/posts/$slug', + path: 'posts/$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const dateResult = findRouteMatch('/posts/2024-01-15', processedTree) + expect(dateResult?.route.id).toBe('/posts/$date') + // params contains raw string values for interpolatePath + expect(dateResult?.params.date).toBe('2024-01-15') + // parsedParams contains the transformed values from parse + expect(dateResult?.parsedParams?.date).toBeInstanceOf(Date) + + const slugResult = findRouteMatch('/posts/my-first-post', processedTree) + expect(slugResult?.route.id).toBe('/posts/$slug') + }) + }) + + describe('nested routes with skipRouteOnParseError', () => { + it('parent validation failure prevents child matching', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$orgId', + fullPath: '/$orgId', + path: '$orgId', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.orgId!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { orgId: num } + }, + }, + skipRouteOnParseError: true, + }, + children: [ + { + id: '/$orgId/settings', + fullPath: '/$orgId/settings', + path: 'settings', + options: {}, + }, + ], + }, + { + id: '/$slug/about', + fullPath: '/$slug/about', + path: '$slug/about', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // numeric org should match the validated route + const numericResult = findRouteMatch('/123/settings', processedTree) + expect(numericResult?.route.id).toBe('/$orgId/settings') + + // non-numeric should not match /$orgId/settings, should match /$slug/about + const slugResult = findRouteMatch('/my-org/about', processedTree) + expect(slugResult?.route.id).toBe('/$slug/about') + }) + + it('child validation failure falls back to sibling', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/users', + fullPath: '/users', + path: 'users', + options: {}, + children: [ + { + id: '/users/$userId', + fullPath: '/users/$userId', + path: '$userId', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.userId!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { userId: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/users/$username', + fullPath: '/users/$username', + path: '$username', + options: {}, + }, + ], + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const numericResult = findRouteMatch('/users/42', processedTree) + expect(numericResult?.route.id).toBe('/users/$userId') + // params contains raw string values for interpolatePath + expect(numericResult?.params).toEqual({ userId: '42' }) + // parsedParams contains the transformed values from parse + expect(numericResult?.parsedParams).toEqual({ userId: 42 }) + + const usernameResult = findRouteMatch('/users/johndoe', processedTree) + expect(usernameResult?.route.id).toBe('/users/$username') + // Non-validated route: params are raw strings, parsedParams is undefined + expect(usernameResult?.params).toEqual({ username: 'johndoe' }) + expect(usernameResult?.parsedParams).toBeUndefined() + }) + }) + + describe('pathless routes with skipRouteOnParseError', () => { + // TODO: This test documents expected behavior that is not yet implemented + // Pathless layouts with skipRouteOnParseError should gate their children + it('pathless layout with validation gates children', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/', + fullPath: '/', + path: '/', + options: {}, + }, + { + id: '/$foo/_layout', + fullPath: '/$foo', + path: '$foo', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.foo!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { foo: num } + }, + }, + skipRouteOnParseError: true, + }, + children: [ + { + id: '/$foo/_layout/bar', + fullPath: '/$foo/bar', + path: 'bar', + options: {}, + }, + { + id: '/$foo/_layout/', + fullPath: '/$foo/', + path: '/', + options: {}, + }, + ], + }, + { + id: '/$foo/hello', + fullPath: '/$foo/hello', + path: '$foo/hello', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // numeric foo should match through the validated layout + const numericBarResult = findRouteMatch('/123/bar', processedTree) + expect(numericBarResult?.route.id).toBe('/$foo/_layout/bar') + + const numericIndexResult = findRouteMatch('/123', processedTree) + expect(numericIndexResult?.route.id).toBe('/$foo/_layout/') + expect(numericIndexResult?.params).toEqual({ foo: 123 }) + + // non-numeric foo should fall through to the non-validated route + const helloResult = findRouteMatch('/abc/hello', processedTree) + expect(helloResult?.route.id).toBe('/$foo/hello') + expect(helloResult?.params).toEqual({ foo: 'abc' }) + }) + }) + + describe('optional params with skipRouteOnParseError', () => { + it('optional param with static fallback', () => { + // Optional param with validation, with a static fallback + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/{-$lang}/home', + fullPath: '/{-$lang}/home', + path: '{-$lang}/home', + options: { + params: { + parse: (params: Record) => { + const validLangs = ['en', 'es', 'fr', 'de'] + if (params.lang && !validLangs.includes(params.lang)) { + throw new Error('Invalid language') + } + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/home', + fullPath: '/home', + path: 'home', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // valid language should match the validated route + const enResult = findRouteMatch('/en/home', processedTree) + expect(enResult?.route.id).toBe('/{-$lang}/home') + expect(enResult?.parsedParams).toEqual({ lang: 'en' }) + + // root path + home - both routes can match + // The optional route (with skipped param) has greater depth, so it wins + // This is the expected behavior per the priority system + const rootResult = findRouteMatch('/home', processedTree) + expect(rootResult?.route.id).toBe('/{-$lang}/home') + + // invalid language should NOT match the validated optional route + // and since there's no dynamic fallback, it should return null + const invalidResult = findRouteMatch('/about/home', processedTree) + expect(invalidResult).toBeNull() + }) + + it('optional param at root with validation', () => { + // Optional param that validates and allows skipping + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/{-$lang}', + fullPath: '/{-$lang}', + path: '{-$lang}', + options: { + params: { + parse: (params: Record) => { + const validLangs = ['en', 'es', 'fr', 'de'] + if (params.lang && !validLangs.includes(params.lang)) { + throw new Error('Invalid language') + } + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // valid language should match + const enResult = findRouteMatch('/en', processedTree) + expect(enResult?.route.id).toBe('/{-$lang}') + expect(enResult?.parsedParams).toEqual({ lang: 'en' }) + + // root path should match (optional skipped) + const rootResult = findRouteMatch('/', processedTree) + expect(rootResult?.route.id).toBe('/{-$lang}') + expect(rootResult?.parsedParams).toEqual({}) + + // invalid language should NOT match (no fallback route) + const invalidResult = findRouteMatch('/about', processedTree) + expect(invalidResult).toBeNull() + }) + }) + + describe('wildcard routes with skipRouteOnParseError', () => { + it('wildcard with validation', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/files/$', + fullPath: '/files/$', + path: 'files/$', + options: { + params: { + parse: (params: Record) => { + if (!params._splat!.endsWith('.txt')) { + throw new Error('Only .txt files allowed') + } + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/files', + fullPath: '/files', + path: 'files', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // .txt file should match the validated wildcard route + const txtResult = findRouteMatch( + '/files/docs/readme.txt', + processedTree, + ) + expect(txtResult?.route.id).toBe('/files/$') + + // non-.txt should fall through (fuzzy match to /files) + const otherResult = findRouteMatch( + '/files/images/photo.jpg', + processedTree, + true, + ) + expect(otherResult?.route.id).toBe('/files') + }) + }) + + describe('multiple validated routes competing', () => { + it('first matching validated route wins', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: (params: Record) => { + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + if (!uuidRegex.test(params.uuid!)) + throw new Error('Not a UUID') + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$number', + fullPath: '/$number', + path: '$number', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.number!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { number: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const uuidResult = findRouteMatch( + '/550e8400-e29b-41d4-a716-446655440000', + processedTree, + ) + expect(uuidResult?.route.id).toBe('/$uuid') + + const numberResult = findRouteMatch('/42', processedTree) + expect(numberResult?.route.id).toBe('/$number') + // params contains raw string values for interpolatePath + expect(numberResult?.params).toEqual({ number: '42' }) + // parsedParams contains the transformed values from parse + expect(numberResult?.parsedParams).toEqual({ number: 42 }) + + const slugResult = findRouteMatch('/hello-world', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + }) + }) + + describe('params.parse without skipRouteOnParseError', () => { + it('params.parse is NOT called during matching when skipRouteOnParseError is false', () => { + let parseCalled = false + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + parseCalled = true + return { id: parseInt(params.id!, 10) } + }, + }, + // skipRouteOnParseError is NOT set + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + // parse should NOT be called during matching + expect(parseCalled).toBe(false) + // params should be raw strings + expect(result?.params).toEqual({ id: '123' }) + }) + }) + + describe('edge cases', () => { + it('empty param value still goes through validation', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/prefix{$id}suffix', + fullPath: '/prefix{$id}suffix', + path: 'prefix{$id}suffix', + options: { + params: { + parse: (params: Record) => { + if (params.id === '') throw new Error('Empty not allowed') + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/prefixsuffix', + fullPath: '/prefixsuffix', + path: 'prefixsuffix', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // with value should match validated route + const withValue = findRouteMatch('/prefixFOOsuffix', processedTree) + expect(withValue?.route.id).toBe('/prefix{$id}suffix') + + // empty value should fall through to static route + const empty = findRouteMatch('/prefixsuffix', processedTree) + expect(empty?.route.id).toBe('/prefixsuffix') + }) + + it('validation error type does not matter', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: () => { + throw 'string error' // not an Error object + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$fallback', + fullPath: '/$fallback', + path: '$fallback', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/test', processedTree) + expect(result?.route.id).toBe('/$fallback') + }) + }) + }) }) describe('processRouteMasks', { sequential: true }, () => {