Skip to content

Commit 98fbbf0

Browse files
committed
Fix trailing-slash Pages routing and asset handling.
1 parent 31745e8 commit 98fbbf0

13 files changed

Lines changed: 242 additions & 30 deletions

‎packages/void/src/codegen/route-types.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,10 @@ export function generateRouteTypes(
146146
lines.push(' ? `${RouteUrlSegment<Segment>}/${RouteSegmentsUrl<Rest>}`');
147147
lines.push(' : RouteUrlSegment<P>;');
148148
lines.push(
149-
' type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${"*" | "[...]"}`',
149+
' type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${"*" | "[...]"}/`',
150150
);
151+
lines.push(' ? `${RouteSegmentsUrl<Prefix>}/` | `${RouteSegmentsUrl<Prefix>}/${string}/`');
152+
lines.push(' : P extends `${infer Prefix}/${"*" | "[...]"}`');
151153
lines.push(
152154
' ? (Prefix extends "" ? "/" : RouteSegmentsUrl<Prefix>) | `${RouteSegmentsUrl<Prefix>}/${string}`',
153155
);

‎packages/void/src/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -868,7 +868,9 @@ export function voidPlugin(options?: {
868868
hasSandbox: false,
869869
}),
870870
prerenderPlugin(root, config),
871-
...nodeTargetPlugin(config.target as 'node' | 'bun' | 'deno'),
871+
...nodeTargetPlugin(config.target as 'node' | 'bun' | 'deno', {
872+
trailingSlash: config.routing?.trailingSlash,
873+
}),
872874
];
873875
}
874876

‎packages/void/src/pages/manifest.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,9 @@ function isStaticPattern(pattern: string): boolean {
131131

132132
/** The RegExp literal a page pattern matches with, the same on the client and the server. */
133133
export function patternToRegex(pattern: string): string {
134-
const regexSource = pattern
134+
// An empty anonymous catch-all uses the prefix's slash as its final separator.
135+
const trailingWildcard = pattern.endsWith('/*/');
136+
const regexSource = (trailingWildcard ? pattern.slice(0, -2) : pattern)
135137
.split('/')
136138
.map((segment) => {
137139
const group = captureGroup(segment);
@@ -145,5 +147,5 @@ export function patternToRegex(pattern: string): string {
145147
return literal;
146148
})
147149
.join('\\/');
148-
return `/^${regexSource}$/`;
150+
return `/^${regexSource}${trailingWildcard ? '(?:(.*)\\/)?' : ''}$/`;
149151
}

‎packages/void/src/plugin-node-target.ts‎

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { existsSync } from 'node:fs';
2+
import { readFile, stat } from 'node:fs/promises';
23
import type { IncomingMessage, ServerResponse } from 'node:http';
34
import { pathToFileURL } from 'node:url';
4-
import { dirname, join, relative } from 'pathslash';
5-
import type { Plugin } from 'vite';
5+
import mime from 'mime';
6+
import { dirname, isAbsolute, join, relative, resolve } from 'pathslash';
7+
import { isFileServingAllowed, type Plugin } from 'vite';
68
import { findVoidDependentPackages } from './installed-packages.ts';
79
import { readProjectPaths } from './project-paths.ts';
810

@@ -114,7 +116,10 @@ function honoMiddleware(
114116
* 4. Build — dual-environment build (client + SSR) for pages apps,
115117
* single SSR build for API-only apps
116118
*/
117-
export function nodeTargetPlugin(target: NodeTarget): Array<Plugin> {
119+
export function nodeTargetPlugin(
120+
target: NodeTarget,
121+
options: { trailingSlash?: boolean } = {},
122+
): Array<Plugin> {
118123
const unavailable = (id: string, root: string, importer: string | undefined) => {
119124
// The import can come from an installed package, so name the file.
120125
const source = importer ? ` Imported by ${relative(root, importer)}.` : '';
@@ -214,14 +219,54 @@ export function nodeTargetPlugin(target: NodeTarget): Array<Plugin> {
214219
},
215220

216221
configureServer(server) {
222+
// The Pages fallback needs the same public-file lookup as production before
223+
// deciding whether a URL belongs to a dynamic page.
224+
const assets = {
225+
async fetch(request: Request): Promise<Response> {
226+
try {
227+
const root = server.config.publicDir;
228+
if (!root) {
229+
return new Response(null, { status: 404 });
230+
}
231+
const pathname = new URL(request.url).pathname;
232+
let file = resolve(root, '.' + decodeURIComponent(pathname));
233+
const rel = relative(root, file);
234+
if (rel === '..' || rel.startsWith('../') || isAbsolute(rel)) {
235+
return new Response(null, { status: 404 });
236+
}
237+
let entry = await stat(file);
238+
if (pathname.endsWith('/') && !entry.isDirectory()) {
239+
return new Response(null, { status: 404 });
240+
}
241+
if (entry.isDirectory()) {
242+
file = join(file, 'index.html');
243+
entry = await stat(file);
244+
}
245+
if (!entry.isFile() || !isFileServingAllowed(server.config, file)) {
246+
return new Response(null, { status: 404 });
247+
}
248+
return new Response(
249+
request.method === 'HEAD' ? null : new Uint8Array(await readFile(file)),
250+
{
251+
headers: { 'Content-Type': mime.getType(file) ?? 'application/octet-stream' },
252+
},
253+
);
254+
} catch {
255+
return new Response(null, { status: 404 });
256+
}
257+
},
258+
};
217259
// Middleware runs BEFORE Vite's built-in middleware so API routes
218260
// and SSR pages are handled before Vite's SPA fallback sends a 404.
219261
// The honoMiddleware helper skips /@, /__, and /node_modules/ paths
220262
// so Vite's HMR and module serving still work normally.
221263
server.middlewares.use(
222264
honoMiddleware(async () => {
223265
const mod = await server.ssrLoadModule('virtual:void-routes');
224-
return mod.default;
266+
if (!options.trailingSlash) {
267+
return mod.default;
268+
}
269+
return { fetch: (request: Request) => mod.default.fetch(request, { ASSETS: assets }) };
225270
}),
226271
);
227272
},

‎packages/void/src/router/compile.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,13 +1070,14 @@ function compilePageRoutes(
10701070
page.renderMode === 'island' && pages.islandClientEntryId
10711071
? 'getIslandsAssetTags'
10721072
: 'getPagesAssetTags';
1073-
const routeOptions = `{ ${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}) })} }`;
1074-
lines.push(
1075-
`app.get(${JSON.stringify(page.pattern)}, __createPageGetHandler(${routeOptions}));`,
1076-
);
1073+
const trailingCatchAll = options.trailingSlash && page.catchAll;
1074+
const pattern = trailingCatchAll ? page.pattern.slice(0, -1) : page.pattern;
1075+
const catchAllParam = page.pattern.match(/:([^/{}]+)\{\.\+\}\/$/)?.[1];
1076+
const routeOptions = `{ ${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}) })} }`;
1077+
lines.push(`app.get(${JSON.stringify(pattern)}, __createPageGetHandler(${routeOptions}));`);
10771078
if (page.methods.includes('action') || page.methods.includes('actions')) {
10781079
lines.push(
1079-
`app.on(["POST", "PUT", "PATCH", "DELETE"], ${JSON.stringify(page.pattern)}, __createPageMutationHandler({ ...${routeOptions}, namedActions: ${JSON.stringify(page.methods.includes('actions'))} }));`,
1080+
`app.on(["POST", "PUT", "PATCH", "DELETE"], ${JSON.stringify(pattern)}, __createPageMutationHandler({ ...${routeOptions}, namedActions: ${JSON.stringify(page.methods.includes('actions'))} }));`,
10801081
);
10811082
}
10821083
}

‎packages/void/src/runtime/route-url.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ export function interpolateRouteParams(
5151
leadingName = name;
5252
}
5353
const value = params[name];
54+
if (anonymous && value === '' && pathname.slice(offset + token.length) === '/') {
55+
return '';
56+
}
5457
if (requireParams && !anonymous && value === '') {
5558
throw new TypeError(`Route param "${name}" must not be empty.`);
5659
}
@@ -85,9 +88,11 @@ type RouteSegmentsUrl<P extends string> = P extends `${infer Segment}/${infer Re
8588
? `${RouteUrlSegment<Segment>}/${RouteSegmentsUrl<Rest>}`
8689
: RouteUrlSegment<P>;
8790
// A trailing `/*` also matches the bare prefix, as in Hono: `/docs/*` matches `/docs`.
88-
type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${'*' | '[...]'}`
89-
? (Prefix extends '' ? '/' : RouteSegmentsUrl<Prefix>) | `${RouteSegmentsUrl<Prefix>}/${string}`
90-
: RouteSegmentsUrl<P>;
91+
type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${'*' | '[...]'}/`
92+
? `${RouteSegmentsUrl<Prefix>}/` | `${RouteSegmentsUrl<Prefix>}/${string}/`
93+
: P extends `${infer Prefix}/${'*' | '[...]'}`
94+
? (Prefix extends '' ? '/' : RouteSegmentsUrl<Prefix>) | `${RouteSegmentsUrl<Prefix>}/${string}`
95+
: RouteSegmentsUrl<P>;
9196
// Fixed segments are also accepted percent-encoded, as `routeUrl()` returns them.
9297
type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;
9398
type RoutePathUrl = RoutePatternUrl<RoutePath | EncodedRoutePath>;

‎packages/void/src/runtime/routing-pages.ts‎

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,26 @@ export type PageRouteOptions = {
2424
headConfig: PageGetArguments[6] | null;
2525
renderOptions: PageGetArguments[7];
2626
namedActions?: boolean;
27+
trailingSlash?: boolean;
28+
catchAllParam?: string;
2729
};
30+
// Hono's trie matcher cannot match a named catch-all followed by a literal slash.
31+
// Register that route without the slash, then enforce the public URL and exclude
32+
// the final separator from the parameter before invoking application code.
33+
function preparePageRequest(c: Context, options: PageRouteOptions): boolean {
34+
if (!options.trailingSlash) {
35+
return true;
36+
}
37+
if (!c.req.path.endsWith('/')) {
38+
return false;
39+
}
40+
if (options.catchAllParam) {
41+
const params = c.req.param();
42+
params[options.catchAllParam] = params[options.catchAllParam].slice(0, -1);
43+
c.req.param = ((key?: string) => (key ? params[key] : { ...params })) as typeof c.req.param;
44+
}
45+
return true;
46+
}
2847
function actionNameOf(url: string): string | undefined {
2948
return new URL(url).searchParams.keys().next().value;
3049
}
@@ -58,6 +77,9 @@ export function createNamedActionMarker(
5877
}
5978
export function createPageGetHandler(options: PageRouteOptions): (c: Context) => Promise<Response> {
6079
return markRouteHandler(async (context: Context) => {
80+
if (!preparePageRequest(context, options)) {
81+
return context.notFound();
82+
}
6183
const mod = options.load ? await options.load() : { head: options.head };
6284
return handlePageGet(
6385
mod.loader,
@@ -75,6 +97,9 @@ export function createPageMutationHandler(
7597
options: PageRouteOptions,
7698
): (c: Context) => Promise<Response> {
7799
const mutationHandler = async (context: Context) => {
100+
if (!preparePageRequest(context, options)) {
101+
return context.notFound();
102+
}
78103
const mod = options.load ? await options.load() : {};
79104
const actionName = options.namedActions ? actionNameOf(context.req.url) : undefined;
80105
// The name comes from the query string, so only own function properties
@@ -131,22 +156,37 @@ export function createPagesFallback(options: {
131156
) {
132157
return c.text('Not Found', 404);
133158
}
159+
const assets = c.env?.ASSETS;
160+
const assetResponse: Response =
161+
assets && typeof assets.fetch === 'function'
162+
? await assets.fetch(c.req.raw)
163+
: options.routing.markNoMatch(c.req.raw, new Response('Not Found', { status: 404 }));
164+
const filePath = path.includes('/.') || path.substring(path.lastIndexOf('/') + 1).includes('.');
134165
// Directory indexes may be served without a redirect by the asset binding.
135-
// Canonicalize known Pages URLs first, without registering overlapping catch-all routes.
136-
if (
166+
// Dynamic page patterns also match real files, which must keep their URLs.
167+
const pageNeedsSlash =
137168
options.trailingSlash &&
138169
!path.endsWith('/') &&
139-
options.pagePatterns?.some((pattern) => pattern.test(decodePagePath(`${path}/`)))
170+
options.pagePatterns?.some((pattern) => pattern.test(decodePagePath(`${path}/`)));
171+
let directoryIndex = false;
172+
if (
173+
pageNeedsSlash &&
174+
assetResponse.status === 200 &&
175+
assetResponse.headers.get('Content-Type')?.split(';')[0] === 'text/html' &&
176+
assets
140177
) {
178+
const url = new URL(c.req.url);
179+
url.pathname += '/';
180+
const index = await assets.fetch(new Request(url, c.req.raw));
181+
directoryIndex = index.status === 200;
182+
await index.body?.cancel();
183+
}
184+
if (pageNeedsSlash && (assetResponse.status === 404 || directoryIndex)) {
185+
await assetResponse.body?.cancel();
141186
const url = new URL(c.req.url);
142187
url.pathname += '/';
143188
return Response.redirect(url.href, 301);
144189
}
145-
const assets = c.env?.ASSETS;
146-
const assetResponse: Response =
147-
assets && typeof assets.fetch === 'function'
148-
? await assets.fetch(c.req.raw)
149-
: options.routing.markNoMatch(c.req.raw, new Response('Not Found', { status: 404 }));
150190
if (assetResponse.status !== 404) {
151191
return markStaticAsset(c, await cachePolicy(c.req.raw, c.env, assetResponse));
152192
}
@@ -156,7 +196,7 @@ export function createPagesFallback(options: {
156196
if (fallback) {
157197
return fallback;
158198
}
159-
if (path.includes('/.') || path.substring(path.lastIndexOf('/') + 1).includes('.')) {
199+
if (filePath) {
160200
return options.errors.serveCustomPage(c, 404, 'Not Found');
161201
}
162202
if (path !== '/' && (options.trailingSlash ? !path.endsWith('/') : path.endsWith('/'))) {

‎packages/void/test/integration/route-url-builder.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,19 @@ void loose;
606606
).toEqual({ output: '', status: 0 });
607607
});
608608

609+
it('checks empty trailing-slash catch-alls through generated declarations', async () => {
610+
const root = await createFixture({
611+
typedRoutes: true,
612+
extraFiles: {
613+
'void.json': JSON.stringify({ routing: { trailingSlash: true } }),
614+
'check-trailing.ts': `import type { RouteUrl } from 'void/routes';
615+
const paths: Array<RouteUrl> = ['/wild/', '/wild/a/b/'];
616+
void paths;`,
617+
},
618+
});
619+
expect(typecheck(root, 'generated', ['check-trailing.ts'])).toEqual({ output: '', status: 0 });
620+
});
621+
609622
it('checks URL strings through the package types alone with routing.typedRoutes', () => {
610623
// The generated declarations repeat the route URL types, so check the
611624
// package's own copy without a generated .void/routes.d.ts.
@@ -618,7 +631,7 @@ void loose;
618631
join(root, 'routes.d.ts'),
619632
`export {};
620633
declare module 'void/routes' {
621-
interface RoutePathMap { '/': never; '/docs/[...]': '*'; '/users/[id]': 'id'; '/café menu': never }
634+
interface RoutePathMap { '/': never; '/docs/[...]': '*'; '/trailing/[...]/': '*'; '/users/[id]': 'id'; '/café menu': never }
622635
interface EncodedRoutePathMap { '/café menu': '/caf%C3%A9%20menu' }
623636
interface RouteTypesConfig { typedRoutes: true }
624637
}
@@ -629,11 +642,13 @@ declare module 'void/routes' {
629642
`import type { Href, RouteUrl } from 'void/routes';
630643
const hrefs: Array<Href> = ['/', '/docs', '/docs/a/b', '/users/42', '/café menu', '/caf%C3%A9%20menu?q=1', '#top', 'https://vite.dev'];
631644
const route: RouteUrl = '/caf%C3%A9%20menu';
645+
const emptyCatchAll: RouteUrl = '/trailing/';
646+
const nestedCatchAll: RouteUrl = '/trailing/a/b/';
632647
// @ts-expect-error unknown routes are rejected
633648
const unknown: Href = '/unknown';
634649
// @ts-expect-error route URLs exclude external links
635650
const external: RouteUrl = 'https://vite.dev';
636-
void [hrefs, route, unknown, external];
651+
void [hrefs, route, emptyCatchAll, nestedCatchAll, unknown, external];
637652
`,
638653
);
639654
writeFileSync(

‎packages/void/test/integration/trailing-slash.test.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,23 @@ describe.each(['node', 'cloudflare'] as const)('trailing-slash Pages on %s', (ta
4343
writeFileSync(
4444
`${file}.server.ts`,
4545
`export const getPrerenderPaths = () => [{ ${name}: ${JSON.stringify(value)} }];
46-
export const loader = (c) => ({ value: c.req.param(${JSON.stringify(name)}) });`,
46+
export const loader = (c) => ({ value: c.req.param(${JSON.stringify(name)}) });
47+
export const action = (c) => c.json({ value: c.req.param(${JSON.stringify(name)}) });`,
4748
);
4849
}
50+
writeFileSync(
51+
join(fixture.root, 'pages/[...fallback].tsx'),
52+
'export default function Page() { return <h1>Fallback route</h1>; }',
53+
);
54+
mkdirSync(join(fixture.root, 'pages/wild'), { recursive: true });
55+
writeFileSync(
56+
join(fixture.root, 'pages/wild/[...].tsx'),
57+
'export default function Page() { return <h1>Anonymous route</h1>; }',
58+
);
59+
mkdirSync(join(fixture.root, 'public'), { recursive: true });
60+
for (const file of ['asset.js', 'favicon.ico', 'terms.html', 'LICENSE']) {
61+
writeFileSync(join(fixture.root, 'public', file), 'public file');
62+
}
4963
execFileSync('vp', ['build'], { cwd: fixture.root, stdio: 'pipe', timeout: 60_000 });
5064
for (const mode of ['dev', 'production']) {
5165
const server = await startServer((port) => {
@@ -122,4 +136,29 @@ export const loader = (c) => ({ value: c.req.param(${JSON.stringify(name)}) });`
122136
await api.text();
123137
}
124138
});
139+
it('keeps public files accessible beside a catch-all page', async () => {
140+
for (const { base, mode } of servers) {
141+
for (const file of ['asset.js', 'favicon.ico', 'LICENSE']) {
142+
const response = await fetch(`${base}/${file}`, { redirect: 'manual' });
143+
expect(response.status, `${mode}: ${file}`).toBe(200);
144+
expect(await response.text(), `${mode}: ${file}`).toBe('public file');
145+
}
146+
const html = await fetch(`${base}/terms.html`);
147+
expect(html.status, mode).toBe(200);
148+
expect(await html.text(), mode).toBe('public file');
149+
}
150+
});
151+
it('preserves catch-all parameters in actions and supports empty anonymous catch-alls', async () => {
152+
for (const { base, mode } of servers) {
153+
const action = await fetch(`${base}/files/guides/intro/`, {
154+
method: 'POST',
155+
headers: { Origin: base },
156+
});
157+
expect(action.status, mode).toBe(200);
158+
expect(await action.json(), mode).toEqual({ value: 'guides/intro' });
159+
const page = await fetch(`${base}/wild/`);
160+
expect(page.status, mode).toBe(200);
161+
expect(await page.text(), mode).toContain('<h1>Anonymous route</h1>');
162+
}
163+
});
125164
});

‎packages/void/test/unit/pages-manifest.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ function matchRouteFor(pattern: string): (url: string) => string | null {
3737
}
3838

3939
describe('generated Pages client route manifest', () => {
40+
it('matches an empty anonymous catch-all with trailing slashes', () => {
41+
const matchRoute = matchRouteFor('/docs/*/');
42+
for (const path of ['/docs/', '/docs/a/', '/docs/a/b/']) {
43+
expect(matchRoute(path), path).toBe('docs/[...slug]');
44+
}
45+
expect(matchRoute('/docs/a')).toBeNull();
46+
});
47+
4048
it('matches named catch-all pages across path segments', () => {
4149
const matchRoute = matchRouteFor('/docs/:slug{.+}');
4250

0 commit comments

Comments
 (0)