From e159822337010bbc103d9d6f9b6e25adbf99f33c Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 15 Feb 2026 01:20:30 +0100 Subject: [PATCH 1/6] matches types --- packages/router-core/src/fileRoute.ts | 6 +- packages/router-core/src/load-matches.ts | 6 +- packages/router-core/src/route.ts | 114 +++++++-- packages/router-core/src/ssr/ssr-client.ts | 4 +- .../tests/head-matches-typing.test-d.ts | 230 ++++++++++++++++++ 5 files changed, 334 insertions(+), 26 deletions(-) create mode 100644 packages/router-core/tests/head-matches-typing.test-d.ts diff --git a/packages/router-core/src/fileRoute.ts b/packages/router-core/src/fileRoute.ts index 90b47ab643..d49884d205 100644 --- a/packages/router-core/src/fileRoute.ts +++ b/packages/router-core/src/fileRoute.ts @@ -78,7 +78,8 @@ export interface FileRouteOptions< TLoaderDeps, AnyContext, TRouteContextFn, - TBeforeLoadFn + TBeforeLoadFn, + TRegister > {} export type CreateFileRoute< @@ -148,7 +149,8 @@ export type LazyRouteOptions = Pick< AnyContext, AnyContext, AnyContext, - AnyContext + AnyContext, + Register >, 'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent' > diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index 838d77e9d3..16a94176b5 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -584,9 +584,9 @@ const executeHead = ( } return Promise.all([ - route.options.head?.(assetContext), - route.options.scripts?.(assetContext), - route.options.headers?.(assetContext), + route.options.head?.(assetContext as any), + route.options.scripts?.(assetContext as any), + route.options.headers?.(assetContext as any), ]).then(([headFnContent, scripts, headers]) => { const meta = headFnContent?.meta const links = headFnContent?.links diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 243e93c989..156ba99e99 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -693,7 +693,8 @@ export interface Route< TLoaderDeps, TRouterContext, TRouteContextFn, - TBeforeLoadFn + TBeforeLoadFn, + TRegister >, ) => this lazy: RouteLazyFn< @@ -854,7 +855,8 @@ export type RouteOptions< NoInfer, NoInfer, NoInfer, - NoInfer + NoInfer, + NoInfer > export type RouteContextFn< @@ -1140,6 +1142,7 @@ export interface BeforeLoadContextOptions< } type AssetFnContextOptions< + in out TRegister, in out TRouteId, in out TFullPath, in out TParentRoute extends AnyRoute, @@ -1154,22 +1157,7 @@ type AssetFnContextOptions< ssr?: { nonce?: string } - matches: Array< - RouteMatch< - TRouteId, - TFullPath, - ResolveAllParamsFromParent, - ResolveFullSearchSchema, - ResolveLoaderData, - ResolveAllContext< - TParentRoute, - TRouterContext, - TRouteContextFn, - TBeforeLoadFn - >, - TLoaderDeps - > - > + matches: InferAssetFnMatches match: RouteMatch< TRouteId, TFullPath, @@ -1188,6 +1176,89 @@ type AssetFnContextOptions< loaderData?: ResolveLoaderData } +type RegisteredRouterRouteTree = + RegisteredRouter extends { + routeTree: infer TRouteTree + } + ? TRouteTree extends AnyRoute + ? TRouteTree + : AnyRoute + : AnyRoute + +/** + * Look up a route by ID from a union of parsed routes. + */ +type LookupRoute = Extract< + TAllRoutes, + { types: { id: TId } } +> + +/** + * Build a tuple of ancestor matches from a route up to the root. + * Walks via parentRoute['types']['id'] and resolves each ancestor + * from the concrete ParseRoute union (not the pre-addChildren ref). + * + * Result: [RootMatch, ..., ParentMatch, SelfMatch] + */ +type BuildAncestorTuple< + TAllRoutes extends AnyRoute, + TRoute extends AnyRoute, +> = TRoute['types']['id'] extends RootRouteId + ? [MakeRouteMatchFromRoute] + : TRoute['types']['parentRoute'] extends infer TParent extends AnyRoute + ? TParent['types']['id'] extends infer TParentId extends string + ? LookupRoute extends infer TConcreteParent extends + AnyRoute + ? [ + ...BuildAncestorTuple, + MakeRouteMatchFromRoute, + ] + : [MakeRouteMatchFromRoute] + : [MakeRouteMatchFromRoute] + : [MakeRouteMatchFromRoute] + +/** + * Check if TDescendantId is a direct or indirect child of TRouteId. + */ +type IsDescendant< + TRouteId extends string, + TDescendantId extends string, +> = TDescendantId extends `${TRouteId}/${string}` + ? true + : TRouteId extends RootRouteId + ? TDescendantId extends RootRouteId + ? false + : true + : false + +/** + * From a union of all routes, extract those that are descendants of TRouteId + * (not including the route itself), and produce a match for each. + */ +type DescendantMatchesUnion< + TAllRoutes extends AnyRoute, + TRouteId extends string, +> = TAllRoutes extends any + ? IsDescendant extends true + ? MakeRouteMatchFromRoute + : never + : never + +export type InferAssetFnMatches = + RegisteredRouterRouteTree extends infer TTree extends AnyRoute + ? TRouteId extends string + ? ParseRoute extends infer TAllRoutes extends AnyRoute + ? LookupRoute extends infer TRoute extends + AnyRoute + ? [ + ...BuildAncestorTuple, + ...Array>, + ] + : never + : never + : never + : never + export interface DefaultUpdatableRouteOptionsExtensions { component?: unknown errorComponent?: unknown @@ -1208,6 +1279,7 @@ export interface UpdatableRouteOptions< in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, + in out TRegister = Register, > extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions { /** @@ -1333,6 +1405,7 @@ export interface UpdatableRouteOptions< ) => void headers?: ( ctx: AssetFnContextOptions< + TRegister, TRouteId, TFullPath, TParentRoute, @@ -1347,6 +1420,7 @@ export interface UpdatableRouteOptions< ) => Awaitable | undefined> head?: ( ctx: AssetFnContextOptions< + TRegister, TRouteId, TFullPath, TParentRoute, @@ -1366,6 +1440,7 @@ export interface UpdatableRouteOptions< }> scripts?: ( ctx: AssetFnContextOptions< + TRegister, TRouteId, TFullPath, TParentRoute, @@ -1894,7 +1969,8 @@ export class BaseRoute< TLoaderDeps, TRouterContext, TRouteContextFn, - TBeforeLoadFn + TBeforeLoadFn, + TRegister >, ): this => { Object.assign(this.options, options) diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index ce314c85f7..42bae1def2 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -195,9 +195,9 @@ export async function hydrate(router: AnyRouter): Promise { params: match.params, loaderData: match.loaderData, } - const headFnContent = await route.options.head?.(assetContext) + const headFnContent = await route.options.head?.(assetContext as any) - const scripts = await route.options.scripts?.(assetContext) + const scripts = await route.options.scripts?.(assetContext as any) match.meta = headFnContent?.meta match.links = headFnContent?.links diff --git a/packages/router-core/tests/head-matches-typing.test-d.ts b/packages/router-core/tests/head-matches-typing.test-d.ts new file mode 100644 index 0000000000..c6ad21f43d --- /dev/null +++ b/packages/router-core/tests/head-matches-typing.test-d.ts @@ -0,0 +1,230 @@ +import { describe, expectTypeOf, test } from 'vitest' + +import type { + AnyRoute, + AnyRouter, + MakeRouteMatchFromRoute, + UpdatableRouteOptions, + RouteMatch, +} from '../src' +import type { InferAssetFnMatches } from '../src/route' +import { BaseRootRoute, BaseRoute, rootRouteId } from '../src' + +type TestRegister = { + router: { routeTree: TRouteTree } +} + +type HeadCtxFor = Parameters< + NonNullable< + UpdatableRouteOptions< + TRoute['types']['parentRoute'], + TRoute['types']['id'], + TRoute['types']['fullPath'], + TRoute['types']['params'], + TRoute['types']['searchValidator'], + NonNullable, + TRoute['types']['loaderDeps'], + TRoute['types']['routerContext'], + TRoute['types']['routeContextFn'], + TRoute['types']['beforeLoadFn'], + TRegister + >['head'] + > +>[0] + +const rootRoute = new BaseRootRoute({ + loader: () => ({ + root: 'root', + }), +}) + +const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => ({ + foo: 123, + }), + head: () => ({}), +}) + +const barRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/bar', + loader: () => ({ + bar: true, + }), + head: () => ({}), +}) + +const bazRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/baz', + loader: () => ({ + baz: true, + }), + head: () => ({}), +}) + +const helloRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hello', + loader: () => ({ + hello: 'hello', + }), + head: () => ({}), +}) + +const worldRoute = new BaseRoute({ + getParentRoute: () => helloRoute, + path: '/world', + loader: () => ({ + world: 1, + }), + head: () => ({}), +}) + +const xyzRoute = new BaseRoute({ + getParentRoute: () => helloRoute, + path: '/xyz', + loader: () => ({ + xyz: 1, + }), + head: () => ({}), +}) + +const routeTree = rootRoute.addChildren([ + fooRoute.addChildren({ + barRoute, + bazRoute, + }), + helloRoute.addChildren([worldRoute, xyzRoute]), +]) + +type RegisterWithTestRouteTree = TestRegister + +type IsAny = 0 extends 1 & T ? true : false + +describe('Route head matches typing', () => { + test('InferAssetFnMatches resolves concrete route types, not any', () => { + type Matches = InferAssetFnMatches + + // With tuple typing, matches[0] should be the root match specifically + type FirstElement = Matches[0] + type RouteIdOfFirst = FirstElement['routeId'] + + // routeId should not be any + expectTypeOf>().toEqualTypeOf() + + // routeId of first element should be exactly the root route ID + expectTypeOf().toEqualTypeOf() + }) + + test('foo head matches: positional tuple [root, foo, ...descendants[]]', () => { + type FooHeadCtx = HeadCtxFor + type FooMatches = FooHeadCtx['matches'] + + // matches should not be any or unknown + expectTypeOf().not.toBeAny() + expectTypeOf().not.toBeUnknown() + + // Position 0: root match + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf<'/'>() + // loaderData is optional on RouteMatch, so it's TLoaderData | undefined + expectTypeOf>().toEqualTypeOf<{ + root: string + }>() + + // Position 1: foo match (self) + expectTypeOf().toEqualTypeOf<'/foo'>() + expectTypeOf().toEqualTypeOf<'/foo'>() + expectTypeOf>().toEqualTypeOf<{ + foo: number + }>() + + // Position 2+: descendants (bar | baz union) + type DescendantRouteIds = NonNullable['routeId'] + expectTypeOf<'/foo/bar'>().toMatchTypeOf() + expectTypeOf<'/foo/baz'>().toMatchTypeOf() + + // Descendants should NOT include unrelated routes + type HelloExtendsDescendants = '/hello' extends DescendantRouteIds + ? true + : false + expectTypeOf().toEqualTypeOf() + }) + + test('hello head matches: positional tuple [root, hello, ...descendants[]]', () => { + type HelloHeadCtx = HeadCtxFor + type HelloMatches = HelloHeadCtx['matches'] + + // Not any or unknown + expectTypeOf().not.toBeAny() + expectTypeOf().not.toBeUnknown() + + // Position 0: root match + expectTypeOf().toEqualTypeOf< + typeof rootRouteId + >() + expectTypeOf().toEqualTypeOf<'/'>() + + // Position 1: hello match (self) + expectTypeOf().toEqualTypeOf<'/hello'>() + expectTypeOf().toEqualTypeOf<'/hello'>() + expectTypeOf>().toEqualTypeOf<{ + hello: string + }>() + + // Position 2+: descendants (world | xyz union) + type DescendantRouteIds = NonNullable['routeId'] + expectTypeOf<'/hello/world'>().toMatchTypeOf() + expectTypeOf<'/hello/xyz'>().toMatchTypeOf() + + // Descendants should NOT include unrelated routes + type FooExtendsDescendants = '/foo' extends DescendantRouteIds + ? true + : false + expectTypeOf().toEqualTypeOf() + }) + + test('bar head matches: positional tuple [root, foo, bar] with no descendants', () => { + type BarHeadCtx = HeadCtxFor + type BarMatches = BarHeadCtx['matches'] + + expectTypeOf().not.toBeAny() + + // Position 0: root + expectTypeOf().toEqualTypeOf() + + // Position 1: foo (parent) + expectTypeOf().toEqualTypeOf<'/foo'>() + + // Position 2: bar (self) + expectTypeOf().toEqualTypeOf<'/foo/bar'>() + expectTypeOf>().toEqualTypeOf<{ + bar: boolean + }>() + }) + + test('root head matches: positional tuple [root, ...all descendants[]]', () => { + type RootHeadCtx = HeadCtxFor + type RootMatches = RootHeadCtx['matches'] + + expectTypeOf().not.toBeAny() + + // Position 0: root (self) + expectTypeOf().toEqualTypeOf< + typeof rootRouteId + >() + expectTypeOf>().toEqualTypeOf<{ + root: string + }>() + + // Position 1+: all other routes as descendants + type DescendantRouteIds = NonNullable['routeId'] + expectTypeOf<'/foo'>().toMatchTypeOf() + expectTypeOf<'/foo/bar'>().toMatchTypeOf() + expectTypeOf<'/hello'>().toMatchTypeOf() + expectTypeOf<'/hello/world'>().toMatchTypeOf() + }) +}) From ea06c6b93d5dea4adeef7371c0d082d35298b99f Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 15 Feb 2026 01:20:35 +0100 Subject: [PATCH 2/6] type perf --- packages/router-core/src/route.ts | 103 ++++++++++++++++++++---------- 1 file changed, 68 insertions(+), 35 deletions(-) diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 156ba99e99..588a82db40 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -1186,36 +1186,51 @@ type RegisteredRouterRouteTree = : AnyRoute /** - * Look up a route by ID from a union of parsed routes. + * Extract the ancestor ID tuple from a route ID string by splitting on '/'. + * + * For '/foo/bar/baz' → ['__root__', '/foo', '/foo/bar', '/foo/bar/baz'] + * For '__root__' → ['__root__'] + * + * This is O(D) string-only manipulation — no union operations. */ -type LookupRoute = Extract< - TAllRoutes, - { types: { id: TId } } -> +type AncestorIdTuple = TRouteId extends RootRouteId + ? [RootRouteId] + : [RootRouteId, ...BuildIdTupleFromSegments>] + +type StripLeadingSlash = T extends `/${infer R}` ? R : T /** - * Build a tuple of ancestor matches from a route up to the root. - * Walks via parentRoute['types']['id'] and resolves each ancestor - * from the concrete ParseRoute union (not the pre-addChildren ref). - * - * Result: [RootMatch, ..., ParentMatch, SelfMatch] + * Given 'foo/bar/baz' and prefix '', build ['/foo', '/foo/bar', '/foo/bar/baz']. + * Recursion depth = number of path segments (typically ≤ 8). */ -type BuildAncestorTuple< - TAllRoutes extends AnyRoute, - TRoute extends AnyRoute, -> = TRoute['types']['id'] extends RootRouteId - ? [MakeRouteMatchFromRoute] - : TRoute['types']['parentRoute'] extends infer TParent extends AnyRoute - ? TParent['types']['id'] extends infer TParentId extends string - ? LookupRoute extends infer TConcreteParent extends - AnyRoute - ? [ - ...BuildAncestorTuple, - MakeRouteMatchFromRoute, - ] - : [MakeRouteMatchFromRoute] - : [MakeRouteMatchFromRoute] - : [MakeRouteMatchFromRoute] +type BuildIdTupleFromSegments< + TSegments extends string, + TPrefix extends string = '', +> = TSegments extends `${infer THead}/${infer TRest}` + ? [ + `${TPrefix}/${THead}`, + ...BuildIdTupleFromSegments, + ] + : TSegments extends '' + ? [] + : [`${TPrefix}/${TSegments}`] + +/** + * Map a tuple of route IDs to a tuple of route matches. + * Uses RouteById for O(1) cached lookups per ID (via the RoutesById mapped type). + */ +type MapIdTupleToMatches< + TRouteTree extends AnyRoute, + TIds extends Array, +> = TIds extends [ + infer TFirst extends string, + ...infer TRest extends Array, +] + ? [ + MakeRouteMatchFromRoute>, + ...MapIdTupleToMatches, + ] + : [] /** * Check if TDescendantId is a direct or indirect child of TRouteId. @@ -1244,18 +1259,36 @@ type DescendantMatchesUnion< : never : never +/** + * Infer the concrete matches tuple for a route's head/scripts/headers callbacks. + * + * Produces: [...AncestorMatches, SelfMatch, ...DescendantMatch[]] + * + * Performance: Ancestor tuple is built by string-splitting the route ID (O(D)) + * then looking up each ancestor via RouteById (O(1) cached mapped-type access). + * Descendants use a single O(N) distributive pass over ParseRoute. + * Total cost per route: O(D + N), where D = nesting depth, N = total routes. + * + * Note on lazy evaluation: UpdatableRouteOptions uses `in out` variance on + * TRegister, which forces TypeScript to fully evaluate InferAssetFnMatches + * for every route — even those without head/scripts/headers. True lazy + * evaluation would require removing TRegister from the variance contract + * or restructuring the API, which is out of scope for this change. + */ export type InferAssetFnMatches = RegisteredRouterRouteTree extends infer TTree extends AnyRoute ? TRouteId extends string - ? ParseRoute extends infer TAllRoutes extends AnyRoute - ? LookupRoute extends infer TRoute extends - AnyRoute - ? [ - ...BuildAncestorTuple, - ...Array>, - ] - : never - : never + ? [ + ...MapIdTupleToMatches>, + ...Array< + DescendantMatchesUnion< + ParseRoute extends infer TAllRoutes extends AnyRoute + ? TAllRoutes + : never, + TRouteId + > + >, + ] : never : never From 97c1942fad3b80398ef2c577f878216af88df590 Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 15 Feb 2026 01:27:28 +0100 Subject: [PATCH 3/6] type perf --- packages/router-core/src/route.ts | 48 ++++++++++++------------------- 1 file changed, 19 insertions(+), 29 deletions(-) diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 588a82db40..36b74c5030 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -1233,30 +1233,23 @@ type MapIdTupleToMatches< : [] /** - * Check if TDescendantId is a direct or indirect child of TRouteId. + * Compute descendant route IDs from the route ID union. + * + * This distributes over a string union (RouteIds) instead of a route-object union, + * which is typically cheaper for the type checker. */ -type IsDescendant< +type DescendantRouteIds< + TRouteTree extends AnyRoute, TRouteId extends string, - TDescendantId extends string, -> = TDescendantId extends `${TRouteId}/${string}` - ? true - : TRouteId extends RootRouteId - ? TDescendantId extends RootRouteId - ? false - : true - : false +> = TRouteId extends RootRouteId + ? Exclude, RootRouteId> + : Extract, `${TRouteId}/${string}`> -/** - * From a union of all routes, extract those that are descendants of TRouteId - * (not including the route itself), and produce a match for each. - */ -type DescendantMatchesUnion< - TAllRoutes extends AnyRoute, - TRouteId extends string, -> = TAllRoutes extends any - ? IsDescendant extends true - ? MakeRouteMatchFromRoute - : never +type DescendantMatchesById< + TRouteTree extends AnyRoute, + TIds, +> = TIds extends string + ? MakeRouteMatchFromRoute> : never /** @@ -1266,8 +1259,10 @@ type DescendantMatchesUnion< * * Performance: Ancestor tuple is built by string-splitting the route ID (O(D)) * then looking up each ancestor via RouteById (O(1) cached mapped-type access). - * Descendants use a single O(N) distributive pass over ParseRoute. - * Total cost per route: O(D + N), where D = nesting depth, N = total routes. + * Descendants distribute over RouteIds (string union) and map IDs to matches via + * RouteById (cached mapped-type access). + * Total cost per route: O(D + Nd), where D = nesting depth, Nd = number of + * descendant IDs in the route tree. * * Note on lazy evaluation: UpdatableRouteOptions uses `in out` variance on * TRegister, which forces TypeScript to fully evaluate InferAssetFnMatches @@ -1281,12 +1276,7 @@ export type InferAssetFnMatches = ? [ ...MapIdTupleToMatches>, ...Array< - DescendantMatchesUnion< - ParseRoute extends infer TAllRoutes extends AnyRoute - ? TAllRoutes - : never, - TRouteId - > + DescendantMatchesById> >, ] : never From 6eb9406a2b2f9112b7c3d7831dcf143f1c8b9179 Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 15 Feb 2026 01:48:55 +0100 Subject: [PATCH 4/6] type perf --- packages/router-core/src/route.ts | 57 ++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 36b74c5030..d8d3d2a32c 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -16,7 +16,13 @@ import type { RouteMatch, } from './Matches' import type { RootRouteId } from './root' -import type { ParseRoute, RouteById, RouteIds, RoutePaths } from './routeInfo' +import type { + ParseRoute, + RouteById, + RouteIds, + RoutePaths, + RoutesById, +} from './routeInfo' import type { AnyRouter, Register, RegisteredRouter, SSROption } from './router' import type { BuildLocationFn, NavigateFn } from './RouterProvider' import type { @@ -1215,20 +1221,29 @@ type BuildIdTupleFromSegments< ? [] : [`${TPrefix}/${TSegments}`] +type RoutesByIdFor = RoutesById + +type RouteIdsFor = RouteIds + +type RouteByIdFrom = Extract< + TRoutesById[TId & keyof TRoutesById], + AnyRoute +> + /** * Map a tuple of route IDs to a tuple of route matches. - * Uses RouteById for O(1) cached lookups per ID (via the RoutesById mapped type). + * Uses RoutesById for O(1) cached lookups per ID. */ type MapIdTupleToMatches< - TRouteTree extends AnyRoute, + TRoutesById, TIds extends Array, > = TIds extends [ infer TFirst extends string, ...infer TRest extends Array, ] ? [ - MakeRouteMatchFromRoute>, - ...MapIdTupleToMatches, + MakeRouteMatchFromRoute>, + ...MapIdTupleToMatches, ] : [] @@ -1239,17 +1254,14 @@ type MapIdTupleToMatches< * which is typically cheaper for the type checker. */ type DescendantRouteIds< - TRouteTree extends AnyRoute, + TAllRouteIds, TRouteId extends string, > = TRouteId extends RootRouteId - ? Exclude, RootRouteId> - : Extract, `${TRouteId}/${string}`> + ? Exclude + : Extract -type DescendantMatchesById< - TRouteTree extends AnyRoute, - TIds, -> = TIds extends string - ? MakeRouteMatchFromRoute> +type DescendantMatchesById = TIds extends string + ? MakeRouteMatchFromRoute> : never /** @@ -1273,12 +1285,19 @@ type DescendantMatchesById< export type InferAssetFnMatches = RegisteredRouterRouteTree extends infer TTree extends AnyRoute ? TRouteId extends string - ? [ - ...MapIdTupleToMatches>, - ...Array< - DescendantMatchesById> - >, - ] + ? RoutesByIdFor extends infer TRoutesById + ? RouteIdsFor extends infer TAllRouteIds + ? [ + ...MapIdTupleToMatches>, + ...Array< + DescendantMatchesById< + TRoutesById, + DescendantRouteIds + > + >, + ] + : never + : never : never : never From 95fd932408ec1e7d479848aa98381fb4d5b0dd0a Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 15 Feb 2026 02:00:53 +0100 Subject: [PATCH 5/6] type perf --- packages/router-core/src/route.ts | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index d8d3d2a32c..dd78cea381 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -1230,20 +1230,26 @@ type RouteByIdFrom = Extract< AnyRoute > +type RouteMatchByIdFor = { + [K in keyof TRoutesById]: MakeRouteMatchFromRoute< + RouteByIdFrom + > +} + /** * Map a tuple of route IDs to a tuple of route matches. * Uses RoutesById for O(1) cached lookups per ID. */ type MapIdTupleToMatches< - TRoutesById, + TRouteMatchById, TIds extends Array, > = TIds extends [ infer TFirst extends string, ...infer TRest extends Array, ] ? [ - MakeRouteMatchFromRoute>, - ...MapIdTupleToMatches, + TRouteMatchById[TFirst & keyof TRouteMatchById], + ...MapIdTupleToMatches, ] : [] @@ -1261,9 +1267,17 @@ type DescendantRouteIds< : Extract type DescendantMatchesById = TIds extends string - ? MakeRouteMatchFromRoute> + ? RouteMatchByIdFor[TIds & keyof RouteMatchByIdFor] : never +type DescendantIdsByRouteId = { + [K in RouteIdsFor]: DescendantRouteIds +} + +type AncestorIdTupleByRouteId = { + [K in RouteIdsFor]: AncestorIdTuple +} + /** * Infer the concrete matches tuple for a route's head/scripts/headers callbacks. * @@ -1288,11 +1302,16 @@ export type InferAssetFnMatches = ? RoutesByIdFor extends infer TRoutesById ? RouteIdsFor extends infer TAllRouteIds ? [ - ...MapIdTupleToMatches>, + ...MapIdTupleToMatches< + RouteMatchByIdFor, + AncestorIdTupleByRouteId[TRouteId & + keyof AncestorIdTupleByRouteId] + >, ...Array< DescendantMatchesById< TRoutesById, - DescendantRouteIds + DescendantIdsByRouteId[TRouteId & + keyof DescendantIdsByRouteId] > >, ] From 9c8ccf23e5b2e1e69dea791c2de81e405e45450f Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 15 Feb 2026 02:03:12 +0100 Subject: [PATCH 6/6] generate nested structure --- .../large-file-based/src/createRoutes.mjs | 64 +++++++++++++++++++ .../large-file-based/src/routes/absolute.tsx | 6 ++ .../large-file-based/src/routes/index.tsx | 6 ++ .../large-file-based/src/routes/linkProps.tsx | 6 ++ .../src/routes/params/$paramsPlaceholder.tsx | 6 ++ .../src/routes/params/route.tsx | 6 ++ .../large-file-based/src/routes/relative.tsx | 6 ++ .../src/routes/search/route.tsx | 6 ++ .../src/routes/search/searchPlaceholder.tsx | 6 ++ 9 files changed, 112 insertions(+) diff --git a/examples/react/large-file-based/src/createRoutes.mjs b/examples/react/large-file-based/src/createRoutes.mjs index c86294b699..816bd79686 100644 --- a/examples/react/large-file-based/src/createRoutes.mjs +++ b/examples/react/large-file-based/src/createRoutes.mjs @@ -2,6 +2,7 @@ import { readFile, writeFile, mkdir } from 'fs/promises' import { existsSync } from 'fs' const length = 100 +const nestedDepth = 3 const main = async () => { const absolute = (await readFile('./src/routes/absolute.tsx')).toString() @@ -34,6 +35,34 @@ const main = async () => { await writeFile('./src/routes/(gen)/search/route.tsx', searchRoute) await writeFile('./src/routes/(gen)/params/route.tsx', paramsRoute) + const nestedRouteTemplate = (path, label, depthIndex) => { + const depthAccess = Array.from({ length: depthIndex + 1 }, (_, index) => + index === 0 ? 'matches[0].routeId' : `matches[${index}]?.routeId`, + ).join(' && ') + + return `import { createFileRoute } from '@tanstack/react-router' +import * as React from 'react' + +export const Route = createFileRoute('${path}')({ + component: ${label}Component, + head: ({ matches }) => { + if (${depthAccess}) { + // ... + } + return {} + }, +}) + +function ${label}Component() { + return ( +
+

${label}

+
+ ) +} +` + } + for (let y = 0; y < length; y = y + 1) { const replacedAbsolute = absolute.replaceAll('/absolute', `/absolute${y}`) const replacedRelative = relative.replaceAll('/relative', `/relative${y}`) @@ -43,6 +72,41 @@ const main = async () => { await writeFile(`./src/routes/(gen)/relative${y}.tsx`, replacedRelative) await writeFile(`./src/routes/(gen)/search/search${y}.tsx`, replacedSearch) await writeFile(`./src/routes/(gen)/params/$param${y}.tsx`, replacedParams) + + const nestedBasePath = `./src/routes/(gen)/nested${y}` + if (!existsSync(nestedBasePath)) { + await mkdir(nestedBasePath) + } + + let currentPath = `/nested${y}` + let currentDir = nestedBasePath + + for (let depth = 0; depth < nestedDepth; depth = depth + 1) { + const label = `Nested${y}Level${depth + 1}` + const segment = `level${depth + 1}` + const routePath = currentPath + + await writeFile( + `${currentDir}/route.tsx`, + nestedRouteTemplate(routePath, label, depth + 1), + ) + + currentPath = `${currentPath}/${segment}` + currentDir = `${currentDir}/${segment}` + + if (!existsSync(currentDir)) { + await mkdir(currentDir) + } + } + + await writeFile( + `${currentDir}/leaf.tsx`, + nestedRouteTemplate( + `${currentPath}/leaf`, + `Nested${y}Leaf`, + nestedDepth + 1, + ), + ) } } diff --git a/examples/react/large-file-based/src/routes/absolute.tsx b/examples/react/large-file-based/src/routes/absolute.tsx index 0dc5578842..00c111af46 100644 --- a/examples/react/large-file-based/src/routes/absolute.tsx +++ b/examples/react/large-file-based/src/routes/absolute.tsx @@ -4,6 +4,12 @@ import { Link } from '@tanstack/react-router' export const Route = createFileRoute('/absolute')({ component: AbsoluteComponent, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function AbsoluteComponent() { diff --git a/examples/react/large-file-based/src/routes/index.tsx b/examples/react/large-file-based/src/routes/index.tsx index 0a5b7572ba..b9ecb0fc52 100644 --- a/examples/react/large-file-based/src/routes/index.tsx +++ b/examples/react/large-file-based/src/routes/index.tsx @@ -3,6 +3,12 @@ import * as React from 'react' export const Route = createFileRoute('/')({ component: Home, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function Home() { diff --git a/examples/react/large-file-based/src/routes/linkProps.tsx b/examples/react/large-file-based/src/routes/linkProps.tsx index d520cf0f96..abfa7f6c7b 100644 --- a/examples/react/large-file-based/src/routes/linkProps.tsx +++ b/examples/react/large-file-based/src/routes/linkProps.tsx @@ -4,6 +4,12 @@ import { Link, linkOptions } from '@tanstack/react-router' export const Route = createFileRoute('/linkProps')({ component: LinkPropsPage, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function LinkPropsPage() { diff --git a/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx b/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx index 1442464a1c..5983539137 100644 --- a/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx +++ b/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx @@ -25,6 +25,12 @@ export const Route = createFileRoute('/params/$paramsPlaceholder')({ component: ParamsComponent, loader: (opts) => opts.context.queryClient.ensureQueryData(paramsQueryOptions), + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + } }) function ParamsComponent() { diff --git a/examples/react/large-file-based/src/routes/params/route.tsx b/examples/react/large-file-based/src/routes/params/route.tsx index 0e29ec1e1e..2ad81c977a 100644 --- a/examples/react/large-file-based/src/routes/params/route.tsx +++ b/examples/react/large-file-based/src/routes/params/route.tsx @@ -3,4 +3,10 @@ import * as React from 'react' export const Route = createFileRoute('/params')({ component: () =>
Hello /params!
, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) diff --git a/examples/react/large-file-based/src/routes/relative.tsx b/examples/react/large-file-based/src/routes/relative.tsx index b2e8c7a10a..341c5a96b4 100644 --- a/examples/react/large-file-based/src/routes/relative.tsx +++ b/examples/react/large-file-based/src/routes/relative.tsx @@ -4,6 +4,12 @@ import { Link } from '@tanstack/react-router' export const Route = createFileRoute('/relative')({ component: RelativeComponent, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function RelativeComponent() { diff --git a/examples/react/large-file-based/src/routes/search/route.tsx b/examples/react/large-file-based/src/routes/search/route.tsx index 33447e4c80..04d790a439 100644 --- a/examples/react/large-file-based/src/routes/search/route.tsx +++ b/examples/react/large-file-based/src/routes/search/route.tsx @@ -10,4 +10,10 @@ const search = z.object({ export const Route = createFileRoute('/search')({ component: () =>
Hello /search!
, validateSearch: search, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) diff --git a/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx b/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx index 8938899d13..430b7e5543 100644 --- a/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx +++ b/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx @@ -32,6 +32,12 @@ export const Route = createFileRoute('/search/searchPlaceholder')({ validateSearch: search, loader: (opts) => opts.context.queryClient.ensureQueryData(searchQueryOptions), + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function SearchComponent() {