diff --git a/packages/void/src/pages/not-found-context.ts b/packages/void/src/pages/not-found-context.ts index c32c5a675..a09428993 100644 --- a/packages/void/src/pages/not-found-context.ts +++ b/packages/void/src/pages/not-found-context.ts @@ -1,22 +1,49 @@ import type { Context } from 'hono'; +const loaderNotFound = new WeakSet(); const loaderBoundaries = new WeakSet(); +/** The loader already answered this URL with `c.notFound()`, so assets must not. */ export function handlesPageLoaderNotFound(c: Context): boolean { + return loaderNotFound.has(c); +} + +/** The active loader's not-found boundary renders instead of the fallback. */ +export function ownsLoaderNotFoundBoundary(c: Context): boolean { return loaderBoundaries.has(c); } -/** Defer only Void's app fallback while a loader can select its own boundary. */ -export async function withLoaderNotFoundBoundary( +/** + * Record a loader's `c.notFound()` for the rest of the request. + * + * Hono resolves `c.notFound()` inside the loader call, so the marker has to be + * set before the fallback runs. It also has to outlive the loader: the loader + * returns the fallback's response, which must never be read as page props. + * Boundary ownership ends with the loader so outer middleware can render the + * root not-found page after `await next()`. + */ +export async function withLoaderNotFoundDecision( c: Context, + ownBoundary: boolean, load: () => unknown, ): Promise { - const alreadyHandled = loaderBoundaries.has(c); - loaderBoundaries.add(c); + const notFound = c.notFound; + const alreadyOwned = loaderBoundaries.has(c); + c.notFound = () => { + // The outer page owns the decision when a fallback render re-enters a loader. + if (!loaderNotFound.has(c)) { + loaderNotFound.add(c); + if (ownBoundary) { + loaderBoundaries.add(c); + } + } + return notFound.call(c); + }; try { return await load(); } finally { - if (!alreadyHandled) { + c.notFound = notFound; + if (!alreadyOwned) { loaderBoundaries.delete(c); } } diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index 0f90a3deb..b2941e974 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -13,7 +13,7 @@ import { type HeadDescriptor, type HeadConfig, } from './head.ts'; -import { withLoaderNotFoundBoundary } from './not-found-context.ts'; +import { withLoaderNotFoundDecision } from './not-found-context.ts'; import { escapeScriptJson } from './script-json.ts'; import { serializePageData } from './serialize.ts'; import type { DevCssAsset, PageRenderMode } from './types.ts'; @@ -352,7 +352,7 @@ async function runLoader( c: CloudContext, render: (props: Record) => Promise, recover?: (error: unknown, response?: Response) => Promise, - recoverNotFound = false, + ownsNotFoundBoundary = false, ): Promise { if (!handler) { return render({}); @@ -360,7 +360,9 @@ async function runLoader( return runPageHandler(handler, c, async (leaf) => { let result: unknown; try { - result = recoverNotFound ? await withLoaderNotFoundBoundary(c, () => leaf(c)) : await leaf(c); + // Always wrapped: even without a boundary, a loader's `c.notFound()` + // decides the response and keeps the asset fallback out of the URL. + result = await withLoaderNotFoundDecision(c, ownsNotFoundBoundary, () => leaf(c)); } catch (error) { const recovered = await recover?.(error); if (recovered) { diff --git a/packages/void/src/runtime/routing-pages.ts b/packages/void/src/runtime/routing-pages.ts index f912ed21b..d8356af9c 100644 --- a/packages/void/src/runtime/routing-pages.ts +++ b/packages/void/src/runtime/routing-pages.ts @@ -4,7 +4,10 @@ import { markActionKey, searchWithoutPreservedQuery, } from '../pages/action-key.ts'; -import { handlesPageLoaderNotFound } from '../pages/not-found-context.ts'; +import { + handlesPageLoaderNotFound, + ownsLoaderNotFoundBoundary, +} from '../pages/not-found-context.ts'; import { handlePageGet, handlePageMutation } from '../pages/protocol.ts'; import { decodePagePath } from '../pages/url.ts'; import type { ClientAssetTags } from './routing-assets.ts'; @@ -181,8 +184,8 @@ export function createPagesFallback(options: { }): (c: Context) => Promise { const cachePolicy = createAssetCachePolicy(options.assetsDir); return async (c) => { - // The loader's boundary owns this 404; skip root rendering and asset fallbacks. - if (handlesPageLoaderNotFound(c)) { + // The loader's own boundary owns this 404; skip root rendering and asset fallbacks. + if (ownsLoaderNotFoundBoundary(c)) { return c.newResponse(null, 404); } const path = c.req.path; @@ -194,8 +197,12 @@ export function createPagesFallback(options: { return c.text('Not Found', 404); } const assets = c.env?.ASSETS; - const assetResponse: Response = - assets && typeof assets.fetch === 'function' + // A loader that called `c.notFound()` already claimed this URL. Serving a + // static file that happens to share the path would turn its bytes into the + // loader's return value, so answer from the not-found path instead. + const assetResponse: Response = handlesPageLoaderNotFound(c) + ? new Response('Not Found', { status: 404 }) + : assets && typeof assets.fetch === 'function' ? await assets.fetch(c.req.raw) : options.routing.markNoMatch(c.req.raw, new Response('Not Found', { status: 404 })); const filePath = path.includes('/.') || path.substring(path.lastIndexOf('/') + 1).includes('.'); diff --git a/packages/void/test/unit/page-boundaries.test.ts b/packages/void/test/unit/page-boundaries.test.ts index 3609bad53..0b8ca02dd 100644 --- a/packages/void/test/unit/page-boundaries.test.ts +++ b/packages/void/test/unit/page-boundaries.test.ts @@ -375,6 +375,113 @@ describe('loader not-found dispatch', () => { } }, ); + + it.each([false, true])( + 'renders the root boundary for middleware after a loader not-found (Pages: %s)', + async (pages) => { + let assetReads = 0; + const app = new Hono(); + const runtime = createRoutingRuntime(app, { nodeTarget: true }); + const common = { + assets: async () => ({ css: '', body: '', preloads: '' }), + headConfig: null, + render: async (page: { component: string }) => `

${page.component}

`, + }; + app.use(runtime.contextMiddleware); + app.use(async (c, next) => { + await next(); + c.res = await c.notFound(); + }); + app.notFound( + createPagesFallback({ + routing: runtime, + errors: createErrorRenderer({ projectRoot: '/project', homeDir: '/home' }), + pageNotFound: createPageGetHandler({ + ...common, + componentId: 'root', + load: async () => ({ loader: () => new Response(null, { status: 404 }) }), + renderOptions: { boundaries: { notFound: 'root-not-found', errors: [] } }, + }), + }), + ); + app.get( + '/items/:id', + createPageGetHandler({ + ...common, + componentId: 'item', + load: async () => ({ loader: (c) => c.notFound() }), + renderOptions: { boundaries: { notFound: 'item-not-found', errors: [] } }, + }), + ); + const response = await app.request( + 'https://app.test/items/missing', + { + headers: pages + ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION } + : {}, + }, + { + ASSETS: { + fetch: async () => { + assetReads++; + return Response.json({ static: 'item' }); + }, + }, + }, + ); + expect(response.status).toBe(404); + expect(assetReads).toBe(0); + const body = await response.text(); + if (pages) { + expect(deserializePageData(body)).toMatchObject({ component: 'root-not-found' }); + } else { + expect(body).toContain('

root-not-found

'); + } + }, + ); + + it('keeps a static file at the same path out of a loader not-found', async () => { + const fetched: Array = []; + const rendered: Array = []; + const app = new Hono(); + app.notFound( + createPagesFallback({ + routing: createRoutingRuntime(app, { nodeTarget: true }), + errors: createErrorRenderer({ projectRoot: '/project', homeDir: '/home' }), + }), + ); + app.get( + '/docs/:name', + createPageGetHandler({ + componentId: 'docs/name', + load: async () => ({ loader: (c) => c.notFound() }), + render: async (page) => { + rendered.push(JSON.stringify(page.props)); + return '
docs page
'; + }, + assets: async () => ({ css: '', body: '', preloads: '' }), + headConfig: null, + renderOptions: { boundaries: { errors: [] } }, + }), + ); + const assets = { + fetch: async (request: Request): Promise => { + const path = new URL(request.url).pathname; + fetched.push(path); + return path === '/docs/readme.json' + ? new Response('{"static":"docs"}', { + headers: { 'Content-Type': 'application/json' }, + }) + : new Response('Not Found', { status: 404 }); + }, + }; + const response = await app.request('https://app.test/docs/readme.json', {}, { ASSETS: assets }); + expect(response.status).toBe(404); + // The loader's `c.notFound()` decides the response, never the asset's bytes. + expect(fetched).not.toContain('/docs/readme.json'); + expect(rendered).toEqual([]); + expect(await response.text()).not.toContain('static'); + }); }); describe('boundary recovery failures', () => {