diff --git a/docs/guide/edge/static-assets.md b/docs/guide/edge/static-assets.md index 612471c96..5fa600843 100644 --- a/docs/guide/edge/static-assets.md +++ b/docs/guide/edge/static-assets.md @@ -118,11 +118,24 @@ The SPA fallback is right for a single-page app, where deep links must boot the Accepted values are `"single-page-application"`, `"404-page"`, and `"none"`. `run_worker_first` keeps its inferred value, so API routes, auth, and `/__void/*` still reach the worker first. Setting anything other than `"single-page-application"` also turns off the worker-side `index.html` fallback described above — otherwise it would answer the request before `not_found_handling` was ever consulted. With `"404-page"` the worker serves whatever the asset binding returns for the unmatched path, which is Cloudflare's nearest `404.html` — but only for HTML navigations (requests whose `Accept` includes `text/html`), so an API route that deliberately returns a 404 keeps its own body, status and headers. If the build has no `404.html`, the worker's own 404 is kept. -The last row is the exception: `routing.notFound` is **ignored** for SvelteKit, Nuxt, Analog, and Astro deploys, and `void deploy` warns when you set it. Those deploys emit no `run_worker_first`, so the asset layer already answers first and real prerendered files win — `not_found_handling` would only change what the framework's own `env.ASSETS.fetch()` delegation returns, where `"single-page-application"` turns genuine 404s into the prerendered home page at 200 and `"404-page"` takes the 404 away from the framework's own error route. TanStack Start and React Router deploys are not affected; they follow the rows above. +The last row is the exception: `routing.notFound` is **ignored** for SvelteKit, Nuxt, Analog, and Astro deploys, and `void deploy` warns when you set it. Those deploys emit no `run_worker_first`, so the asset layer already answers first and real prerendered files win — `not_found_handling` would only change what the framework's own `env.ASSETS.fetch()` delegation returns, where `"single-page-application"` turns genuine 404s into the prerendered home page at 200 and `"404-page"` takes the 404 away from the framework's own error route. + +TanStack Start, React Router, and vinext follow the rows above on a managed `void deploy` — that path resolves the asset config itself and applies it to the uploaded worker. Void writes no `assets` policy into their generated worker wrangler config: + +| Framework | Generated worker config | +| -------------- | ---------------------------- | +| TanStack Start | `dist/server/wrangler.json` | +| React Router | `build/server/wrangler.json` | +| vinext (App) | `dist/server/wrangler.json` | +| vinext (Pages) | `dist/ssr/wrangler.json` | + +So on a self-hosted `wrangler deploy` the setting takes effect only if that config declares a complete `assets` policy of its own — `binding`, `directory`, `not_found_handling`, and `run_worker_first`. Void leaves those fields alone, so a policy you write yourself is honored by the generated wrapper; with no policy at all, Cloudflare's default applies. `vite build` warns when `routing.notFound` is set so the choice is not silent. ### Generated config -Void owns the generated asset routing policy during dev and build. If a root `wrangler.jsonc` contains stale `not_found_handling` or `run_worker_first` values, Void replaces those fields so generated config cannot accidentally change which layer sees a request first. +Void owns the generated asset routing policy during dev and build for Void apps. If a root `wrangler.jsonc` contains stale `not_found_handling` or `run_worker_first` values, Void replaces those fields so generated config cannot accidentally change which layer sees a request first. + +TanStack Start and React Router are the exception: Void generates no asset policy for them and leaves both fields to your own wrangler config. Writing `not_found_handling` alone would make the asset layer answer unmatched requests and the framework worker would never run, and completing the policy needs `assets.binding` and `assets.directory` that the framework owns, not Void. ## API routes and SSR pages diff --git a/docs/reference/config.md b/docs/reference/config.md index d350ef56e..ab4455777 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -396,6 +396,8 @@ Set `"404-page"` when your assets come from a static site generator (VitePress, This does **not** apply to SvelteKit, Nuxt, Analog, or Astro deploys: those pin `not_found_handling` to `"none"` because the framework's own worker owns unmatched HTML, and `void deploy` warns if you set `routing.notFound` anyway. +TanStack Start, React Router, and vinext honor it on a managed `void deploy`, which resolves the asset config itself. Void writes no `assets` policy into their generated worker wrangler config (`dist/server` for TanStack Start and vinext App, `build/server` for React Router, `dist/ssr` for vinext Pages), so on a self-hosted `wrangler deploy` it applies only if that config declares a complete `assets` policy of its own — `binding`, `directory`, `not_found_handling`, and `run_worker_first`. Void leaves those fields untouched, so your own policy is honored; with none, Cloudflare's default applies. `vite build` warns when it is set. See [Static Assets](../guide/edge/static-assets.md#unmatched-requests) for the per-framework paths. + ### `inference` Configuration for build-time inference, including how Void detects your app type, bindings, and build process. diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 64137cf4d..81e939c28 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -490,6 +490,27 @@ function prependLocalBinToPath(env: NodeJS.ProcessEnv, root: string): NodeJS.Pro return env; } +/** + * Marks a build child as driven by a MANAGED `void deploy`. + * + * The platform resolves the asset routing policy out-of-band (`resolveAssetConfig` + * → `manifest.assetConfig`) and applies it to the uploaded script, so settings the + * Vite plugin cannot safely write into the built wrangler config — `routing.notFound` + * for a Class A framework, which needs an `assets` policy Void does not own there — + * are still honored on this path. `void:framework-build-wrapper` warns about exactly + * those when this flag is ABSENT, i.e. on a self-hosted `vite build && wrangler deploy`. + * + * Passed through the CHILD env only (never `process.env`), the same way + * `VOID_DEPLOY_PROJECT_ID` is, so it cannot leak into an unrelated child process or a + * later `void dev` in the same shell. + * + * Deliberately NOT set by `runCloudflareDeploy` (`--backend cloudflare`): that flow + * hands the built output to `wrangler deploy` against the user's own account and IS the + * self-host path the warning is about. (It rejects framework SSR outright today, so no + * Class A build reaches it either way.) + */ +const MANAGED_DEPLOY_BUILD_ENV = { VOID_DEPLOY_BUILD: '1' } as const; + /** * Deploy-time env selectors that pin the WRONG worker/config out from under the * top-level config this flow provisions + preflights. Scrubbed from every child env @@ -5390,7 +5411,7 @@ export async function runStaticDeploy( execSync(preset.buildCommand, { cwd: root, stdio: 'inherit', - env: buildEnv(undefined, { localBinRoot: root }), + env: buildEnv({ ...MANAGED_DEPLOY_BUILD_ENV }, { localBinRoot: root }), }); cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); } else if (skipBuild) { @@ -5564,7 +5585,7 @@ async function runFrameworkDeploy( execSync(voidConfig.inference?.build ?? resolveProjectCommand(root, fwPreset.buildCommand), { cwd: root, stdio: 'inherit', - env: buildEnv(undefined, { localBinRoot: root }), + env: buildEnv({ ...MANAGED_DEPLOY_BUILD_ENV }, { localBinRoot: root }), }); cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); } else { @@ -5908,7 +5929,10 @@ async function runFullDeploy( execSync(buildExec, { cwd: root, stdio: 'inherit', - env: buildEnv({ VOID_DEPLOY_PROJECT_ID: config.projectId }, { localBinRoot: root }), + env: buildEnv( + { VOID_DEPLOY_PROJECT_ID: config.projectId, ...MANAGED_DEPLOY_BUILD_ENV }, + { localBinRoot: root }, + ), }); cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); } catch (err: unknown) { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index c2ae0f217..7f7b708e4 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -266,10 +266,7 @@ function generateClassATriggerWrapper( * Resolved `assetConfig.not_found_handling`. A Class A app deploys through * `runFullDeploy`, which honors `routing.notFound`, so this wrapper's * `serveWithAssets` has to honor it too or the asset binding's 404 page is - * fetched and then thrown away. The reverse also holds — the wrapper's - * `404-page` branch is inert unless the BINDING is set to `404-page`, which - * is why `void:framework-build-wrapper` also writes it into the built - * wrangler config for anyone deploying that output themselves. + * fetched and then thrown away. */ notFound?: NotFoundHandling, ): string { @@ -991,20 +988,9 @@ export function voidPlugin(options?: { // wrangler settings instead of letting the Cloudflare plugin concatenate // them with generated rules. This preserves static-first behavior for // API-only apps while avoiding asset-served HTML bypassing middleware. - // - // Per FIELD, not per object: the default mode always generates both keys, - // but a Class A framework build generates ONLY `not_found_handling` (from - // an explicit `routing.notFound` — Void infers no asset policy for those - // apps). Deleting the whole pair there would silently drop a root - // wrangler `run_worker_first` that Void has no replacement for. - const generatedAssets = workerConfig.assets as Record | undefined; - if (generatedAssets && resolved.assets) { - if (generatedAssets.not_found_handling !== undefined) { - delete (resolved.assets as Record).not_found_handling; - } - if (generatedAssets.run_worker_first !== undefined) { - delete (resolved.assets as Record).run_worker_first; - } + if (workerConfig.assets && resolved.assets) { + delete (resolved.assets as Record).not_found_handling; + delete (resolved.assets as Record).run_worker_first; } // D1 — auth requires the app DB only for sqlite apps @@ -1519,40 +1505,48 @@ export function voidPlugin(options?: { devTriggerToken, config.routing?.notFound, ); + // `routing.notFound` only reaches a Class A worker through the DEPLOYED + // script's `assets` config, and Void writes none for these frameworks: the + // Class A branch returns long before `applyAssetRoutingPolicy`, and writing + // `not_found_handling` on its own is worse than nothing — Cloudflare's asset + // layer would then answer unmatched requests itself and the framework worker + // would never run (only `run_worker_first` sends them to the worker first, + // and Void does not own `assets.binding`/`directory` here to complete that + // policy). Managed `void deploy` supplies the policy out-of-band + // (`runFullDeploy` → `resolveAssetConfig` → `manifest.assetConfig`), so it + // IS honored there. + // + // On a hand-rolled `vite build && wrangler deploy` it is NOT necessarily + // dropped, which is why this says "Void does not generate it" rather than + // "it does nothing": the generated wrapper consumes `routing.notFound` and + // serves through `env.ASSETS`, and `mergeBindings` leaves a Class A root + // wrangler config's `assets` untouched (its gate needs `workerConfig.assets`, + // which is never set here). So a user who declares a COMPLETE policy of their + // own — `binding`, `directory`, `not_found_handling`, `run_worker_first` — + // gets working behavior, and must not be told their config is inert. Warn + // once per build, and only when this build is not a managed deploy + // (`void deploy` sets `VOID_DEPLOY_BUILD` on the build child env). + let notFoundIgnoredWarned = false; const frameworkBuildWrapperPlugin: Plugin = { name: 'void:framework-build-wrapper', - // The wrapper's `404-page` branch only fires when the asset binding - // itself answers with an HTML 404 page, which needs - // `assets.not_found_handling: '404-page'` on the deployed worker. - // Managed `void deploy` supplies that out-of-band (`runFullDeploy` - // resolves `manifest.assetConfig`, which is what the platform applies), - // but the built `dist/ssr/wrangler.json` never carried it: the Class A - // branch returns before `applyAssetRoutingPolicy`. So a `wrangler - // deploy` of the same build read the root wrangler value — normally - // absent, i.e. CF's `none` — and the option was inert. - // - // Write only `not_found_handling`, and only when the user asked for it. - // `run_worker_first`, `binding` and `directory` stay whatever the - // framework/root config says: Void infers no asset policy for Class A - // apps, and `defu` merges our partial over the resolved config. - // - // Build-only, matching the wrapper: the dev wrapper has no - // `serveWithAssets`, and flipping the dev asset router would change - // which layer answers an unmatched navigation in `vite dev`. - config(_userConfig, env) { - const notFound = config.routing?.notFound; - if (env.command !== 'build' || notFound === undefined) { - return; - } - workerConfig.assets = { - ...(workerConfig.assets as Record | undefined), - not_found_handling: notFound, - }; - }, configResolved(resolved) { if (resolved.command !== 'build') { return; } + if ( + config.routing?.notFound !== undefined && + !process.env.VOID_DEPLOY_BUILD && + !notFoundIgnoredWarned + ) { + notFoundIgnoredWarned = true; + voidWarn( + `Void generates no asset routing policy for a ${framework} build, so "routing.notFound" in ` + + 'void.json is not written to the built worker config. On a self-hosted `vite build && ' + + 'wrangler deploy` it takes effect only if your own wrangler config declares a complete ' + + '`assets` policy (`binding`, `directory`, `not_found_handling`, `run_worker_first`); ' + + "otherwise Cloudflare's default applies. Managed `void deploy` supplies the policy for you.", + ); + } generateClassATriggerWrapper( root, framework, diff --git a/packages/void/test/unit/plugin-class-a-wrapper.test.ts b/packages/void/test/unit/plugin-class-a-wrapper.test.ts index 8454d6922..15af453bd 100644 --- a/packages/void/test/unit/plugin-class-a-wrapper.test.ts +++ b/packages/void/test/unit/plugin-class-a-wrapper.test.ts @@ -35,30 +35,6 @@ function createTanStackRoot(voidConfig?: Record): string { return root; } -function callConfig(plugin: Plugin, command: 'build' | 'serve') { - const hook = plugin.config; - const fn = typeof hook === 'function' ? hook : hook?.handler; - if (typeof fn !== 'function') { - throw new Error('config not callable'); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (fn as any)({}, { command, mode: command === 'build' ? 'production' : 'development' }); -} - -/** Run the Cloudflare plugin's `config` customizer the way the real plugin does. */ -function mergeWorkerConfig( - plugins: Array, - resolved: Record = {}, -): Record { - const cloudflarePlugin = plugins.find((plugin) => plugin.name === 'mock:cloudflare'); - if (!cloudflarePlugin) { - throw new Error('Expected mocked Cloudflare plugin.'); - } - const pluginConfig = (cloudflarePlugin.api as { pluginConfig: MockCloudflarePluginConfig }) - .pluginConfig; - return pluginConfig.config(resolved); -} - function callConfigResolved(plugin: Plugin, config: Partial) { const hook = plugin.configResolved; const fn = typeof hook === 'function' ? hook : hook?.handler; @@ -132,68 +108,102 @@ describe('Class A framework build wrapper', () => { }); }); -// The wrapper above only has an HTML 404 page to pass through when the asset -// binding itself is set to `404-page`. Managed `void deploy` supplies that via -// `manifest.assetConfig`; the built `dist/ssr/wrangler.json` has to carry it too -// or a `wrangler deploy` of the same build silently ignores `routing.notFound`. -describe('Class A wrangler asset config', () => { - async function loadPlugins(voidConfig?: Record): Promise> { - const root = createTanStackRoot(voidConfig); +// `routing.notFound` reaches a Class A worker only through the DEPLOYED script's +// `assets` config, and Void writes none for these frameworks. Managed +// `void deploy` supplies it out-of-band (`manifest.assetConfig`) and marks the +// build child with `VOID_DEPLOY_BUILD`; every other build is a self-hosted +// `vite build && wrangler deploy`, which has to be told that Void generated +// nothing instead of having the setting dropped silently. +// +// The warning must NOT say the setting does nothing. The generated wrapper +// consumes `routing.notFound` and serves through `env.ASSETS`, and +// `mergeBindings` leaves a Class A root wrangler `assets` block untouched, so a +// user who writes a complete policy themselves has a WORKING config and must +// not be told otherwise. +describe('Class A routing.notFound self-host warning', () => { + /** Run a Class A `build` twice and return every line the plugin logged. */ + async function buildTwiceWithNotFound(): Promise> { + const root = createTanStackRoot({ routing: { notFound: '404-page' } }); vi.spyOn(process, 'cwd').mockReturnValue(root); - const { voidPlugin } = await import('../../src/index.ts'); - return voidPlugin(); - } + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); - function wrapperOf(plugins: Array): Plugin { - const plugin = plugins.find((p) => p.name === 'void:framework-build-wrapper'); - if (!plugin) { + const { voidPlugin } = await import('../../src/index.ts'); + const wrapperPlugin = voidPlugin().find( + (plugin) => plugin.name === 'void:framework-build-wrapper', + ); + if (!wrapperPlugin) { throw new Error('Expected Class A wrapper plugin.'); } - return plugin; - } + const resolved = { + command: 'build', + build: { assetsDir: 'static' } as ResolvedConfig['build'], + } as Partial; + // Twice on purpose: at most one warning per build, however many times the + // hook runs (the Cloudflare plugin resolves config per environment). + callConfigResolved(wrapperPlugin, resolved); + callConfigResolved(wrapperPlugin, resolved); - it('writes routing.notFound into the built worker asset config', async () => { - const plugins = await loadPlugins({ routing: { notFound: '404-page' } }); - callConfig(wrapperOf(plugins), 'build'); + return logSpy.mock.calls.map((args) => args.join(' ')); + } - const merged = mergeWorkerConfig(plugins); - expect(merged.assets).toEqual({ not_found_handling: '404-page' }); - }); + function notFoundWarnings(lines: Array): Array { + return lines.filter((line) => line.includes('"routing.notFound" in void.json')); + } - it('invents no asset policy when routing.notFound is unset', async () => { - const plugins = await loadPlugins(); - callConfig(wrapperOf(plugins), 'build'); + it('warns once that a self-hosted build generates no policy for routing.notFound', async () => { + const warnings = notFoundWarnings(await buildTwiceWithNotFound()); - expect(mergeWorkerConfig(plugins).assets).toBeUndefined(); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('tanstack-start'); + expect(warnings[0]).toContain('vite build && wrangler deploy'); + expect(warnings[0]).toContain('void deploy'); }); - it('leaves the dev asset router alone', async () => { - const plugins = await loadPlugins({ routing: { notFound: '404-page' } }); - callConfig(wrapperOf(plugins), 'serve'); + // Guards the correction from PR review: an earlier draft told every self-host + // build the setting was "inert", which is false for anyone who declares their + // own complete `assets` policy — Void leaves that policy alone and the wrapper + // honors it. + it('does not claim the setting is inert, and names the config that makes it work', async () => { + const [warning] = notFoundWarnings(await buildTwiceWithNotFound()); + + expect(warning).toBeDefined(); + expect(warning).not.toMatch(/\binert\b/); + for (const field of ['binding', 'directory', 'not_found_handling', 'run_worker_first']) { + expect(warning).toContain(field); + } + }); - expect(mergeWorkerConfig(plugins).assets).toBeUndefined(); + it('stays quiet when a managed `void deploy` drives the build', async () => { + const previous = process.env.VOID_DEPLOY_BUILD; + process.env.VOID_DEPLOY_BUILD = '1'; + try { + expect(notFoundWarnings(await buildTwiceWithNotFound())).toEqual([]); + } finally { + if (previous === undefined) { + delete process.env.VOID_DEPLOY_BUILD; + } else { + process.env.VOID_DEPLOY_BUILD = previous; + } + } }); - // Void generates no `run_worker_first` for Class A, so the root wrangler value - // is the only one there is — replacing the pair wholesale would drop it. - it('replaces a stale root not_found_handling but keeps root run_worker_first', async () => { - const plugins = await loadPlugins({ routing: { notFound: '404-page' } }); - callConfig(wrapperOf(plugins), 'build'); + it('says nothing when routing.notFound is unset', async () => { + const root = createTanStackRoot(); + vi.spyOn(process, 'cwd').mockReturnValue(root); + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); - const resolved = { - assets: { - binding: 'ASSETS', - directory: './dist/client', - not_found_handling: 'single-page-application', - run_worker_first: ['/api/*'], - }, - }; - mergeWorkerConfig(plugins, resolved); - - expect(resolved.assets).toEqual({ - binding: 'ASSETS', - directory: './dist/client', - run_worker_first: ['/api/*'], - }); + const { voidPlugin } = await import('../../src/index.ts'); + const wrapperPlugin = voidPlugin().find( + (plugin) => plugin.name === 'void:framework-build-wrapper', + ); + if (!wrapperPlugin) { + throw new Error('Expected Class A wrapper plugin.'); + } + callConfigResolved(wrapperPlugin, { + command: 'build', + build: { assetsDir: 'static' } as ResolvedConfig['build'], + } as Partial); + + expect(notFoundWarnings(logSpy.mock.calls.map((args) => args.join(' ')))).toEqual([]); }); });