From 50f9505c6988e0dbb0d0ef5b234609e43be755c3 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Tue, 17 Nov 2026 09:57:31 +0800 Subject: [PATCH 01/12] fix(routes): improve routeUrl TypeScript diagnostics --- packages/void/src/codegen/route-types.ts | 114 +++++++++++++++++- .../void/src/runtime/routing/route-url.ts | 92 +++++++++++++- .../integration/route-url-builder.test.ts | 70 +++++++++++ .../test/unit/route-url-builder.typecheck.ts | 12 ++ 4 files changed, 277 insertions(+), 11 deletions(-) diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 7578b4ccf..24185f456 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -198,11 +198,115 @@ export function generateRouteTypes( ); lines.push(' : string;'); lines.push(' export type RouteUrlInput = Href | URL | RouteDestination;'); - lines.push(' export function routeUrl

('); - lines.push(' path: P,'); - lines.push(' ...args: [RoutePathMap[NoInfer

]] extends [never]'); - lines.push(' ? [options?: RouteOptions

]'); - lines.push(' : [options: RouteOptions

]'); + lines.push(' // Keep route/option shapes visible to editor completion while inferring the'); + lines.push(" // caller's input separately, so invalid calls can explain the correction."); + lines.push( + ' type RouteUrlError = { readonly __routeUrlError: Message };', + ); + lines.push(' type RouteUrlOptionsInput

= {'); + lines.push( + ' params?: { [K in RoutePathMap[P] & string]?: unknown } | Record;', + ); + lines.push(' query?: Record;'); + lines.push(' hash?: unknown;'); + lines.push(' };'); + lines.push(' type RouteUrlArgs

= [RoutePathMap[P]] extends [never]'); + lines.push(' ? [options?: RouteOptions

]'); + lines.push(' : [options: RouteOptions

];'); + lines.push( + ' type MissingRouteParam

= P extends RoutePath', + ); + lines.push(' ? K extends RoutePathMap[P]'); + lines.push(' ? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.`'); + lines.push(' : never'); + lines.push(' : never;'); + lines.push(' type MissingRouteParamKeys

= {'); + lines.push(' [K in RoutePathMap[P] & string]: Params extends Record ? never : K;'); + lines.push(' }[RoutePathMap[P] & string];'); + lines.push(' type InvalidRouteParamKeys

= {'); + lines.push( + ' [K in RoutePathMap[P] & string]: Params extends Record ? never : K;', + ); + lines.push(' }[RoutePathMap[P] & string];'); + lines.push(' type InvalidRouteValueKeys = {'); + lines.push(' [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K;'); + lines.push(' }[keyof Values] &'); + lines.push(' string;'); + lines.push( + ' type RouteUrlParamError

= [RoutePathMap[P]] extends [never]', + ); + lines.push(" ? 'params' extends keyof O"); + lines.push(" ? [O['params']] extends [undefined]"); + lines.push(' ? never'); + lines.push(' : `Route ${P} has no path params. Remove params.`'); + lines.push(' : never'); + lines.push(' : O extends { params: infer Params }'); + lines.push(' ? Params extends object'); + lines.push(' ? [Exclude] extends [never]'); + lines.push(' ? [MissingRouteParamKeys] extends [never]'); + lines.push(' ? [InvalidRouteParamKeys] extends [never]'); + lines.push(' ? never'); + lines.push( + ' : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.`', + ); + lines.push(' : MissingRouteParam>'); + lines.push( + ' : `Unknown param ${Exclude & string} for route ${P}. Use the parameter names in the route pattern.`', + ); + lines.push( + " : `Params for route ${P} must be an object with the route's parameter names.`", + ); + lines.push(' : MissingRouteParam;'); + lines.push( + ' type RouteUrlQueryError

= [Query] extends [RouteQuery | undefined]', + ); + lines.push(' ? never'); + lines.push( + ' : `Invalid query param ${InvalidRouteValueKeys, RouteQueryValue | ReadonlyArray>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`;', + ); + lines.push(' type RouteUrlOptionsError

= [P] extends [RoutePath]'); + lines.push(' ? O extends undefined'); + lines.push(' ? MissingRouteParam'); + lines.push(' : O extends object'); + lines.push(' ?'); + lines.push(' | RouteUrlParamError'); + lines.push(" | ('query' extends keyof O ? RouteUrlQueryError : never)"); + lines.push(" | ('hash' extends keyof O"); + lines.push(" ? [O['hash']] extends [string | undefined]"); + lines.push(' ? never'); + lines.push(' : `Hash for route ${P} must be a string.`'); + lines.push(' : never)'); + lines.push( + " | (Exclude extends infer K extends string", + ); + lines.push(' ? `Unknown routeUrl option: ${K}. Use params, query, or hash.`'); + lines.push(' : never)'); + lines.push(' : `Options for route ${P} must be an object with params, query, or hash.`'); + lines.push(' : never;'); + lines.push(' type ValidateRouteUrlArgs

= ['); + lines.push(' RouteUrlOptionsError,'); + lines.push(' ] extends [never]'); + lines.push(' ? unknown'); + lines.push(' : RouteUrlOptionsError;'); + lines.push(''); + lines.push(' export function routeUrl<'); + lines.push(' P extends RoutePath | (string & {}),'); + lines.push(' A extends [options?: unknown] = RouteUrlArgs>,'); + lines.push(' >('); + lines.push(' path: P &'); + lines.push(' ('); + lines.push(' | RoutePath'); + lines.push(' | RouteUrlError<'); + lines.push(' string extends NoInfer

'); + lines.push(" ? 'Pass a route pattern literal to routeUrl(); string is too broad.'"); + lines.push( + ' : `Unknown route: ${NoInfer

}. Pass a registered route pattern as the first argument.`', + ); + lines.push(' >'); + lines.push(' ),'); + lines.push(' ...args: A &'); + lines.push(' [options?: RouteUrlOptionsInput, RoutePath>>] &'); + lines.push(' ValidateRouteUrlArgs, NoInfer>'); lines.push(' ): RouteUrl;'); lines.push(''); lines.push(' export interface RouteTypesConfig {'); diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index 75c631804..baa4eb2bf 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -157,14 +157,94 @@ type UrlOptions = { hash?: string; }; +// Keep route/option shapes visible to editor completion while inferring the +// caller's input separately, so invalid calls can explain the correction. +type RouteUrlError = { readonly __routeUrlError: Message }; +type RouteUrlOptionsInput

= { + params?: { [K in RoutePathMap[P] & string]?: unknown } | Record; + query?: Record; + hash?: unknown; +}; +type RouteUrlArgs

= [RoutePathMap[P]] extends [never] + ? [options?: RouteOptions

] + : [options: RouteOptions

]; +type MissingRouteParam

= P extends RoutePath + ? K extends RoutePathMap[P] + ? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.` + : never + : never; +type MissingRouteParamKeys

= { + [K in RoutePathMap[P] & string]: Params extends Record ? never : K; +}[RoutePathMap[P] & string]; +type InvalidRouteParamKeys

= { + [K in RoutePathMap[P] & string]: Params extends Record ? never : K; +}[RoutePathMap[P] & string]; +type InvalidRouteValueKeys = { + [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K; +}[keyof Values] & + string; +type RouteUrlParamError

= [RoutePathMap[P]] extends [never] + ? 'params' extends keyof O + ? [O['params']] extends [undefined] + ? never + : `Route ${P} has no path params. Remove params.` + : never + : O extends { params: infer Params } + ? Params extends object + ? [Exclude] extends [never] + ? [MissingRouteParamKeys] extends [never] + ? [InvalidRouteParamKeys] extends [never] + ? never + : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.` + : MissingRouteParam> + : `Unknown param ${Exclude & string} for route ${P}. Use the parameter names in the route pattern.` + : `Params for route ${P} must be an object with the route's parameter names.` + : MissingRouteParam; +type RouteUrlQueryError

= [Query] extends [RouteQuery | undefined] + ? never + : `Invalid query param ${InvalidRouteValueKeys, RouteQueryValue | ReadonlyArray>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`; +type RouteUrlOptionsError

= [P] extends [RoutePath] + ? O extends undefined + ? MissingRouteParam + : O extends object + ? + | RouteUrlParamError + | ('query' extends keyof O ? RouteUrlQueryError : never) + | ('hash' extends keyof O + ? [O['hash']] extends [string | undefined] + ? never + : `Hash for route ${P} must be a string.` + : never) + | (Exclude extends infer K extends string + ? `Unknown routeUrl option: ${K}. Use params, query, or hash.` + : never) + : `Options for route ${P} must be an object with params, query, or hash.` + : never; +type ValidateRouteUrlArgs

= [ + RouteUrlOptionsError, +] extends [never] + ? unknown + : RouteUrlOptionsError; + /** Build a relative URL from a known route pattern. */ -export function routeUrl

( - path: P, - ...args: [RoutePathMap[NoInfer

]] extends [never] - ? [options?: RouteOptions

] - : [options: RouteOptions

] +export function routeUrl< + P extends RoutePath | (string & {}), + A extends [options?: unknown] = RouteUrlArgs>, +>( + path: P & + ( + | RoutePath + | RouteUrlError< + string extends NoInfer

+ ? 'Pass a route pattern literal to routeUrl(); string is too broad.' + : `Unknown route: ${NoInfer

}. Pass a registered route pattern as the first argument.` + > + ), + ...args: A & + [options?: RouteUrlOptionsInput, RoutePath>>] & + ValidateRouteUrlArgs, NoInfer> ): RouteUrl { - return buildRouteUrl(path, args[0]) as RouteUrl; + return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl; } /** @internal Convert navigation inputs to URL strings without requiring an origin. */ diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 07fb68e7b..d4bfd5010 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -343,6 +343,17 @@ routeUrl('/wild/*', { params: { '*': 'a/b' } }); routeUrl('/users/[id]', { params: { id: 123 } }); routeUrl('/files/[...path]', { params: { path: 'docs/start' } }); routeUrl('/wild/[...]', { params: { '*': 'a/b' } }); +routeUrl<'/users/[id]'>('/users/[id]', { params: { id: 123 } }); +interface UserParams { id: number; } +const userParams: UserParams = { id: 123 }; +routeUrl('/users/[id]', { params: userParams }); +declare const either: '/about' | '/users/[id]'; +routeUrl(either, { params: { id: 123 } }); +// @ts-expect-error every possible route's params must be present +routeUrl(either); +declare const optional: [options?: RouteOptions<'/users/[id]'>]; +// @ts-expect-error an optional tuple cannot guarantee required params +routeUrl('/users/[id]', ...optional); // @ts-expect-error bracket patterns require params routeUrl('/users/[id]'); // @ts-expect-error bracket catch-all patterns require params @@ -468,6 +479,65 @@ function typecheck( } describe('standalone routeUrl utility', () => { + it.each(['generated', 'package'] as const)( + 'explains invalid routeUrl calls through the %s declarations', + async (declarations) => { + const cases = [ + ["routeUrl('/missing');", 'Unknown route: /missing.'], + ["routeUrl('/missing', {});", 'Unknown route: /missing.'], + ["routeUrl('/users/42');", 'Unknown route: /users/42.'], + ["routeUrl('/users/[id]');", 'Missing param id for route /users/[id].'], + ["routeUrl('/users/[id]', {});", 'Missing param id for route /users/[id].'], + [ + "routeUrl('/users/[id]', { query: { page: 1 } });", + 'Missing param id for route /users/[id].', + ], + ["routeUrl('/users/[id]', { params: {} });", 'Missing param id for route /users/[id].'], + [ + "routeUrl('/users/[id]', { params: { userId: 42 } });", + 'Unknown param userId for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: { id: 42, extra: 'x' } });", + 'Unknown param extra for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: { id: true } });", + 'Param id for route /users/[id] must be a string or number.', + ], + ["routeUrl('/about', { params: {} });", 'Route /about has no path params.'], + ["routeUrl('/about', { hash: 123 });", 'Hash for route /about must be a string.'], + [ + "routeUrl('/about', { query: { nested: { value: 'x' } } });", + 'Invalid query param nested for route /about.', + ], + ["routeUrl('/about', { search: 'x' });", 'Unknown routeUrl option: search.'], + ["routeUrl('/users/[id]', undefined);", 'Missing param id for route /users/[id].'], + ["routeUrl('' as '/about' | '/users/[id]');", 'Missing param id for route /users/[id].'], + [ + "routeUrl('' as string);", + 'Pass a route pattern literal to routeUrl(); string is too broad.', + ], + ]; + const root = await createFixture({ + extraFiles: { + 'check-diagnostics.ts': [ + "import { routeUrl } from 'void/routes';", + ...cases.map(([call]) => call), + ].join('\n'), + }, + }); + const { output, status } = typecheck(root, declarations, ['check-diagnostics.ts']); + expect(status).toBe(1); + const diagnostics = output + .split(/.*check-diagnostics\.ts\(\d+,\d+\): error TS\d+: /) + .slice(1); + expect(diagnostics).toHaveLength(cases.length); + cases.forEach(([, message], index) => expect(diagnostics[index]).toContain(message)); + expect(output).not.toContain('TS2554'); + }, + ); + it.each(['generated', 'package'] as const)( 'preserves HTTP, WebSocket and page action contracts for both syntaxes through %s declarations', async (declarations) => { diff --git a/packages/void/test/unit/route-url-builder.typecheck.ts b/packages/void/test/unit/route-url-builder.typecheck.ts index e6f3da4bf..384115f23 100644 --- a/packages/void/test/unit/route-url-builder.typecheck.ts +++ b/packages/void/test/unit/route-url-builder.typecheck.ts @@ -22,6 +22,13 @@ describe('routeUrl types', () => { routeUrl('/route-types/files/*', { params: { '*': 'a/b' } }); const options: RouteOptions<'/route-types/:id'> = { params: { id: '123' } }; routeUrl('/route-types/:id', options); + routeUrl<'/route-types/:id'>('/route-types/:id', options); + interface Params { + id: number; + } + const params: Params = { id: 123 }; + routeUrl('/route-types/:id', { params }); + routeUrl('/route-types', undefined); }); it('rejects unknown paths and incorrect params', () => { @@ -31,6 +38,8 @@ describe('routeUrl types', () => { routeUrl('/route-types/123'); // @ts-expect-error params are required routeUrl('/route-types/:id'); + // @ts-expect-error undefined options cannot bypass required params + routeUrl('/route-types/:id', undefined); // @ts-expect-error params are required even when other options are provided routeUrl('/route-types/:id', { query: { page: 1 } }); // @ts-expect-error param names must match @@ -57,5 +66,8 @@ describe('routeUrl types', () => { // @ts-expect-error one of the possible routes requires params routeUrl(path); routeUrl(path, { params: { id: '123' } }); + const optional: [options?: RouteOptions<'/route-types/:id'>] = []; + // @ts-expect-error an optional tuple cannot guarantee required params + routeUrl('/route-types/:id', ...optional); }); }); From 7659101cb635602069ce5730d84eebe9d7b513c8 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Tue, 17 Nov 2026 11:08:17 +0800 Subject: [PATCH 02/12] fix(routes): preserve routeUrl compatibility --- packages/void/src/codegen/route-types.ts | 188 +++--------------- .../void/src/runtime/routing/route-url.ts | 43 ++-- .../src/runtime/routing/url-diagnostics.ts | 14 ++ .../integration/route-url-builder.test.ts | 93 +++++++++ packages/void/test/unit/route-types.test.ts | 7 +- 5 files changed, 152 insertions(+), 193 deletions(-) create mode 100644 packages/void/src/runtime/routing/url-diagnostics.ts diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 24185f456..5ba6cad81 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -1,4 +1,5 @@ -import { relative } from 'pathslash'; +import { fileURLToPath } from 'node:url'; +import { isAbsolute, relative } from 'pathslash'; import type { RouteDefinition } from '../router/parse-filename.ts'; import type { ScanResult } from '../router/scan.ts'; import type { WebSocketRouteDefinition } from '../router/websocket.ts'; @@ -139,175 +140,34 @@ export function generateRouteTypes( lines.push(' export interface WebSocketRouteMap {}'); lines.push(' export interface PageActionMap {}'); lines.push(''); - // Projects resolve void/routes to this generated declaration through their - // tsconfig paths, so keep the standalone helper's declarations here as well. - lines.push(' export type RoutePath = keyof RoutePathMap & string;'); - lines.push(' export type RouteQueryValue = string | number | boolean | null | undefined;'); - lines.push( - ' export type RouteQuery = Record>;', - ); - lines.push(' export type RouteOptions

= {'); - lines.push(' query?: RouteQuery;'); - lines.push(' hash?: string;'); - lines.push(' } & ([RoutePathMap[P]] extends [never]'); - lines.push(' ? { params?: never }'); - lines.push(' : { params: { [K in RoutePathMap[P] & string]: string | number } });'); - lines.push( - ' export type RouteDestination

= P extends RoutePath', - ); - lines.push(' ? { pathname: P } & RouteOptions

'); - lines.push(' : never;'); - lines.push( - ' type RouteUrlSegment = S extends `:${string}` | `[${string}]` | "*" ? string : S;', - ); - lines.push( - ' type CheckedRoutePath

= P extends `/${infer Segment}/${infer Rest}`', - ); - lines.push(' ? Rest extends ""'); - lines.push(' ? string extends RouteUrlSegment ? never : P'); - lines.push(' : P'); - lines.push(' : P extends `/${infer Segment}`'); - lines.push(' ? string extends RouteUrlSegment ? never : P'); - lines.push(' : P;'); - lines.push( - ' type RouteSegmentsUrl

= P extends `${infer Segment}/${infer Rest}`', - ); - lines.push(' ? `${RouteUrlSegment}/${RouteSegmentsUrl}`'); - lines.push(' : RouteUrlSegment

;'); - lines.push( - ' type RoutePatternUrl

= P extends `${infer Prefix}/${"*" | "[...]"}/`', - ); - lines.push(' ? `${RouteSegmentsUrl}/` | `${RouteSegmentsUrl}/${string}/`'); - lines.push(' : P extends `${infer Prefix}/${"*" | "[...]"}`'); - lines.push( - ' ? (Prefix extends "" ? "/" : RouteSegmentsUrl) | `${RouteSegmentsUrl}/${string}`', - ); - lines.push(' : RouteSegmentsUrl

;'); - lines.push(' type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;'); - lines.push( - ' type RoutePathUrl = RoutePatternUrl>;', - ); - lines.push(' type BuiltRouteUrl = string & { readonly __voidRouteUrl: true };'); - lines.push(' type TypedRoutes = RouteTypesConfig extends { typedRoutes: true } ? true : false;'); - lines.push(' export type RouteUrl = TypedRoutes extends true'); - lines.push(' ? BuiltRouteUrl | RoutePathUrl | `${RoutePathUrl}${"?" | "#"}${string}`'); - lines.push(' : string;'); - lines.push(' export type Href = TypedRoutes extends true'); - lines.push( - ' ? RouteUrl | `${"?" | "#"}${string}` | `${"http://" | "https://" | "mailto:" | "tel:"}${string}`', - ); - lines.push(' : string;'); - lines.push(' export type RouteUrlInput = Href | URL | RouteDestination;'); - lines.push(' // Keep route/option shapes visible to editor completion while inferring the'); - lines.push(" // caller's input separately, so invalid calls can explain the correction."); - lines.push( - ' type RouteUrlError = { readonly __routeUrlError: Message };', - ); - lines.push(' type RouteUrlOptionsInput

= {'); - lines.push( - ' params?: { [K in RoutePathMap[P] & string]?: unknown } | Record;', + // Keep URL contracts and diagnostics in the runtime declarations. Referencing + // void/routes here would be circular when this file augments that package entry. + const sdkRoutesPath = relative( + outDir, + fileURLToPath(import.meta.resolve('#self/runtime/route-url')), ); - lines.push(' query?: Record;'); - lines.push(' hash?: unknown;'); - lines.push(' };'); - lines.push(' type RouteUrlArgs

= [RoutePathMap[P]] extends [never]'); - lines.push(' ? [options?: RouteOptions

]'); - lines.push(' : [options: RouteOptions

];'); - lines.push( - ' type MissingRouteParam

= P extends RoutePath', - ); - lines.push(' ? K extends RoutePathMap[P]'); - lines.push(' ? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.`'); - lines.push(' : never'); - lines.push(' : never;'); - lines.push(' type MissingRouteParamKeys

= {'); - lines.push(' [K in RoutePathMap[P] & string]: Params extends Record ? never : K;'); - lines.push(' }[RoutePathMap[P] & string];'); - lines.push(' type InvalidRouteParamKeys

= {'); - lines.push( - ' [K in RoutePathMap[P] & string]: Params extends Record ? never : K;', - ); - lines.push(' }[RoutePathMap[P] & string];'); - lines.push(' type InvalidRouteValueKeys = {'); - lines.push(' [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K;'); - lines.push(' }[keyof Values] &'); - lines.push(' string;'); - lines.push( - ' type RouteUrlParamError

= [RoutePathMap[P]] extends [never]', - ); - lines.push(" ? 'params' extends keyof O"); - lines.push(" ? [O['params']] extends [undefined]"); - lines.push(' ? never'); - lines.push(' : `Route ${P} has no path params. Remove params.`'); - lines.push(' : never'); - lines.push(' : O extends { params: infer Params }'); - lines.push(' ? Params extends object'); - lines.push(' ? [Exclude] extends [never]'); - lines.push(' ? [MissingRouteParamKeys] extends [never]'); - lines.push(' ? [InvalidRouteParamKeys] extends [never]'); - lines.push(' ? never'); - lines.push( - ' : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.`', + const sdkRoutesModule = JSON.stringify( + isAbsolute(sdkRoutesPath) || sdkRoutesPath.startsWith('.') + ? sdkRoutesPath + : `./${sdkRoutesPath}`, ); - lines.push(' : MissingRouteParam>'); - lines.push( - ' : `Unknown param ${Exclude & string} for route ${P}. Use the parameter names in the route pattern.`', - ); - lines.push( - " : `Params for route ${P} must be an object with the route's parameter names.`", - ); - lines.push(' : MissingRouteParam;'); - lines.push( - ' type RouteUrlQueryError

= [Query] extends [RouteQuery | undefined]', - ); - lines.push(' ? never'); - lines.push( - ' : `Invalid query param ${InvalidRouteValueKeys, RouteQueryValue | ReadonlyArray>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`;', - ); - lines.push(' type RouteUrlOptionsError

= [P] extends [RoutePath]'); - lines.push(' ? O extends undefined'); - lines.push(' ? MissingRouteParam'); - lines.push(' : O extends object'); - lines.push(' ?'); - lines.push(' | RouteUrlParamError'); - lines.push(" | ('query' extends keyof O ? RouteUrlQueryError : never)"); - lines.push(" | ('hash' extends keyof O"); - lines.push(" ? [O['hash']] extends [string | undefined]"); - lines.push(' ? never'); - lines.push(' : `Hash for route ${P} must be a string.`'); - lines.push(' : never)'); + for (const name of [ + 'RoutePath', + 'RouteQueryValue', + 'RouteQuery', + 'RouteUrl', + 'Href', + 'RouteUrlInput', + ]) { + lines.push(` export type ${name} = import(${sdkRoutesModule}).${name};`); + } lines.push( - " | (Exclude extends infer K extends string", + ` export type RouteOptions

= import(${sdkRoutesModule}).RouteOptions

;`, ); - lines.push(' ? `Unknown routeUrl option: ${K}. Use params, query, or hash.`'); - lines.push(' : never)'); - lines.push(' : `Options for route ${P} must be an object with params, query, or hash.`'); - lines.push(' : never;'); - lines.push(' type ValidateRouteUrlArgs

= ['); - lines.push(' RouteUrlOptionsError,'); - lines.push(' ] extends [never]'); - lines.push(' ? unknown'); - lines.push(' : RouteUrlOptionsError;'); - lines.push(''); - lines.push(' export function routeUrl<'); - lines.push(' P extends RoutePath | (string & {}),'); - lines.push(' A extends [options?: unknown] = RouteUrlArgs>,'); - lines.push(' >('); - lines.push(' path: P &'); - lines.push(' ('); - lines.push(' | RoutePath'); - lines.push(' | RouteUrlError<'); - lines.push(' string extends NoInfer

'); - lines.push(" ? 'Pass a route pattern literal to routeUrl(); string is too broad.'"); lines.push( - ' : `Unknown route: ${NoInfer

}. Pass a registered route pattern as the first argument.`', + ` export type RouteDestination

= import(${sdkRoutesModule}).RouteDestination

;`, ); - lines.push(' >'); - lines.push(' ),'); - lines.push(' ...args: A &'); - lines.push(' [options?: RouteUrlOptionsInput, RoutePath>>] &'); - lines.push(' ValidateRouteUrlArgs, NoInfer>'); - lines.push(' ): RouteUrl;'); + lines.push(` export const routeUrl: typeof import(${sdkRoutesModule}).routeUrl;`); lines.push(''); lines.push(' export interface RouteTypesConfig {'); if (options.typedRoutes) { diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index baa4eb2bf..a02463f25 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -1,4 +1,5 @@ import type { EncodedRoutePathMap, RoutePathMap, RouteTypesConfig } from 'void/routes'; +import type { DiagnosticKeyName, InvalidValueKeys, UrlTypeError } from './url-diagnostics.ts'; /** * Encode one path segment of a route param. `encodeURIComponent` keeps dots, and @@ -157,9 +158,8 @@ type UrlOptions = { hash?: string; }; -// Keep route/option shapes visible to editor completion while inferring the -// caller's input separately, so invalid calls can explain the correction. -type RouteUrlError = { readonly __routeUrlError: Message }; +// Diagnostics describe invalid calls; the valid-call overload below remains +// independent so generic helpers and structural objects retain their contract. type RouteUrlOptionsInput

= { params?: { [K in RoutePathMap[P] & string]?: unknown } | Record; query?: Record; @@ -179,10 +179,6 @@ type MissingRouteParamKeys

= { type InvalidRouteParamKeys

= { [K in RoutePathMap[P] & string]: Params extends Record ? never : K; }[RoutePathMap[P] & string]; -type InvalidRouteValueKeys = { - [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K; -}[keyof Values] & - string; type RouteUrlParamError

= [RoutePathMap[P]] extends [never] ? 'params' extends keyof O ? [O['params']] extends [undefined] @@ -197,12 +193,12 @@ type RouteUrlParamError

= [RoutePathMap[P]] extends [nev ? never : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.` : MissingRouteParam> - : `Unknown param ${Exclude & string} for route ${P}. Use the parameter names in the route pattern.` + : `Unknown param ${DiagnosticKeyName>} for route ${P}. Use the parameter names in the route pattern.` : `Params for route ${P} must be an object with the route's parameter names.` : MissingRouteParam; type RouteUrlQueryError

= [Query] extends [RouteQuery | undefined] ? never - : `Invalid query param ${InvalidRouteValueKeys, RouteQueryValue | ReadonlyArray>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`; + : `Invalid query param ${DiagnosticKeyName, RouteQueryValue | ReadonlyArray>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`; type RouteUrlOptionsError

= [P] extends [RoutePath] ? O extends undefined ? MissingRouteParam @@ -215,35 +211,34 @@ type RouteUrlOptionsError

= [P] extends [RoutePath] ? never : `Hash for route ${P} must be a string.` : never) - | (Exclude extends infer K extends string - ? `Unknown routeUrl option: ${K}. Use params, query, or hash.` - : never) + | `Unknown routeUrl option: ${DiagnosticKeyName>}. Use params, query, or hash.` : `Options for route ${P} must be an object with params, query, or hash.` : never; -type ValidateRouteUrlArgs

= [ - RouteUrlOptionsError, -] extends [never] - ? unknown - : RouteUrlOptionsError; - /** Build a relative URL from a known route pattern. */ +export function routeUrl

(path: P, ...args: RouteUrlArgs>): RouteUrl; +// The default preserves the native tuple for explicit type arguments and +// Parameters>. Inferred diagnostic tuples always require +// an unsatisfied marker, even when an error calculation resolves to never. export function routeUrl< P extends RoutePath | (string & {}), - A extends [options?: unknown] = RouteUrlArgs>, + A extends [options?: unknown] = never, >( path: P & ( | RoutePath - | RouteUrlError< + | UrlTypeError< string extends NoInfer

? 'Pass a route pattern literal to routeUrl(); string is too broad.' : `Unknown route: ${NoInfer

}. Pass a registered route pattern as the first argument.` > ), - ...args: A & - [options?: RouteUrlOptionsInput, RoutePath>>] & - ValidateRouteUrlArgs, NoInfer> -): RouteUrl { + ...args: [A] extends [never] + ? RouteUrlArgs>> + : A & + [options?: RouteUrlOptionsInput, RoutePath>>] & + UrlTypeError, NoInfer[0]>> +): RouteUrl; +export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl { return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl; } diff --git a/packages/void/src/runtime/routing/url-diagnostics.ts b/packages/void/src/runtime/routing/url-diagnostics.ts new file mode 100644 index 000000000..51cad1200 --- /dev/null +++ b/packages/void/src/runtime/routing/url-diagnostics.ts @@ -0,0 +1,14 @@ +/** An unsatisfied marker for diagnostic fallbacks, never an accepted input. */ +export type UrlTypeError = { readonly __voidUrlError: Message }; + +/** Inspect every union member, including members with disjoint property names. */ +export type InvalidValueKeys = Values extends unknown + ? { [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K }[keyof Values] + : never; + +/** Preserve numeric and symbol keys when explaining an invalid property. */ +export type DiagnosticKeyName = K extends string | number + ? `${K}` + : K extends symbol + ? 'symbol' + : never; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index d4bfd5010..12c7eb4ec 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -479,6 +479,90 @@ function typecheck( } describe('standalone routeUrl utility', () => { + it.each(['generated', 'package'] as const)( + 'preserves generic helpers and structural options through the %s declarations', + async (declarations) => { + const root = await createFixture({ + extraFiles: { + 'check-compatibility.ts': `import { routeUrl, type RouteDestination, type RouteOptions } from 'void/routes'; +function userUrl(id: T) { + return routeUrl('/users/[id]', { params: { id } }); +} +function forwardOptions>(options: T) { + return routeUrl('/users/[id]', options); +} +function forwardStaticOptions>(options: T) { + return routeUrl('/about', options); +} +function forwardDestination>(destination: T) { + return routeUrl('/users/[id]', destination); +} +function forwardArgs(...args: Parameters>) { + return routeUrl(...args); +} +forwardArgs('/users/[id]', { params: { id: 42 } }); +const user = { id: 42, name: 'Alice' }; +routeUrl('/users/[id]', { params: user }); +const options = { params: user, trace: 'request' }; +routeUrl('/users/[id]', options); +const destination: RouteDestination<'/users/[id]'> = { + pathname: '/users/[id]', params: { id: 42 }, +}; +routeUrl('/users/[id]', destination); +const staticDestination: RouteDestination<'/about'> = { pathname: '/about' }; +routeUrl('/about', staticDestination); +void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forwardArgs]; +`, + }, + }); + expect(typecheck(root, declarations, ['check-compatibility.ts'])).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(['generated', 'package'] as const)( + 'rejects invalid unions and numeric keys through the %s declarations', + async (declarations) => { + const root = await createFixture({ + extraFiles: { + 'check-invalid-unions.ts': `import { routeUrl } from 'void/routes'; +declare const query: { q: string } | { filter: { id: number } }; +// @ts-expect-error every query union member must contain supported values +routeUrl('/about', { query }); +declare const optionalQuery: { q?: string } | { filter?: { id: number } }; +// @ts-expect-error optional query keys cannot hide invalid union members +routeUrl('/about', { query: optionalQuery }); +// @ts-expect-error numeric params do not supply the required id +routeUrl('/users/[id]', { params: { 0: 'missing-id' } }); +// @ts-expect-error fresh numeric extra params are still rejected +routeUrl('/users/[id]', { params: { id: 42, 0: 'extra' } }); +declare const params: { id: number } | { 0: string }; +// @ts-expect-error every params union member must supply id +routeUrl('/users/[id]', { params }); +declare const key: unique symbol; +// @ts-expect-error symbol keys cannot hide a missing id +routeUrl('/users/[id]', { params: { [key]: 42 } }); +// @ts-expect-error numeric option keys do not belong to RouteOptions +routeUrl('/about', { 0: 'unknown-option' }); +declare const options: { query: { q: string } } | { query: { filter: { id: number } } }; +// @ts-expect-error every options union member must be valid +routeUrl('/about', options); +// @ts-expect-error explicit type arguments retain fresh-object excess checks +routeUrl<'/users/[id]'>('/users/[id]', { params: { id: 42, extra: 'x' } }); +// @ts-expect-error widening the type argument cannot omit required params +routeUrl('/users/[id]'); +`, + }, + }); + expect(typecheck(root, declarations, ['check-invalid-unions.ts'])).toEqual({ + output: '', + status: 0, + }); + }, + ); + it.each(['generated', 'package'] as const)( 'explains invalid routeUrl calls through the %s declarations', async (declarations) => { @@ -511,6 +595,15 @@ describe('standalone routeUrl utility', () => { "routeUrl('/about', { query: { nested: { value: 'x' } } });", 'Invalid query param nested for route /about.', ], + [ + "routeUrl('/about', { query: null as unknown as { q: string } | { filter: { id: number } } });", + 'Invalid query param filter for route /about.', + ], + [ + "routeUrl('/users/[id]', { params: { 0: 'missing-id' } });", + 'Unknown param 0 for route /users/[id].', + ], + ["routeUrl('/about', { 0: 'unknown' });", 'Unknown routeUrl option: 0.'], ["routeUrl('/about', { search: 'x' });", 'Unknown routeUrl option: search.'], ["routeUrl('/users/[id]', undefined);", 'Missing param id for route /users/[id].'], ["routeUrl('' as '/about' | '/users/[id]');", 'Missing param id for route /users/[id].'], diff --git a/packages/void/test/unit/route-types.test.ts b/packages/void/test/unit/route-types.test.ts index afe1b4aff..8aec37f67 100644 --- a/packages/void/test/unit/route-types.test.ts +++ b/packages/void/test/unit/route-types.test.ts @@ -298,9 +298,6 @@ describe('generateRouteTypes', () => { ' "/café/[id]": "/caf%C3%A9/[id]";', ' "/café/:id": "/caf%C3%A9/:id";', ]); - expect(dts).toContain( - 'type RoutePathUrl = RoutePatternUrl>;', - ); }); it('turns on typed route URLs only when routing.typedRoutes is set', () => { @@ -327,8 +324,8 @@ describe('generateRouteTypes', () => { expect(typesConfig(off).trim()).toBe(''); expect(typesConfig(on).trim()).toBe('typedRoutes: true;'); expect(on.replace(' typedRoutes: true;\n', '')).toBe(off); - expect(off).toContain('export type RouteUrlInput = Href | URL | RouteDestination;'); - expect(off).toContain(' ): RouteUrl;'); + expect(off).toMatch(/export type RouteUrlInput = import\("[^"]+"\)\.RouteUrlInput;/); + expect(off).toMatch(/export const routeUrl: typeof import\("[^"]+"\)\.routeUrl;/); }); it('generates PageActionMap for pages with actions', () => { From 3de6f116bafe37aa7f359a204d87730986e008d8 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Tue, 17 Nov 2026 12:11:46 +0800 Subject: [PATCH 03/12] fix(routes): preserve generic forwarding and stable type imports --- packages/void/package.json | 3 + packages/void/src/codegen/route-types.ts | 17 +-- .../void/src/runtime/routing/route-url.ts | 2 +- .../integration/route-url-builder.test.ts | 106 +++++++++++++++++- 4 files changed, 110 insertions(+), 18 deletions(-) diff --git a/packages/void/package.json b/packages/void/package.json index f3106e33e..02e7a0b25 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -313,6 +313,9 @@ "require": "./dist/runtime/env/public.mjs" } }, + "./_route-url-types": { + "types": "./dist/runtime/routing/route-url.d.mts" + }, "./_env": { "types": "./dist/runtime/env/runtime.d.mts", "import": "./dist/runtime/env/runtime.mjs", diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 5ba6cad81..433ccac01 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -1,5 +1,4 @@ -import { fileURLToPath } from 'node:url'; -import { isAbsolute, relative } from 'pathslash'; +import { relative } from 'pathslash'; import type { RouteDefinition } from '../router/parse-filename.ts'; import type { ScanResult } from '../router/scan.ts'; import type { WebSocketRouteDefinition } from '../router/websocket.ts'; @@ -140,17 +139,9 @@ export function generateRouteTypes( lines.push(' export interface WebSocketRouteMap {}'); lines.push(' export interface PageActionMap {}'); lines.push(''); - // Keep URL contracts and diagnostics in the runtime declarations. Referencing - // void/routes here would be circular when this file augments that package entry. - const sdkRoutesPath = relative( - outDir, - fileURLToPath(import.meta.resolve('#self/runtime/route-url')), - ); - const sdkRoutesModule = JSON.stringify( - isAbsolute(sdkRoutesPath) || sdkRoutesPath.startsWith('.') - ? sdkRoutesPath - : `./${sdkRoutesPath}`, - ); + // A bare types-only entry follows the installed SDK through upgrades. + // void/routes would be circular because this file augments that entry. + const sdkRoutesModule = JSON.stringify('void/_route-url-types'); for (const name of [ 'RoutePath', 'RouteQueryValue', diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index a02463f25..f386ebfdb 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -233,7 +233,7 @@ export function routeUrl< > ), ...args: [A] extends [never] - ? RouteUrlArgs>> + ? RouteUrlArgs & RoutePath> : A & [options?: RouteUrlOptionsInput, RoutePath>>] & UrlTypeError, NoInfer[0]>> diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 12c7eb4ec..7b5b49622 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -1,11 +1,20 @@ import { spawnSync } from 'node:child_process'; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { + cpSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; import { chromium } from 'playwright'; -import { build } from 'vite'; +import { build, transformWithOxc } from 'vite'; import { afterEach, describe, expect, it } from 'vite-plus/test'; import { analyzeApplication } from '../../src/application-routing.ts'; import { createProjectTsconfig } from '../../src/codegen/project-tsconfig.ts'; @@ -484,7 +493,7 @@ describe('standalone routeUrl utility', () => { async (declarations) => { const root = await createFixture({ extraFiles: { - 'check-compatibility.ts': `import { routeUrl, type RouteDestination, type RouteOptions } from 'void/routes'; + 'check-compatibility.ts': `import { routeUrl, type RouteDestination, type RouteOptions, type RoutePath } from 'void/routes'; function userUrl(id: T) { return routeUrl('/users/[id]', { params: { id } }); } @@ -500,6 +509,9 @@ function forwardDestination>(destinati function forwardArgs(...args: Parameters>) { return routeUrl(...args); } +function forwardGenericArgs

(...args: Parameters>) { + return routeUrl(...args); +} forwardArgs('/users/[id]', { params: { id: 42 } }); const user = { id: 42, name: 'Alice' }; routeUrl('/users/[id]', { params: user }); @@ -511,7 +523,7 @@ const destination: RouteDestination<'/users/[id]'> = { routeUrl('/users/[id]', destination); const staticDestination: RouteDestination<'/about'> = { pathname: '/about' }; routeUrl('/about', staticDestination); -void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forwardArgs]; +void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs]; `, }, }); @@ -522,6 +534,92 @@ void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forward }, ); + it.each(['generated', 'package'] as const)( + 'retains URL checks after an SDK upgrade without regenerating the %s declarations', + async (declarations) => { + const root = mkdtempSync(join(tmpdir(), 'void-route-upgrade-')); + roots.push(root); + const outDir = join(root, '.void'); + const packageLink = join(root, 'node_modules/void'); + mkdirSync(outDir, { recursive: true }); + const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')); + const generatorCode = ( + await transformWithOxc( + readFileSync(join(packageRoot, 'src/codegen/route-types.ts'), 'utf8'), + 'route-types.ts', + ) + ).code; + function createSdkVersion(version: string): string { + const directory = join(root, 'node_modules/.pnpm', `void@${version}/node_modules/void`); + mkdirSync(join(directory, 'src/codegen'), { recursive: true }); + cpSync(join(packageRoot, 'dist'), join(directory, 'dist'), { recursive: true }); + symlinkSync(join(packageRoot, 'node_modules'), join(directory, 'node_modules'), 'junction'); + writeFileSync(join(directory, 'src/codegen/route-types.mjs'), generatorCode); + writeFileSync(join(directory, 'package.json'), JSON.stringify({ ...manifest, version })); + return directory; + } + const oldSdk = createSdkVersion('1.9.1'); + const newSdk = createSdkVersion('1.9.2'); + symlinkSync(oldSdk, packageLink, 'junction'); + writeFileSync(join(root, 'package.json'), '{"type":"module"}'); + const generator = pathToFileURL(join(oldSdk, 'src/codegen/route-types.mjs')).href; + const generation = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import { generateRouteTypes } from ${JSON.stringify(generator)}; +const scan = { routes: [ + { pattern: '/about', params: [], methods: [] }, + { pattern: '/users/:id', params: ['id'], methods: [] }, +], pages: { pages: [] } }; +process.stdout.write(generateRouteTypes(scan, ${JSON.stringify(join(root, 'routes'))}, ${JSON.stringify(outDir)}, undefined, { typedRoutes: true }).dts);`, + ], + { encoding: 'utf8' }, + ); + expect({ status: generation.status, errors: generation.stderr }).toEqual({ + status: 0, + errors: '', + }); + const routeTypesPath = join(outDir, 'routes.d.ts'); + writeFileSync(routeTypesPath, generation.stdout); + writeFileSync( + join(outDir, 'tsconfig.json'), + JSON.stringify(createProjectTsconfig(root, true)), + ); + writeFileSync( + join(root, 'check-upgrade.ts'), + `import { routeUrl, type Href } from 'void/routes'; +const href: Href = routeUrl('/users/[id]', { params: { id: 42 } }); +routeUrl('/about'); +// @ts-expect-error unknown route patterns remain checked +routeUrl('/missing'); +// @ts-expect-error required params remain checked +routeUrl('/users/[id]'); +// @ts-expect-error param values remain checked +routeUrl('/users/[id]', { params: { id: true } }); +// @ts-expect-error raw URLs retain their existing route checks +const unknown: Href = '/missing'; +void [href, unknown]; +`, + ); + expect(typecheck(root, declarations, ['check-upgrade.ts'])).toEqual({ + output: '', + status: 0, + }); + + rmSync(packageLink, { force: true, recursive: true }); + symlinkSync(newSdk, packageLink, 'junction'); + rmSync(oldSdk, { force: true, recursive: true }); + + expect(readFileSync(routeTypesPath, 'utf8')).toBe(generation.stdout); + expect(typecheck(root, declarations, ['check-upgrade.ts'])).toEqual({ + output: '', + status: 0, + }); + }, + ); + it.each(['generated', 'package'] as const)( 'rejects invalid unions and numeric keys through the %s declarations', async (declarations) => { From 7e24feca5a5487c6470189959d3b7994668f2635 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Tue, 17 Nov 2026 13:14:50 +0800 Subject: [PATCH 04/12] fix(routes): preserve checked routeUrl signatures --- packages/void/package.json | 7 + .../void/src/runtime/routing/route-url.ts | 85 ++++--- .../integration/route-url-builder.test.ts | 239 +++++++++++++++--- 3 files changed, 264 insertions(+), 67 deletions(-) diff --git a/packages/void/package.json b/packages/void/package.json index 02e7a0b25..8d26b8d7d 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -26,6 +26,13 @@ "sandbox.Dockerfile" ], "type": "module", + "typesVersions": { + "*": { + "_route-url-types": [ + "./dist/runtime/routing/route-url.d.mts" + ] + } + }, "imports": { "#self/_env": "./dist/runtime/env/runtime.mjs", "#self/email": "./dist/runtime/email/index.mjs", diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index f386ebfdb..ad61b6d4a 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -173,12 +173,28 @@ type MissingRouteParam

= P extends RouteP ? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.` : never : never; -type MissingRouteParamKeys

= { - [K in RoutePathMap[P] & string]: Params extends Record ? never : K; -}[RoutePathMap[P] & string]; +// An index signature permits a key without guaranteeing that it is present. +type RequiredParamKeys = keyof { + [K in keyof Params as string extends K ? never : {} extends Pick ? never : K]: unknown; +}; +type MissingRouteParamKeys

= Exclude< + RoutePathMap[P] & string, + RequiredParamKeys +>; type InvalidRouteParamKeys

= { - [K in RoutePathMap[P] & string]: Params extends Record ? never : K; + [K in RoutePathMap[P] & string]: K extends keyof Params + ? [Params[K]] extends [string | number] + ? never + : K + : K; }[RoutePathMap[P] & string]; +type RequiredRouteParamError

= [ + MissingRouteParamKeys, +] extends [never] + ? [InvalidRouteParamKeys] extends [never] + ? never + : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.` + : MissingRouteParam>; type RouteUrlParamError

= [RoutePathMap[P]] extends [never] ? 'params' extends keyof O ? [O['params']] extends [undefined] @@ -187,18 +203,23 @@ type RouteUrlParamError

= [RoutePathMap[P]] extends [nev : never : O extends { params: infer Params } ? Params extends object - ? [Exclude] extends [never] - ? [MissingRouteParamKeys] extends [never] - ? [InvalidRouteParamKeys] extends [never] - ? never - : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.` - : MissingRouteParam> - : `Unknown param ${DiagnosticKeyName>} for route ${P}. Use the parameter names in the route pattern.` + ? string extends keyof Params + ? RequiredRouteParamError + : [Exclude] extends [never] + ? RequiredRouteParamError + : `Unknown param ${DiagnosticKeyName>} for route ${P}. Use the parameter names in the route pattern.` : `Params for route ${P} must be an object with the route's parameter names.` : MissingRouteParam; type RouteUrlQueryError

= [Query] extends [RouteQuery | undefined] ? never - : `Invalid query param ${DiagnosticKeyName, RouteQueryValue | ReadonlyArray>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`; + : [ + InvalidValueKeys< + Exclude, + RouteQueryValue | ReadonlyArray + >, + ] extends [never] + ? `Query for route ${P} must be an object with supported query values.` + : `Invalid query param ${DiagnosticKeyName, RouteQueryValue | ReadonlyArray>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`; type RouteUrlOptionsError

= [P] extends [RoutePath] ? O extends undefined ? MissingRouteParam @@ -214,29 +235,29 @@ type RouteUrlOptionsError

= [P] extends [RoutePath] | `Unknown routeUrl option: ${DiagnosticKeyName>}. Use params, query, or hash.` : `Options for route ${P} must be an object with params, query, or hash.` : never; +type RouteUrlCallArgs = [path: RoutePath | (string & {}), options?: unknown]; +type RouteUrlCallError

= [P] extends [RoutePath] + ? [RouteUrlOptionsError] extends [never] + ? `Invalid options for route ${P}. Pass an object with params, query, or hash.` + : RouteUrlOptionsError + : string extends P + ? 'Pass a route pattern literal to routeUrl(); string is too broad.' + : `Unknown route: ${P}. Pass a registered route pattern as the first argument.`; /** Build a relative URL from a known route pattern. */ export function routeUrl

(path: P, ...args: RouteUrlArgs>): RouteUrl; -// The default preserves the native tuple for explicit type arguments and -// Parameters>. Inferred diagnostic tuples always require -// an unsatisfied marker, even when an error calculation resolves to never. -export function routeUrl< - P extends RoutePath | (string & {}), - A extends [options?: unknown] = never, ->( - path: P & - ( - | RoutePath - | UrlTypeError< - string extends NoInfer

- ? 'Pass a route pattern literal to routeUrl(); string is too broad.' - : `Unknown route: ${NoInfer

}. Pass a registered route pattern as the first argument.` - > - ), - ...args: [A] extends [never] - ? RouteUrlArgs & RoutePath> +// Function helpers instantiate A at its constraint, where they must see the +// native checked tuple. Inferred calls capture a specific tuple and require an +// unsatisfied diagnostic marker. Both type arguments are required so

keeps +// selecting the native overload, including in Parameters>. +export function routeUrl

( + ...args: RouteUrlCallArgs extends A + ? [path: P, ...args: RouteUrlArgs>] : A & - [options?: RouteUrlOptionsInput, RoutePath>>] & - UrlTypeError, NoInfer[0]>> + [ + path: RoutePath | (string & {}), + options?: RouteUrlOptionsInput[0], RoutePath>>, + ] & + UrlTypeError[0], NoInfer[1]>> ): RouteUrl; export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl { return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 7b5b49622..ee39e6a95 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -1,13 +1,5 @@ import { spawnSync } from 'node:child_process'; -import { - cpSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - symlinkSync, - writeFileSync, -} from 'node:fs'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; @@ -24,6 +16,16 @@ import { readConfig } from '../../src/config.ts'; const packageRoot = join(import.meta.dirname, '../..'); const adapterSource = (path: string) => JSON.stringify(join(packageRoot, '..', path)); const roots: Array = []; +const compilers = [ + createRequire(import.meta.url), + createRequire(join(packageRoot, '../../playground/analog/package.json')), +].map((require) => ({ + version: require('typescript/package.json').version as string, + tsc: join(dirname(require.resolve('typescript/package.json')), 'bin/tsc'), +})); +const declarationChecks = compilers.flatMap((compiler) => + (['generated', 'package'] as const).map((declarations) => ({ ...compiler, declarations })), +); afterEach(() => { for (const root of roots.splice(0)) { @@ -456,6 +458,7 @@ function typecheck( declarations: 'generated' | 'package', include: Array, compilerOptions: Record = {}, + tsc = compilers[0].tsc, ) { const config = `tsconfig.${include.join('-')}.json`; writeFileSync( @@ -477,10 +480,6 @@ function typecheck( include, }), ); - const tsc = join( - dirname(createRequire(import.meta.url).resolve('typescript/package.json')), - 'bin/tsc', - ); const result = spawnSync(process.execPath, [tsc, '-p', join(root, config)], { encoding: 'utf8', }); @@ -488,9 +487,9 @@ function typecheck( } describe('standalone routeUrl utility', () => { - it.each(['generated', 'package'] as const)( - 'preserves generic helpers and structural options through the %s declarations', - async (declarations) => { + it.each(declarationChecks)( + 'preserves generic helpers and structural options through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { const root = await createFixture({ extraFiles: { 'check-compatibility.ts': `import { routeUrl, type RouteDestination, type RouteOptions, type RoutePath } from 'void/routes'; @@ -523,17 +522,114 @@ const destination: RouteDestination<'/users/[id]'> = { routeUrl('/users/[id]', destination); const staticDestination: RouteDestination<'/about'> = { pathname: '/about' }; routeUrl('/about', staticDestination); +declare const indexedParams: Record & { id: number }; +routeUrl('/users/[id]', { params: indexedParams }); void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs]; `, }, }); - expect(typecheck(root, declarations, ['check-compatibility.ts'])).toEqual({ + expect(typecheck(root, declarations, ['check-compatibility.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'checks function helpers through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-function-helpers.ts': `import { routeUrl, type RouteOptions, type RoutePath } from 'void/routes'; +function forward(...args: Parameters) { + return routeUrl(...args); +} +declare const options: RouteOptions; +const userUrl = routeUrl.bind(undefined, '/users/[id]'); +userUrl(options); +routeUrl.call(undefined, '/users/[id]', options); +routeUrl.apply(undefined, ['/users/[id]', options]); +forward('/users/[id]', options); +const specificUserUrl = (routeUrl<'/users/[id]'>).bind(undefined, '/users/[id]'); +specificUserUrl({ params: { id: 42 } }); +// @ts-expect-error bound functions retain required params +userUrl(); +// @ts-expect-error bound functions retain param value checks +userUrl({ params: { id: true } }); +// @ts-expect-error bound functions retain query value checks +userUrl({ ...options, query: { nested: { id: 42 } } }); +// @ts-expect-error call retains required params +routeUrl.call(undefined, '/users/[id]'); +// @ts-expect-error call retains param value checks +routeUrl.call(undefined, '/users/[id]', { params: { id: true } }); +// @ts-expect-error call retains route checks +routeUrl.call(undefined, '/missing', options); +// @ts-expect-error apply retains required params +routeUrl.apply(undefined, ['/users/[id]']); +// @ts-expect-error apply retains param value checks +routeUrl.apply(undefined, ['/users/[id]', { params: { id: true } }]); +// @ts-expect-error apply retains hash checks +routeUrl.apply(undefined, ['/users/[id]', { ...options, hash: 42 }]); +// @ts-expect-error extracted arguments retain required params +forward('/users/[id]'); +// @ts-expect-error extracted arguments retain param value checks +forward('/users/[id]', { params: { id: true } }); +// @ts-expect-error widening a route type cannot bypass static-route checks +routeUrl('/about', options); +// @ts-expect-error widening a route type cannot bypass dynamic-route checks +routeUrl('/users/[id]', options); +// @ts-expect-error explicit diagnostic type arguments cannot widen the route type +routeUrl('/about', options); +`, + }, + }); + expect(typecheck(root, declarations, ['check-function-helpers.ts'], {}, tsc)).toEqual({ output: '', status: 0, }); }, ); + it.each([false, true])( + 'retains legacy Node URL checks with skipLibCheck=%s', + async (skipLibCheck) => { + const root = await createFixture({ + typedRoutes: true, + extraFiles: { + 'check-legacy.ts': `import { routeUrl, type Href } from 'void/routes'; +routeUrl('/about'); +routeUrl('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error unknown route patterns remain checked +routeUrl('/missing'); +// @ts-expect-error required params remain checked +routeUrl('/users/[id]'); +// @ts-expect-error raw URLs retain their existing checks +const unknown: Href = '/missing'; +void unknown; +`, + }, + }); + const { scan } = await analyzeApplication(root, { config: readConfig(root) }); + // Legacy resolution can consume generated routes without resolving SDK runtime imports. + scan.routes = scan.routes.map((route) => ({ ...route, methods: [] })); + writeFileSync( + join(root, '.void/routes.d.ts'), + generateRouteTypes(scan, join(root, 'routes'), join(root, '.void'), undefined, { + typedRoutes: true, + }).dts, + ); + expect( + typecheck( + root, + 'generated', + ['check-legacy.ts'], + { moduleResolution: 'node', ignoreDeprecations: '6.0', skipLibCheck }, + compilers[1].tsc, + ), + ).toEqual({ output: '', status: 0 }); + }, + ); + it.each(['generated', 'package'] as const)( 'retains URL checks after an SDK upgrade without regenerating the %s declarations', async (declarations) => { @@ -549,17 +645,48 @@ void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forward 'route-types.ts', ) ).code; - function createSdkVersion(version: string): string { + function createSdkVersion(version: string, updateQueryTypes = false): string { const directory = join(root, 'node_modules/.pnpm', `void@${version}/node_modules/void`); mkdirSync(join(directory, 'src/codegen'), { recursive: true }); - cpSync(join(packageRoot, 'dist'), join(directory, 'dist'), { recursive: true }); + const copied = new Set(); + function copyDeclaration(path: string): void { + if (copied.has(path)) { + return; + } + copied.add(path); + const content = readFileSync(join(packageRoot, path), 'utf8'); + mkdirSync(dirname(join(directory, path)), { recursive: true }); + writeFileSync(join(directory, path), content); + for (const [, specifier] of content.matchAll( + /(?:from\s*|import\()\s*["'](\.[^"']+)["']/g, + )) { + copyDeclaration(join(dirname(path), specifier.replace(/\.mjs$/, '.d.mts'))); + } + } + copyDeclaration(manifest.exports['./routes'].types); + copyDeclaration(manifest.exports['./_route-url-types'].types); + if (updateQueryTypes) { + // Give the second SDK a different contract, not just a different location. + const path = [...copied].find((path) => + readFileSync(join(directory, path), 'utf8').includes('type RouteQueryValue ='), + ); + expect(path).toBeDefined(); + const file = join(directory, path!); + const previous = readFileSync(file, 'utf8'); + const updated = previous.replace( + 'type RouteQueryValue = string | number | boolean | null | undefined;', + 'type RouteQueryValue = string | number | null | undefined;', + ); + expect(updated).not.toBe(previous); + writeFileSync(file, updated); + } symlinkSync(join(packageRoot, 'node_modules'), join(directory, 'node_modules'), 'junction'); writeFileSync(join(directory, 'src/codegen/route-types.mjs'), generatorCode); writeFileSync(join(directory, 'package.json'), JSON.stringify({ ...manifest, version })); return directory; } const oldSdk = createSdkVersion('1.9.1'); - const newSdk = createSdkVersion('1.9.2'); + const newSdk = createSdkVersion('1.9.2', true); symlinkSync(oldSdk, packageLink, 'junction'); writeFileSync(join(root, 'package.json'), '{"type":"module"}'); const generator = pathToFileURL(join(oldSdk, 'src/codegen/route-types.mjs')).href; @@ -587,11 +714,11 @@ process.stdout.write(generateRouteTypes(scan, ${JSON.stringify(join(root, 'route join(outDir, 'tsconfig.json'), JSON.stringify(createProjectTsconfig(root, true)), ); - writeFileSync( - join(root, 'check-upgrade.ts'), - `import { routeUrl, type Href } from 'void/routes'; + const upgradeCheck = `import { routeUrl, type Href, type RouteQuery } from 'void/routes'; const href: Href = routeUrl('/users/[id]', { params: { id: 42 } }); routeUrl('/about'); +const query: RouteQuery = { enabled: true }; +routeUrl('/about', { query: { enabled: true } }); // @ts-expect-error unknown route patterns remain checked routeUrl('/missing'); // @ts-expect-error required params remain checked @@ -600,9 +727,9 @@ routeUrl('/users/[id]'); routeUrl('/users/[id]', { params: { id: true } }); // @ts-expect-error raw URLs retain their existing route checks const unknown: Href = '/missing'; -void [href, unknown]; -`, - ); +void [href, unknown, query]; +`; + writeFileSync(join(root, 'check-upgrade.ts'), upgradeCheck); expect(typecheck(root, declarations, ['check-upgrade.ts'])).toEqual({ output: '', status: 0, @@ -613,6 +740,18 @@ void [href, unknown]; rmSync(oldSdk, { force: true, recursive: true }); expect(readFileSync(routeTypesPath, 'utf8')).toBe(generation.stdout); + writeFileSync( + join(root, 'check-upgrade.ts'), + upgradeCheck + .replace( + 'const query:', + '// @ts-expect-error the new SDK query type is used\nconst query:', + ) + .replace( + "routeUrl('/about', { query:", + "// @ts-expect-error the new SDK function signature is used\nrouteUrl('/about', { query:", + ), + ); expect(typecheck(root, declarations, ['check-upgrade.ts'])).toEqual({ output: '', status: 0, @@ -620,9 +759,9 @@ void [href, unknown]; }, ); - it.each(['generated', 'package'] as const)( - 'rejects invalid unions and numeric keys through the %s declarations', - async (declarations) => { + it.each(declarationChecks)( + 'rejects invalid unions and numeric keys through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { const root = await createFixture({ extraFiles: { 'check-invalid-unions.ts': `import { routeUrl } from 'void/routes'; @@ -654,16 +793,16 @@ routeUrl('/users/[id]'); `, }, }); - expect(typecheck(root, declarations, ['check-invalid-unions.ts'])).toEqual({ + expect(typecheck(root, declarations, ['check-invalid-unions.ts'], {}, tsc)).toEqual({ output: '', status: 0, }); }, ); - it.each(['generated', 'package'] as const)( - 'explains invalid routeUrl calls through the %s declarations', - async (declarations) => { + it.each(declarationChecks)( + 'explains invalid routeUrl calls through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { const cases = [ ["routeUrl('/missing');", 'Unknown route: /missing.'], ["routeUrl('/missing', {});", 'Unknown route: /missing.'], @@ -689,6 +828,34 @@ routeUrl('/users/[id]'); ], ["routeUrl('/about', { params: {} });", 'Route /about has no path params.'], ["routeUrl('/about', { hash: 123 });", 'Hash for route /about must be a string.'], + [ + "routeUrl('/users/[id]', { params: {} as Record });", + 'Missing param id for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: {} as { id?: string } });", + 'Missing param id for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: {} as Record & { id: boolean } });", + 'Param id for route /users/[id] must be a string or number.', + ], + [ + "routeUrl('/users/[id]', { params: {} as Record & { id: string }, query: { nested: {} } });", + 'Invalid query param nested for route /users/[id].', + ], + [ + "routeUrl('/about', { query: () => 'x' });", + 'Query for route /about must be an object with supported query values.', + ], + [ + "routeUrl('/about', { query: null });", + 'Query for route /about must be an object with supported query values.', + ], + [ + "routeUrl('/about', () => 'x');", + 'Invalid options for route /about. Pass an object with params, query, or hash.', + ], [ "routeUrl('/about', { query: { nested: { value: 'x' } } });", 'Invalid query param nested for route /about.', @@ -718,14 +885,16 @@ routeUrl('/users/[id]'); ].join('\n'), }, }); - const { output, status } = typecheck(root, declarations, ['check-diagnostics.ts']); - expect(status).toBe(1); + const { output, status } = typecheck(root, declarations, ['check-diagnostics.ts'], {}, tsc); + expect(status).not.toBe(0); const diagnostics = output .split(/.*check-diagnostics\.ts\(\d+,\d+\): error TS\d+: /) .slice(1); expect(diagnostics).toHaveLength(cases.length); cases.forEach(([, message], index) => expect(diagnostics[index]).toContain(message)); expect(output).not.toContain('TS2554'); + expect(output).not.toContain('UrlTypeError'); + expect(output).not.toContain('Unknown param ${string}'); }, ); From b1521b7a78b6e77d3132f5b03d904819378dbd53 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Tue, 17 Nov 2026 18:39:38 +0800 Subject: [PATCH 05/12] fix(routes): clarify diagnostics on invalid arguments --- docs/guide/type-safety.md | 2 + packages/void/AGENTS.md | 5 + .../void/src/runtime/routing/route-url.ts | 70 ++++++----- .../src/runtime/routing/url-diagnostics.ts | 4 +- .../integration/route-url-builder.test.ts | 112 ++++++++++++++++++ 5 files changed, 164 insertions(+), 29 deletions(-) diff --git a/docs/guide/type-safety.md b/docs/guide/type-safety.md index 4f3de869e..824bf4829 100644 --- a/docs/guide/type-safety.md +++ b/docs/guide/type-safety.md @@ -149,6 +149,8 @@ const url = routeUrl('/users/[id]', { TypeScript checks the route and required parameter names. Patterns follow your filenames: `pages/users/[id].tsx`, `.vue`, or `.svelte` uses `/users/[id]`. +Type errors identify unknown route patterns and missing or invalid parameters. + Parameters accept strings or numbers and are URL-encoded for you. Query values can be strings, numbers, booleans, or arrays. Arrays become repeated keys; `null` and `undefined` values are omitted. The same bracket patterns work with typed `fetch()`, WebSocket `connect()`, page actions, and `useParams()`. diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 9ab870aec..5503ee14a 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -173,6 +173,11 @@ Vite/CLI dependency graph. `void/remote` stays exported only for semver. Generated code imports `#self/remote`. Remove the subpath in the next major version. +Generated `.void/routes.d.ts` files import `void/_route-url-types`. Keep this +types-only export and its legacy `typesVersions` mapping stable across compatible +SDK releases, including when an app has not regenerated its declarations. +Removing or renaming it requires an explicit breaking-change migration plan. + Build output uses `.mjs` / `.d.mts` extensions (`vp pack` / tsdown default). ### Route Filename Parsing Rules diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index ad61b6d4a..fdb1b1041 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -160,11 +160,6 @@ type UrlOptions = { // Diagnostics describe invalid calls; the valid-call overload below remains // independent so generic helpers and structural objects retain their contract. -type RouteUrlOptionsInput

= { - params?: { [K in RoutePathMap[P] & string]?: unknown } | Record; - query?: Record; - hash?: unknown; -}; type RouteUrlArgs

= [RoutePathMap[P]] extends [never] ? [options?: RouteOptions

] : [options: RouteOptions

]; @@ -224,18 +219,16 @@ type RouteUrlOptionsError

= [P] extends [RoutePath] ? O extends undefined ? MissingRouteParam : O extends object - ? - | RouteUrlParamError - | ('query' extends keyof O ? RouteUrlQueryError : never) - | ('hash' extends keyof O - ? [O['hash']] extends [string | undefined] - ? never - : `Hash for route ${P} must be a string.` - : never) - | `Unknown routeUrl option: ${DiagnosticKeyName>}. Use params, query, or hash.` + ? | RouteUrlParamError + | ('query' extends keyof O ? RouteUrlQueryError : never) + | ('hash' extends keyof O + ? [O['hash']] extends [string | undefined] + ? never + : `Hash for route ${P} must be a string.` + : never) + | `Unknown routeUrl option: ${DiagnosticKeyName>}. Use params, query, or hash.` : `Options for route ${P} must be an object with params, query, or hash.` : never; -type RouteUrlCallArgs = [path: RoutePath | (string & {}), options?: unknown]; type RouteUrlCallError

= [P] extends [RoutePath] ? [RouteUrlOptionsError] extends [never] ? `Invalid options for route ${P}. Pass an object with params, query, or hash.` @@ -243,21 +236,42 @@ type RouteUrlCallError

= [P] extends [RoutePath] : string extends P ? 'Pass a route pattern literal to routeUrl(); string is too broad.' : `Unknown route: ${P}. Pass a registered route pattern as the first argument.`; +type UnknownRouteUrlOptions = { + [ + K in Exclude + ]: UrlTypeError<`Unknown routeUrl option: ${DiagnosticKeyName}. Use params, query, or hash.`>; +}; +// Keep the diagnostic branch uninhabitable, even for boxed strings or index signatures. +declare const invalid: unique symbol; /** Build a relative URL from a known route pattern. */ export function routeUrl

(path: P, ...args: RouteUrlArgs>): RouteUrl; -// Function helpers instantiate A at its constraint, where they must see the -// native checked tuple. Inferred calls capture a specific tuple and require an -// unsatisfied diagnostic marker. Both type arguments are required so

keeps -// selecting the native overload, including in Parameters>. -export function routeUrl

( - ...args: RouteUrlCallArgs extends A - ? [path: P, ...args: RouteUrlArgs>] - : A & - [ - path: RoutePath | (string & {}), - options?: RouteUrlOptionsInput[0], RoutePath>>, - ] & - UrlTypeError[0], NoInfer[1]>> +// Function helpers instantiate O as unknown and retain the native checked signature. +// Calls infer S and O independently, so diagnostics point at the incorrect argument. +// Requiring two type arguments keeps

and Parameters> native. +export function routeUrl

( + path: unknown extends O + ? S & P + : [O] extends [never] + ? { + readonly 'This route may require params. Pass its options as the second argument.': never; + readonly [invalid]: never; + } & UrlTypeError> + : S & + ([S] extends [RoutePath] + ? unknown + : UrlTypeError, undefined>>), + ...args: unknown extends O + ? RouteUrlArgs> + : [O] extends [never] + ? [options?: never] + : [ + options: [O] extends [object] + ? ([Exclude] extends [never] + ? RouteUrlCallError, NoInfer> + : UnknownRouteUrlOptions) & + O & { readonly [invalid]: never } + : UrlTypeError, NoInfer>>, + ] ): RouteUrl; export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl { return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl; diff --git a/packages/void/src/runtime/routing/url-diagnostics.ts b/packages/void/src/runtime/routing/url-diagnostics.ts index 51cad1200..b3ce144ab 100644 --- a/packages/void/src/runtime/routing/url-diagnostics.ts +++ b/packages/void/src/runtime/routing/url-diagnostics.ts @@ -1,5 +1,7 @@ /** An unsatisfied marker for diagnostic fallbacks, never an accepted input. */ -export type UrlTypeError = { readonly __voidUrlError: Message }; +export type UrlTypeError = [Message] extends [never] + ? never + : { readonly [K in Message]: never }; /** Inspect every union member, including members with disjoint property names. */ export type InvalidValueKeys = Values extends unknown diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index ee39e6a95..c7e19f7a8 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -790,6 +790,22 @@ routeUrl('/about', options); routeUrl<'/users/[id]'>('/users/[id]', { params: { id: 42, extra: 'x' } }); // @ts-expect-error widening the type argument cannot omit required params routeUrl('/users/[id]'); +declare const uncheckedOptions: Record; +// @ts-expect-error index signatures cannot satisfy the diagnostic rejection guard +routeUrl('/users/[id]', uncheckedOptions); +const boxed = Object.assign('Param id for route /users/[id] must be a string or number.' as const, { params: { id: true } }); +// @ts-expect-error a boxed diagnostic message is still invalid options +routeUrl('/users/[id]', boxed); +// @ts-expect-error diagnostic message strings cannot act as options +routeUrl('/about', 'Invalid options for route /about. Pass an object with params, query, or hash.'); +// @ts-expect-error diagnostic message values cannot turn unknown options into valid ones +routeUrl('/about', { search: 'Unknown routeUrl option: search. Use params, query, or hash.' }); +const fakePath = { + get 'This route may require params. Pass its options as the second argument.'(): never { throw new Error(); }, + get 'Pass a route pattern literal to routeUrl(); string is too broad.'(): never { throw new Error(); }, +}; +// @ts-expect-error diagnostic objects cannot act as route patterns +routeUrl(fakePath); `, }, }); @@ -895,6 +911,102 @@ routeUrl('/users/[id]'); expect(output).not.toContain('TS2554'); expect(output).not.toContain('UrlTypeError'); expect(output).not.toContain('Unknown param ${string}'); + expect(output).not.toContain('RouteUrlOptionsInput'); + expect(output).not.toContain('__voidUrlError'); + expect(diagnostics[7]).toContain( + `parameter of type '"Unknown param userId for route /users/[id].`, + ); + expect(diagnostics[7]).not.toContain('Argument of type \'["/users/[id]"'); + }, + ); + + it.each(declarationChecks)( + 'explains missing options for generic routes through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-generic-diagnostic.ts': `import { routeUrl, type RoutePath } from 'void/routes'; +function bare

(path: P) { + return routeUrl(path); +} +void bare; +`, + }, + }); + const { output, status } = typecheck( + root, + declarations, + ['check-generic-diagnostic.ts'], + {}, + tsc, + ); + expect(status).not.toBe(0); + expect(output).toContain( + 'This route may require params. Pass its options as the second argument.', + ); + }, + ); + + it.each(['generated', 'package'] as const)( + 'keeps diagnostic details out of completions through the %s declarations', + async (declarations) => { + const root = await createFixture(); + const check = join(root, 'check-completions.ts'); + writeFileSync( + check, + `import { routeUrl } from 'void/routes'; +routeUrl('/*route*/'); +routeUrl('/users/[id]', { /*options*/ }); +routeUrl('/users/[id]', { params: { /*params*/ } }); +`, + ); + const tsModule = createRequire(compilers[1].tsc).resolve('typescript'); + const options = { + target: 'ES2022', + module: declarations === 'generated' ? 'ESNext' : 'NodeNext', + moduleResolution: declarations === 'generated' ? 'Bundler' : 'NodeNext', + strict: true, + skipLibCheck: true, + types: [], + paths: + declarations === 'generated' ? { 'void/routes': [join(root, '.void/routes.d.ts')] } : {}, + }; + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import ts from ${JSON.stringify(pathToFileURL(tsModule).href)}; +const root = ${JSON.stringify(root)}; +const file = ${JSON.stringify(check)}; +const content = ts.sys.readFile(file); +const options = ts.convertCompilerOptionsFromJson(${JSON.stringify(options)}, root).options; +const service = ts.createLanguageService({ + getScriptFileNames: () => [file, ${JSON.stringify(join(root, '.void/routes.d.ts'))}], + getScriptVersion: () => '0', + getScriptSnapshot: (path) => ts.sys.fileExists(path) ? ts.ScriptSnapshot.fromString(ts.sys.readFile(path)) : undefined, + getCurrentDirectory: () => root, + getCompilationSettings: () => options, + getDefaultLibFileName: (settings) => ts.getDefaultLibFilePath(settings), + fileExists: ts.sys.fileExists, + readFile: ts.sys.readFile, + readDirectory: ts.sys.readDirectory, +}); +const completions = Object.fromEntries(['route', 'options', 'params'].map((marker) => [ + marker, + (service.getCompletionsAtPosition(file, content.indexOf('/*' + marker + '*/'), {})?.entries ?? []).map((entry) => entry.name).sort(), +])); +service.dispose(); +process.stdout.write(JSON.stringify(completions));`, + ], + { encoding: 'utf8' }, + ); + expect({ status: result.status, errors: result.stderr }).toEqual({ status: 0, errors: '' }); + const completions = JSON.parse(result.stdout); + expect(completions.route).toEqual(expect.arrayContaining(['/about', '/users/[id]'])); + expect(completions.route.every((name: string) => name.startsWith('/'))).toBe(true); + expect(completions.options).toEqual(['hash', 'params', 'query']); + expect(completions.params).toEqual(['id']); }, ); From 2bb401ab16a2d5af4658d44361666f6d0335ba9f Mon Sep 17 00:00:00 2001 From: Yangshun Date: Wed, 18 Nov 2026 15:17:32 +0800 Subject: [PATCH 06/12] fix(routes): use native errors for known route options --- .../void/src/runtime/routing/route-url.ts | 135 +++---------- .../src/runtime/routing/url-diagnostics.ts | 14 +- .../integration/route-url-builder.test.ts | 191 +++++++++++++----- 3 files changed, 177 insertions(+), 163 deletions(-) diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index fdb1b1041..b7a2479ac 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -1,5 +1,5 @@ import type { EncodedRoutePathMap, RoutePathMap, RouteTypesConfig } from 'void/routes'; -import type { DiagnosticKeyName, InvalidValueKeys, UrlTypeError } from './url-diagnostics.ts'; +import type { UrlErrorToken, UrlTypeError } from './url-diagnostics.ts'; /** * Encode one path segment of a route param. `encodeURIComponent` keeps dots, and @@ -158,119 +158,48 @@ type UrlOptions = { hash?: string; }; -// Diagnostics describe invalid calls; the valid-call overload below remains -// independent so generic helpers and structural objects retain their contract. type RouteUrlArgs

= [RoutePathMap[P]] extends [never] ? [options?: RouteOptions

] : [options: RouteOptions

]; -type MissingRouteParam

= P extends RoutePath - ? K extends RoutePathMap[P] - ? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.` - : never - : never; -// An index signature permits a key without guaranteeing that it is present. -type RequiredParamKeys = keyof { - [K in keyof Params as string extends K ? never : {} extends Pick ? never : K]: unknown; -}; -type MissingRouteParamKeys

= Exclude< - RoutePathMap[P] & string, - RequiredParamKeys ->; -type InvalidRouteParamKeys

= { - [K in RoutePathMap[P] & string]: K extends keyof Params - ? [Params[K]] extends [string | number] - ? never - : K - : K; -}[RoutePathMap[P] & string]; -type RequiredRouteParamError

= [ - MissingRouteParamKeys, -] extends [never] - ? [InvalidRouteParamKeys] extends [never] +type UnknownRouteMessage

= string extends P + ? 'Expected a route pattern literal; string is too broad.' + : `Unknown route: ${Exclude}. Use a registered route pattern.`; +type RoutePathWithParams

= P extends RoutePath + ? [RoutePathMap[P]] extends [never] ? never - : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.` - : MissingRouteParam>; -type RouteUrlParamError

= [RoutePathMap[P]] extends [never] - ? 'params' extends keyof O - ? [O['params']] extends [undefined] - ? never - : `Route ${P} has no path params. Remove params.` - : never - : O extends { params: infer Params } - ? Params extends object - ? string extends keyof Params - ? RequiredRouteParamError - : [Exclude] extends [never] - ? RequiredRouteParamError - : `Unknown param ${DiagnosticKeyName>} for route ${P}. Use the parameter names in the route pattern.` - : `Params for route ${P} must be an object with the route's parameter names.` - : MissingRouteParam; -type RouteUrlQueryError

= [Query] extends [RouteQuery | undefined] - ? never - : [ - InvalidValueKeys< - Exclude, - RouteQueryValue | ReadonlyArray - >, - ] extends [never] - ? `Query for route ${P} must be an object with supported query values.` - : `Invalid query param ${DiagnosticKeyName, RouteQueryValue | ReadonlyArray>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`; -type RouteUrlOptionsError

= [P] extends [RoutePath] - ? O extends undefined - ? MissingRouteParam - : O extends object - ? | RouteUrlParamError - | ('query' extends keyof O ? RouteUrlQueryError : never) - | ('hash' extends keyof O - ? [O['hash']] extends [string | undefined] - ? never - : `Hash for route ${P} must be a string.` - : never) - | `Unknown routeUrl option: ${DiagnosticKeyName>}. Use params, query, or hash.` - : `Options for route ${P} must be an object with params, query, or hash.` + : P : never; -type RouteUrlCallError

= [P] extends [RoutePath] - ? [RouteUrlOptionsError] extends [never] - ? `Invalid options for route ${P}. Pass an object with params, query, or hash.` - : RouteUrlOptionsError - : string extends P - ? 'Pass a route pattern literal to routeUrl(); string is too broad.' - : `Unknown route: ${P}. Pass a registered route pattern as the first argument.`; -type UnknownRouteUrlOptions = { - [ - K in Exclude - ]: UrlTypeError<`Unknown routeUrl option: ${DiagnosticKeyName}. Use params, query, or hash.`>; -}; -// Keep the diagnostic branch uninhabitable, even for boxed strings or index signatures. -declare const invalid: unique symbol; + /** Build a relative URL from a known route pattern. */ export function routeUrl

(path: P, ...args: RouteUrlArgs>): RouteUrl; -// Function helpers instantiate O as unknown and retain the native checked signature. -// Calls infer S and O independently, so diagnostics point at the incorrect argument. -// Requiring two type arguments keeps

and Parameters> native. +// Function helpers instantiate O as unknown and keep the original checked tuple. +// Explicit

calls use the valid overload because this one requires two type arguments. +// Known routes with options repeat the native types so their errors show the +// required properties and values, rather than a sentence used as a string type. export function routeUrl

( path: unknown extends O - ? S & P - : [O] extends [never] - ? { - readonly 'This route may require params. Pass its options as the second argument.': never; - readonly [invalid]: never; - } & UrlTypeError> - : S & - ([S] extends [RoutePath] - ? unknown - : UrlTypeError, undefined>>), + ? string extends S + ? S & P + : [S] extends [RoutePath] + ? S & P + : S & UrlTypeError>> & UrlErrorToken + : [S] extends [RoutePath] + ? [O] extends [undefined] + ? UrlTypeError<`Missing options for ${RoutePathWithParams & RoutePath>}. Pass { params: { ... } } as the second argument.`> & + UrlErrorToken + : S + : S & UrlTypeError>> & UrlErrorToken, ...args: unknown extends O ? RouteUrlArgs> - : [O] extends [never] - ? [options?: never] - : [ - options: [O] extends [object] - ? ([Exclude] extends [never] - ? RouteUrlCallError, NoInfer> - : UnknownRouteUrlOptions) & - O & { readonly [invalid]: never } - : UrlTypeError, NoInfer>>, + : [O] extends [undefined] + ? [options?: undefined] + : // Infer O before selecting the known route's native options type. + [ + options: O extends never + ? O + : [S] extends [RoutePath] + ? RouteOptions & RoutePath> + : unknown, ] ): RouteUrl; export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl { diff --git a/packages/void/src/runtime/routing/url-diagnostics.ts b/packages/void/src/runtime/routing/url-diagnostics.ts index b3ce144ab..a0a78a891 100644 --- a/packages/void/src/runtime/routing/url-diagnostics.ts +++ b/packages/void/src/runtime/routing/url-diagnostics.ts @@ -3,14 +3,6 @@ export type UrlTypeError = [Message] extends [never] ? never : { readonly [K in Message]: never }; -/** Inspect every union member, including members with disjoint property names. */ -export type InvalidValueKeys = Values extends unknown - ? { [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K }[keyof Values] - : never; - -/** Preserve numeric and symbol keys when explaining an invalid property. */ -export type DiagnosticKeyName = K extends string | number - ? `${K}` - : K extends symbol - ? 'symbol' - : never; +declare const invalid: unique symbol; +/** A private token prevents diagnostic path types from becoming valid inputs. */ +export type UrlErrorToken = { readonly [invalid]: never }; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index c7e19f7a8..578c492b2 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -330,6 +330,7 @@ async function createFixture({ 'pages/café menu.tsx': 'export default function Page() { return null; }', 'pages/café/[id].tsx': 'export default function Page() { return null; }', 'pages/users/[id].tsx': 'export default function Page() { return null; }', + 'pages/blog/[category]/[slug].tsx': 'export default function Page() { return null; }', 'pages/files/[...path].tsx': 'export default function Page() { return null; }', 'pages/wild/[...].tsx': 'export default function Page() { return null; }', 'check.ts': `import type { Context, MiddlewareHandler } from 'hono'; @@ -760,17 +761,20 @@ void [href, unknown, query]; ); it.each(declarationChecks)( - 'rejects invalid unions and numeric keys through $declarations declarations with TS $version', + 'keeps invalid inputs rejected through $declarations declarations with TS $version', async ({ declarations, tsc }) => { const root = await createFixture({ extraFiles: { - 'check-invalid-unions.ts': `import { routeUrl } from 'void/routes'; + 'check-invalid-unions.ts': `import { routeUrl, type RoutePath } from 'void/routes'; declare const query: { q: string } | { filter: { id: number } }; // @ts-expect-error every query union member must contain supported values routeUrl('/about', { query }); declare const optionalQuery: { q?: string } | { filter?: { id: number } }; // @ts-expect-error optional query keys cannot hide invalid union members routeUrl('/about', { query: optionalQuery }); +declare const overlappingQuery: { q: string } | { q: string; filter: { id: number } }; +// @ts-expect-error a valid union member cannot hide invalid values on another member +routeUrl('/about', { query: overlappingQuery }); // @ts-expect-error numeric params do not supply the required id routeUrl('/users/[id]', { params: { 0: 'missing-id' } }); // @ts-expect-error fresh numeric extra params are still rejected @@ -793,19 +797,54 @@ routeUrl('/users/[id]'); declare const uncheckedOptions: Record; // @ts-expect-error index signatures cannot satisfy the diagnostic rejection guard routeUrl('/users/[id]', uncheckedOptions); -const boxed = Object.assign('Param id for route /users/[id] must be a string or number.' as const, { params: { id: true } }); +const boxed = Object.assign('Param id for /users/[id] must be a string or number.' as const, { params: { id: true } }); // @ts-expect-error a boxed diagnostic message is still invalid options routeUrl('/users/[id]', boxed); // @ts-expect-error diagnostic message strings cannot act as options -routeUrl('/about', 'Invalid options for route /about. Pass an object with params, query, or hash.'); +routeUrl('/about', 'Options for /about must be an object.'); // @ts-expect-error diagnostic message values cannot turn unknown options into valid ones -routeUrl('/about', { search: 'Unknown routeUrl option: search. Use params, query, or hash.' }); +routeUrl('/about', { search: 'Unknown routeUrl option: search.' }); const fakePath = { - get 'This route may require params. Pass its options as the second argument.'(): never { throw new Error(); }, - get 'Pass a route pattern literal to routeUrl(); string is too broad.'(): never { throw new Error(); }, + get 'Missing options for /users/[id]. Pass { params: { ... } } as the second argument.'(): never { throw new Error(); }, + get 'Expected a route pattern literal; string is too broad.'(): never { throw new Error(); }, }; // @ts-expect-error diagnostic objects cannot act as route patterns routeUrl(fakePath); +const fakeUnknownPath = Object.assign('/missing' as const, { + get 'Unknown route: /missing. Use a registered route pattern.'(): never { throw new Error(); }, +}); +// @ts-expect-error a boxed error message cannot make an unknown path valid +routeUrl(fakeUnknownPath); +const fakeMissingOptions = { + get 'Missing options for /users/[id]. Pass { params: { ... } } as the second argument.'(): never { throw new Error(); }, +}; +// @ts-expect-error a diagnostic object cannot replace a path and its required options +routeUrl(fakeMissingOptions); +// @ts-expect-error a diagnostic message cannot become a params object +routeUrl('/users/[id]', { params: "Params for /users/[id] must be an object." }); +// @ts-expect-error a diagnostic message cannot become a query object +routeUrl('/about', { query: 'Query for /about must be an object with supported query values.' }); +// @ts-expect-error an any-valued unknown option remains invalid +routeUrl('/about', { search: undefined as any }); +// @ts-expect-error an array of diagnostic messages cannot become options +routeUrl('/about', ['Unknown routeUrl option: 0.'] as const); +// @ts-expect-error explicit diagnostic type arguments retain native params checking +routeUrl('/users/[id]', { params: 'Param id for /users/[id] must be a string or number.' }); +// @ts-expect-error diagnostic type arguments cannot widen the original checked tuple +routeUrl('/users/[id]', { params: 'Param id for /users/[id] must be a string or number.' }); +`, + 'check-exact-optional.ts': `import { routeUrl } from 'void/routes'; +routeUrl('/about'); +routeUrl('/users/[id]', { params: { id: 42 } }); +declare const value: any; +// @ts-expect-error exact optional properties do not allow params on static routes +routeUrl('/about', { params: value }); +// @ts-expect-error query cannot be explicitly undefined in exact mode +routeUrl('/about', { query: undefined }); +// @ts-expect-error hash cannot be explicitly undefined in exact mode +routeUrl('/about', { hash: undefined }); +// @ts-expect-error fresh extra params stay rejected when their value is any +routeUrl('/users/[id]', { params: { id: 42, extra: value } }); `, }, }); @@ -813,84 +852,121 @@ routeUrl(fakePath); output: '', status: 0, }); + expect( + typecheck( + root, + declarations, + ['check-exact-optional.ts'], + { exactOptionalPropertyTypes: true }, + tsc, + ), + ).toEqual({ output: '', status: 0 }); }, ); it.each(declarationChecks)( - 'explains invalid routeUrl calls through $declarations declarations with TS $version', - async ({ declarations, tsc }) => { - const cases = [ - ["routeUrl('/missing');", 'Unknown route: /missing.'], - ["routeUrl('/missing', {});", 'Unknown route: /missing.'], - ["routeUrl('/users/42');", 'Unknown route: /users/42.'], - ["routeUrl('/users/[id]');", 'Missing param id for route /users/[id].'], - ["routeUrl('/users/[id]', {});", 'Missing param id for route /users/[id].'], + 'uses native option errors and custom path errors through $declarations declarations with TS $version', + async ({ declarations, tsc, version }) => { + const cases: Array<[call: string, message: string | RegExp, kind: 'native' | 'custom']> = [ + ["routeUrl('/missing');", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', {});", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/users/42');", 'Unknown route: /users/42.', 'custom'], + ["routeUrl('/users/[id]');", 'Missing options for /users/[id].', 'custom'], + ["routeUrl('/users/[id]', {});", "Property 'params' is missing", 'native'], [ "routeUrl('/users/[id]', { query: { page: 1 } });", - 'Missing param id for route /users/[id].', + "Property 'params' is missing", + 'native', ], - ["routeUrl('/users/[id]', { params: {} });", 'Missing param id for route /users/[id].'], + ["routeUrl('/users/[id]', { params: {} });", "Property 'id' is missing", 'native'], [ "routeUrl('/users/[id]', { params: { userId: 42 } });", - 'Unknown param userId for route /users/[id].', + "'userId' does not exist", + 'native', ], [ "routeUrl('/users/[id]', { params: { id: 42, extra: 'x' } });", - 'Unknown param extra for route /users/[id].', + "'extra' does not exist", + 'native', ], [ "routeUrl('/users/[id]', { params: { id: true } });", - 'Param id for route /users/[id] must be a string or number.', + "Type 'boolean' is not assignable to type 'string | number'.", + 'native', + ], + [ + "routeUrl('/about', { params: {} });", + "Type '{}' is not assignable to type 'undefined'.", + 'native', + ], + [ + "routeUrl('/about', { hash: 123 });", + "Type 'number' is not assignable to type 'string'.", + 'native', ], - ["routeUrl('/about', { params: {} });", 'Route /about has no path params.'], - ["routeUrl('/about', { hash: 123 });", 'Hash for route /about must be a string.'], [ "routeUrl('/users/[id]', { params: {} as Record });", - 'Missing param id for route /users/[id].', + "Property 'id' is missing", + 'native', ], [ "routeUrl('/users/[id]', { params: {} as { id?: string } });", - 'Missing param id for route /users/[id].', + "Type 'undefined' is not assignable to type 'string | number'.", + 'native', ], [ "routeUrl('/users/[id]', { params: {} as Record & { id: boolean } });", - 'Param id for route /users/[id] must be a string or number.', + "Type 'boolean' is not assignable to type 'string | number'.", + 'native', ], [ "routeUrl('/users/[id]', { params: {} as Record & { id: string }, query: { nested: {} } });", - 'Invalid query param nested for route /users/[id].', + /Type '\{\}' is not assignable to type '.*RouteQueryValue/, + 'native', ], [ "routeUrl('/about', { query: () => 'x' });", - 'Query for route /about must be an object with supported query values.', + "Index signature for type 'string' is missing", + 'native', ], [ "routeUrl('/about', { query: null });", - 'Query for route /about must be an object with supported query values.', - ], - [ - "routeUrl('/about', () => 'x');", - 'Invalid options for route /about. Pass an object with params, query, or hash.', + "Type 'null' is not assignable to type 'RouteQuery | undefined'.", + 'native', ], + ["routeUrl('/about', () => 'x');", 'has no properties in common', 'native'], [ "routeUrl('/about', { query: { nested: { value: 'x' } } });", - 'Invalid query param nested for route /about.', + "'value' does not exist", + 'native', ], [ "routeUrl('/about', { query: null as unknown as { q: string } | { filter: { id: number } } });", - 'Invalid query param filter for route /about.', + "Property 'filter' is incompatible with index signature.", + 'native', ], [ "routeUrl('/users/[id]', { params: { 0: 'missing-id' } });", - 'Unknown param 0 for route /users/[id].', + "'0' does not exist", + 'native', ], - ["routeUrl('/about', { 0: 'unknown' });", 'Unknown routeUrl option: 0.'], - ["routeUrl('/about', { search: 'x' });", 'Unknown routeUrl option: search.'], - ["routeUrl('/users/[id]', undefined);", 'Missing param id for route /users/[id].'], - ["routeUrl('' as '/about' | '/users/[id]');", 'Missing param id for route /users/[id].'], + ["routeUrl('/about', { 0: 'unknown' });", "'0' does not exist", 'native'], + ["routeUrl('/about', { search: 'x' });", "'search' does not exist", 'native'], + ["routeUrl('/users/[id]', undefined);", 'Missing options for /users/[id].', 'custom'], + ["routeUrl('' as '/about' | '/users/[id]');", 'Missing options for /users/[id].', 'custom'], [ "routeUrl('' as string);", - 'Pass a route pattern literal to routeUrl(); string is too broad.', + 'Expected a route pattern literal; string is too broad.', + 'custom', + ], + ["routeUrl('' as '/about' | '/missing', {});", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', undefined);", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', {} as unknown);", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', {} as any);", 'Unknown route: /missing.', 'custom'], + [ + "routeUrl('/blog/[category]/[slug]', { params: { category: 'typescript' } });", + "Property 'slug' is missing", + 'native', ], ]; const root = await createFixture({ @@ -907,16 +983,34 @@ routeUrl(fakePath); .split(/.*check-diagnostics\.ts\(\d+,\d+\): error TS\d+: /) .slice(1); expect(diagnostics).toHaveLength(cases.length); - cases.forEach(([, message], index) => expect(diagnostics[index]).toContain(message)); + cases.forEach(([, message, kind], index) => { + expect(diagnostics[index]).toMatch(message); + if (kind === 'native') { + expect(diagnostics[index]).not.toContain('UrlTypeError'); + expect(diagnostics[index]).not.toContain('UrlErrorToken'); + expect(diagnostics[index]).not.toContain('[invalid]'); + expect(diagnostics[index]).not.toContain('Missing options for'); + expect(diagnostics[index]).not.toMatch( + /not assignable to type '"(?:Missing|Unknown|Invalid|Param|Query|Hash|Options)/, + ); + } + }); expect(output).not.toContain('TS2554'); expect(output).not.toContain('UrlTypeError'); - expect(output).not.toContain('Unknown param ${string}'); expect(output).not.toContain('RouteUrlOptionsInput'); expect(output).not.toContain('__voidUrlError'); - expect(diagnostics[7]).toContain( - `parameter of type '"Unknown param userId for route /users/[id].`, - ); - expect(diagnostics[7]).not.toContain('Argument of type \'["/users/[id]"'); + expect(diagnostics[25]).not.toContain('Missing options for /about.'); + expect(diagnostics[27]).not.toContain('Unknown route: /about.'); + const missingSlug = diagnostics.at(-1)!.trim(); + const detail = + "Property 'slug' is missing in type '{ category: string; }' but required in type '{ category: string | number; slug: string | number; }'."; + expect(missingSlug).toContain(detail); + if (version.startsWith('7.')) { + expect(missingSlug).toBe( + `No overload matches this call.\n The last overload gave the following error.\n ${detail}`, + ); + expect(missingSlug.length).toBeLessThan(250); + } }, ); @@ -941,9 +1035,8 @@ void bare; tsc, ); expect(status).not.toBe(0); - expect(output).toContain( - 'This route may require params. Pass its options as the second argument.', - ); + expect(output).toContain('Missing options for'); + expect(output).toContain('Pass { params: { ... } } as the second argument.'); }, ); From 24ee3d631d59b50cca024622542e68eeefafa3c0 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Wed, 18 Nov 2026 16:19:48 +0800 Subject: [PATCH 07/12] fix(routes): restore callback and CommonJS type compatibility Preserve required options for paths typed as any. Keep routeUrl diagnostics and function helper types while making generated route types compatible with Node16 CommonJS projects. --- packages/void/src/codegen/route-types.ts | 14 ++-- .../void/src/runtime/routing/route-url.ts | 66 +++++++++++-------- .../integration/route-url-builder.test.ts | 58 ++++++++++++++-- packages/void/test/unit/route-types.test.ts | 5 +- 4 files changed, 103 insertions(+), 40 deletions(-) diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 433ccac01..784aa9ad2 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -141,7 +141,9 @@ export function generateRouteTypes( lines.push(''); // A bare types-only entry follows the installed SDK through upgrades. // void/routes would be circular because this file augments that entry. - const sdkRoutesModule = JSON.stringify('void/_route-url-types'); + // Resolve the SDK's ESM declarations from CommonJS projects as well. + const sdkRouteTypes = + 'import("void/_route-url-types", { with: { "resolution-mode": "import" } })'; for (const name of [ 'RoutePath', 'RouteQueryValue', @@ -150,15 +152,13 @@ export function generateRouteTypes( 'Href', 'RouteUrlInput', ]) { - lines.push(` export type ${name} = import(${sdkRoutesModule}).${name};`); + lines.push(` export type ${name} = ${sdkRouteTypes}.${name};`); } + lines.push(` export type RouteOptions

= ${sdkRouteTypes}.RouteOptions

;`); lines.push( - ` export type RouteOptions

= import(${sdkRoutesModule}).RouteOptions

;`, + ` export type RouteDestination

= ${sdkRouteTypes}.RouteDestination

;`, ); - lines.push( - ` export type RouteDestination

= import(${sdkRoutesModule}).RouteDestination

;`, - ); - lines.push(` export const routeUrl: typeof import(${sdkRoutesModule}).routeUrl;`); + lines.push(` export const routeUrl: typeof ${sdkRouteTypes}.routeUrl;`); lines.push(''); lines.push(' export interface RouteTypesConfig {'); if (options.typedRoutes) { diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index b7a2479ac..220b3855c 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -169,38 +169,52 @@ type RoutePathWithParams

= P extends RoutePath ? never : P : never; +type StaticRoutePath = Exclude>; +type IsAny = 0 extends 1 & T ? true : false; /** Build a relative URL from a known route pattern. */ export function routeUrl

(path: P, ...args: RouteUrlArgs>): RouteUrl; +// TypeScript erases Erased to any when comparing overloads to a callback. Give +// that comparison a static route signature. Calls can only instantiate it as never. // Function helpers instantiate O as unknown and keep the original checked tuple. // Explicit

calls use the valid overload because this one requires two type arguments. -// Known routes with options repeat the native types so their errors show the -// required properties and values, rather than a sentence used as a string type. -export function routeUrl

( - path: unknown extends O - ? string extends S - ? S & P - : [S] extends [RoutePath] +export function routeUrl< + P extends RoutePath, + S extends RoutePath | (string & {}), + O = never, + Erased extends never = never, +>( + path: IsAny extends true + ? StaticRoutePath + : unknown extends O + ? string extends S ? S & P - : S & UrlTypeError>> & UrlErrorToken - : [S] extends [RoutePath] - ? [O] extends [undefined] - ? UrlTypeError<`Missing options for ${RoutePathWithParams & RoutePath>}. Pass { params: { ... } } as the second argument.`> & - UrlErrorToken - : S - : S & UrlTypeError>> & UrlErrorToken, - ...args: unknown extends O - ? RouteUrlArgs> - : [O] extends [undefined] - ? [options?: undefined] - : // Infer O before selecting the known route's native options type. - [ - options: O extends never - ? O - : [S] extends [RoutePath] - ? RouteOptions & RoutePath> - : unknown, - ] + : [S] extends [RoutePath] + ? S & P + : S & UrlTypeError>> & UrlErrorToken + : [S] extends [RoutePath] + ? [O] extends [undefined] + ? UrlTypeError<`Missing options for ${RoutePathWithParams & RoutePath>}. Pass { params: { ... } } as the second argument.`> & + UrlErrorToken + : S + : S & UrlTypeError>> & UrlErrorToken, + ...args: IsAny extends true + ? RouteUrlArgs + : unknown extends O + ? RouteUrlArgs> + : [O] extends [undefined] + ? // Paths typed as any may require options. Keep the native arity check. + IsAny extends true + ? RouteUrlArgs + : [options?: undefined] + : // Infer O before selecting the known route's native options type. + [ + options: O extends never + ? O + : [S] extends [RoutePath] + ? RouteOptions & RoutePath> + : unknown, + ] ): RouteUrl; export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl { return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 578c492b2..b82c39075 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -311,8 +311,9 @@ ${['react', 'vue', 'svelte', 'solid'] async function createFixture({ typedRoutes = false, + includeHandlers = true, extraFiles = {}, -}: { typedRoutes?: boolean; extraFiles?: Record } = {}) { +}: { typedRoutes?: boolean; includeHandlers?: boolean; extraFiles?: Record } = {}) { const root = mkdtempSync(join(tmpdir(), 'void-route-util-')); roots.push(root); const files: Record = { @@ -321,10 +322,12 @@ async function createFixture({ 'check-solid-link.ts': solidLinkHrefCheck, 'check-use-params.ts': useParamsCheck, 'package.json': '{"type":"module"}', - 'routes/api/users/[id].ts': - "import { defineHandler } from 'void/handler'; export const GET = defineHandler(() => ({ ok: true }));", - 'routes/api/legacy.ts': - "import { defineHandler } from 'void/handler'; export default defineHandler(() => ({ ok: true }));", + ...(includeHandlers && { + 'routes/api/users/[id].ts': + "import { defineHandler } from 'void/handler'; export const GET = defineHandler(() => ({ ok: true }));", + 'routes/api/legacy.ts': + "import { defineHandler } from 'void/handler'; export default defineHandler(() => ({ ok: true }));", + }), 'pages/index.tsx': 'export default function Page() { return null; }', 'pages/about.tsx': 'export default function Page() { return null; }', 'pages/café menu.tsx': 'export default function Page() { return null; }', @@ -545,6 +548,11 @@ void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forward function forward(...args: Parameters) { return routeUrl(...args); } +const buildAbout: (path: '/about') => string = routeUrl; +const buildAboutWithOptions: (path: '/about', options?: RouteOptions<'/about'>) => string = routeUrl; +// @ts-expect-error a dynamic route cannot be used as a one-argument callback +const buildUser: (path: '/users/[id]') => string = routeUrl; +void [buildAbout, buildAboutWithOptions, buildUser]; declare const options: RouteOptions; const userUrl = routeUrl.bind(undefined, '/users/[id]'); userUrl(options); @@ -591,6 +599,38 @@ routeUrl('/about', options); }, ); + it.each(compilers)( + 'checks generated routes in Node16 CommonJS with TS $version', + async ({ tsc }) => { + const root = await createFixture({ + typedRoutes: true, + includeHandlers: false, + extraFiles: { + 'package.json': '{"type":"commonjs"}', + 'check-commonjs.ts': `import { routeUrl, type Href } from 'void/routes'; +const url: Href = routeUrl('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error known dynamic routes require params +routeUrl('/users/[id]'); +// @ts-expect-error unknown route patterns remain checked +routeUrl('/missing'); +// @ts-expect-error raw URLs remain checked +const missing: Href = '/missing'; +void [url, missing]; +`, + }, + }); + expect( + typecheck( + root, + 'generated', + ['check-commonjs.ts'], + { module: 'Node16', moduleResolution: 'Node16', skipLibCheck: false }, + tsc, + ), + ).toEqual({ output: '', status: 0 }); + }, + ); + it.each([false, true])( 'retains legacy Node URL checks with skipLibCheck=%s', async (skipLibCheck) => { @@ -797,6 +837,14 @@ routeUrl('/users/[id]'); declare const uncheckedOptions: Record; // @ts-expect-error index signatures cannot satisfy the diagnostic rejection guard routeUrl('/users/[id]', uncheckedOptions); +const uncheckedPath = JSON.parse('"/users/[id]"'); +routeUrl(uncheckedPath, { params: { id: 42 } }); +// @ts-expect-error a path typed as any may require options +routeUrl(uncheckedPath); +// @ts-expect-error undefined cannot supply the options for a path typed as any +routeUrl(uncheckedPath, undefined); +// @ts-expect-error explicit type arguments cannot select the erased callback signature +routeUrl(uncheckedPath); const boxed = Object.assign('Param id for /users/[id] must be a string or number.' as const, { params: { id: true } }); // @ts-expect-error a boxed diagnostic message is still invalid options routeUrl('/users/[id]', boxed); diff --git a/packages/void/test/unit/route-types.test.ts b/packages/void/test/unit/route-types.test.ts index 8aec37f67..9fed8c120 100644 --- a/packages/void/test/unit/route-types.test.ts +++ b/packages/void/test/unit/route-types.test.ts @@ -324,8 +324,9 @@ describe('generateRouteTypes', () => { expect(typesConfig(off).trim()).toBe(''); expect(typesConfig(on).trim()).toBe('typedRoutes: true;'); expect(on.replace(' typedRoutes: true;\n', '')).toBe(off); - expect(off).toMatch(/export type RouteUrlInput = import\("[^"]+"\)\.RouteUrlInput;/); - expect(off).toMatch(/export const routeUrl: typeof import\("[^"]+"\)\.routeUrl;/); + const sdkTypes = 'import("void/_route-url-types", { with: { "resolution-mode": "import" } })'; + expect(off).toContain(`export type RouteUrlInput = ${sdkTypes}.RouteUrlInput;`); + expect(off).toContain(`export const routeUrl: typeof ${sdkTypes}.routeUrl;`); }); it('generates PageActionMap for pages with actions', () => { From 166ef94c272a9cebf13b333c1687183132bd7c52 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Thu, 19 Nov 2026 10:41:12 +0800 Subject: [PATCH 08/12] fix(routes): preserve routeUrl wrapper inference --- .../void/src/runtime/routing/route-url.ts | 79 ++----- .../src/runtime/routing/url-diagnostics.ts | 6 +- .../integration/route-url-builder.test.ts | 219 ++++++++++++------ 3 files changed, 177 insertions(+), 127 deletions(-) diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index 220b3855c..2ddbfa396 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -158,63 +158,32 @@ type UrlOptions = { hash?: string; }; -type RouteUrlArgs

= [RoutePathMap[P]] extends [never] - ? [options?: RouteOptions

] - : [options: RouteOptions

]; -type UnknownRouteMessage

= string extends P - ? 'Expected a route pattern literal; string is too broad.' - : `Unknown route: ${Exclude}. Use a registered route pattern.`; -type RoutePathWithParams

= P extends RoutePath - ? [RoutePathMap[P]] extends [never] - ? never - : P - : never; -type StaticRoutePath = Exclude>; -type IsAny = 0 extends 1 & T ? true : false; +// An unknown pattern has no matching route params, so TypeScript can report +// the path error even if the options argument is absent. In static-only apps, +// keep P alone so an unchecked path doesn't affect the optional options tuple. +// A broad candidate must also keep P so it cannot widen the checked pattern. +type MatchingRoute

= [ + RoutePathMap[RoutePath], +] extends [never] + ? P + : string extends Candidate + ? P + : P & Candidate; + +// Function helpers can widen Candidate to string when they infer the signature. +type UnknownRoute = string extends Candidate + ? never + : Candidate & + UrlTypeError<`Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.`> & + UrlErrorToken; /** Build a relative URL from a known route pattern. */ -export function routeUrl

(path: P, ...args: RouteUrlArgs>): RouteUrl; -// TypeScript erases Erased to any when comparing overloads to a callback. Give -// that comparison a static route signature. Calls can only instantiate it as never. -// Function helpers instantiate O as unknown and keep the original checked tuple. -// Explicit

calls use the valid overload because this one requires two type arguments. -export function routeUrl< - P extends RoutePath, - S extends RoutePath | (string & {}), - O = never, - Erased extends never = never, ->( - path: IsAny extends true - ? StaticRoutePath - : unknown extends O - ? string extends S - ? S & P - : [S] extends [RoutePath] - ? S & P - : S & UrlTypeError>> & UrlErrorToken - : [S] extends [RoutePath] - ? [O] extends [undefined] - ? UrlTypeError<`Missing options for ${RoutePathWithParams & RoutePath>}. Pass { params: { ... } } as the second argument.`> & - UrlErrorToken - : S - : S & UrlTypeError>> & UrlErrorToken, - ...args: IsAny extends true - ? RouteUrlArgs - : unknown extends O - ? RouteUrlArgs> - : [O] extends [undefined] - ? // Paths typed as any may require options. Keep the native arity check. - IsAny extends true - ? RouteUrlArgs - : [options?: undefined] - : // Infer O before selecting the known route's native options type. - [ - options: O extends never - ? O - : [S] extends [RoutePath] - ? RouteOptions & RoutePath> - : unknown, - ] +// A single signature with a positional path preserves inference in wrappers and currying helpers. +export function routeUrl

( + path: MatchingRoute | UnknownRoute, + ...options: [RoutePathMap[NoInfer>]] extends [never] + ? [options?: RouteOptions>] + : [options: RouteOptions>] ): RouteUrl; export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl { return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl; diff --git a/packages/void/src/runtime/routing/url-diagnostics.ts b/packages/void/src/runtime/routing/url-diagnostics.ts index a0a78a891..e248c42ee 100644 --- a/packages/void/src/runtime/routing/url-diagnostics.ts +++ b/packages/void/src/runtime/routing/url-diagnostics.ts @@ -3,6 +3,6 @@ export type UrlTypeError = [Message] extends [never] ? never : { readonly [K in Message]: never }; -declare const invalid: unique symbol; -/** A private token prevents diagnostic path types from becoming valid inputs. */ -export type UrlErrorToken = { readonly [invalid]: never }; +// Require a property ordinary argument lists cannot supply. A well-known symbol +// can be named in declarations emitted for functions that wrap routeUrl. +export type UrlErrorToken = { readonly [Symbol.toPrimitive]: never }; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index b82c39075..9fcada880 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -312,8 +312,14 @@ ${['react', 'vue', 'svelte', 'solid'] async function createFixture({ typedRoutes = false, includeHandlers = true, + staticOnly = false, extraFiles = {}, -}: { typedRoutes?: boolean; includeHandlers?: boolean; extraFiles?: Record } = {}) { +}: { + typedRoutes?: boolean; + includeHandlers?: boolean; + staticOnly?: boolean; + extraFiles?: Record; +} = {}) { const root = mkdtempSync(join(tmpdir(), 'void-route-util-')); roots.push(root); const files: Record = { @@ -323,19 +329,23 @@ async function createFixture({ 'check-use-params.ts': useParamsCheck, 'package.json': '{"type":"module"}', ...(includeHandlers && { - 'routes/api/users/[id].ts': - "import { defineHandler } from 'void/handler'; export const GET = defineHandler(() => ({ ok: true }));", 'routes/api/legacy.ts': "import { defineHandler } from 'void/handler'; export default defineHandler(() => ({ ok: true }));", + ...(!staticOnly && { + 'routes/api/users/[id].ts': + "import { defineHandler } from 'void/handler'; export const GET = defineHandler(() => ({ ok: true }));", + }), }), 'pages/index.tsx': 'export default function Page() { return null; }', 'pages/about.tsx': 'export default function Page() { return null; }', 'pages/café menu.tsx': 'export default function Page() { return null; }', - 'pages/café/[id].tsx': 'export default function Page() { return null; }', - 'pages/users/[id].tsx': 'export default function Page() { return null; }', - 'pages/blog/[category]/[slug].tsx': 'export default function Page() { return null; }', - 'pages/files/[...path].tsx': 'export default function Page() { return null; }', - 'pages/wild/[...].tsx': 'export default function Page() { return null; }', + ...(!staticOnly && { + 'pages/café/[id].tsx': 'export default function Page() { return null; }', + 'pages/users/[id].tsx': 'export default function Page() { return null; }', + 'pages/blog/[category]/[slug].tsx': 'export default function Page() { return null; }', + 'pages/files/[...path].tsx': 'export default function Page() { return null; }', + 'pages/wild/[...].tsx': 'export default function Page() { return null; }', + }), 'check.ts': `import type { Context, MiddlewareHandler } from 'hono'; import { getCookie } from 'hono/cookie'; import { @@ -503,6 +513,20 @@ function userUrl(id: T) { function forwardOptions>(options: T) { return routeUrl('/users/[id]', options); } +function forwardRouteOptions

(path: P, options: RouteOptions

) { + return routeUrl(path, options); +} +function forwardRouteOptionsSubtype

>(path: P, options: O) { + return routeUrl(path, options); +} +function forwardExplicitOptions

(path: P, options: RouteOptions

) { + return routeUrl

(path, options); +} +function forwardAnyOptions

(path: P, options: any) { + return routeUrl(path, options); +} +const buildRoute:

(path: P, options: RouteOptions

) => string = routeUrl; +const buildRouteWithSubtype:

>(path: P, options: O) => string = routeUrl; function forwardStaticOptions>(options: T) { return routeUrl('/about', options); } @@ -528,7 +552,7 @@ const staticDestination: RouteDestination<'/about'> = { pathname: '/about' }; routeUrl('/about', staticDestination); declare const indexedParams: Record & { id: number }; routeUrl('/users/[id]', { params: indexedParams }); -void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs]; +void [userUrl, forwardOptions, forwardRouteOptions, forwardRouteOptionsSubtype, forwardExplicitOptions, forwardAnyOptions, buildRoute, buildRouteWithSubtype, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs]; `, }, }); @@ -548,10 +572,33 @@ void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forward function forward(...args: Parameters) { return routeUrl(...args); } +function wrap(fn: (...args: A) => R): (...args: A) => R { + return (...args) => fn(...args); +} +function curry(fn: (path: P, ...args: A) => R) { + return (path: P) => (...args: A): R => fn(path, ...args); +} +export const wrapped = wrap(routeUrl); +wrapped('/about'); +wrapped('/users/[id]', { params: { id: 42 } }); +wrapped('/blog/[category]/[slug]', { params: { category: 'typescript', slug: 'routes' } }); +// @ts-expect-error wrapping retains required params +wrapped('/users/[id]'); +// @ts-expect-error wrapping retains per-route param names +wrapped('/users/[id]', { params: { slug: 'routes' } }); +// @ts-expect-error wrapping retains route checks +wrapped('/missing'); +function forwardWrappedOptions

>(path: P, options: O) { + return wrapped(path, options); +} +forwardWrappedOptions('/users/[id]', { params: { id: 42 }, trace: 'request' }); +// @ts-expect-error forwarding an options subtype still requires the route's params +forwardWrappedOptions('/users/[id]', { hash: 'team' }); +export const curried = curry(routeUrl); const buildAbout: (path: '/about') => string = routeUrl; const buildAboutWithOptions: (path: '/about', options?: RouteOptions<'/about'>) => string = routeUrl; -// @ts-expect-error a dynamic route cannot be used as a one-argument callback -const buildUser: (path: '/users/[id]') => string = routeUrl; +// @ts-expect-error a builder specialized to a dynamic route requires options +const buildUser: (path: '/users/[id]') => string = routeUrl<'/users/[id]'>; void [buildAbout, buildAboutWithOptions, buildUser]; declare const options: RouteOptions; const userUrl = routeUrl.bind(undefined, '/users/[id]'); @@ -587,18 +634,78 @@ forward('/users/[id]', { params: { id: true } }); routeUrl('/about', options); // @ts-expect-error widening a route type cannot bypass dynamic-route checks routeUrl('/users/[id]', options); -// @ts-expect-error explicit diagnostic type arguments cannot widen the route type -routeUrl('/about', options); +// @ts-expect-error an unknown candidate cannot make options optional for a dynamic route +routeUrl('/users/[id]'); +`, + 'check-inferred-exports.ts': `import { curried, wrapped } from './dist/check-function-helpers.js'; +curried('/about')(); +curried('/about')({ hash: 'team' }); +curried('/users/[id]')({ params: { id: 42 } }); +// @ts-expect-error currying retains required params +curried('/users/[id]')(); +// @ts-expect-error currying retains per-route param names +curried('/users/[id]')({ params: { slug: 'routes' } }); +// @ts-expect-error currying retains route checks +curried('/missing'); +wrapped('/about'); +wrapped('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error the emitted wrapper declaration retains required params +wrapped('/users/[id]'); `, }, }); - expect(typecheck(root, declarations, ['check-function-helpers.ts'], {}, tsc)).toEqual({ + expect( + typecheck( + root, + declarations, + ['check-function-helpers.ts'], + { declaration: true, emitDeclarationOnly: true, noEmit: false, outDir: './dist' }, + tsc, + ), + ).toEqual({ output: '', status: 0 }); + expect(typecheck(root, declarations, ['check-inferred-exports.ts'], {}, tsc)).toEqual({ output: '', status: 0, }); }, ); + it.each(declarationChecks)( + 'keeps options optional in static function helpers through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + includeHandlers: false, + staticOnly: true, + extraFiles: { + 'check-static-binding.ts': `import { routeUrl } from 'void/routes'; +const build = routeUrl.bind(undefined, '/about'); +build(); +build({ hash: 'team' }); +const buildAbout = (routeUrl<'/about'>).bind(undefined, '/about'); +buildAbout(); +buildAbout({ hash: 'team' }); +// @ts-expect-error static routes still reject params when bound +buildAbout({ params: { id: 42 } }); +declare const unchecked: any; +routeUrl.call(undefined, unchecked); +routeUrl.call(undefined, unchecked, undefined); +`, + }, + }); + for (const compilerOptions of [ + { exactOptionalPropertyTypes: true }, + { strictNullChecks: false }, + ]) { + expect + .soft( + typecheck(root, declarations, ['check-static-binding.ts'], compilerOptions, tsc), + JSON.stringify(compilerOptions), + ) + .toEqual({ output: '', status: 0 }); + } + }, + ); + it.each(compilers)( 'checks generated routes in Node16 CommonJS with TS $version', async ({ tsc }) => { @@ -835,7 +942,7 @@ routeUrl<'/users/[id]'>('/users/[id]', { params: { id: 42, extra: 'x' } }); // @ts-expect-error widening the type argument cannot omit required params routeUrl('/users/[id]'); declare const uncheckedOptions: Record; -// @ts-expect-error index signatures cannot satisfy the diagnostic rejection guard +// @ts-expect-error an index signature does not supply the required params routeUrl('/users/[id]', uncheckedOptions); const uncheckedPath = JSON.parse('"/users/[id]"'); routeUrl(uncheckedPath, { params: { id: 42 } }); @@ -843,47 +950,30 @@ routeUrl(uncheckedPath, { params: { id: 42 } }); routeUrl(uncheckedPath); // @ts-expect-error undefined cannot supply the options for a path typed as any routeUrl(uncheckedPath, undefined); -// @ts-expect-error explicit type arguments cannot select the erased callback signature -routeUrl(uncheckedPath); -const boxed = Object.assign('Param id for /users/[id] must be a string or number.' as const, { params: { id: true } }); -// @ts-expect-error a boxed diagnostic message is still invalid options -routeUrl('/users/[id]', boxed); -// @ts-expect-error diagnostic message strings cannot act as options -routeUrl('/about', 'Options for /about must be an object.'); -// @ts-expect-error diagnostic message values cannot turn unknown options into valid ones -routeUrl('/about', { search: 'Unknown routeUrl option: search.' }); -const fakePath = { - get 'Missing options for /users/[id]. Pass { params: { ... } } as the second argument.'(): never { throw new Error(); }, - get 'Expected a route pattern literal; string is too broad.'(): never { throw new Error(); }, -}; -// @ts-expect-error diagnostic objects cannot act as route patterns -routeUrl(fakePath); +// @ts-expect-error a broad candidate cannot make required options optional +routeUrl(uncheckedPath); const fakeUnknownPath = Object.assign('/missing' as const, { get 'Unknown route: /missing. Use a registered route pattern.'(): never { throw new Error(); }, }); // @ts-expect-error a boxed error message cannot make an unknown path valid routeUrl(fakeUnknownPath); -const fakeMissingOptions = { - get 'Missing options for /users/[id]. Pass { params: { ... } } as the second argument.'(): never { throw new Error(); }, -}; -// @ts-expect-error a diagnostic object cannot replace a path and its required options -routeUrl(fakeMissingOptions); -// @ts-expect-error a diagnostic message cannot become a params object -routeUrl('/users/[id]', { params: "Params for /users/[id] must be an object." }); -// @ts-expect-error a diagnostic message cannot become a query object -routeUrl('/about', { query: 'Query for /about must be an object with supported query values.' }); // @ts-expect-error an any-valued unknown option remains invalid routeUrl('/about', { search: undefined as any }); -// @ts-expect-error an array of diagnostic messages cannot become options -routeUrl('/about', ['Unknown routeUrl option: 0.'] as const); // @ts-expect-error explicit diagnostic type arguments retain native params checking -routeUrl('/users/[id]', { params: 'Param id for /users/[id] must be a string or number.' }); -// @ts-expect-error diagnostic type arguments cannot widen the original checked tuple -routeUrl('/users/[id]', { params: 'Param id for /users/[id] must be a string or number.' }); +routeUrl('/users/[id]', { params: { id: true } }); +// @ts-expect-error an any candidate cannot bypass the route pattern check +routeUrl<'/about', any>('/missing', { params: {} }); +// @ts-expect-error an any candidate cannot bypass per-route param checks +routeUrl<'/users/[id]', any>('/users/[id]', { params: {} }); `, - 'check-exact-optional.ts': `import { routeUrl } from 'void/routes'; + 'check-exact-optional.ts': `import { routeUrl, type RouteOptions } from 'void/routes'; routeUrl('/about'); +routeUrl('/about', undefined); routeUrl('/users/[id]', { params: { id: 42 } }); +function forwardStaticOptions>(options?: O) { + return routeUrl('/about', options); +} +void forwardStaticOptions; declare const value: any; // @ts-expect-error exact optional properties do not allow params on static routes routeUrl('/about', { params: value }); @@ -914,12 +1004,12 @@ routeUrl('/users/[id]', { params: { id: 42, extra: value } }); it.each(declarationChecks)( 'uses native option errors and custom path errors through $declarations declarations with TS $version', - async ({ declarations, tsc, version }) => { + async ({ declarations, tsc }) => { const cases: Array<[call: string, message: string | RegExp, kind: 'native' | 'custom']> = [ ["routeUrl('/missing');", 'Unknown route: /missing.', 'custom'], ["routeUrl('/missing', {});", 'Unknown route: /missing.', 'custom'], ["routeUrl('/users/42');", 'Unknown route: /users/42.', 'custom'], - ["routeUrl('/users/[id]');", 'Missing options for /users/[id].', 'custom'], + ["routeUrl('/users/[id]');", 'Expected 2 arguments, but got 1.', 'native'], ["routeUrl('/users/[id]', {});", "Property 'params' is missing", 'native'], [ "routeUrl('/users/[id]', { query: { page: 1 } });", @@ -1000,13 +1090,13 @@ routeUrl('/users/[id]', { params: { id: 42, extra: value } }); ], ["routeUrl('/about', { 0: 'unknown' });", "'0' does not exist", 'native'], ["routeUrl('/about', { search: 'x' });", "'search' does not exist", 'native'], - ["routeUrl('/users/[id]', undefined);", 'Missing options for /users/[id].', 'custom'], - ["routeUrl('' as '/about' | '/users/[id]');", 'Missing options for /users/[id].', 'custom'], [ - "routeUrl('' as string);", - 'Expected a route pattern literal; string is too broad.', - 'custom', + "routeUrl('/users/[id]', undefined);", + "Argument of type 'undefined' is not assignable", + 'native', ], + ["routeUrl('' as '/about' | '/users/[id]');", 'Expected 2 arguments, but got 1.', 'native'], + ["routeUrl('' as string, {});", "Argument of type 'string' is not assignable", 'native'], ["routeUrl('' as '/about' | '/missing', {});", 'Unknown route: /missing.', 'custom'], ["routeUrl('/missing', undefined);", 'Unknown route: /missing.', 'custom'], ["routeUrl('/missing', {} as unknown);", 'Unknown route: /missing.', 'custom'], @@ -1036,34 +1126,26 @@ routeUrl('/users/[id]', { params: { id: 42, extra: value } }); if (kind === 'native') { expect(diagnostics[index]).not.toContain('UrlTypeError'); expect(diagnostics[index]).not.toContain('UrlErrorToken'); - expect(diagnostics[index]).not.toContain('[invalid]'); - expect(diagnostics[index]).not.toContain('Missing options for'); + expect(diagnostics[index]).not.toContain('Symbol.toPrimitive'); expect(diagnostics[index]).not.toMatch( /not assignable to type '"(?:Missing|Unknown|Invalid|Param|Query|Hash|Options)/, ); } }); - expect(output).not.toContain('TS2554'); + expect(output).not.toContain('No overload matches this call'); expect(output).not.toContain('UrlTypeError'); expect(output).not.toContain('RouteUrlOptionsInput'); expect(output).not.toContain('__voidUrlError'); - expect(diagnostics[25]).not.toContain('Missing options for /about.'); - expect(diagnostics[27]).not.toContain('Unknown route: /about.'); + expect(output).not.toContain('Unknown route: /about.'); const missingSlug = diagnostics.at(-1)!.trim(); - const detail = - "Property 'slug' is missing in type '{ category: string; }' but required in type '{ category: string | number; slug: string | number; }'."; - expect(missingSlug).toContain(detail); - if (version.startsWith('7.')) { - expect(missingSlug).toBe( - `No overload matches this call.\n The last overload gave the following error.\n ${detail}`, - ); - expect(missingSlug.length).toBeLessThan(250); - } + expect(missingSlug).toBe( + "Property 'slug' is missing in type '{ category: string; }' but required in type '{ category: string | number; slug: string | number; }'.", + ); }, ); it.each(declarationChecks)( - 'explains missing options for generic routes through $declarations declarations with TS $version', + 'requires options for generic paths through $declarations declarations with TS $version', async ({ declarations, tsc }) => { const root = await createFixture({ extraFiles: { @@ -1083,8 +1165,7 @@ void bare; tsc, ); expect(status).not.toBe(0); - expect(output).toContain('Missing options for'); - expect(output).toContain('Pass { params: { ... } } as the second argument.'); + expect(output).toContain("Argument of type '[]' is not assignable"); }, ); From b0548b0f8c32fc2b8a9d0217c4605ca06aa88aa7 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Thu, 19 Nov 2026 11:54:31 +0800 Subject: [PATCH 09/12] fix(routes): keep routeUrl generic paths and large apps compatible Infer P and Candidate from the whole path argument so generic helpers such as `P & RoutePath` keep compiling. Keep the unknown-route marker from being a subtype of the path, so method signatures and code without strictFunctionTypes still reject unknown routes. Bound Candidate by plain string to avoid TS2590 in apps with more than ~316 route keys. Co-Authored-By: Claude Opus 5.5 --- .../void/src/runtime/routing/route-url.ts | 21 ++++- .../integration/route-url-builder.test.ts | 87 ++++++++++++++++++- 2 files changed, 103 insertions(+), 5 deletions(-) diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index 2ddbfa396..b8754a4f5 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -171,16 +171,29 @@ type MatchingRoute

= [ : P & Candidate; // Function helpers can widen Candidate to string when they infer the signature. +// The marker must not be a subtype of the path: method signatures and code without +// strictFunctionTypes compare parameters bivariantly and would accept the route. type UnknownRoute = string extends Candidate ? never - : Candidate & - UrlTypeError<`Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.`> & + : UrlTypeError<`Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.`> & UrlErrorToken; +// Keep P and Candidate out of a top-level union so TypeScript infers each from the +// whole argument. A generic path such as `P & RoutePath` would otherwise be inferred +// from its first member alone. The inner check always holds; its false branch only +// gives Candidate an inference site. +type RouteArgument

= string extends Candidate + ? P + : [Candidate] extends [unknown] + ? MatchingRoute | UnknownRoute + : Candidate; + /** Build a relative URL from a known route pattern. */ // A single signature with a positional path preserves inference in wrappers and currying helpers. -export function routeUrl

( - path: MatchingRoute | UnknownRoute, +// Candidate is bounded by plain string: with `RoutePath | (string & {})`, the constraint of +// `P & Candidate` is a cross product of the route union that overflows past ~316 routes. +export function routeUrl

( + path: RouteArgument, ...options: [RoutePathMap[NoInfer>]] extends [never] ? [options?: RouteOptions>] : [options: RouteOptions>] diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 9fcada880..062727569 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -539,6 +539,18 @@ function forwardArgs(...args: Parameters>) { function forwardGenericArgs

(...args: Parameters>) { return routeUrl(...args); } +function forwardIntersectedPath

(path: P & RoutePath, options: any) { + return routeUrl(path, options); +} +function forwardUnconstrainedPath

(path: P & RoutePath, options: any) { + return routeUrl(path, options); +} +function forwardStaticIntersection

(path: P & ('/' | '/about')) { + return routeUrl(path); +} +function forwardPathOrAbout

(path: P | '/about', options: any) { + return routeUrl(path, options); +} forwardArgs('/users/[id]', { params: { id: 42 } }); const user = { id: 42, name: 'Alice' }; routeUrl('/users/[id]', { params: user }); @@ -552,7 +564,7 @@ const staticDestination: RouteDestination<'/about'> = { pathname: '/about' }; routeUrl('/about', staticDestination); declare const indexedParams: Record & { id: number }; routeUrl('/users/[id]', { params: indexedParams }); -void [userUrl, forwardOptions, forwardRouteOptions, forwardRouteOptionsSubtype, forwardExplicitOptions, forwardAnyOptions, buildRoute, buildRouteWithSubtype, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs]; +void [userUrl, forwardOptions, forwardRouteOptions, forwardRouteOptionsSubtype, forwardExplicitOptions, forwardAnyOptions, buildRoute, buildRouteWithSubtype, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs, forwardIntersectedPath, forwardUnconstrainedPath, forwardStaticIntersection, forwardPathOrAbout]; `, }, }); @@ -1002,6 +1014,79 @@ routeUrl('/users/[id]', { params: { id: 42, extra: value } }); }, ); + it.each(declarationChecks)( + 'rejects unknown routes in bivariant parameter checks through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-bivariant.ts': `import { routeUrl } from 'void/routes'; +interface Builder { url(path: '/missing'): string } +// @ts-expect-error method signatures compare parameters bivariantly but still reject unknown routes +const builder: Builder = { url: routeUrl }; +// @ts-expect-error a class property implementing a method signature still rejects unknown routes +class RouteBuilder implements Builder { url = routeUrl; } +// @ts-expect-error an unknown bracket route would throw for its missing param at runtime +const renamed: { url(path: '/users/[uid]'): string } = { url: routeUrl }; +// @ts-expect-error a known route cannot hide an unknown one in the same union +const mixed: { url(path: '/about' | '/missing'): string } = { url: routeUrl }; +// @ts-expect-error function types without strictFunctionTypes still reject unknown routes +const callback: (path: '/missing') => string = routeUrl; +const known: { url(path: '/about'): string } = { url: routeUrl }; +void [builder, RouteBuilder, renamed, mixed, callback, known]; +`, + }, + }); + for (const compilerOptions of [{}, { strictFunctionTypes: false }]) { + expect + .soft( + typecheck(root, declarations, ['check-bivariant.ts'], compilerOptions, tsc), + JSON.stringify(compilerOptions), + ) + .toEqual({ output: '', status: 0 }); + } + }, + ); + + it.each(declarationChecks)( + 'checks routeUrl in apps with hundreds of routes through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + // A non-primitive member in Candidate's constraint made `P & Candidate` a cross product + // of the route union, which TypeScript rejects (TS2590) past ~316 route keys. + const pages = Object.fromEntries( + Array.from({ length: 150 }, (_, index) => [ + [`pages/large/s${index}.tsx`, 'export default function Page() { return null; }'], + [`pages/large/d${index}/[id].tsx`, 'export default function Page() { return null; }'], + ]).flat(), + ); + const root = await createFixture({ + extraFiles: { + ...pages, + 'check-large.ts': `import { routeUrl, type RouteOptions, type RoutePath } from 'void/routes'; +routeUrl('/large/s0'); +routeUrl('/large/d0/[id]', { params: { id: 1 } }); +declare const path: RoutePath; +routeUrl(path, {} as any); +function forward

(path: P, options: RouteOptions

) { + return routeUrl(path, options); +} +function forwardIntersectedPath

(path: P & RoutePath, options: any) { + return routeUrl(path, options); +} +// @ts-expect-error unknown routes are still rejected +routeUrl('/large/missing'); +// @ts-expect-error params are still required +routeUrl('/large/d0/[id]'); +void [forward, forwardIntersectedPath]; +`, + }, + }); + expect(typecheck(root, declarations, ['check-large.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + it.each(declarationChecks)( 'uses native option errors and custom path errors through $declarations declarations with TS $version', async ({ declarations, tsc }) => { From 83422853931bfb1977bf8192f98c951ef4dd2e6c Mon Sep 17 00:00:00 2001 From: Yangshun Date: Fri, 20 Nov 2026 07:36:39 +0800 Subject: [PATCH 10/12] fix(routes): check generic paths in large apps and quote unknown routes Infer the route candidate through a template literal, so only string literals produce one and generic paths such as `P & RoutePath` resolve like a plain parameter. This avoids TS2859 in apps with more than ~1,400 route keys. Keep P whole when every candidate is a known route, so paths such as `P | '/about'` still compile. Spell the unknown-route marker as a string literal. TypeScript then prints the argument as the path the caller wrote instead of `string`, and the marker still rejects unknown routes in bivariant parameter checks. Co-Authored-By: Claude Opus 5.5 --- .../void/src/runtime/routing/route-url.ts | 37 ++++++++++++------- .../src/runtime/routing/url-diagnostics.ts | 5 --- .../integration/route-url-builder.test.ts | 13 +++++-- 3 files changed, 33 insertions(+), 22 deletions(-) diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index b8754a4f5..0ff177629 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -1,5 +1,5 @@ import type { EncodedRoutePathMap, RoutePathMap, RouteTypesConfig } from 'void/routes'; -import type { UrlErrorToken, UrlTypeError } from './url-diagnostics.ts'; +import type { UrlErrorToken } from './url-diagnostics.ts'; /** * Encode one path segment of a route param. `encodeURIComponent` keeps dots, and @@ -161,32 +161,43 @@ type UrlOptions = { // An unknown pattern has no matching route params, so TypeScript can report // the path error even if the options argument is absent. In static-only apps, // keep P alone so an unchecked path doesn't affect the optional options tuple. -// A broad candidate must also keep P so it cannot widen the checked pattern. +// A broad candidate must also keep P so it cannot widen the checked pattern. Candidate +// holds only the string literals in the path, so narrow P by it only when one of them +// is unknown: a path such as `P | '/about'` has other members that P must keep. type MatchingRoute

= [ RoutePathMap[RoutePath], ] extends [never] ? P - : string extends Candidate + : [Candidate] extends [RoutePath] ? P - : P & Candidate; + : string extends Candidate + ? P + : P & Candidate; // Function helpers can widen Candidate to string when they infer the signature. // The marker must not be a subtype of the path: method signatures and code without // strictFunctionTypes compare parameters bivariantly and would accept the route. +// A string-literal message also keeps the quoted path in the error: TypeScript prints +// the argument as `string` when the parameter type has no literal or template members. type UnknownRoute = string extends Candidate ? never - : UrlTypeError<`Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.`> & + : `Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.` & UrlErrorToken; -// Keep P and Candidate out of a top-level union so TypeScript infers each from the -// whole argument. A generic path such as `P & RoutePath` would otherwise be inferred -// from its first member alone. The inner check always holds; its false branch only -// gives Candidate an inference site. -type RouteArgument

= string extends Candidate +// Keep P out of a top-level union so TypeScript infers it from the whole argument. A +// generic path such as `P & RoutePath` would otherwise be inferred from its first member +// alone. The inner check always holds; its false branch only gives Candidate an inference +// site. That site is a template literal, so only string literals infer a candidate. Other +// paths, such as `P & RoutePath` in a generic helper, infer never and resolve to P like a +// plain parameter. Left deferred, the check would compare every route in that union with +// every other one, which exceeds TypeScript's complexity limit in apps with ~1,400 routes. +type RouteArgument

= [Candidate] extends [never] ? P - : [Candidate] extends [unknown] - ? MatchingRoute | UnknownRoute - : Candidate; + : string extends Candidate + ? P + : [Candidate] extends [unknown] + ? MatchingRoute | UnknownRoute + : `${Candidate}`; /** Build a relative URL from a known route pattern. */ // A single signature with a positional path preserves inference in wrappers and currying helpers. diff --git a/packages/void/src/runtime/routing/url-diagnostics.ts b/packages/void/src/runtime/routing/url-diagnostics.ts index e248c42ee..782a769c2 100644 --- a/packages/void/src/runtime/routing/url-diagnostics.ts +++ b/packages/void/src/runtime/routing/url-diagnostics.ts @@ -1,8 +1,3 @@ -/** An unsatisfied marker for diagnostic fallbacks, never an accepted input. */ -export type UrlTypeError = [Message] extends [never] - ? never - : { readonly [K in Message]: never }; - // Require a property ordinary argument lists cannot supply. A well-known symbol // can be named in declarations emitted for functions that wrap routeUrl. export type UrlErrorToken = { readonly [Symbol.toPrimitive]: never }; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 062727569..b4c984fb1 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -1048,12 +1048,14 @@ void [builder, RouteBuilder, renamed, mixed, callback, known]; ); it.each(declarationChecks)( - 'checks routeUrl in apps with hundreds of routes through $declarations declarations with TS $version', + 'checks routeUrl in apps with thousands of routes through $declarations declarations with TS $version', async ({ declarations, tsc }) => { - // A non-primitive member in Candidate's constraint made `P & Candidate` a cross product - // of the route union, which TypeScript rejects (TS2590) past ~316 route keys. + // About 1,800 route keys, since each dynamic page also has a `:param` alias. A + // non-primitive member in Candidate's constraint made `P & Candidate` a cross product + // that TypeScript rejects (TS2590) past ~316 keys, and a deferred path check rejected + // generic helpers (TS2859) past ~1,400. const pages = Object.fromEntries( - Array.from({ length: 150 }, (_, index) => [ + Array.from({ length: 600 }, (_, index) => [ [`pages/large/s${index}.tsx`, 'export default function Page() { return null; }'], [`pages/large/d${index}/[id].tsx`, 'export default function Page() { return null; }'], ]).flat(), @@ -1215,6 +1217,9 @@ void [forward, forwardIntersectedPath]; expect(diagnostics[index]).not.toMatch( /not assignable to type '"(?:Missing|Unknown|Invalid|Param|Query|Hash|Options)/, ); + } else { + // The error names the path the caller wrote, not its widened `string` type. + expect(diagnostics[index]).toMatch(/^Argument of type '"/); } }); expect(output).not.toContain('No overload matches this call'); From ee085ba9db82031ae08cb5a88e1fe2dfe25fb96b Mon Sep 17 00:00:00 2001 From: Yangshun Date: Fri, 20 Nov 2026 08:02:30 +0800 Subject: [PATCH 11/12] test(routes): request plain diagnostics from fixture compilers The diagnostics test parses `file(line,col): error` lines. Under FORCE_COLOR, which `vp run` sets for tests, TypeScript 7 and tsrs print pretty diagnostics even when tsconfig sets `pretty: false`, so pass `--pretty false` on the command line. Co-Authored-By: Claude Opus 5.5 --- packages/void/test/integration/route-url-builder.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index b6dea3f33..3cfa94047 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -504,7 +504,9 @@ function typecheck( include, }), ); - const result = spawnSync(process.execPath, [tsc, '-p', join(root, config)], { + // Tests parse `file(line,col): error` lines. Under FORCE_COLOR, which `vp run` sets for + // tests, TypeScript 7 and tsrs print pretty diagnostics unless the command line opts out. + const result = spawnSync(process.execPath, [tsc, '-p', join(root, config), '--pretty', 'false'], { encoding: 'utf8', }); return { output: result.stdout + result.stderr, status: result.status }; From 8b7d2f70cd0105d096c1d0a12a3cd32cd6ac8686 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Fri, 20 Nov 2026 08:54:28 +0800 Subject: [PATCH 12/12] fix(routes): keep routeUrl implementations and helper types from main Functions written to match `typeof routeUrl` with a `RoutePath` or generic path parameter, such as mocks and class members, stopped compiling: TypeScript could not show that the unknown-route marker is a route. Distribute the marker over the written path so its constraint reduces to `P`. Generated route declarations on main also exported the URL helper types (`TypedRoutes`, `RoutePathUrl` and others) from `void/routes`. Re-export them from the SDK. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/codegen/route-types.ts | 14 +++++ .../void/src/runtime/routing/route-url.ts | 35 +++++++---- .../integration/route-url-builder.test.ts | 58 +++++++++++++++++++ 3 files changed, 95 insertions(+), 12 deletions(-) diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 784aa9ad2..f89954840 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -144,6 +144,8 @@ export function generateRouteTypes( // Resolve the SDK's ESM declarations from CommonJS projects as well. const sdkRouteTypes = 'import("void/_route-url-types", { with: { "resolution-mode": "import" } })'; + // Earlier generated files declared the URL helpers here, which exported them from + // void/routes too, so keep every one of those names importable. for (const name of [ 'RoutePath', 'RouteQueryValue', @@ -151,9 +153,21 @@ export function generateRouteTypes( 'RouteUrl', 'Href', 'RouteUrlInput', + 'TypedRoutes', + 'BuiltRouteUrl', + 'EncodedRoutePath', + 'RoutePathUrl', ]) { lines.push(` export type ${name} = ${sdkRouteTypes}.${name};`); } + for (const name of [ + 'RouteUrlSegment', + 'CheckedRoutePath', + 'RouteSegmentsUrl', + 'RoutePatternUrl', + ]) { + lines.push(` export type ${name}

= ${sdkRouteTypes}.${name}

;`); + } lines.push(` export type RouteOptions

= ${sdkRouteTypes}.RouteOptions

;`); lines.push( ` export type RouteDestination

= ${sdkRouteTypes}.RouteDestination

;`, diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index 0ff177629..9f0f03084 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -81,13 +81,18 @@ export function interpolateRouteParams( /** Known page, HTTP and WebSocket route patterns. */ export type RoutePath = keyof RoutePathMap & string; +// The helpers below are exported because generated route declarations re-export them: +// earlier generated files declared them, so apps can import them from `void/routes`. + // Dynamic segments in either public or legacy patterns match any text, // so `/users/[id]` accepts `/users/${string}`. Template // literal types cannot exclude empty or `/`-leading text without per-character unions. -type RouteUrlSegment = S extends `:${string}` | `[${string}]` | '*' ? string : S; +export type RouteUrlSegment = S extends `:${string}` | `[${string}]` | '*' + ? string + : S; // Root params and catch-alls would accept every absolute path. Keep those // patterns available to routeUrl(), but require explicit construction for them. -type CheckedRoutePath

= P extends `/${infer Segment}/${infer Rest}` +export type CheckedRoutePath

= P extends `/${infer Segment}/${infer Rest}` ? Rest extends '' ? string extends RouteUrlSegment ? never @@ -98,21 +103,21 @@ type CheckedRoutePath

= P extends `/${infer Segment}/${infer R ? never : P : P; -type RouteSegmentsUrl

= P extends `${infer Segment}/${infer Rest}` +export type RouteSegmentsUrl

= P extends `${infer Segment}/${infer Rest}` ? `${RouteUrlSegment}/${RouteSegmentsUrl}` : RouteUrlSegment

; // A trailing `/*` also matches the bare prefix, as in Hono: `/docs/*` matches `/docs`. -type RoutePatternUrl

= P extends `${infer Prefix}/${'*' | '[...]'}/` +export type RoutePatternUrl

= P extends `${infer Prefix}/${'*' | '[...]'}/` ? `${RouteSegmentsUrl}/` | `${RouteSegmentsUrl}/${string}/` : P extends `${infer Prefix}/${'*' | '[...]'}` ? (Prefix extends '' ? '/' : RouteSegmentsUrl) | `${RouteSegmentsUrl}/${string}` : RouteSegmentsUrl

; // Fixed segments are also accepted percent-encoded, as `routeUrl()` returns them. -type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string; -type RoutePathUrl = RoutePatternUrl>; +export type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string; +export type RoutePathUrl = RoutePatternUrl>; // Use a structural marker so package and generated declarations agree when a // helper-built URL crosses into a navigation, form, or stream client. -type BuiltRouteUrl = string & { readonly __voidRouteUrl: true }; +export type BuiltRouteUrl = string & { readonly __voidRouteUrl: true }; /** Whether `routing.typedRoutes` is on in the generated route types. */ export type TypedRoutes = RouteTypesConfig extends { typedRoutes: true } ? true : false; @@ -179,10 +184,15 @@ type MatchingRoute

= [ // strictFunctionTypes compare parameters bivariantly and would accept the route. // A string-literal message also keeps the quoted path in the error: TypeScript prints // the argument as `string` when the parameter type has no literal or template members. -type UnknownRoute = string extends Candidate +// Distributing over Candidate lets an implementation of `typeof routeUrl` accept the path +// as `RoutePath`: TypeScript checks it with Candidate widened to string, which yields P. +// That result must not be never, or TypeScript would not use it. +type UnknownRoute

= Candidate extends RoutePath ? never - : `Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.` & - UrlErrorToken; + : string extends Candidate + ? NoInfer

+ : `Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.` & + UrlErrorToken; // Keep P out of a top-level union so TypeScript infers it from the whole argument. A // generic path such as `P & RoutePath` would otherwise be inferred from its first member @@ -191,13 +201,14 @@ type UnknownRoute = string extends Candidate // paths, such as `P & RoutePath` in a generic helper, infer never and resolve to P like a // plain parameter. Left deferred, the check would compare every route in that union with // every other one, which exceeds TypeScript's complexity limit in apps with ~1,400 routes. +// The unreachable branch is also a route so that every branch is assignable to P. type RouteArgument

= [Candidate] extends [never] ? P : string extends Candidate ? P : [Candidate] extends [unknown] - ? MatchingRoute | UnknownRoute - : `${Candidate}`; + ? MatchingRoute | UnknownRoute + : `${Candidate}` & NoInfer

; /** Build a relative URL from a known route pattern. */ // A single signature with a positional path preserves inference in wrappers and currying helpers. diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 3cfa94047..d83204e3c 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -587,6 +587,64 @@ void [userUrl, forwardOptions, forwardRouteOptions, forwardRouteOptionsSubtype, }, ); + it.each(declarationChecks)( + 'accepts implementations and helper types from main through $declarations declarations with $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-implementations.ts': `import { routeUrl, type RoutePath, type RouteUrl } from 'void/routes'; +import type { BuiltRouteUrl, CheckedRoutePath, EncodedRoutePath, RoutePathUrl, RoutePatternUrl, RouteSegmentsUrl, RouteUrlSegment, TypedRoutes } from 'void/routes'; +const routePath: typeof routeUrl = (path: RoutePath, options?: unknown) => path as RouteUrl; +const routePathRest: typeof routeUrl = (path: RoutePath, ...rest: unknown[]) => path as RouteUrl; +const genericRest: typeof routeUrl =

(path: P, ...args: any[]) => path as RouteUrl; +const forwarded: typeof routeUrl = (path, ...options) => routeUrl(path, ...options); +const satisfied = ((path: RoutePath, options?: unknown) => path as RouteUrl) satisfies typeof routeUrl; +function declared

(path: P, ...args: any[]): RouteUrl { + return path as RouteUrl; +} +const fromDeclaration: typeof routeUrl = declared; +const dependencies: { routeUrl: typeof routeUrl } = { + routeUrl(path: RoutePath, options?: unknown) { + return path as RouteUrl; + }, +}; +interface UrlBuilder { + build: typeof routeUrl; +} +class FakeBuilder implements UrlBuilder { + build(path: RoutePath, options?: unknown) { + return path as RouteUrl; + } +} +function withBuilder(build: typeof routeUrl = (path: RoutePath, options?: unknown) => path as RouteUrl) { + return build; +} +declare function fn any>(implementation?: T): T & { + mockImplementation(implementation: T): void; +}; +const mock: typeof routeUrl = fn((path: RoutePath, options?: unknown) => path as RouteUrl); +fn(routeUrl).mockImplementation((path: RoutePath) => path as RouteUrl); +routePath('/about'); +routePath('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error an implementation keeps routeUrl's required params +routePath('/users/[id]'); +// @ts-expect-error an implementation keeps routeUrl's route check +forwarded('/missing'); +const typed: TypedRoutes = false; +const built = '' as BuiltRouteUrl; +const pathUrl: RoutePathUrl = '/users/42'; +type Helpers = [EncodedRoutePath, CheckedRoutePath<'/about'>, RoutePatternUrl<'/files/[...]'>, RouteSegmentsUrl<'a/b'>, RouteUrlSegment<'[id]'>]; +void [routePathRest, genericRest, satisfied, fromDeclaration, dependencies, FakeBuilder, withBuilder, mock, typed, built, pathUrl, {} as Helpers]; +`, + }, + }); + expect(typecheck(root, declarations, ['check-implementations.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + it.each(declarationChecks)( 'checks function helpers through $declarations declarations with $version', async ({ declarations, tsc }) => {