diff --git a/docs/guide/type-safety.md b/docs/guide/type-safety.md
index c04f22485..4f3de869e 100644
--- a/docs/guide/type-safety.md
+++ b/docs/guide/type-safety.md
@@ -337,7 +337,9 @@ import { routeUrl } from 'void/routes';
Links also accept same-page queries and hashes (`?page=2`, `#comments`), and `http://`, `https://`, `mailto:`, and `tel:` URLs. Use absolute paths within your app; relative paths such as `../settings` are rejected. Static path segments accept raw text such as `/café menu` or uppercase percent encoding such as `/caf%C3%A9%20menu`.
-String checks use TypeScript patterns, which don't validate individual dynamic segments. For example, `/users/[id]` also accepts `/users/` and `/users/42/edit`. A root dynamic page can accept `//example.com`. Prefer `routeUrl()` to encode parameters, and validate untrusted URLs at runtime.
+With `routing.typedRoutes`, URLs handled only by root dynamic routes (`/[slug]`, `/[...slug]`, or `/[...]`) require `routeUrl()`, for example `routeUrl('/[...slug]', { params: { slug: 'dashboard' } })`. Other declared routes still accept checked URL strings. For a custom 404 page, use [`_not-found`](./pages-routing/errors.md#missing-pages).
+
+String checks use TypeScript patterns, which don't validate individual dynamic segments. For example, `/users/[id]` also accepts `/users/` and `/users/42/edit`. Prefer `routeUrl()` to encode parameters, and validate untrusted URLs at runtime.
The [SSE](./sse.md#client) and [live stream](./live.md#subscribe-from-the-browser) clients accept route URLs and external `http://` or `https://` URLs. Same-page links, `mailto:`, `tel:`, and `ws://` aren't stream destinations.
diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts
index 2d0ef798f..9b3cb2b8c 100644
--- a/packages/void/src/codegen/route-types.ts
+++ b/packages/void/src/codegen/route-types.ts
@@ -160,6 +160,15 @@ export function generateRouteTypes(
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}`',
);
@@ -175,10 +184,13 @@ export function generateRouteTypes(
);
lines.push(' : RouteSegmentsUrl
;');
lines.push(' type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;');
- lines.push(' type RoutePathUrl = RoutePatternUrl;');
+ 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(' ? RoutePathUrl | `${RoutePathUrl}${"?" | "#"}${string}`');
+ lines.push(' ? BuiltRouteUrl | RoutePathUrl | `${RoutePathUrl}${"?" | "#"}${string}`');
lines.push(' : string;');
lines.push(' export type Href = TypedRoutes extends true');
lines.push(
diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts
index 429ce4712..75c631804 100644
--- a/packages/void/src/runtime/routing/route-url.ts
+++ b/packages/void/src/runtime/routing/route-url.ts
@@ -84,6 +84,19 @@ export type RoutePath = keyof RoutePathMap & string;
// so `/users/[id]` accepts `/users/${string}`. Template
// literal types cannot exclude empty or `/`-leading text without per-character unions.
type RouteUrlSegment = S extends `:${string}` | `[${string}]` | '*' ? string : S;
+// Root params and catch-alls would accept every absolute path. Keep those
+// patterns available to routeUrl(), but require explicit construction for them.
+type CheckedRoutePath = P extends `/${infer Segment}/${infer Rest}`
+ ? Rest extends ''
+ ? string extends RouteUrlSegment
+ ? never
+ : P
+ : P
+ : P extends `/${infer Segment}`
+ ? string extends RouteUrlSegment
+ ? never
+ : P
+ : P;
type RouteSegmentsUrl = P extends `${infer Segment}/${infer Rest}`
? `${RouteUrlSegment}/${RouteSegmentsUrl}`
: RouteUrlSegment;
@@ -95,14 +108,17 @@ type RoutePatternUrl
= P extends `${infer Prefix}/${'*' | '[..
: RouteSegmentsUrl
;
// Fixed segments are also accepted percent-encoded, as `routeUrl()` returns them.
type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;
-type RoutePathUrl = RoutePatternUrl;
+type RoutePathUrl = RoutePatternUrl>;
+// Use a structural marker so package and generated declarations agree when a
+// helper-built URL crosses into a navigation, form, or stream client.
+type BuiltRouteUrl = string & { readonly __voidRouteUrl: true };
/** Whether `routing.typedRoutes` is on in the generated route types. */
export type TypedRoutes = RouteTypesConfig extends { typedRoutes: true } ? true : false;
/** The URL of one of the app's routes. A plain string unless `routing.typedRoutes` is on. */
export type RouteUrl = TypedRoutes extends true
- ? RoutePathUrl | `${RoutePathUrl}${'?' | '#'}${string}`
+ ? BuiltRouteUrl | RoutePathUrl | `${RoutePathUrl}${'?' | '#'}${string}`
: string;
/** Anything a link can point to: a route URL, a same-page query or hash, or an external URL. */
diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts
index b15f8ac9f..07fb68e7b 100644
--- a/packages/void/test/integration/route-url-builder.test.ts
+++ b/packages/void/test/integration/route-url-builder.test.ts
@@ -72,7 +72,7 @@ const unknown: Href = '/unknown';
const unchecked: Href = dynamic;
// @ts-expect-error relative paths are rejected
const relative: Href = '../about';
-// @ts-expect-error protocol-relative URLs are rejected when no root dynamic route matches them
+// @ts-expect-error protocol-relative URLs are rejected
const protocolRelative: Href = '//example.com/about';
// @ts-expect-error empty strings are rejected
const empty: Href = '';
@@ -176,7 +176,7 @@ defineConfig({
});
`;
-const linkHrefCheck = `import type { Href } from 'void/routes';
+const linkHrefCheck = `import { routeUrl, type Href } from 'void/routes';
import type { LinkProps as ReactLinkProps } from ${adapterSource('react/src/runtime/link.tsx')};
import type { Link as VueLink } from ${adapterSource('vue/src/runtime/link.ts')};
import type { LinkProps as SvelteLinkProps } from ${adapterSource('svelte/src/runtime/link-props.ts')};
@@ -192,13 +192,18 @@ const known: [ReactLinkProps['href'], VueLinkProps['href'], SvelteLinkProps['hre
'/users/42',
'/users/42',
];
+const built: [ReactLinkProps['href'], VueLinkProps['href'], SvelteLinkProps['href']] = [
+ routeUrl('/users/[id]', { params: { id: 42 } }),
+ routeUrl('/users/[id]', { params: { id: 42 } }),
+ routeUrl('/users/[id]', { params: { id: 42 } }),
+];
// @ts-expect-error React Link rejects unknown routes
const react: ReactLinkProps['href'] = '/unknown';
// @ts-expect-error Vue Link rejects unknown routes
const vue: VueLinkProps['href'] = '/unknown';
// @ts-expect-error Svelte Link rejects unknown routes
const svelte: SvelteLinkProps['href'] = '/unknown';
-void [same, known, react, vue, svelte];
+void [same, known, built, react, vue, svelte];
`;
// Svelte's implementation uses runes, so this tsc fixture covers the other adapters.
@@ -221,14 +226,15 @@ void solidForm.put('https://example.com');
void vueForm.submit('/unknown', 'POST');
`;
-const solidLinkHrefCheck = `import type { Href } from 'void/routes';
+const solidLinkHrefCheck = `import { routeUrl, type Href } from 'void/routes';
import type { LinkProps } from ${adapterSource('solid/src/runtime/link.tsx')};
type Same = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const same: Same = true;
const known: LinkProps['href'] = '/users/42';
+const built: LinkProps['href'] = routeUrl('/users/[id]', { params: { id: 42 } });
// @ts-expect-error Solid Link rejects unknown routes
const unknown: LinkProps['href'] = '/unknown';
-void [same, known, unknown];
+void [same, known, built, unknown];
`;
// Page params typed through each adapter's useParams().
@@ -561,24 +567,95 @@ action('/users/[id]?missing', { params: { id: '42' } });
},
);
- it('lets a root dynamic page match any single-segment URL with routing.typedRoutes', async () => {
+ it.each([
+ { file: '[slug]', pattern: '/[slug]', legacy: '/:slug', param: 'slug' },
+ { file: '[...slug]', pattern: '/[...slug]', legacy: '/:slug{.+}', param: 'slug' },
+ { file: '[...]', pattern: '/[...]', legacy: '/*', param: '*' },
+ ])('keeps raw URL checks with a root $file page', async ({ file, pattern, legacy, param }) => {
const root = await createFixture({
typedRoutes: true,
extraFiles: {
- 'pages/[slug].tsx': 'export default function Page() { return null; }',
- // Template literal types cannot exclude empty or slash-leading segments.
- 'check-root-dynamic.ts': `import type { RouteUrl } from 'void/routes';
-const loose: Array = ['/anything', '/users/', '//example.com'];
-void loose;
+ [`pages/${file}.tsx`]: 'export default function Page() { return null; }',
+ 'pages/[locale]/localized.tsx': 'export default function Page() { return null; }',
+ 'check-root-dynamic.ts': `import { routeUrl, type Href, type RouteDestination, type RoutePath, type RouteUrl } from 'void/routes';
+import type { VoidRouter } from 'void/pages-client';
+import type { CloudContext } from 'void/handler';
+import { revalidate } from 'void/isr';
+import { connectEventStream } from 'void/sse/client';
+import { connectLiveStream } from 'void/live/client';
+const path: RoutePath = ${JSON.stringify(pattern)};
+const destination: RouteDestination = { pathname: path, params: { ${JSON.stringify(param)}: 'dashboard' } };
+const url: RouteUrl = routeUrl(path, { params: { ${JSON.stringify(param)}: 'dashboard' } });
+const alias: Href = routeUrl(${JSON.stringify(legacy)}, { params: { ${JSON.stringify(param)}: 'dashboard' } });
+const text: string = url;
+const known: Href[] = ['/about', '/about?tab=activity', '/users/42', '/files/docs/start', '/wild/a/b', '/fr/localized', url, alias];
+// @ts-expect-error root dynamic routes do not admit misspelled static URLs
+const typo: Href = '/abuot';
+// @ts-expect-error root dynamic routes require explicit URL construction
+const dynamic: RouteUrl = '/dashboard';
+// @ts-expect-error root dynamic routes do not admit arbitrary nested URLs
+const nested: Href = '/dashboard/settings';
+// @ts-expect-error root dynamic routes do not admit protocol-relative URLs
+const external: Href = '//example.com';
+// @ts-expect-error query strings do not bypass route checks
+const query: RouteUrl = '/dashboard?tab=activity';
+// @ts-expect-error hashes do not bypass route checks
+const hash: RouteUrl = '/dashboard#details';
+// @ts-expect-error params remain required for root dynamic routes
+routeUrl(${JSON.stringify(pattern)});
+// @ts-expect-error root dynamic parameter names remain checked
+routeUrl(${JSON.stringify(pattern)}, { params: { wrong: 'dashboard' } });
+// @ts-expect-error routeUrl still requires a registered pattern
+routeUrl('/abuot');
+declare const router: VoidRouter;
+declare const context: CloudContext;
+void router.visit(url);
+void router.prefetch(destination);
+context.redirect(url);
+void context.rewrite(url);
+void revalidate({ paths: [url] });
+connectEventStream(url);
+connectLiveStream(url);
+void [known, text, typo, dynamic, nested, external, query, hash];
`,
},
});
- expect(typecheck(root, 'generated', ['check-root-dynamic.ts'])).toEqual({
- output: '',
- status: 0,
- });
+ for (const declarations of ['generated', 'package'] as const) {
+ expect(typecheck(root, declarations, ['check-typed.ts', 'check-root-dynamic.ts'])).toEqual({
+ output: '',
+ status: 0,
+ });
+ }
});
+ it.each(['[slug]', '[...slug]', '[...]'])(
+ 'keeps raw URL checks with a trailing-slash root %s page',
+ async (file) => {
+ const root = await createFixture({
+ typedRoutes: true,
+ extraFiles: {
+ 'void.json': JSON.stringify({ routing: { trailingSlash: true } }),
+ [`pages/${file}.tsx`]: 'export default function Page() { return null; }',
+ 'check-root-trailing.ts': `import { routeUrl, type Href } from 'void/routes';
+const url: Href = routeUrl('/${file}/', { params: { ${JSON.stringify(file === '[...]' ? '*' : 'slug')}: 'dashboard' } });
+const known: Href = '/about/';
+// @ts-expect-error root dynamic routes do not admit misspelled trailing-slash URLs
+const typo: Href = '/abuot/';
+// @ts-expect-error root dynamic routes do not admit nested trailing-slash URLs
+const nested: Href = '/dashboard/settings/';
+void [url, known, typo, nested];
+`,
+ },
+ });
+ for (const declarations of ['generated', 'package'] as const) {
+ expect(typecheck(root, declarations, ['check-root-trailing.ts'])).toEqual({
+ output: '',
+ status: 0,
+ });
+ }
+ },
+ );
+
it('checks useIslandForm URLs in every adapter with routing.typedRoutes', async () => {
const root = await createFixture({
typedRoutes: true,
@@ -592,7 +669,10 @@ void loose;
});
it('checks Link href in every adapter with routing.typedRoutes', async () => {
- const root = await createFixture({ typedRoutes: true });
+ const root = await createFixture({
+ typedRoutes: true,
+ extraFiles: { 'pages/[...slug].tsx': 'export default function Page() { return null; }' },
+ });
const tsSources = { allowImportingTsExtensions: true };
expect(
typecheck(root, 'generated', ['check-links.ts'], { ...tsSources, jsx: 'react-jsx' }),
diff --git a/packages/void/test/unit/route-types.test.ts b/packages/void/test/unit/route-types.test.ts
index 42d4002a4..4720d2540 100644
--- a/packages/void/test/unit/route-types.test.ts
+++ b/packages/void/test/unit/route-types.test.ts
@@ -298,7 +298,9 @@ describe('generateRouteTypes', () => {
' "/café/[id]": "/caf%C3%A9/[id]";',
' "/café/:id": "/caf%C3%A9/:id";',
]);
- expect(dts).toContain('type RoutePathUrl = RoutePatternUrl;');
+ expect(dts).toContain(
+ 'type RoutePathUrl = RoutePatternUrl>;',
+ );
});
it('turns on typed route URLs only when routing.typedRoutes is set', () => {