From 50f9505c6988e0dbb0d0ef5b234609e43be755c3 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Tue, 17 Nov 2026 09:57:31 +0800 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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', () => {