Skip to content
Draft
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 @@ -174,6 +174,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/runtime/db-session": "./dist/runtime/db/session.mjs",
Expand Down Expand Up @@ -314,6 +321,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
95 changes: 32 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,40 @@ 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" } })';
// Earlier generated files declared the URL helpers here, which exported them from
// void/routes too, so keep every one of those names importable.
for (const name of [
'RoutePath',
'RouteQueryValue',
'RouteQuery',
'RouteUrl',
'Href',
'RouteUrlInput',
'TypedRoutes',
'BuiltRouteUrl',
'EncodedRoutePath',
'RoutePathUrl',
]) {
lines.push(` export type ${name} = ${sdkRouteTypes}.${name};`);
}
for (const name of [
'RouteUrlSegment',
'CheckedRoutePath',
'RouteSegmentsUrl',
'RoutePatternUrl',
]) {
lines.push(` export type ${name}<P extends string> = ${sdkRouteTypes}.${name}<P>;`);
}
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
85 changes: 71 additions & 14 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 } from './url-diagnostics.ts';

/**
* Encode one path segment of a route param. `encodeURIComponent` keeps dots, and
Expand Down Expand Up @@ -80,13 +81,18 @@ export function interpolateRouteParams(
/** Known page, HTTP and WebSocket route patterns. */
export type RoutePath = keyof RoutePathMap & string;

// The helpers below are exported because generated route declarations re-export them:
// earlier generated files declared them, so apps can import them from `void/routes`.

// Dynamic segments in either public or legacy patterns match any text,
// so `/users/[id]` accepts `/users/${string}`. Template
// literal types cannot exclude empty or `/`-leading text without per-character unions.
type RouteUrlSegment<S extends string> = S extends `:${string}` | `[${string}]` | '*' ? string : S;
export type RouteUrlSegment<S extends string> = S extends `:${string}` | `[${string}]` | '*'
? string
: S;
// Root params and catch-alls would accept every absolute path. Keep those
// patterns available to routeUrl(), but require explicit construction for them.
type CheckedRoutePath<P extends string> = P extends `/${infer Segment}/${infer Rest}`
export type CheckedRoutePath<P extends string> = P extends `/${infer Segment}/${infer Rest}`
? Rest extends ''
? string extends RouteUrlSegment<Segment>
? never
Expand All @@ -97,21 +103,21 @@ type CheckedRoutePath<P extends string> = P extends `/${infer Segment}/${infer R
? never
: P
: P;
type RouteSegmentsUrl<P extends string> = P extends `${infer Segment}/${infer Rest}`
export type RouteSegmentsUrl<P extends string> = P extends `${infer Segment}/${infer Rest}`
? `${RouteUrlSegment<Segment>}/${RouteSegmentsUrl<Rest>}`
: RouteUrlSegment<P>;
// A trailing `/*` also matches the bare prefix, as in Hono: `/docs/*` matches `/docs`.
type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${'*' | '[...]'}/`
export type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${'*' | '[...]'}/`
? `${RouteSegmentsUrl<Prefix>}/` | `${RouteSegmentsUrl<Prefix>}/${string}/`
: P extends `${infer Prefix}/${'*' | '[...]'}`
? (Prefix extends '' ? '/' : RouteSegmentsUrl<Prefix>) | `${RouteSegmentsUrl<Prefix>}/${string}`
: RouteSegmentsUrl<P>;
// Fixed segments are also accepted percent-encoded, as `routeUrl()` returns them.
type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;
type RoutePathUrl = RoutePatternUrl<CheckedRoutePath<RoutePath | EncodedRoutePath>>;
export type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;
export type RoutePathUrl = RoutePatternUrl<CheckedRoutePath<RoutePath | EncodedRoutePath>>;
// Use a structural marker so package and generated declarations agree when a
// helper-built URL crosses into a navigation, form, or stream client.
type BuiltRouteUrl = string & { readonly __voidRouteUrl: true };
export type BuiltRouteUrl = string & { readonly __voidRouteUrl: true };

/** Whether `routing.typedRoutes` is on in the generated route types. */
export type TypedRoutes = RouteTypesConfig extends { typedRoutes: true } ? true : false;
Expand Down Expand Up @@ -157,14 +163,65 @@ type UrlOptions = {
hash?: string;
};

// An unknown pattern has no matching route params, so TypeScript can report
// the path error even if the options argument is absent. In static-only apps,
// keep P alone so an unchecked path doesn't affect the optional options tuple.
// A broad candidate must also keep P so it cannot widen the checked pattern. Candidate
// holds only the string literals in the path, so narrow P by it only when one of them
// is unknown: a path such as `P | '/about'` has other members that P must keep.
type MatchingRoute<P extends RoutePath, Candidate extends string> = [
RoutePathMap[RoutePath],
] extends [never]
? P
: [Candidate] extends [RoutePath]
? P
: string extends Candidate
? P
: P & Candidate;

// Function helpers can widen Candidate to string when they infer the signature.
// The marker must not be a subtype of the path: method signatures and code without
// strictFunctionTypes compare parameters bivariantly and would accept the route.
// A string-literal message also keeps the quoted path in the error: TypeScript prints
// the argument as `string` when the parameter type has no literal or template members.
// Distributing over Candidate lets an implementation of `typeof routeUrl` accept the path
// as `RoutePath`: TypeScript checks it with Candidate widened to string, which yields P.
// That result must not be never, or TypeScript would not use it.
type UnknownRoute<P extends RoutePath, Candidate extends string> = Candidate extends RoutePath
? never
: string extends Candidate
? NoInfer<P>
: `Unknown route: ${Exclude<NoInfer<Candidate>, RoutePath>}. Use a registered route pattern.` &
UrlErrorToken;

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

/** 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;
// A single signature with a positional path preserves inference in wrappers and currying helpers.
// Candidate is bounded by plain string: with `RoutePath | (string & {})`, the constraint of
// `P & Candidate` is a cross product of the route union that overflows past ~316 routes.
export function routeUrl<P extends RoutePath, Candidate extends string = P>(
path: RouteArgument<P, Candidate>,
...options: [RoutePathMap[NoInfer<MatchingRoute<P, Candidate>>]] extends [never]
? [options?: RouteOptions<MatchingRoute<P, Candidate>>]
: [options: RouteOptions<MatchingRoute<P, Candidate>>]
): 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
3 changes: 3 additions & 0 deletions packages/void/src/runtime/routing/url-diagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Require a property ordinary argument lists cannot supply. A well-known symbol
// can be named in declarations emitted for functions that wrap routeUrl.
export type UrlErrorToken = { readonly [Symbol.toPrimitive]: never };
Loading