Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/guide/type-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`.
Expand Down
5 changes: 5 additions & 0 deletions packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions packages/void/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -313,6 +320,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",
Expand Down
81 changes: 18 additions & 63 deletions packages/void/src/codegen/route-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,71 +139,26 @@ 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<string, RouteQueryValue | ReadonlyArray<RouteQueryValue>>;',
);
lines.push(' export type RouteOptions<P extends RoutePath> = {');
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 = RoutePath> = P extends RoutePath',
);
lines.push(' ? { pathname: P } & RouteOptions<P>');
lines.push(' : never;');
lines.push(
' type RouteUrlSegment<S extends string> = S extends `:${string}` | `[${string}]` | "*" ? string : S;',
);
lines.push(
' type CheckedRoutePath<P extends string> = P extends `/${infer Segment}/${infer Rest}`',
);
lines.push(' ? Rest extends ""');
lines.push(' ? string extends RouteUrlSegment<Segment> ? never : P');
lines.push(' : P');
lines.push(' : P extends `/${infer Segment}`');
lines.push(' ? string extends RouteUrlSegment<Segment> ? never : P');
lines.push(' : P;');
lines.push(
' type RouteSegmentsUrl<P extends string> = P extends `${infer Segment}/${infer Rest}`',
);
lines.push(' ? `${RouteUrlSegment<Segment>}/${RouteSegmentsUrl<Rest>}`');
lines.push(' : RouteUrlSegment<P>;');
lines.push(
' type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${"*" | "[...]"}/`',
);
lines.push(' ? `${RouteSegmentsUrl<Prefix>}/` | `${RouteSegmentsUrl<Prefix>}/${string}/`');
lines.push(' : P extends `${infer Prefix}/${"*" | "[...]"}`');
lines.push(
' ? (Prefix extends "" ? "/" : RouteSegmentsUrl<Prefix>) | `${RouteSegmentsUrl<Prefix>}/${string}`',
);
lines.push(' : RouteSegmentsUrl<P>;');
lines.push(' type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;');
lines.push(
' type RoutePathUrl = RoutePatternUrl<CheckedRoutePath<RoutePath | EncodedRoutePath>>;',
);
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');
// A bare types-only entry follows the installed SDK through upgrades.
// void/routes would be circular because this file augments that entry.
// 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',
'RouteQuery',
'RouteUrl',
'Href',
'RouteUrlInput',
]) {
lines.push(` export type ${name} = ${sdkRouteTypes}.${name};`);
}
lines.push(` export type RouteOptions<P extends RoutePath> = ${sdkRouteTypes}.RouteOptions<P>;`);
lines.push(
' ? RouteUrl | `${"?" | "#"}${string}` | `${"http://" | "https://" | "mailto:" | "tel:"}${string}`',
` export type RouteDestination<P extends RoutePath = RoutePath> = ${sdkRouteTypes}.RouteDestination<P>;`,
);
lines.push(' : string;');
lines.push(' export type RouteUrlInput = Href | URL | RouteDestination;');
lines.push(' export function routeUrl<P extends RoutePath>(');
lines.push(' path: P,');
lines.push(' ...args: [RoutePathMap[NoInfer<P>]] extends [never]');
lines.push(' ? [options?: RouteOptions<P>]');
lines.push(' : [options: RouteOptions<P>]');
lines.push(' ): RouteUrl;');
lines.push(` export const routeUrl: typeof ${sdkRouteTypes}.routeUrl;`);
lines.push('');
lines.push(' export interface RouteTypesConfig {');
if (options.typedRoutes) {
Expand Down
67 changes: 60 additions & 7 deletions packages/void/src/runtime/routing/route-url.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { EncodedRoutePathMap, RoutePathMap, RouteTypesConfig } from 'void/routes';
import type { UrlErrorToken, UrlTypeError } from './url-diagnostics.ts';

/**
* Encode one path segment of a route param. `encodeURIComponent` keeps dots, and
Expand Down Expand Up @@ -157,14 +158,66 @@ type UrlOptions = {
hash?: string;
};

type RouteUrlArgs<P extends RoutePath> = [RoutePathMap[P]] extends [never]
? [options?: RouteOptions<P>]
: [options: RouteOptions<P>];
type UnknownRouteMessage<P extends string> = string extends P
? 'Expected a route pattern literal; string is too broad.'
: `Unknown route: ${Exclude<P, RoutePath>}. Use a registered route pattern.`;
type RoutePathWithParams<P extends RoutePath> = P extends RoutePath
? [RoutePathMap[P]] extends [never]
? never
: P
: never;
type StaticRoutePath = Exclude<RoutePath, RoutePathWithParams<RoutePath>>;
type IsAny<T> = 0 extends 1 & T ? true : false;

/** Build a relative URL from a known route pattern. */
export function routeUrl<P extends RoutePath>(
path: P,
...args: [RoutePathMap[NoInfer<P>]] extends [never]
? [options?: RouteOptions<P>]
: [options: RouteOptions<P>]
): RouteUrl {
return buildRouteUrl(path, args[0]) as RouteUrl;
export function routeUrl<P extends RoutePath>(path: P, ...args: RouteUrlArgs<NoInfer<P>>): 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 <P> calls use the valid overload because this one requires two type arguments.
export function routeUrl<
P extends RoutePath,
S extends RoutePath | (string & {}),
O = never,
Erased extends never = never,
>(
path: IsAny<Erased> extends true
? StaticRoutePath
: unknown extends O
? string extends S
? S & P
: [S] extends [RoutePath]
? S & P
: S & UrlTypeError<UnknownRouteMessage<NoInfer<S>>> & UrlErrorToken
: [S] extends [RoutePath]
? [O] extends [undefined]
? UrlTypeError<`Missing options for ${RoutePathWithParams<NoInfer<S> & RoutePath>}. Pass { params: { ... } } as the second argument.`> &
UrlErrorToken
: S
: S & UrlTypeError<UnknownRouteMessage<NoInfer<S>>> & UrlErrorToken,
...args: IsAny<Erased> extends true
? RouteUrlArgs<StaticRoutePath>
: unknown extends O
? RouteUrlArgs<NoInfer<P>>
: [O] extends [undefined]
? // Paths typed as any may require options. Keep the native arity check.
IsAny<S> extends true
? RouteUrlArgs<S & RoutePath>
: [options?: undefined]
: // Infer O before selecting the known route's native options type.
[
options: O extends never
? O
: [S] extends [RoutePath]
? RouteOptions<NoInfer<S> & RoutePath>
: unknown,
]
): RouteUrl;
export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl {
return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl;
}

/** @internal Convert navigation inputs to URL strings without requiring an origin. */
Expand Down
8 changes: 8 additions & 0 deletions packages/void/src/runtime/routing/url-diagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/** An unsatisfied marker for diagnostic fallbacks, never an accepted input. */
export type UrlTypeError<Message extends string> = [Message] extends [never]
? never
: { readonly [K in Message]: never };

declare const invalid: unique symbol;
/** A private token prevents diagnostic path types from becoming valid inputs. */
export type UrlErrorToken = { readonly [invalid]: never };
Loading
Loading