diff --git a/docs/guide/app-types.md b/docs/guide/app-types.md index c2d02bd73..35ece5cf7 100644 --- a/docs/guide/app-types.md +++ b/docs/guide/app-types.md @@ -73,6 +73,48 @@ At the edge, the resolution order is: **Deploy:** `void deploy` or `void deploy --dir ` uploads static files directly. Assets are served from the edge with automatic caching. +## Adding a backend to a static site + +A static site generator plus a few API routes is a Void app, not a static site. Auto-detection sees the SSG dependency first (priority 2 below), so if you leave `inference.appType` unset, `void deploy` refuses rather than deploying the site and silently dropping `routes/`. Tell it which you meant. + +To deploy the site **and** the backend, run both builds from one command and let Void's build fold the generated site into its client output: + +```json +// void.json +{ + "inference": { + "appType": "void", + "build": "vitepress build && vite build" + } +} +``` + +```ts +// vite.config.ts +import { defineConfig } from 'vite'; +import { voidPlugin } from 'void'; + +export default defineConfig({ + plugins: [voidPlugin()], + // The SSG's output becomes the static assets of the Void build. + publicDir: '.vitepress/dist', +}); +``` + +`vitepress build` emits the site, then `vite build` copies `publicDir` into `dist/client` and emits the worker into `dist/ssr`. Keep `voidPlugin()` in the **root** `vite.config.ts` only — not in the generator's own config (e.g. `.vitepress/config.ts`). + +Because the worker now owns unmatched requests, add [`routing.notFound`](../reference/config.md#routing-notfound) if you want the generator's `404.html` instead of the SPA-style `index.html` fallback: + +```json +{ "routing": { "notFound": "404-page" } } +``` + +To deploy the static output only and **not** the backend, say so explicitly: + +```json +{ "inference": { "appType": "static" } } +``` + ## Auto-Detection When running `void deploy` and no `inference.appType` is set in `void.json`, the detection logic runs in this order: @@ -81,6 +123,7 @@ When running `void deploy` and no `inference.appType` is set in `void.json`, the | -------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | 1 | `--dir` flag | Static (or SPA with `--spa`) | | 2 | Known SSG in dependencies (`vitepress`, `@docusaurus/core`) | Static, builds with SSG CLI | +| 2a | ...and backend files also exist | Refused — set `inference.appType` yourself | | 3 | `@tanstack/react-start`, `@react-router/dev`, `@sveltejs/kit`, `nuxt`, `@analogjs/platform`, or `astro` in deps | Framework | | 4 | Backend files exist (`routes/`, `pages/`, `middleware/`, `crons/`, `queues/`, SSR entry) | Void app | | 5 | `vite` or `vite-plus` in dependencies, no backend files | SPA, builds with `vite build` or `vp build` | diff --git a/docs/guide/edge/static-assets.md b/docs/guide/edge/static-assets.md index 32a28f5d7..612471c96 100644 --- a/docs/guide/edge/static-assets.md +++ b/docs/guide/edge/static-assets.md @@ -97,6 +97,29 @@ This is the path needed for preview auth and other middleware. Cloudflare's plat For Void apps with only `/api` routes, Void keeps the platform SPA fallback and scopes `run_worker_first` to `/api` and `/api/*`. Static assets and non-API SPA navigations stay on the asset platform. API requests, including browser document navigations such as OAuth callbacks, reach the worker instead of being rewritten to `index.html`. +### Unmatched requests + +`not_found_handling` decides what the asset layer does with a request that matched no asset and no worker route. Void infers it: + +| App shape | Inferred value | Result for an unknown URL | +| ------------------------------------------------- | -------------------------------- | -------------------------------- | +| Pages or SSR | `none` | The worker's own 404 | +| Worker owns HTML, no `pages/`, no SSR entry | `none` + worker fallback | `index.html` with status **200** | +| Asset-first (only `/api` routes, or none) | `single-page-application` | `index.html` with status **200** | +| Framework deploy (SvelteKit, Nuxt, Analog, Astro) | `none` — pinned, not overridable | The framework worker's own 404 | + +The middle row is a worker with `middleware/`, a route outside `/api`, a document websocket, or Live, but no `pages/` and no SSR entry. `run_worker_first: ['/**']` sends everything to the worker, which bypasses the platform's SPA switch, so the generated worker does that fallback itself for HTML navigations — after your middleware has run, so auth gates and OAuth callbacks still see the request first. + +The SPA fallback is right for a single-page app, where deep links must boot the client router. It is wrong for a site whose HTML was generated per page: unknown URLs return 200 instead of 404, and the generator's `404.html` is never served. Nothing in a built asset tree distinguishes the two, so Void does not guess — override it with [`routing.notFound`](../../reference/config.md#routing-notfound): + +```json +{ "routing": { "notFound": "404-page" } } +``` + +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. + ### 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. diff --git a/docs/integrations/frameworks/overview.md b/docs/integrations/frameworks/overview.md index 9f1a08a60..099bdf0be 100644 --- a/docs/integrations/frameworks/overview.md +++ b/docs/integrations/frameworks/overview.md @@ -77,6 +77,7 @@ Most configuration is inferred automatically. Use `void.json` to override defaul | `routing.prerender` | Paths to prerender as static HTML at deploy time | | `routing.revalidate` | Default revalidation TTL in seconds for cached responses | | `inference.bindings` | Override inferred bindings. You only need this if auto-detection is not doing what you want. Accepts `true` or a custom binding name such as `"db": "MY_DB"`. | +| `routing.notFound` | **Ignored.** SvelteKit, Nuxt, Analog, and Astro pin `not_found_handling` to `"none"` — the framework worker owns unmatched HTML. `void deploy` warns if set. | See [Configuration](../../reference/config.md) for the full reference. diff --git a/docs/reference/config.md b/docs/reference/config.md index e198296ff..d350ef56e 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -378,6 +378,24 @@ Paths to prerender as static HTML at deploy time. Each path must start with `/`. } ``` +#### `routing.notFound` + +Override how the asset layer answers a request that matched no asset and no worker route. One of `"single-page-application"`, `"404-page"`, or `"none"`. If omitted, Void infers it — see [Static Assets](../guide/edge/static-assets.md#unmatched-requests). + +```json +{ + "routing": { + "notFound": "404-page" + } +} +``` + +Set `"404-page"` when your assets come from a static site generator (VitePress, Docusaurus, …) and you want unknown URLs to serve the generator's own `404.html` with a real HTTP 404. Without it, an app whose only backend is API routes keeps the inferred SPA fallback, so every unknown URL returns `index.html` with a `200` — correct for a single-page app, wrong for a generated site, and bad for crawlers. + +`run_worker_first` is untouched, so API routes, auth, and `/__void/*` still reach the worker first. When the worker owns HTML routing it also serves the resolved behavior itself, since `run_worker_first: ["/**"]` means the platform switch never runs — see [Unmatched requests](../guide/edge/static-assets.md#unmatched-requests). + +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. + ### `inference` Configuration for build-time inference, including how Void detects your app type, bindings, and build process. @@ -403,12 +421,20 @@ Custom names are used in the deploy manifest, Wrangler config generation/sync, r #### `inference.build` -Override the build command. Useful for frameworks with their own CLIs (Nuxt, Astro) or static apps with custom build scripts. If omitted, the CLI uses the detected default build command for the current app type. +Override the build command. Useful for frameworks with their own CLIs (Nuxt, Astro) or static apps with custom build scripts. If omitted, the CLI uses the detected default build command for the current app type. It applies to every app type, including `"void"` (where the default is `vite build`). ```json { "inference": { "build": "nuxt build --preset cloudflare-module" } } ``` +The command is run through a shell from the project root, with the project's own `node_modules/.bin` on `PATH`, so bare binaries and `&&` chains work: + +```json +{ "inference": { "build": "vitepress build && vite build" } } +``` + +That chain is how a static site generator and a Void backend ship together — see [Adding a backend to a static site](../guide/app-types.md#adding-a-backend-to-a-static-site). + #### `inference.scanDirs` Override which directories are scanned for [binding inference](./resource-inference.md). Paths are relative to the project root. Replaces the default directories for the current mode. diff --git a/packages/void/schema.json b/packages/void/schema.json index 706f62098..60dd139ab 100644 --- a/packages/void/schema.json +++ b/packages/void/schema.json @@ -144,6 +144,11 @@ "type": "object", "description": "Routing configuration — headers, redirects, rewrites, fallbacks, revalidation, prerendering.", "properties": { + "notFound": { + "type": "string", + "enum": ["single-page-application", "404-page", "none"], + "description": "Override how the asset layer answers a request that matched no asset and no worker route. Void infers \"single-page-application\" when the worker does not own HTML routing; set \"404-page\" for a static-site-generator build so unknown URLs serve 404.html with a real HTTP 404 instead of index.html with a 200. Does not change run_worker_first. Ignored for SvelteKit, Nuxt, Analog, and Astro deploys, which pin not_found_handling to \"none\" because the framework's own worker owns unmatched HTML." + }, "revalidate": { "description": "Edge caching TTL in seconds. A number sets a global TTL for all SSR pages. An object maps URL patterns to TTLs (first match wins). Set to 0 to disable caching for a path.", "oneOf": [ diff --git a/packages/void/src/asset-routing.ts b/packages/void/src/asset-routing.ts index 1078c6dfa..3cfef7323 100644 --- a/packages/void/src/asset-routing.ts +++ b/packages/void/src/asset-routing.ts @@ -1,4 +1,5 @@ import type { AssetConfig } from './cli/types.ts'; +import type { NotFoundHandling } from './config.ts'; import type { RouteDefinition } from './router/parse-filename.ts'; export type AssetRoutingInputs = { @@ -11,6 +12,13 @@ export type AssetRoutingInputs = { hasWebSockets?: boolean; authEnabled?: boolean; liveEnabled?: boolean; + /** + * `routing.notFound` from void.json. Overrides the INFERRED + * `not_found_handling`. `run_worker_first`, `workerFirst` and + * `apiWorkerFirst` are untouched, so which layer sees a request first never + * changes. `workerSpaFallback` DOES follow it — see below. + */ + notFound?: NotFoundHandling; }; export type AssetRoutingPolicy = { @@ -76,10 +84,35 @@ export function resolveAssetRoutingPolicy(inputs: AssetRoutingInputs): AssetRout not_found_handling: 'single-page-application', run_worker_first: [...VOID_INTERNAL_WORKER_FIRST], }; + // Explicit `routing.notFound` wins over the inferred value. Applied here (on + // the inputs) rather than at the call sites so dev, build, and deploy can't + // drift apart. `run_worker_first` is deliberately left as inferred. + if (inputs.notFound !== undefined) { + assetConfig.not_found_handling = inputs.notFound; + } return { assetConfig, apiWorkerFirst, workerFirst, - workerSpaFallback: workerFirst && !inputs.isSsr && !inputs.hasPages, + // The worker-side SPA fallback exists to REPLACE the SPA behavior the + // INFERRED config gives up on this shape: `workerFirst` infers + // `not_found_handling: 'none'`, so `env.ASSETS.fetch()` hands back a bare + // 404 for an unmatched navigation and the worker has to hardcode + // `/index.html` at status 200 itself. + // + // `run_worker_first: ['/**']` is NOT what disables the platform switch — it + // only decides who sees the request FIRST. It skips the pre-worker asset + // layer, but `not_found_handling` still applies inside `env.ASSETS.fetch()`. + // + // So an explicit `notFound` that asks for anything else must turn the + // fallback off, or the generated helper answers the unmatched navigation + // with the shell before `not_found_handling` is ever consulted and the + // override is inert. `single-page-application` keeps it (that is what it + // asks for); `undefined` keeps the inferred behavior. + workerSpaFallback: + workerFirst && + !inputs.isSsr && + !inputs.hasPages && + (inputs.notFound === undefined || inputs.notFound === 'single-page-application'), }; } diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 576d331ae..64137cf4d 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -28,6 +28,7 @@ import { readConfig, resolveBindingNames, type DatabaseDialect, + type NotFoundHandling, type RoutingConfig, type VoidConfig, getDatabaseDialect, @@ -445,11 +446,47 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi * `cfAccessHeaders(process.env)` / the cloudflared pair-guard AFTER the build * step. Only the service-token pair is scrubbed; the cloudflared * `CF_ACCESS_TOKEN` JWT (dev path) is left untouched. + * + * `localBinRoot` is an explicit OPT-IN, not a default. Build commands are run + * through a shell (`execSync`) and a user-configured `inference.build` (e.g. + * `vitepress build && vite build`) names bare binaries that only exist in the + * project's own `node_modules/.bin`; under the build container's + * `npx --yes void deploy` that happens to work — npx prepends every ancestor + * `.bin` itself — but a directly invoked `node_modules/.bin/void deploy` or a + * globally installed `void` inherits no such PATH and the bare binary fails to + * resolve. Passing it makes the project's bin dir shadow the system one for + * that child, so it belongs ONLY on the three build execs. The other callers + * (`getGitCommit`, the drizzle-kit spawn) exec a system binary or an absolute + * path and must not hand a dependency-shipped `node_modules/.bin/git` a child + * process holding `VOID_TOKEN`. */ -export function buildEnv(extra?: Record): NodeJS.ProcessEnv { +export function buildEnv( + extra?: Record, + options?: { localBinRoot?: string }, +): NodeJS.ProcessEnv { const env = { ...process.env, ...extra }; delete env.CF_ACCESS_CLIENT_ID; delete env.CF_ACCESS_CLIENT_SECRET; + return options?.localBinRoot === undefined + ? env + : prependLocalBinToPath(env, options.localBinRoot); +} + +/** + * Prepend `/node_modules/.bin` to the child env's PATH, preserving + * whatever was already there. + * + * PATH is looked up case-insensitively and written back under the SAME key the + * env already used: Windows reports it as `Path`, and `{ ...process.env }` + * drops the case-insensitive lookup that `process.env` itself provides, so + * hardcoding `PATH` would leave the real variable untouched and add a dead one. + */ +function prependLocalBinToPath(env: NodeJS.ProcessEnv, root: string): NodeJS.ProcessEnv { + const binDir = join(root, 'node_modules', '.bin'); + const delimiter = process.platform === 'win32' ? ';' : ':'; + const pathKey = Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'PATH'; + const existing = env[pathKey]; + env[pathKey] = existing ? `${binDir}${delimiter}${existing}` : binDir; return env; } @@ -4693,6 +4730,10 @@ async function runDeployInner( const gitMetadata = collectGitDeployMetadata( root, options?.skipBuild ? null : getGitCommit(root), + process.env, + // Same scrub as `getGitCommit` right above: these git children can + // reach repo-configured hooks/credential helpers. + buildEnv(), ); const fwPreset = FRAMEWORK_PRESETS[detected.name]; if (detected.class === 'b' || detected.class === 'c') { @@ -4717,6 +4758,7 @@ async function runDeployInner( root, config, client, + voidConfig, fwPreset, options?.skipBuild, gitMetadata, @@ -4728,7 +4770,13 @@ async function runDeployInner( } if (!preset && !voidConfig.inference?.appType) { // No configured app type and no detected framework — detect from project structure. - preset = detectPreset(root, { spa: options?.spa }); + // `strictBackend` only here: this is the branch where the user has said + // NOTHING about the app type, so an SSG project that also has a backend is + // genuinely ambiguous and must be refused rather than silently deployed as + // static. The explicit-intent paths (`--dir`, configured + // `inference.appType`) resolve through `resolveStaticDeployPreset` above + // and keep working without the guard. + preset = detectPreset(root, { spa: options?.spa, strictBackend: true }); } // appType === "void" or "framework" without a detected framework → full deploy. @@ -4736,6 +4784,8 @@ async function runDeployInner( const gitMetadata = collectGitDeployMetadata( root, options?.skipBuild ? null : getGitCommit(root), + process.env, + buildEnv(), ); if (preset) { @@ -4766,6 +4816,7 @@ async function runDeployInner( root, config, client, + voidConfig, undefined, options?.skipBuild, gitMetadata, @@ -4836,6 +4887,70 @@ export function resolveStaticBuildCommand( return buildOverride ?? preset.buildCommand; } +/** + * Resolve the build command for a FULL (Class A / Void app) deploy. + * + * `inference.build` wins when set, matching `runFrameworkDeploy` and the static + * path's `resolveStaticBuildCommand`. Without it the full path was the only + * deploy mode that ignored the config and hardcoded `vite build`, so an app that + * needs more than one build step — an SSG that emits the site, then Void's build + * packaging it via `publicDir` alongside the worker — had no way to express it + * and died on the missing `index.html` entry. + * + * The two returned strings are deliberately different for the FALLBACK: `label` + * goes to the user (`formatProjectCommand` rewrites `vite` → `vp` without + * expanding an absolute bin path), `command` is what actually runs + * (`resolveProjectCommand` expands to the local bin). A configured command is + * the user's own text and is used verbatim for both, so what is printed is + * exactly what is executed. + */ +export function resolveFullDeployBuildCommand( + root: string, + buildOverride?: string, +): { label: string; command: string } { + if (buildOverride) { + return { label: buildOverride, command: buildOverride }; + } + return { + label: formatProjectCommand(root, 'vite build'), + command: resolveProjectCommand(root, 'vite build'), + }; +} + +export type PrerenderSourceInputs = { + /** `pages/` exists — file-based pages contribute static + `getPrerenderPaths()` paths. */ + hasPages: boolean; + /** A custom SSR entry exists — it may export a top-level `getPrerenderPaths()`. */ + hasSsrEntry: boolean; + /** `routing.prerender` from void.json — compiled in as explicit paths. */ + explicitPrerenderPaths: ReadonlyArray | undefined; +}; + +/** + * Whether the built worker's `__voidCollectPrerenderPaths` can return anything + * at all. When it cannot, booting it is pure cost and the deploy skips it. + * + * These three are exactly — and only — the sources `compilePrerenderCollector` + * (`router/compile.ts`) emits a `paths.push(...)` for: + * 1. `scan.pages.pages` — static patterns + dynamic pages' `getPrerenderPaths()` + * 2. the custom SSR entry's top-level `getPrerenderPaths()` (`ssr` argument) + * 3. `options.explicitPrerenderPaths` — void.json `routing.prerender` + * With none of them present the collector is a generated function whose body + * returns `[...new Set([])]`, so skipping is result-identical. + * + * Skipping matters beyond speed. `collectPrerenderPaths` boots the worker in + * Miniflare with bindings from `wranglerVars + loadEnv('production', root, '')` + * only, and the generated fetch handler validates the `env.ts` schema at boot. + * An app whose secrets live on the platform (never in a committed `.env`) gets + * an HTTP 500 there and the deploy dies — for an app that had nothing to + * prerender in the first place. The only workaround was moving the secret into + * `.env.production`, which `loadDeployEnv` then publishes as a plaintext + * manifest var. So this guard also removes a real incentive to leak secrets. + */ +export function hasPrerenderSources(inputs: PrerenderSourceInputs): boolean { + return inputs.hasPages || inputs.hasSsrEntry || (inputs.explicitPrerenderPaths?.length ?? 0) > 0; +} + export function resolveStaticDeployPreset( root: string, voidConfig: VoidConfig, @@ -5255,6 +5370,13 @@ export async function runStaticDeploy( fallbackRules?: Array, routing?: RoutingConfig, cliLog?: CliLogger, + /** + * Explicit `routing.notFound`. Normally carried by `routing`, but the + * "all pages prerendered -> static" redirect in `runFullDeploy` passes + * `routing: undefined` (its rules were already merged upstream), so that + * call site hands the value over directly. Wins over `routing.notFound`. + */ + notFound?: NotFoundHandling, ): Promise { const typeLabel = preset.appType === 'spa' ? 'Static SPA' : 'Static Site'; log.info(`${typeLabel} deploy`); @@ -5265,7 +5387,11 @@ export async function runStaticDeploy( log.step('Building...'); cliLog?.info('build_start', { command: preset.buildCommand }); const buildStartedAt = Date.now(); - execSync(preset.buildCommand, { cwd: root, stdio: 'inherit', env: buildEnv() }); + execSync(preset.buildCommand, { + cwd: root, + stdio: 'inherit', + env: buildEnv(undefined, { localBinRoot: root }), + }); cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); } else if (skipBuild) { cliLog?.info('build_skipped', { reason: 'skipBuild' }); @@ -5321,6 +5447,7 @@ export async function runStaticDeploy( headerRules, redirectRules, fallbackRules, + notFound: notFound ?? routing?.notFound, }); cliLog?.info('package_end', { mode: 'static', @@ -5379,6 +5506,36 @@ export function warnRedundantForceOn3xx(count: number): void { ); } +/** + * Class B/C framework deploys pin `not_found_handling: 'none'`, so + * `routing.notFound` does nothing there — say so instead of dropping it + * silently. + * + * These presets emit no `run_worker_first`, so Cloudflare's default applies and + * the asset layer answers before the framework worker: real prerendered files + * already win. `not_found_handling` only governs what the framework's own + * `env.ASSETS.fetch()` delegation returns, which is framework-internal + * plumbing. Honoring the override there would be a behavior change, not a fix — + * `single-page-application` makes an unmatched delegation return + * `dist/client/index.html` at **200** (Astro/SvelteKit hybrid builds commonly + * prerender the root, so real 404s silently become the home page), and + * `404-page` steals the 404 from the framework's own error route. + * + * Silenced when unset. + */ +export function warnIgnoredNotFoundForFramework( + notFound: NotFoundHandling | undefined, + frameworkName: string, +): void { + if (notFound === undefined) { + return; + } + log.warn( + `"routing.notFound" in void.json is ignored for ${frameworkName} deploys ` + + `(not_found_handling is pinned to "none" — the framework's own worker owns unmatched HTML).`, + ); +} + /** * Class B/C framework deploy: build with framework CLI, package with preset output paths. */ @@ -5407,7 +5564,7 @@ async function runFrameworkDeploy( execSync(voidConfig.inference?.build ?? resolveProjectCommand(root, fwPreset.buildCommand), { cwd: root, stdio: 'inherit', - env: buildEnv(), + env: buildEnv(undefined, { localBinRoot: root }), }); cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); } else { @@ -5432,6 +5589,11 @@ async function runFrameworkDeploy( }); warnRedundantForceOn3xx(redundantForceOn3xx); + // `assetConfig` below is pinned to `not_found_handling: 'none'` on this path, + // so `routing.notFound` is inert. Warned here (outside the packaging spinner) + // rather than at the pin itself. + warnIgnoredNotFoundForFramework(voidConfig.routing?.notFound, detected.name); + // Lint each phase independently: duplicates across phases (redirects vs // fallbacks) don't shadow each other, only duplicates within a phase do. lintDuplicateSources(redirectRules, 'redirects/rewrites (pre-asset)'); @@ -5639,6 +5801,9 @@ async function runFrameworkDeploy( revalidate, revalidateQueryAllowlist: voidConfig.routing?.revalidateQueryAllowlist, prerender, + // Pinned, NOT threaded from `routing.notFound` — see + // `warnIgnoredNotFoundForFramework` for why the override must not apply to + // Class B/C. The warning above tells the user when they set it anyway. assetConfig: { not_found_handling: 'none' }, vars: envVars, packageOptions, @@ -5708,6 +5873,14 @@ async function runFullDeploy( root: string, config: ProjectConfig, client: PlatformClient, + /** + * The already-read `void.json`, threaded from `runDeploy` the same way + * `runFrameworkDeploy` receives it. The build step reads + * `inference.build` from it, so it must be available BEFORE the build — + * this used to be read further down as `deployConfig`, after the build had + * already run with a hardcoded command. + */ + voidConfig: VoidConfig, fwPreset?: FrameworkPreset, skipBuild?: boolean, gitMetadata?: GitDeployMetadata, @@ -5721,7 +5894,10 @@ async function runFullDeploy( // 3. Build (child process to avoid Vite API side effects on bundle output) if (!skipBuild) { - const buildCmd = formatProjectCommand(root, 'vite build'); + const { label: buildCmd, command: buildExec } = resolveFullDeployBuildCommand( + root, + voidConfig.inference?.build, + ); log.step(`Building (${buildCmd})...`); cliLog?.info('build_start', { command: buildCmd }); const buildStartedAt = Date.now(); @@ -5729,10 +5905,10 @@ async function runFullDeploy( // Pass VOID_DEPLOY_PROJECT_ID so plugin-prerender (running inside this // child vite build) can resolve the Void projectId without relying on // .void/project.json, which may be stale or absent under `--project `. - execSync(resolveProjectCommand(root, 'vite build'), { + execSync(buildExec, { cwd: root, stdio: 'inherit', - env: buildEnv({ VOID_DEPLOY_PROJECT_ID: config.projectId }), + env: buildEnv({ VOID_DEPLOY_PROJECT_ID: config.projectId }, { localBinRoot: root }), }); cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); } catch (err: unknown) { @@ -5772,7 +5948,7 @@ async function runFullDeploy( const isFrameworkMode = detected != null; // 6. Infer bindings (expanded scan dirs in framework mode, or custom from config) - const deployConfig = readConfig(root); + const deployConfig = voidConfig; const paths = resolveProjectPaths(root, deployConfig); const dialect = getDatabaseDialect(deployConfig); const deployScanDirs = @@ -5922,9 +6098,12 @@ async function runFullDeploy( const hasDocumentRoutes = routeScanHasDocumentRoutes(routeScan.routes); const hasMiddleware = routeScan.middleware.length > 0; const hasWebSockets = webSockets.length > 0; + // Kept lazy behind `isFrameworkMode` exactly as the inline call was: a Class-A + // framework app has no Void SSR entry to validate. + const ssrEntry = isFrameworkMode ? null : validateSsrEntry(root, paths); const isSsr = isFrameworkMode ? true - : Boolean(validateSsrEntry(root, paths)) || (hasPages && deployConfig.output !== 'static'); + : Boolean(ssrEntry) || (hasPages && deployConfig.output !== 'static'); // Resolve revalidate config from void.json + per-page .server.ts exports. // The page scan is also reused by the fully-static optimization below. @@ -5962,20 +6141,31 @@ async function runFullDeploy( headerRules, redirectRules, fallbackRules, + // Rules were already merged above — pass only the notFound override. undefined, cliLog, + deployConfig.routing?.notFound, ); } } - // Resolve prerender paths. Skip in two cases: + // Resolve prerender paths. Skip in three cases: // - output: "static" — pages are already built as static assets. // - framework mode (Class A) — the framework's own worker entry has no // /__void/prerender-paths endpoint (only compileWorkerEntry / // compileNodeApp emit it for Void apps). Class-A frameworks handle // prerendering through their own build pipelines. + // - the app has no prerender source at all (no `pages/`, no SSR entry, no + // `routing.prerender`) — the collector provably returns `[]`, so booting + // the worker in Miniflare can only fail, never contribute. See + // `hasPrerenderSources` for why that failure mode matters. + const prerenderSourcesPresent = hasPrerenderSources({ + hasPages, + hasSsrEntry: ssrEntry !== null, + explicitPrerenderPaths: deployConfig.routing?.prerender, + }); const uniquePrerenderPaths = - deployConfig.output === 'static' || isFrameworkMode + deployConfig.output === 'static' || isFrameworkMode || !prerenderSourcesPresent ? [] : isNodeTarget(deployConfig.target) ? await collectPrerenderPathsNode({ @@ -6033,6 +6223,7 @@ async function runFullDeploy( hasWebSockets: routeScanHasDocumentRoutes(webSockets), authEnabled, liveEnabled: liveConfig !== undefined, + notFound: deployConfig.routing?.notFound, }); // Preflight: hash assets and check which ones changed. diff --git a/packages/void/src/cli/git-metadata.ts b/packages/void/src/cli/git-metadata.ts index c1af62499..488f4cce2 100644 --- a/packages/void/src/cli/git-metadata.ts +++ b/packages/void/src/cli/git-metadata.ts @@ -7,12 +7,13 @@ export type GitDeployMetadata = { repositoryUrl: string | null; }; -function git(root: string, args: Array): string | null { +function git(root: string, args: Array, env?: NodeJS.ProcessEnv): string | null { try { return execFileSync('git', args, { cwd: root, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], + env, }).trim(); } catch { return null; @@ -101,11 +102,25 @@ export function collectGitDeployMetadata( root: string, commit: string | null, env: NodeJS.ProcessEnv = process.env, + /** + * Env handed to the `git` CHILDREN. Separate from `env` (which is only READ, + * for the `GITHUB_*` CI vars) because the two are not interchangeable: a + * caller may pass a synthetic `env` to describe CI, and that must not become + * the child's whole environment. + * + * `void deploy` passes its scrubbed `buildEnv()` here. `git remote get-url` / + * `git rev-parse` can invoke repo-configured hooks and credential helpers, so + * the CF Access service-token pair must stay out of them — exactly what + * `getGitCommit` does for its own git children right beside this call. + * Defaults to `process.env`, which is what these children inherited before. + */ + childEnv: NodeJS.ProcessEnv = process.env, ): GitDeployMetadata { const repositoryUrl = getGitHubRepositoryUrl(env) ?? - normalizeGitRemoteUrl(git(root, ['remote', 'get-url', 'origin'])); - const gitRef = getGitRefFromEnv(env) ?? git(root, ['rev-parse', '--abbrev-ref', 'HEAD']); + normalizeGitRemoteUrl(git(root, ['remote', 'get-url', 'origin'], childEnv)); + const gitRef = + getGitRefFromEnv(env) ?? git(root, ['rev-parse', '--abbrev-ref', 'HEAD'], childEnv); return { commit, diff --git a/packages/void/src/cli/package.ts b/packages/void/src/cli/package.ts index 003a8cab4..01570cab9 100644 --- a/packages/void/src/cli/package.ts +++ b/packages/void/src/cli/package.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { hash as blake3hash } from 'blake3-jit'; import ignore from 'ignore'; import { extname, join, relative } from 'pathslash'; +import type { NotFoundHandling } from '../config.ts'; import type { InferredBindings } from '../inference/walk.ts'; import { buildMigrationPlanBundle } from '../migrations/plan.ts'; import type { MigrationFile } from '../migrations/validate.ts'; @@ -76,19 +77,36 @@ function stripDevOnlyRuleFields( * * When the user has no fallbacks configured, the platform-level SPA switch * is left intact (zero worker-side overhead for the common case). + * + * `notFound` is the explicit `routing.notFound` from void.json. It overrides + * the value this function would otherwise infer from `appType`, mirroring + * `resolveAssetRoutingPolicy` on the worker-with-assets path. It is resolved + * *before* the SPA branch, not patched onto the result afterwards: an override + * away from `single-page-application` must also skip the synthetic + * `/* -> /index.html` rule below, otherwise the SPA shell would still be + * served — just through a fallback rule instead of the platform switch — and + * the override would be a no-op. This matters because `detectPreset` + * classifies any Vite project without backend files as `spa`, so a plain Vite + * MPA lands on `appType: 'spa'` and `routing.notFound: '404-page'` is its only + * escape hatch. */ export function resolveSpaFallbackChain( appType: 'spa' | 'static' | undefined, fallbackRules: Array | undefined, + notFound?: NotFoundHandling, ): { assetConfig: AssetConfig; fallbackRules: Array | undefined; } { const userRules = fallbackRules && fallbackRules.length > 0 ? fallbackRules : undefined; - if (appType !== 'spa') { + const handling: NotFoundHandling = + notFound ?? + (appType === 'spa' ? 'single-page-application' : appType === 'static' ? '404-page' : 'none'); + + if (handling !== 'single-page-application') { return { - assetConfig: { not_found_handling: appType === 'static' ? '404-page' : 'none' }, + assetConfig: { not_found_handling: handling }, fallbackRules: userRules, }; } @@ -454,12 +472,16 @@ function toLiveManifest(live?: LiveBindingConfig): import('./types.ts').LiveMani } /** - * If the user configured `routing.fallbacks` on a non-SPA app, the platform - * still applies the rules but no `/* -> /index.html` SPA shell is synthesised - * — unmatched paths fall through to the platform 404. Returns the warning + * If the user configured `routing.fallbacks` on an app whose resolved + * `not_found_handling` is not `single-page-application`, the platform still + * applies the rules but no `/* -> /index.html` SPA shell is synthesised — + * unmatched paths fall through to the platform 404. Returns the warning * message string when that mismatch is detected, or `null` otherwise. Pure * function; callers decide whether/how to surface the message (CLI progress, * `console.warn`, etc.). + * + * The message names `not_found_handling` rather than the app type because an + * explicit `routing.notFound` can land here too — the app may well be a SPA. */ export function detectNonSpaFallbackWarning( assetConfig: AssetConfig | undefined, @@ -472,7 +494,8 @@ export function detectNonSpaFallbackWarning( return null; } return ( - `routing.fallbacks is set but appType is not "spa"; fallbacks will be applied, ` + + `routing.fallbacks is set but not_found_handling is not "single-page-application"; ` + + `fallbacks will be applied, ` + `but no "/* -> /index.html" SPA shell fallback is synthesised — unmatched paths fall through to the platform 404.` ); } @@ -717,11 +740,14 @@ export function buildStaticManifest(opts: { headerRules?: Array; redirectRules?: Array; fallbackRules?: Array; + /** Explicit `routing.notFound` — overrides the appType-inferred handling. */ + notFound?: NotFoundHandling; }): DeployManifest { - const { appType, hashedAssetsPrefix, headerRules, redirectRules, fallbackRules } = opts; + const { appType, hashedAssetsPrefix, headerRules, redirectRules, fallbackRules, notFound } = opts; const { assetConfig, fallbackRules: resolvedFallbackRules } = resolveSpaFallbackChain( appType, fallbackRules, + notFound, ); const manifest: DeployManifest = { diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index 655491cbb..6ce32a75e 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -1,14 +1,14 @@ import { existsSync, readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; -import { dirname, join, resolve } from 'pathslash'; +import { dirname, join, relative, resolve } from 'pathslash'; import { readProjectPaths } from '../project-paths.ts'; import { getPackageDependencies, hasPackageDependency, readPackageJson, } from '../shared/package-json.ts'; -import { hasSsrEntry } from '../ssr/entry.ts'; +import { getSsrServerEntryPath, hasSsrEntry } from '../ssr/entry.ts'; /** Build output conventions for a known SSG (static site generator). */ export type SsgPreset = { @@ -362,10 +362,19 @@ export function formatProjectCommand(root: string, command: string): string { /** * Detect a static deploy preset based on the project root. * Returns null when the project requires a full worker deploy. + * + * `strictBackend` refuses (throws) instead of returning an SSG preset when the + * project ALSO has backend sources. SSG detection (step 2) deliberately runs + * before the backend check (step 3), so without this an SSG repo that grew a + * single `routes/api/*.ts` would deploy as a pure static site with the backend + * silently dropped and no diagnostic. Opt-in because only the UNCONFIGURED + * auto-detect path is ambiguous: `--dir` and a configured + * `inference.appType: "static" | "spa"` are the user stating what they want, and + * must keep working silently. */ export function detectPreset( root: string, - options?: { dir?: string; spa?: boolean }, + options?: { dir?: string; spa?: boolean; strictBackend?: boolean }, ): StaticPreset | null { // 1. Explicit --dir flag: skip build, use provided directory if (options?.dir) { @@ -382,6 +391,12 @@ export function detectPreset( const allDeps = getPackageDependencies(pkg); for (const preset of Object.values(SSG_PRESETS)) { if (preset.dep in allDeps) { + if (options?.strictBackend) { + const backendSources = findBackendSources(root); + if (backendSources.length > 0) { + throw new Error(ssgWithBackendMessage(preset.dep, backendSources)); + } + } const overrides = preset.resolve?.(root); const cmd = overrides?.buildCommand ?? preset.buildCommand; const out = overrides?.outputDir ?? preset.outputDir; @@ -429,6 +444,26 @@ export function detectPreset( return null; } +/** + * The refusal shown when an SSG project also carries backend sources and no + * `inference.appType` says which one to deploy. Names the exact directories + * found and both ways out. + */ +function ssgWithBackendMessage(ssgDep: string, backendSources: Array): string { + return [ + `deploy: "${ssgDep}" was detected, but this project also has backend code: ${backendSources.join(', ')}.`, + 'A static deploy would silently drop it, so Void will not guess. Pick one in void.json:', + '', + ' Deploy the static output only (the backend is NOT deployed):', + ' { "inference": { "appType": "static" } }', + '', + ' Deploy both — the SSG emits the site, then Void packages it with the worker:', + ' { "inference": { "appType": "void", "build": " build && vite build" } }', + ' ...and in vite.config.ts add voidPlugin() plus `publicDir: ""`,', + ' so the generated site is copied into the client build alongside the worker.', + ].join('\n'); +} + /** * Resolve a local node_modules/.bin executable path. * Falls back to bare command name if the bin doesn't exist locally. @@ -492,6 +527,34 @@ function detectViteBinary(root: string): 'vite' | 'vp' { return 'vite'; } +/** + * Every backend source in the project that requires a full worker deploy, named + * relative to the root (e.g. `routes/`, `src/main.ssr.tsx`). + * + * Returned as a list rather than a boolean so a caller that has to REJECT a + * static deploy can tell the user exactly what would have been dropped. + */ +export function findBackendSources(root: string): Array { + const paths = readProjectPaths(root); + const found: Array = []; + for (const dir of [ + paths.routesDir, + paths.pagesDir, + paths.middlewareDir, + paths.cronsDir, + paths.queuesDir, + ]) { + if (existsSync(dir)) { + found.push(`${relative(root, dir)}/`); + } + } + const ssrEntry = getSsrServerEntryPath(root, paths); + if (ssrEntry) { + found.push(relative(root, ssrEntry)); + } + return found; +} + /** * Check whether the project has backend files that require a full worker deploy. */ diff --git a/packages/void/src/config.ts b/packages/void/src/config.ts index 8d7806274..7ee550510 100644 --- a/packages/void/src/config.ts +++ b/packages/void/src/config.ts @@ -25,6 +25,12 @@ export type WranglerConfig = { vars?: Record; }; +/** + * How the asset layer answers a request that matched no asset and no worker + * route. Mirrors Cloudflare's `assets.not_found_handling`. + */ +export type NotFoundHandling = 'single-page-application' | '404-page' | 'none'; + /** Routing configuration — headers, redirects, rewrites, fallbacks, revalidation, prerendering. */ export type RoutingConfig = { revalidate?: number | Record; @@ -34,6 +40,20 @@ export type RoutingConfig = { redirects?: Record; rewrites?: Record; fallbacks?: Record; + /** + * Override the inferred `not_found_handling` for the asset layer. + * + * Void infers `single-page-application` whenever the worker does not own HTML + * routing, because a real SPA needs `/index.html` served for deep links. An + * app whose assets were emitted by a static site generator (VitePress, + * Docusaurus, …) wants the opposite: unknown URLs should serve the generator's + * own `404.html` with a real HTTP 404, not `index.html` with a 200. Nothing in + * a built asset tree distinguishes the two, so this is an explicit opt-in. + * + * Only `not_found_handling` is affected — `run_worker_first` is unchanged, so + * API routes, auth, and `/__void/*` still reach the worker first. + */ + notFound?: NotFoundHandling; }; /** Inference configuration — bindings, scanDirs, build, outputDir, appType. */ @@ -82,6 +102,15 @@ const CONFIG_FILE = 'void.json'; const VALID_TARGETS = new Set(['cloudflare', 'node', 'bun', 'deno']); const VALID_APP_TYPES = new Set(['spa', 'static', 'void', 'framework']); const VALID_OUTPUTS = new Set(['server', 'static']); +/** + * Accepted `routing.notFound` values. Source of truth for the framework, the + * `AssetConfig.not_found_handling` field, and the schema.json enum. + */ +export const VALID_NOT_FOUND_HANDLING: Set = new Set([ + 'single-page-application', + '404-page', + 'none', +]); /** * Allowed 3xx redirect statuses. Source of truth for the framework, the * `_redirects` parser (`cli/headers.ts`), and the schema.json enum. 303 is @@ -461,6 +490,15 @@ export function readConfig(root: string): VoidConfig { } const routing = obj.routing as Record; + // Validate routing.notFound + if (routing.notFound !== undefined) { + if (typeof routing.notFound !== 'string' || !VALID_NOT_FOUND_HANDLING.has(routing.notFound)) { + throw new Error( + `config: "routing.notFound" in ${CONFIG_FILE} must be one of: ${[...VALID_NOT_FOUND_HANDLING].join(', ')}.`, + ); + } + } + // Validate routing.revalidate if (routing.revalidate !== undefined) { if (typeof routing.revalidate === 'number') { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index e8afe4cda..c2ae0f217 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -27,7 +27,13 @@ import { syncWranglerBindings, } from './cli/wrangler.ts'; import { writeFileIfChanged } from './codegen/write-if-changed.ts'; -import { readConfig, resolveBindingNames, isNodeTarget, getDatabaseDialect } from './config.ts'; +import { + readConfig, + resolveBindingNames, + isNodeTarget, + getDatabaseDialect, + type NotFoundHandling, +} from './config.ts'; import { scanJobsSync } from './crons/scan.ts'; import { inferBindingsFromSource } from './inference/walk.ts'; import { voidLog, voidWarn, voidError } from './log.ts'; @@ -187,7 +193,12 @@ function warnIfPackageJsonIsNotEsm(root: string): void { * dead-code-eliminated in `vite build`. Production deploys go through * `cli/wrapper.ts` instead. */ -function getFrameworkEntry(framework: Framework, root: string, devTriggerToken: string): string { +function getFrameworkEntry( + framework: Framework, + root: string, + devTriggerToken: string, + notFound?: NotFoundHandling, +): string { const isBuild = isViteBuildOrPreview(); // In dev, eagerly write the dispatch file so the wrapper's dynamic // import resolves on the very first request (the plugin's @@ -208,6 +219,8 @@ function getFrameworkEntry(framework: Framework, root: string, devTriggerToken: framework, getOriginalFrameworkEntry(framework, root), isBuild, + undefined, + notFound, ); } @@ -249,6 +262,16 @@ function generateClassATriggerWrapper( original: string, isBuild: boolean, assetsDir = 'assets', + /** + * 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. + */ + notFound?: NotFoundHandling, ): string { const outDir = join(root, '.void'); mkdirSync(outDir, { recursive: true }); @@ -263,7 +286,7 @@ export default { return serveWithAssets(request, env, await original.fetch(request, env, ctx)); }, }; -${compileAssetFallbackHelper(assetsDir)} +${compileAssetFallbackHelper(assetsDir, false, notFound)} ` : `// @ts-nocheck — Auto-generated by Void in dev. Do NOT edit. import original from ${JSON.stringify(original)}; @@ -968,9 +991,20 @@ 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. - if (workerConfig.assets && resolved.assets) { - delete (resolved.assets as Record).not_found_handling; - delete (resolved.assets as Record).run_worker_first; + // + // 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; + } } // D1 — auth requires the app DB only for sqlite apps @@ -1479,9 +1513,42 @@ export function voidPlugin(options?: { }; if (framework) { - workerConfig.main = getFrameworkEntry(framework, root, devTriggerToken); + workerConfig.main = getFrameworkEntry( + framework, + root, + devTriggerToken, + config.routing?.notFound, + ); 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; @@ -1492,6 +1559,7 @@ export function voidPlugin(options?: { getOriginalFrameworkEntry(framework, root), true, resolved.build.assetsDir, + config.routing?.notFound, ); }, }; @@ -1664,6 +1732,7 @@ export function voidPlugin(options?: { hasWebSockets: routeScanHasDocumentRoutes(websocketRoutes), authEnabled, liveEnabled: liveConfig !== undefined, + notFound: config.routing?.notFound, }); workerConfig.main = join(root, '.void', 'entry.ts'); diff --git a/packages/void/src/plugin-routing.ts b/packages/void/src/plugin-routing.ts index 66243893e..1426ec79a 100644 --- a/packages/void/src/plugin-routing.ts +++ b/packages/void/src/plugin-routing.ts @@ -16,7 +16,7 @@ import { findEnvFileForPaths } from './codegen/env-types.ts'; import { generateQueueTypes } from './codegen/queue-types.ts'; import { generateRouteTypes } from './codegen/route-types.ts'; import { writeFileIfChanged } from './codegen/write-if-changed.ts'; -import { readConfig, getDatabaseDialect } from './config.ts'; +import { readConfig, getDatabaseDialect, type NotFoundHandling } from './config.ts'; import { collectRevalidate, hasRevalidate } from './isr-config.ts'; import { readProjectPaths } from './project-paths.ts'; import { @@ -370,6 +370,16 @@ export function routingPlugin(root: string, options: RoutingPluginOptions): Plug return resolveCurrentAssetRoutingPolicy().workerSpaFallback; } + /** + * The `not_found_handling` the generated worker entry must agree with. Read + * off the SAME resolved policy that produces the wrangler asset config, so + * the emitted `serveWithAssets` can never disagree with the platform switch + * it is standing in for. + */ + function currentNotFoundHandling(): NotFoundHandling { + return resolveCurrentAssetRoutingPolicy().assetConfig.not_found_handling ?? 'none'; + } + function resolveCurrentAssetRoutingPolicy(): AssetRoutingPolicy { if (!scan) { return resolveAssetRoutingPolicy({ @@ -381,6 +391,7 @@ export function routingPlugin(root: string, options: RoutingPluginOptions): Plug hasWebSockets: false, authEnabled: compileOptions.auth !== null, liveEnabled: options.live !== undefined, + notFound: options.routing?.notFound, }); } return resolveAssetRoutingPolicy({ @@ -395,6 +406,7 @@ export function routingPlugin(root: string, options: RoutingPluginOptions): Plug hasWebSockets: hasDocumentRoutes(scan.websockets ?? []), authEnabled: compileOptions.auth !== null, liveEnabled: options.live !== undefined, + notFound: options.routing?.notFound, }); } @@ -568,6 +580,7 @@ export function routingPlugin(root: string, options: RoutingPluginOptions): Plug shouldServeSpaFallback(), options.live, isr, + currentNotFoundHandling(), ), ); } @@ -703,6 +716,8 @@ export function routingPlugin(root: string, options: RoutingPluginOptions): Plug : false, shouldServeSpaFallback(), options.live, + undefined, + currentNotFoundHandling(), ), ); } diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 274ba72b2..d2de8be04 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1,5 +1,6 @@ import type { VoidAuthProvider } from '../auth/providers.ts'; import type { DevRedirectRule, HeaderRule } from '../cli/types.ts'; +import type { NotFoundHandling } from '../config.ts'; import type { MigrationPlanBundle } from '../migrations/plan.ts'; import { resolveLayoutIds } from '../pages/layout-resolution.ts'; import { INTERNAL_BINDING_EXACT_NAMES, INTERNAL_BINDING_PREFIXES } from '../runtime/env-raw.ts'; @@ -2358,9 +2359,49 @@ function compilePageRoutes( * Class A framework wrappers. If the app returns 404, check ASSETS binding * for static files and set cache headers. Edge caching of hashed assets * happens at the dispatch layer (see design doc 0042). + * + * `notFound` is the RESOLVED `assetConfig.not_found_handling` for this build + * (`resolveAssetRoutingPolicy`), and it decides what happens once the asset + * binding has also answered 404. It is a separate argument from + * `serveSpaFallback` because the two are not derived from each other: the + * common worker-first app runs with `not_found_handling: 'none'` and STILL + * wants the worker-side shell fallback (that is the whole reason the flag + * exists). They are mutually exclusive in practice — `resolveAssetRoutingPolicy` + * clears `workerSpaFallback` whenever an explicit `routing.notFound` asks for + * anything other than the SPA shell. */ -export function compileAssetFallbackHelper(assetsDir = 'assets', serveSpaFallback = false): string { - const spaFallbackCode = serveSpaFallback +export function compileAssetFallbackHelper( + assetsDir = 'assets', + serveSpaFallback = false, + notFound: NotFoundHandling = 'none', +): string { + // `404-page`: the asset binding served its nearest `404.html` WITH a 404 + // status, so the `asset.status !== 404` guard above discards it and the + // worker's generic body wins — making `routing.notFound: '404-page'` inert on + // every worker-first app. Pass the asset response through instead of fetching + // `/404.html` by hand: Cloudflare's `404-page` handling is directory-aware + // ("nearest 404.html"), a hardcoded root path is not. Guarded on an HTML + // content-type because with no `404.html` anywhere the binding answers a bare + // 404, and the worker's own response is the better answer then. + // + // Also gated on the REQUEST accepting HTML — same guard the SPA-fallback + // branch below uses, and for the same reason. `serveWithAssets` wraps EVERY + // app response with no path filtering, so without this a GET/HEAD API handler + // that deliberately answers 404 with JSON has its body, content-type, and any + // middleware-set headers (CORS included) replaced by the site's HTML 404 page. + // `routing.notFound` is about document navigations; on the asset-first shape + // this branch is reached ONLY on `run_worker_first` paths (`/api/*`, + // `/__void/*`), where an HTML 404 page is never the right answer. + const notFoundPageCode = ` const accept = request.headers.get("accept") ?? ""; + const assetContentType = asset.headers.get("content-type") ?? ""; + if (accept.includes("text/html") && assetContentType.includes("text/html")) { + const res = new Response(asset.body, asset); + res.headers.set("Cache-Control", "no-store"); + return res; + } + return response;`; + + const fallthroughCode = serveSpaFallback ? ` // SPA fallback: when HTML-owning features make // assetConfig.not_found_handling = 'none', the asset binding returns 404 // instead of falling back to index.html itself. Do that fallback here, after @@ -2381,7 +2422,9 @@ export function compileAssetFallbackHelper(assetsDir = 'assets', serveSpaFallbac } } return response;` - : ` return response;`; + : notFound === '404-page' + ? notFoundPageCode + : ` return response;`; return ` async function serveWithAssets(request, env, response) { @@ -2396,7 +2439,7 @@ async function serveWithAssets(request, env, response) { } return res; } -${spaFallbackCode} +${fallthroughCode} } `; } @@ -2439,6 +2482,13 @@ export function compileWorkerEntry( * behavioral change for managed/dev/no-ISR builds). */ isr?: { runtimePath: string }, + /** + * Resolved `assetConfig.not_found_handling` for this build. Threaded to + * `compileAssetFallbackHelper` so `routing.notFound: '404-page'` is honored + * on the worker-first path instead of being discarded. Defaults to `'none'`, + * which emits the pre-existing helper byte-for-byte. + */ + notFound: NotFoundHandling = 'none', ): string { const remotePath = remote?.remotePath; const remoteBindingNames = JSON.stringify(remote?.bindingNames); @@ -2527,7 +2577,7 @@ function __filterInternalBindings(env) { } `; - const assetHelper = compileAssetFallbackHelper(assetsDir, serveSpaFallback); + const assetHelper = compileAssetFallbackHelper(assetsDir, serveSpaFallback, notFound); // ISR wiring (self-host only; injected by Task 8 for non-managed builds). When // `isr` is absent every fragment below is an empty string, so the generated diff --git a/packages/void/test/integration/direct-r2-deploy.test.ts b/packages/void/test/integration/direct-r2-deploy.test.ts index 67019f82b..67b25411e 100644 --- a/packages/void/test/integration/direct-r2-deploy.test.ts +++ b/packages/void/test/integration/direct-r2-deploy.test.ts @@ -414,6 +414,68 @@ describe('direct-to-R2 deploy flow', () => { expect(body.preflight).toBe('true'); }); + // `routing.notFound` must reach the STATIC manifest, not only the + // worker-with-assets path. `detectPreset` classifies any Vite project with + // no backend files as `spa`, so a plain Vite MPA lands here and would + // otherwise ship `not_found_handling: 'single-page-application'` — every + // unknown URL answered with index.html and HTTP 200. + it('threads routing.notFound into the finalize manifest (static path)', async () => { + const state = installPlatformMocks(); + const client = makeClient(); + + await runStaticDeploy( + workdir, + { projectId: 'proj_t', slug: 'test' }, + client, + { buildCommand: null, outputDir: assetsDir, appType: 'spa' }, + true, + undefined, + undefined, + undefined, + undefined, + undefined, + { notFound: '404-page' }, + undefined, + ); + + const body = JSON.parse(state.finalizeCalls[0].init.body as string); + expect(body.manifest.type).toBe('spa'); + expect(body.manifest.assetConfig).toEqual({ not_found_handling: '404-page' }); + // Overriding away from SPA must NOT leave the synthetic `/* -> /index.html` + // fallback behind, or the shell would still be served via a rule. + expect(body.manifest.fallbackRules).toBeUndefined(); + }); + + // Calling convention of the "all pages prerendered -> static" redirect in + // `runFullDeploy`: it merged the routing RULES upstream and deliberately + // passes `routing: undefined`, so the notFound override has to ride the + // dedicated trailing param or it is silently dropped there too. + it('honors an explicit notFound when routing is undefined (full->static redirect shape)', async () => { + const state = installPlatformMocks(); + const client = makeClient(); + + await runStaticDeploy( + workdir, + { projectId: 'proj_t', slug: 'test' }, + client, + { buildCommand: null, outputDir: assetsDir, appType: 'static' }, + true, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'single-page-application', + ); + + const body = JSON.parse(state.finalizeCalls[0].init.body as string); + expect(body.manifest.assetConfig).toEqual({ + not_found_handling: 'single-page-application', + }); + }); + it('retries 5xx R2 PUT failures up to 3 times', async () => { let attemptsForFirstAsset = 0; const state = installPlatformMocks({ diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index e939bf9bd..6971ee3f0 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -2448,6 +2448,62 @@ describe('compileWorkerEntry', () => { expect(code).toMatch(/env\.ASSETS\.fetch\(new Request\(indexUrl/); }); + // `routing.notFound: '404-page'` sets `assetConfig.not_found_handling`, so + // CF's asset binding answers an unmatched path with the NEAREST `404.html` — + // at a 404 status, which the `asset.status !== 404` guard above discards. The + // resolved handling has to reach the generated helper or the override is + // inert on every worker-first app. + it('serveWithAssets passes the asset 404 page through for not_found_handling: 404-page', () => { + const code = compileWorkerEntry( + false, + undefined, + 'assets', + [], + 'void/_env', + undefined, + false, + false, + undefined, + undefined, + '404-page', + ); + + // Pass the binding's own response through — CF's `404-page` is + // directory-aware ("nearest 404.html"); a hardcoded `/404.html` fetch is not. + expect(code).toContain('asset.headers.get("content-type")'); + expect(code).toContain('new Response(asset.body, asset)'); + expect(code).not.toContain('"/404.html"'); + // And it is NOT the SPA shell path. + expect(code).not.toContain('"/index.html"'); + // Gated on the REQUEST accepting HTML as well. `serveWithAssets` wraps every + // app response with no path filtering, so without this an API handler's + // deliberate JSON 404 gets replaced by the site's HTML 404 page. + expect(code).toContain('request.headers.get("accept")'); + expect(code).toContain( + 'accept.includes("text/html") && assetContentType.includes("text/html")', + ); + }); + + it('serveWithAssets keeps the worker response for not_found_handling: none', () => { + const code = compileWorkerEntry( + false, + undefined, + 'assets', + [], + 'void/_env', + undefined, + false, + false, + undefined, + undefined, + 'none', + ); + + // Byte-identical to the pre-existing default — `none` is what every + // worker-first app infers, so this is the no-regression guard. + expect(code).toBe(compileWorkerEntry()); + }); + it('serveWithAssets only falls back to index.html for HTML accept', () => { const code = compileWorkerEntry( false, diff --git a/packages/void/test/unit/config.test.ts b/packages/void/test/unit/config.test.ts index 88fa851f5..e34532dc9 100644 --- a/packages/void/test/unit/config.test.ts +++ b/packages/void/test/unit/config.test.ts @@ -373,6 +373,46 @@ describe('readConfig', () => { cleanup(); }); + // `routing.notFound` overrides the INFERRED asset `not_found_handling`. + // Typos must fail at config-read time: an unvalidated string would be written + // straight into `assets.not_found_handling`, and the failure would only show + // up as Cloudflare rejecting the deployed worker config. + it('accepts routing.notFound: "404-page"', () => { + setup(JSON.stringify({ routing: { notFound: '404-page' } })); + expect(readConfig(tmpDir).routing?.notFound).toBe('404-page'); + cleanup(); + }); + + it('accepts routing.notFound: "single-page-application"', () => { + setup(JSON.stringify({ routing: { notFound: 'single-page-application' } })); + expect(readConfig(tmpDir).routing?.notFound).toBe('single-page-application'); + cleanup(); + }); + + it('accepts routing.notFound: "none"', () => { + setup(JSON.stringify({ routing: { notFound: 'none' } })); + expect(readConfig(tmpDir).routing?.notFound).toBe('none'); + cleanup(); + }); + + it('leaves routing.notFound undefined when omitted', () => { + setup(JSON.stringify({ routing: { revalidate: 60 } })); + expect(readConfig(tmpDir).routing?.notFound).toBeUndefined(); + cleanup(); + }); + + it('throws on an unknown routing.notFound value', () => { + setup(JSON.stringify({ routing: { notFound: '404' } })); + expect(() => readConfig(tmpDir)).toThrow('"routing.notFound"'); + cleanup(); + }); + + it('throws on a non-string routing.notFound', () => { + setup(JSON.stringify({ routing: { notFound: true } })); + expect(() => readConfig(tmpDir)).toThrow('"routing.notFound"'); + cleanup(); + }); + it('throws on invalid routing type', () => { setup(JSON.stringify({ routing: 'invalid' })); expect(() => readConfig(tmpDir)).toThrow('"routing" in void.json must be an object'); diff --git a/packages/void/test/unit/deploy-asset-config.test.ts b/packages/void/test/unit/deploy-asset-config.test.ts index bb314ff67..ad25ed9f2 100644 --- a/packages/void/test/unit/deploy-asset-config.test.ts +++ b/packages/void/test/unit/deploy-asset-config.test.ts @@ -6,6 +6,7 @@ import { resolveAssetRoutingPolicy, workerOwnsHtmlRouting, } from '../../src/asset-routing.ts'; +import { compileAssetFallbackHelper } from '../../src/router/compile.ts'; // `not_found_handling: 'none'` → asset binding 404s on unmatched paths, // worker (run_worker_first) owns HTML responses. @@ -290,3 +291,418 @@ describe('resolveAssetConfig', () => { }); }); }); + +// `routing.notFound` (void.json) is an explicit escape hatch, not a new default. +// +// Without it, an app whose assets came from a static site generator and whose +// only backend is an API route takes the `apiWorkerFirst` branch, so unknown +// URLs are answered with `index.html` and HTTP **200**. The generator's real +// `404.html` is never served and crawlers see 200 for every URL. The default +// cannot change — a genuine SPA needs that fallback for deep links, and a built +// asset tree carries nothing that distinguishes the two — so the user says so. +// +// `run_worker_first`, `workerFirst` and `apiWorkerFirst` stay as inferred, so +// which layer sees a request first is unaffected. `workerSpaFallback` is the one +// derived flag that MUST follow the override — see the worker-first describe +// below for why. +describe('resolveAssetRoutingPolicy — routing.notFound override', () => { + const SPA_API_WORKER_FIRST = ['/api', '/api/*', '/__void', '/__void/*']; + + const ssgWithApi = { + isSsr: false, + hasPages: false, + hasApiRoutes: true, + hasDocumentRoutes: false, + hasMiddleware: false, + } as const; + + it('leaves the inferred SPA fallback in place when unset', () => { + expect(resolveAssetRoutingPolicy(ssgWithApi).assetConfig).toEqual({ + not_found_handling: 'single-page-application', + run_worker_first: SPA_API_WORKER_FIRST, + }); + }); + + it('serves a real 404 page when set to "404-page"', () => { + expect(resolveAssetRoutingPolicy({ ...ssgWithApi, notFound: '404-page' }).assetConfig).toEqual({ + not_found_handling: '404-page', + run_worker_first: SPA_API_WORKER_FIRST, + }); + }); + + it('leaves run_worker_first and the request-trigger flags untouched', () => { + const inferred = resolveAssetRoutingPolicy(ssgWithApi); + const overridden = resolveAssetRoutingPolicy({ ...ssgWithApi, notFound: '404-page' }); + expect(overridden.assetConfig.run_worker_first).toEqual(inferred.assetConfig.run_worker_first); + expect(overridden.apiWorkerFirst).toBe(inferred.apiWorkerFirst); + expect(overridden.workerFirst).toBe(inferred.workerFirst); + // This shape is asset-first, so there is no worker-side shell fallback to + // begin with. The worker-first shape is a different story — below. + expect(inferred.workerSpaFallback).toBe(false); + expect(overridden.workerSpaFallback).toBe(false); + }); + + it('applies on the plain-asset branch too (no API routes)', () => { + const inputs = { + isSsr: false, + hasPages: false, + hasDocumentRoutes: false, + hasMiddleware: false, + } as const; + expect(resolveAssetRoutingPolicy({ ...inputs, notFound: 'none' }).assetConfig).toEqual({ + not_found_handling: 'none', + run_worker_first: ['/__void', '/__void/*'], + }); + }); + + it('can also override the worker-first branch, which infers "none"', () => { + const workerFirst = { + isSsr: false, + hasPages: true, + hasDocumentRoutes: false, + hasMiddleware: false, + } as const; + expect(resolveAssetRoutingPolicy(workerFirst).assetConfig.not_found_handling).toBe('none'); + expect(resolveAssetRoutingPolicy({ ...workerFirst, notFound: '404-page' }).assetConfig).toEqual( + { + not_found_handling: '404-page', + run_worker_first: ['/**'], + }, + ); + }); + + it('is reachable through resolveAssetConfig (the deploy entry point)', () => { + expect(resolveAssetConfig({ ...ssgWithApi, notFound: '404-page' }).not_found_handling).toBe( + '404-page', + ); + }); +}); + +// The shape the `routing.notFound` override was silently inert on. +// +// `workerSpaFallback` is true for `workerFirst && !isSsr && !hasPages` — any +// non-SSR app with no `pages/` that still owns HTML routing: a `middleware/` +// file, a route outside `/api`, a document websocket, or Live. That flag makes +// the generated `serveWithAssets` answer every unmatched HTML navigation with +// `/index.html` at status **200**, before `not_found_handling` is ever +// consulted. So setting `routing.notFound: '404-page'` changed the wrangler +// asset config and changed nothing a user could observe. +// +// This is exactly the app the docs walk people into: `docs/guide/app-types.md` +// recommends `routing.notFound` for `appType: "void"` + `vitepress build && +// vite build`, and `docs/guide/edge/static-assets.md` names it as the override +// for "Worker owns HTML (Pages, SSR, middleware…)". Add one `middleware/` file +// to that VitePress app and the documented escape hatch stopped working. +describe('resolveAssetRoutingPolicy — notFound on the worker-first SPA-fallback shape', () => { + // middleware/ → workerOwnsHtmlRouting, no pages/, no SSR. + const ssgWithMiddleware = { + isSsr: false, + hasPages: false, + hasDocumentRoutes: false, + hasMiddleware: true, + } as const; + + it('keeps the worker-side shell fallback when notFound is unset', () => { + const policy = resolveAssetRoutingPolicy(ssgWithMiddleware); + expect(policy.workerFirst).toBe(true); + expect(policy.assetConfig.not_found_handling).toBe('none'); + expect(policy.workerSpaFallback).toBe(true); + }); + + it('clears the worker-side shell fallback for notFound: "404-page"', () => { + const policy = resolveAssetRoutingPolicy({ ...ssgWithMiddleware, notFound: '404-page' }); + expect(policy.assetConfig.not_found_handling).toBe('404-page'); + expect(policy.workerSpaFallback).toBe(false); + // Which layer sees the request first is still unchanged. + expect(policy.workerFirst).toBe(true); + expect(policy.assetConfig.run_worker_first).toEqual(['/**']); + }); + + it('clears it for notFound: "none" too', () => { + expect( + resolveAssetRoutingPolicy({ ...ssgWithMiddleware, notFound: 'none' }).workerSpaFallback, + ).toBe(false); + }); + + it('keeps it for an explicit notFound: "single-page-application"', () => { + // The override names the shell, so the shell is what it gets. + expect( + resolveAssetRoutingPolicy({ + ...ssgWithMiddleware, + notFound: 'single-page-application', + }).workerSpaFallback, + ).toBe(true); + }); + + it('applies to every workerOwnsHtmlRouting trigger, not just middleware', () => { + for (const trigger of [ + { hasDocumentRoutes: true, hasMiddleware: false }, + { hasDocumentRoutes: false, hasMiddleware: false, hasWebSockets: true }, + { hasDocumentRoutes: false, hasMiddleware: false, liveEnabled: true }, + ]) { + const base = { isSsr: false, hasPages: false, ...trigger } as const; + expect(resolveAssetRoutingPolicy(base).workerSpaFallback).toBe(true); + expect(resolveAssetRoutingPolicy({ ...base, notFound: '404-page' }).workerSpaFallback).toBe( + false, + ); + } + }); +}); + +// End-to-end over the REAL generated helper: policy in, executed worker code +// out. A unit assertion on `workerSpaFallback` alone would not have caught the +// second half of the bug — with the flag cleared the app returns a real 404, +// but with the WORKER's generic body, while the docs promise the generator's +// own `404.html`. `compileAssetFallbackHelper` has to pass the asset binding's +// 404 through, and only executing it proves that. +describe('generated serveWithAssets — routing.notFound end to end', () => { + /** Stand-in for CF's asset binding, implementing `not_found_handling`. */ + function makeAssets(handling: string | undefined, opts?: { has404Page?: boolean }) { + return { + async fetch(req: Request): Promise { + const path = new URL(req.url).pathname; + if (path === '/index.html') { + return new Response('SPA SHELL', { + status: 200, + headers: { 'content-type': 'text/html' }, + }); + } + if (handling === 'single-page-application') { + return new Response('SPA SHELL', { + status: 200, + headers: { 'content-type': 'text/html' }, + }); + } + // CF serves the NEAREST 404.html, with a real 404 status — which is + // precisely why the helper's `asset.status !== 404` guard dropped it. + if (handling === '404-page' && opts?.has404Page !== false) { + return new Response('GENERATED 404', { + status: 404, + headers: { 'content-type': 'text/html' }, + }); + } + return new Response('', { status: 404 }); + }, + }; + } + + /** + * Runs the generated helper and hands back the raw `Response`, so a caller can + * assert on headers and not just status/body. `path`, `accept` and the worker + * response default to a browser navigation to an unmatched document path. + */ + async function serveRaw( + inputs: Parameters[0], + opts?: { + has404Page?: boolean; + path?: string; + /** `null` omits the header entirely. */ + accept?: string | null; + workerResponse?: () => Response; + }, + ): Promise { + const policy = resolveAssetRoutingPolicy(inputs); + const handling = policy.assetConfig.not_found_handling; + const source = compileAssetFallbackHelper('assets', policy.workerSpaFallback, handling); + const mod = (await import( + `data:text/javascript,${encodeURIComponent(`${source}\nexport { serveWithAssets };`)}` + )) as { + serveWithAssets: (req: Request, env: unknown, res: Response) => Promise; + }; + const accept = opts?.accept === undefined ? 'text/html' : opts.accept; + const request = new Request(`https://app.test${opts?.path ?? '/deep/link'}`, { + headers: accept === null ? {} : { accept }, + }); + return await mod.serveWithAssets( + request, + { ASSETS: makeAssets(handling, opts) }, + opts?.workerResponse?.() ?? new Response('worker 404', { status: 404 }), + ); + } + + async function serveUnmatched( + inputs: Parameters[0], + opts?: { has404Page?: boolean }, + ): Promise<{ status: number; body: string }> { + const res = await serveRaw(inputs, opts); + return { status: res.status, body: await res.text() }; + } + + const ssgWithMiddleware = { + isSsr: false, + hasPages: false, + hasDocumentRoutes: false, + hasMiddleware: true, + } as const; + + it('serves the SPA shell at 200 when notFound is unset (unchanged default)', async () => { + expect(await serveUnmatched(ssgWithMiddleware)).toEqual({ + status: 200, + body: 'SPA SHELL', + }); + }); + + it('serves the generator 404 page with a 404 status for notFound: "404-page"', async () => { + expect(await serveUnmatched({ ...ssgWithMiddleware, notFound: '404-page' })).toEqual({ + status: 404, + body: 'GENERATED 404', + }); + }); + + it('keeps the worker response when 404-page finds no 404.html to serve', async () => { + // A bodyless platform 404 is strictly worse than whatever the worker said. + expect( + await serveUnmatched({ ...ssgWithMiddleware, notFound: '404-page' }, { has404Page: false }), + ).toEqual({ status: 404, body: 'worker 404' }); + }); + + it('serves the worker 404 for notFound: "none"', async () => { + expect(await serveUnmatched({ ...ssgWithMiddleware, notFound: 'none' })).toEqual({ + status: 404, + body: 'worker 404', + }); + }); + + it('still serves the shell for an explicit notFound: "single-page-application"', async () => { + expect( + await serveUnmatched({ ...ssgWithMiddleware, notFound: 'single-page-application' }), + ).toEqual({ status: 200, body: 'SPA SHELL' }); + }); + + it('honors 404-page on the SSR shape, which never had a shell fallback', async () => { + expect( + await serveUnmatched({ + isSsr: true, + hasPages: false, + hasDocumentRoutes: false, + hasMiddleware: false, + notFound: '404-page', + }), + ).toEqual({ status: 404, body: 'GENERATED 404' }); + }); + + // Guard against a recurring misreading of `workerSpaFallback: false` on the + // SSR/Pages shapes as "the explicit override cannot work there". It already + // works: `serveWithAssets` returns the asset response as soon as it is not a + // 404, so SPA mode hands back the shell at 200 BEFORE `fallthroughCode` — the + // only place `workerSpaFallback` matters — is ever reached. Enabling the flag + // for `isSsr` / `hasPages` would be strictly dead code, so it must stay off. + for (const shape of [ + { label: 'SSR', isSsr: true, hasPages: false }, + { label: 'Pages', isSsr: false, hasPages: true }, + ]) { + it(`serves the shell at 200 for ${shape.label} + notFound: "single-page-application", with the worker fallback off`, async () => { + const inputs = { + isSsr: shape.isSsr, + hasPages: shape.hasPages, + hasDocumentRoutes: false, + hasMiddleware: false, + notFound: 'single-page-application', + } as const; + expect(resolveAssetRoutingPolicy(inputs).workerSpaFallback).toBe(false); + expect(await serveUnmatched(inputs)).toEqual({ + status: 200, + body: 'SPA SHELL', + }); + }); + } + + // The axis the cases above miss: they all send `accept: text/html` to a + // document path with a generic worker 404, so nothing here distinguished + // "browser asked for a page" from "an API client asked for data". + // + // `serveWithAssets` wraps EVERY app response with no path filtering and + // engages on any 404, so a GET/HEAD API handler that deliberately answers 404 + // has to survive it intact. On the asset-first shape — this feature's own + // documented recipe — `404-page` means the asset layer answers document misses + // itself, so the worker only ever reaches this branch on `run_worker_first` + // paths (`/api/*`, `/__void/*`), where an HTML 404 page is never the answer. + describe('an API 404 is not replaced by the HTML 404 page', () => { + /** A handler deliberately answering 404 with JSON, plus a CORS header. */ + const apiJson404 = () => + new Response(JSON.stringify({ error: 'not found' }), { + status: 404, + headers: { + 'content-type': 'application/json', + 'access-control-allow-origin': 'https://client.test', + }, + }); + + async function serveApi(accept: string | null) { + const res = await serveRaw( + { ...ssgWithMiddleware, notFound: '404-page' }, + { path: '/api/thing', accept, workerResponse: apiJson404 }, + ); + return { + status: res.status, + contentType: res.headers.get('content-type'), + cors: res.headers.get('access-control-allow-origin'), + body: await res.text(), + }; + } + + it('preserves body, status and content-type for an API client (accept: application/json)', async () => { + expect(await serveApi('application/json')).toEqual({ + status: 404, + contentType: 'application/json', + cors: 'https://client.test', + body: '{"error":"not found"}', + }); + }); + + it('preserves it for a curl-style accept: */*', async () => { + // `*/*` does not literally contain `text/html`, and it must not be widened + // to match: a wildcard is what every non-browser client sends by default. + expect(await serveApi('*/*')).toEqual({ + status: 404, + contentType: 'application/json', + cors: 'https://client.test', + body: '{"error":"not found"}', + }); + }); + + it('preserves it when the request sends no accept header at all', async () => { + expect(await serveApi(null)).toEqual({ + status: 404, + contentType: 'application/json', + cors: 'https://client.test', + body: '{"error":"not found"}', + }); + }); + + it('keeps a middleware-set CORS header on an HTML-accepting API 404 too', async () => { + // Rebuilding the response from the asset would drop it, and a browser + // `fetch()` would then see a CORS failure instead of a 404. Only the + // document-navigation shape below is allowed to swap in the 404 page. + const res = await serveRaw( + { ...ssgWithMiddleware, notFound: '404-page' }, + { path: '/api/thing', accept: 'application/json, text/plain', workerResponse: apiJson404 }, + ); + expect(res.headers.get('access-control-allow-origin')).toBe('https://client.test'); + }); + + // Regression guards for the intended target — both document shapes still + // get the generator's 404 page. The `.html` case matters because VitePress + // defaults to `cleanUrls: false`, so its URLs carry the extension. + it('still serves the HTML 404 page for a browser navigation to an extension-less path', async () => { + expect(await serveUnmatched({ ...ssgWithMiddleware, notFound: '404-page' })).toEqual({ + status: 404, + body: 'GENERATED 404', + }); + }); + + it('still serves the HTML 404 page for a browser navigation to a .html path', async () => { + const res = await serveRaw( + { ...ssgWithMiddleware, notFound: '404-page' }, + { + path: '/guide/missing.html', + accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + }, + ); + expect({ status: res.status, body: await res.text() }).toEqual({ + status: 404, + body: 'GENERATED 404', + }); + }); + }); +}); diff --git a/packages/void/test/unit/deploy-auth.test.ts b/packages/void/test/unit/deploy-auth.test.ts index bac6ba405..3176e0758 100644 --- a/packages/void/test/unit/deploy-auth.test.ts +++ b/packages/void/test/unit/deploy-auth.test.ts @@ -365,6 +365,146 @@ describe('buildEnv', () => { }); }); +// Build commands are handed to a SHELL (`execSync`), and a user-configured +// `inference.build` names bare binaries (`vitepress build && vite build`) that +// only exist under the project's own node_modules/.bin. Under the build +// container's `npx --yes void deploy` this happens to work — npx prepends every +// ancestor `.bin` itself — so the gap is invisible there and only bites a +// directly invoked `node_modules/.bin/void deploy` or a globally installed +// `void`, where nothing puts the project's bin dir on PATH. +// +// It is an explicit OPT-IN (`{ localBinRoot }`), never the default: prepending +// the project's bin dir makes a dependency-shipped `node_modules/.bin/` +// shadow the system binary of that name for the child. That is exactly what a +// build command wants, and exactly what `getGitCommit`'s `git` children — which +// run BEFORE any build, with `VOID_TOKEN` in env, even in the no-build deploy +// modes (`--dir`, static/spa presets with no build command) — must not get. +describe('buildEnv — local node_modules/.bin on PATH', () => { + const DELIMITER = process.platform === 'win32' ? ';' : ':'; + + /** Read PATH the way a child process would: case-insensitively (Windows: `Path`). */ + function readPath(env: NodeJS.ProcessEnv): string | undefined { + const key = Object.keys(env).find((k) => k.toLowerCase() === 'path'); + return key ? env[key] : undefined; + } + + it('prepends /node_modules/.bin', () => { + const root = mkdtempSync(join(tmpdir(), 'void-build-env-')); + try { + const childPath = readPath(buildEnv(undefined, { localBinRoot: root })); + expect(childPath?.startsWith(join(root, 'node_modules', '.bin') + DELIMITER)).toBe(true); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('preserves the inherited PATH after the prepended entry', () => { + const root = mkdtempSync(join(tmpdir(), 'void-build-env-')); + const savedPath = process.env.PATH; + try { + process.env.PATH = `/usr/bin${DELIMITER}/bin`; + const childPath = readPath(buildEnv(undefined, { localBinRoot: root })); + expect(childPath).toBe( + `${join(root, 'node_modules', '.bin')}${DELIMITER}/usr/bin${DELIMITER}/bin`, + ); + } finally { + if (savedPath === undefined) { + delete process.env.PATH; + } else { + process.env.PATH = savedPath; + } + rmSync(root, { recursive: true, force: true }); + } + }); + + it('uses the platform PATH delimiter', () => { + const root = mkdtempSync(join(tmpdir(), 'void-build-env-')); + const savedPath = process.env.PATH; + try { + process.env.PATH = '/usr/bin'; + const childPath = readPath(buildEnv(undefined, { localBinRoot: root })); + const binDir = join(root, 'node_modules', '.bin'); + expect(childPath).toBe(`${binDir}${DELIMITER}/usr/bin`); + // Guard against the classic `:`-everywhere bug: on Windows a `:` would + // make the whole variable one unusable entry (`C:\...` already has a `:`). + expect(DELIMITER).toBe(process.platform === 'win32' ? ';' : ':'); + } finally { + if (savedPath === undefined) { + delete process.env.PATH; + } else { + process.env.PATH = savedPath; + } + rmSync(root, { recursive: true, force: true }); + } + }); + + it('sets PATH to just the bin dir when nothing was inherited', () => { + const root = mkdtempSync(join(tmpdir(), 'void-build-env-')); + const savedPath = process.env.PATH; + try { + delete process.env.PATH; + expect(readPath(buildEnv(undefined, { localBinRoot: root }))).toBe( + join(root, 'node_modules', '.bin'), + ); + } finally { + if (savedPath === undefined) { + delete process.env.PATH; + } else { + process.env.PATH = savedPath; + } + rmSync(root, { recursive: true, force: true }); + } + }); + + it('still scrubs the CF Access pair and still passes extras through', () => { + const root = mkdtempSync(join(tmpdir(), 'void-build-env-')); + const savedId = process.env.CF_ACCESS_CLIENT_ID; + try { + process.env.CF_ACCESS_CLIENT_ID = 'svc-id.access'; + const childEnv = buildEnv({ VOID_DEPLOY_PROJECT_ID: 'proj_1' }, { localBinRoot: root }); + expect(childEnv.CF_ACCESS_CLIENT_ID).toBeUndefined(); + expect(childEnv.VOID_DEPLOY_PROJECT_ID).toBe('proj_1'); + expect(readPath(childEnv)?.startsWith(join(root, 'node_modules', '.bin'))).toBe(true); + } finally { + if (savedId === undefined) { + delete process.env.CF_ACCESS_CLIENT_ID; + } else { + process.env.CF_ACCESS_CLIENT_ID = savedId; + } + rmSync(root, { recursive: true, force: true }); + } + }); + + // The privileged case must be opt-in. `getGitCommit` and the drizzle-kit + // spawn call `buildEnv()` with no options, and a dependency that ships + // `node_modules/.bin/git` must not be able to hijack them — `getGitCommit` + // runs before the build and, on `void deploy --dir dist` or a static/spa + // preset with no build command, is the ONLY child the deploy spawns. + it('leaves PATH untouched when no localBinRoot is given', () => { + const savedPath = process.env.PATH; + try { + process.env.PATH = `/usr/bin${DELIMITER}/bin`; + expect(readPath(buildEnv())).toBe(`/usr/bin${DELIMITER}/bin`); + expect(readPath(buildEnv({ VOID_DEPLOY_PROJECT_ID: 'proj_1' }))).toBe( + `/usr/bin${DELIMITER}/bin`, + ); + } finally { + if (savedPath === undefined) { + delete process.env.PATH; + } else { + process.env.PATH = savedPath; + } + } + }); + + it('hands the child the parent PATH byte-for-byte when no localBinRoot is given', () => { + // Deliberately NOT asserting on `process.cwd()/node_modules/.bin`: the test + // runner itself puts that on PATH, so an absence check there would be + // vacuous. Identity with the parent is the property that matters. + expect(readPath(buildEnv())).toBe(process.env.PATH); + }); +}); + afterEach(() => { Object.defineProperty(process.stdin, 'isTTY', { value: originalIsTTY, configurable: true }); if (savedVoidToken === undefined) { diff --git a/packages/void/test/unit/deploy-events.test.ts b/packages/void/test/unit/deploy-events.test.ts index b8ec4b0b4..7c627fda4 100644 --- a/packages/void/test/unit/deploy-events.test.ts +++ b/packages/void/test/unit/deploy-events.test.ts @@ -15,6 +15,7 @@ import type { SpinnerResult } from '@clack/prompts'; import { applyDeployEvent, streamDeployEvents, + warnIgnoredNotFoundForFramework, warnUnpublishedRouting, } from '../../src/cli/deploy.ts'; import type { CliLogger } from '../../src/cli/log-file.ts'; @@ -281,3 +282,46 @@ describe('warnUnpublishedRouting', () => { expect(warnSpy).not.toHaveBeenCalled(); }); }); + +// Class B/C framework deploys pin `not_found_handling: 'none'` and never read +// `routing.notFound`. The config validator accepts the key in every mode, so +// without this warning the option looks supported and silently does nothing. +describe('warnIgnoredNotFoundForFramework', () => { + it('warns, naming the framework and the pinned value, when routing.notFound is set', async () => { + const { log } = await import('@clack/prompts'); + const warnSpy = log.warn as ReturnType; + warnSpy.mockClear(); + + warnIgnoredNotFoundForFramework('404-page', 'astro'); + + expect(warnSpy).toHaveBeenCalledOnce(); + const msg = String(warnSpy.mock.calls[0][0]); + expect(msg).toContain('"routing.notFound"'); + expect(msg).toContain('astro'); + expect(msg).toContain('"none"'); + expect(msg).toMatch(/ignored/i); + }); + + it('warns for every accepted value, including the pinned one', async () => { + // Even `'none'` warns: it happens to match what the path pins, but the key + // is still not read, and staying silent there would teach that it works. + const { log } = await import('@clack/prompts'); + const warnSpy = log.warn as ReturnType; + + for (const value of ['single-page-application', '404-page', 'none'] as const) { + warnSpy.mockClear(); + warnIgnoredNotFoundForFramework(value, 'sveltekit'); + expect(warnSpy).toHaveBeenCalledOnce(); + } + }); + + it('does not warn when routing.notFound is unset', async () => { + const { log } = await import('@clack/prompts'); + const warnSpy = log.warn as ReturnType; + warnSpy.mockClear(); + + warnIgnoredNotFoundForFramework(undefined, 'nuxt'); + + expect(warnSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/void/test/unit/deploy-prerender-skip.test.ts b/packages/void/test/unit/deploy-prerender-skip.test.ts new file mode 100644 index 000000000..a939e4aba --- /dev/null +++ b/packages/void/test/unit/deploy-prerender-skip.test.ts @@ -0,0 +1,204 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { hasPrerenderSources } from '../../src/cli/deploy.ts'; +import { compileRouteTable } from '../../src/router/compile.ts'; +import type { ScanResult } from '../../src/router/scan.ts'; + +// `collectPrerenderPaths` boots the BUILT worker in Miniflare with bindings from +// `wranglerVars + loadEnv('production', root, '')` only. The generated fetch +// handler validates the `env.ts` schema at boot, so an app whose secrets live on +// the platform (never in a committed `.env`) gets HTTP 500 there and the deploy +// dies. The only workaround was moving the secret into `.env.production`, which +// `loadDeployEnv` then publishes as a PLAINTEXT manifest var — so skipping the +// boot when it provably cannot contribute anything also removes a real incentive +// to leak a secret. +// +// The skip is only safe if it is result-identical, which is what the second +// describe block below pins against the real code generator. +describe('hasPrerenderSources', () => { + it('is false when there is no pages dir, no SSR entry and no routing.prerender', () => { + expect( + hasPrerenderSources({ + hasPages: false, + hasSsrEntry: false, + explicitPrerenderPaths: undefined, + }), + ).toBe(false); + }); + + it('is true when pages/ exists', () => { + expect( + hasPrerenderSources({ + hasPages: true, + hasSsrEntry: false, + explicitPrerenderPaths: undefined, + }), + ).toBe(true); + }); + + // Custom SSR mode (`src/main.ssr.ts`) exports a top-level `getPrerenderPaths()` + // and has NO pages/ directory. Keying the skip on pages alone would silently + // stop prerendering for every one of these apps. + it('is true for a custom SSR entry with no pages/', () => { + expect( + hasPrerenderSources({ + hasPages: false, + hasSsrEntry: true, + explicitPrerenderPaths: undefined, + }), + ).toBe(true); + }); + + // `routing.prerender` is compiled into the collector as explicit paths and is + // likewise independent of pages/. + it('is true for routing.prerender with no pages/ and no SSR entry', () => { + expect( + hasPrerenderSources({ + hasPages: false, + hasSsrEntry: false, + explicitPrerenderPaths: ['/', '/about'], + }), + ).toBe(true); + }); + + it('treats an empty routing.prerender array as no source', () => { + expect( + hasPrerenderSources({ + hasPages: false, + hasSsrEntry: false, + explicitPrerenderPaths: [], + }), + ).toBe(false); + }); +}); + +// Equivalence proof: the three inputs above are exactly the sources +// `compilePrerenderCollector` emits a `paths.push(...)` for. With none of them, +// the generated collector body has no push at all and can only return `[]`, so +// not booting it returns the same answer the boot would have. +describe('__voidCollectPrerenderPaths — sources that can push a path', () => { + const testOptions = { + honoPath: '/resolved/hono/index.mjs', + responsePath: '/resolved/void/runtime/response.mjs', + handlerPath: '/resolved/void/runtime/handler.mjs', + runtimeEnvPath: '/resolved/void/runtime/env.mjs', + projectRoot: '/project', + homeDir: '/Users/test', + webSocketRuntimePath: '/resolved/void/runtime/ws-server.mjs', + reactRefresh: false, + auth: null, + }; + + const pagesOptions = { + pagesDir: '/pages', + pagesDirRelative: 'pages', + protocolPath: '/resolved/void/pages-protocol.mjs', + headPath: '/resolved/void/pages-head.mjs', + clientEntryId: 'virtual:void-pages-client', + }; + + const emptyScan: ScanResult = { + routes: [], + middleware: [], + jobs: [], + queues: [], + pages: { pages: [], layouts: [], namedLayouts: [] }, + }; + + /** An API-only app: routes, but nothing that can ever be prerendered. */ + const apiOnlyScan: ScanResult = { + ...emptyScan, + routes: [ + { + pattern: '/api/newsletter', + methods: ['POST'], + params: [], + catchAll: false, + env: null, + filePath: 'api/newsletter.ts', + }, + ], + }; + + const prerenderablePage = { + componentId: 'pages/about.vue', + componentPath: '/pages/about.vue', + serverPath: null, + pattern: '/about', + params: [], + catchAll: false, + methods: [], + ssrMode: 'auto' as const, + prerenderMode: 'auto' as const, + renderMode: 'server' as const, + shouldPrerender: true, + }; + + function collectorBody(code: string): string { + const marker = 'export async function __voidCollectPrerenderPaths'; + const start = code.indexOf(marker); + expect(start).toBeGreaterThanOrEqual(0); + const end = code.indexOf('\n}\n', start); + expect(end).toBeGreaterThan(start); + return code.slice(start, end); + } + + function compile( + scan: ScanResult, + ssr: { serverEntryPath: string; clientEntryRelativePath: string } | null, + explicitPrerenderPaths?: Array, + withPages = false, + ): string { + return compileRouteTable( + scan, + '/routes', + '/middleware', + '/crons', + '/queues', + ssr, + { ...testOptions, explicitPrerenderPaths }, + withPages ? pagesOptions : null, + ); + } + + it('emits no push at all with no pages, no SSR entry and no explicit paths', () => { + expect(collectorBody(compile(apiOnlyScan, null))).not.toContain('paths.push('); + }); + + it('emits a push for a prerenderable page', () => { + const body = collectorBody( + compile( + { ...emptyScan, pages: { pages: [prerenderablePage], layouts: [], namedLayouts: [] } }, + null, + undefined, + true, + ), + ); + expect(body).toContain('paths.push("/about")'); + }); + + it('emits a push for the custom SSR entry getPrerenderPaths()', () => { + const body = collectorBody( + compile(apiOnlyScan, { + serverEntryPath: '/project/src/main.ssr.ts', + clientEntryRelativePath: 'src/main.client.ts', + }), + ); + expect(body).toContain('mod.getPrerenderPaths'); + expect(body).toContain('paths.push(path)'); + }); + + it('emits a push for each routing.prerender path', () => { + const body = collectorBody(compile(apiOnlyScan, null, ['/', '/pricing'])); + expect(body).toContain('paths.push("/")'); + expect(body).toContain('paths.push("/pricing")'); + }); + + // Routes and middleware are NOT prerender sources — an app can be full of them + // and still have nothing to collect. + it('routes and middleware alone still emit no push', () => { + const body = collectorBody( + compile({ ...apiOnlyScan, middleware: [{ order: 1, filePath: '01.logger.ts' }] }, null), + ); + expect(body).not.toContain('paths.push('); + }); +}); diff --git a/packages/void/test/unit/deploy-project.test.ts b/packages/void/test/unit/deploy-project.test.ts index b43eac9eb..373a7b3ff 100644 --- a/packages/void/test/unit/deploy-project.test.ts +++ b/packages/void/test/unit/deploy-project.test.ts @@ -10,11 +10,16 @@ import { resolveDeployWorkerMain, resolveDistDir, resolveDeployWranglerCompat, + resolveFullDeployBuildCommand, resolveStaticDeployPreset, resolveStaticBuildCommand, resolveWorkerDirName, } from '../../src/cli/deploy.ts'; -import { FRAMEWORK_PRESETS } from '../../src/cli/preset.ts'; +import { + formatProjectCommand, + resolveProjectCommand, + FRAMEWORK_PRESETS, +} from '../../src/cli/preset.ts'; import { getRequestedProjectSlug, inferDefaultSlug, @@ -416,6 +421,54 @@ describe('resolveStaticBuildCommand', () => { }); }); +// The FULL (Class A / Void app) deploy used to hardcode `vite build`, ignoring +// `inference.build`. That made "two builds, one command" impossible: an SSG that +// emits the site first and then lets Void's own build package it (via +// `publicDir`) alongside the worker had no way to say so, and a repo with no +// root `index.html` died on `[UNRESOLVED_ENTRY] Cannot resolve entry module +// index.html`. The static and framework paths already honored the override. +describe('resolveFullDeployBuildCommand', () => { + const root = '/tmp/void-full-deploy-build-cmd'; + + it('uses inference.build verbatim when set', () => { + expect(resolveFullDeployBuildCommand(root, 'vitepress build && vite build')).toEqual({ + label: 'vitepress build && vite build', + command: 'vitepress build && vite build', + }); + }); + + it('prints exactly what it runs for a configured command', () => { + // No `formatProjectCommand`/`resolveProjectCommand` rewriting on the + // override path — the user's text is both shown and executed, so a shell + // chain like `a && b` cannot be mangled into an unrunnable single command. + const { label, command } = resolveFullDeployBuildCommand(root, 'pnpm run build:site'); + expect(label).toBe(command); + }); + + it('falls back to the built-in vite build when inference.build is unset', () => { + expect(resolveFullDeployBuildCommand(root)).toEqual({ + label: formatProjectCommand(root, 'vite build'), + command: resolveProjectCommand(root, 'vite build'), + }); + }); + + it('keeps the fallback label/command distinction (display vs. local bin)', () => { + // `formatProjectCommand` is the user-facing form (`vite` → `vp`, no absolute + // path); `resolveProjectCommand` expands to node_modules/.bin. Collapsing + // them would either print an absolute path or execute an unresolvable bin. + const { label, command } = resolveFullDeployBuildCommand(root); + expect(label).toBe(formatProjectCommand(root, 'vite build')); + expect(command).toBe(resolveProjectCommand(root, 'vite build')); + }); + + it('treats an empty inference.build as unset', () => { + expect(resolveFullDeployBuildCommand(root, '')).toEqual({ + label: formatProjectCommand(root, 'vite build'), + command: resolveProjectCommand(root, 'vite build'), + }); + }); +}); + describe('resolveStaticDeployPreset', () => { afterEach(() => { while (tempDirs.length > 0) { diff --git a/packages/void/test/unit/git-metadata.test.ts b/packages/void/test/unit/git-metadata.test.ts index dc67f5835..84cf5609a 100644 --- a/packages/void/test/unit/git-metadata.test.ts +++ b/packages/void/test/unit/git-metadata.test.ts @@ -1,3 +1,6 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'pathslash'; import { describe, expect, it } from 'vite-plus/test'; import { buildCommitUrl, @@ -30,6 +33,49 @@ describe('git deploy metadata', () => { ); }); + // The two git children here run right beside `getGitCommit`, which has + // scrubbed the CF Access service-token pair since it was written. These + // inherited `process.env` verbatim instead — `execFileSync` with no `env` — + // so the pair reached any repo-configured hook or credential helper they + // triggered. `childEnv` is what `void deploy` scrubs. + it.skipIf(process.platform === 'win32')('runs the git children under childEnv', () => { + const dir = mkdtempSync(join(tmpdir(), 'void-git-meta-')); + const saved = process.env.CF_ACCESS_CLIENT_SECRET; + try { + mkdirSync(join(dir, 'bin'), { recursive: true }); + const shim = join(dir, 'bin', 'git'); + // Reports back whatever the CHILD's env holds, so an inherited secret is + // visible in the return value instead of having to be inferred. + writeFileSync(shim, '#!/bin/sh\necho "seen=${CF_ACCESS_CLIENT_SECRET:-none}"\n'); + chmodSync(shim, 0o755); + process.env.CF_ACCESS_CLIENT_SECRET = 'svc-secret.access'; + + const scrubbed = collectGitDeployMetadata(dir, null, {}, { PATH: join(dir, 'bin') }); + expect(scrubbed.gitRef).toBe('seen=none'); + + // Control: the same shim DOES see it when the child env carries it, so + // the assertion above is about the env we handed over, not about the + // shim failing to run. + const leaked = collectGitDeployMetadata( + dir, + null, + {}, + { + PATH: join(dir, 'bin'), + CF_ACCESS_CLIENT_SECRET: 'svc-secret.access', + }, + ); + expect(leaked.gitRef).toBe('seen=svc-secret.access'); + } finally { + if (saved === undefined) { + delete process.env.CF_ACCESS_CLIENT_SECRET; + } else { + process.env.CF_ACCESS_CLIENT_SECRET = saved; + } + rmSync(dir, { recursive: true, force: true }); + } + }); + it('uses GitHub Actions metadata when available', () => { expect( collectGitDeployMetadata('/does/not/exist', 'abc123', { diff --git a/packages/void/test/unit/package.test.ts b/packages/void/test/unit/package.test.ts index 0bb835bcf..19829e9b6 100644 --- a/packages/void/test/unit/package.test.ts +++ b/packages/void/test/unit/package.test.ts @@ -3,6 +3,7 @@ import { hash as blake3hash } from 'blake3-jit'; import { join } from 'pathslash'; import { afterEach, beforeEach, describe, expect, it } from 'vite-plus/test'; import { + buildStaticManifest, buildVoidManifest, computeAssetHash, collectAndHashAssets, @@ -250,6 +251,85 @@ describe('resolveSpaFallbackChain', () => { expect(result.assetConfig).toEqual({ not_found_handling: 'none' }); expect(result.fallbackRules).toBeUndefined(); }); + + // `routing.notFound` (void.json) is appType-independent — the worker path + // already honors it via `resolveAssetRoutingPolicy`. `detectPreset` + // classifies any Vite project with no backend files as `spa`, so a plain + // Vite MPA lands on `appType: 'spa'` and this override is its only way to + // get a real 404 instead of the SPA shell with HTTP 200. + it('honors an explicit notFound over the appType-inferred handling (SPA)', () => { + expect(resolveSpaFallbackChain('spa', undefined, '404-page').assetConfig).toEqual({ + not_found_handling: '404-page', + }); + expect(resolveSpaFallbackChain('spa', undefined, 'none').assetConfig).toEqual({ + not_found_handling: 'none', + }); + }); + + it('does not synthesise the SPA catch-all when notFound overrides away from SPA', () => { + // Applying the override AFTER the SPA branch would leave the synthetic + // `/* -> /index.html` rule in place, so the SPA shell would still be + // served (via a rule instead of the platform switch) and the override + // would be a no-op. + const userRules = [{ source: '/docs/*', destination: '/docs.html', status: 200, force: false }]; + const result = resolveSpaFallbackChain('spa', userRules, '404-page'); + expect(result.assetConfig).toEqual({ not_found_handling: '404-page' }); + expect(result.fallbackRules).toEqual(userRules); + }); + + it('takes the SPA branch when notFound explicitly asks for single-page-application', () => { + const userRules = [{ source: '/docs/*', destination: '/docs.html', status: 200, force: false }]; + const result = resolveSpaFallbackChain('static', userRules, 'single-page-application'); + expect(result.assetConfig).toEqual({ not_found_handling: 'none' }); + expect(result.fallbackRules).toEqual([ + ...userRules, + { + source: '/*', + destination: '/index.html', + status: 200, + force: false, + origin: 'spa-default', + }, + ]); + }); + + it('falls back to the appType-inferred handling when notFound is undefined', () => { + expect(resolveSpaFallbackChain('static', undefined, undefined).assetConfig).toEqual({ + not_found_handling: '404-page', + }); + expect(resolveSpaFallbackChain('spa', undefined, undefined).assetConfig).toEqual({ + not_found_handling: 'single-page-application', + }); + }); +}); + +describe('buildStaticManifest', () => { + it('infers not_found_handling from appType when notFound is unset', () => { + expect(buildStaticManifest({ appType: 'static' }).assetConfig).toEqual({ + not_found_handling: '404-page', + }); + expect(buildStaticManifest({ appType: 'spa' }).assetConfig).toEqual({ + not_found_handling: 'single-page-application', + }); + }); + + it('threads routing.notFound into manifest.assetConfig', () => { + const manifest = buildStaticManifest({ appType: 'spa', notFound: '404-page' }); + expect(manifest.type).toBe('spa'); + expect(manifest.assetConfig).toEqual({ not_found_handling: '404-page' }); + }); + + it('ships only the user fallbacks when notFound overrides the SPA default', () => { + const manifest = buildStaticManifest({ + appType: 'spa', + notFound: '404-page', + fallbackRules: [{ source: '/docs/*', destination: '/docs.html', status: 200, force: false }], + }); + expect(manifest.assetConfig).toEqual({ not_found_handling: '404-page' }); + expect(manifest.fallbackRules).toEqual([ + { source: '/docs/*', destination: '/docs.html', status: 200 }, + ]); + }); }); describe('computeAssetHash', () => { 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 529d7c219..8454d6922 100644 --- a/packages/void/test/unit/plugin-class-a-wrapper.test.ts +++ b/packages/void/test/unit/plugin-class-a-wrapper.test.ts @@ -16,7 +16,7 @@ vi.mock('@cloudflare/vite-plugin', () => ({ const roots: Array = []; -function createTanStackRoot(): string { +function createTanStackRoot(voidConfig?: Record): string { const root = mkdtempSync(join(tmpdir(), 'void-class-a-wrapper-')); roots.push(root); writeFileSync( @@ -30,11 +30,35 @@ function createTanStackRoot(): string { ); writeFileSync( join(root, 'void.json'), - JSON.stringify({ worker: { compatibility_date: '2026-02-24' } }), + JSON.stringify({ worker: { compatibility_date: '2026-02-24' }, ...voidConfig }), ); 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; @@ -77,5 +101,99 @@ describe('Class A framework build wrapper', () => { expect(code).toContain('request.method !== "GET" && request.method !== "HEAD"'); expect(code).toContain('"public, max-age=31536000, immutable"'); expect(code).toContain('"/static/"'); + // No `routing.notFound` → the pre-existing "hand the framework's own 404 + // back" behavior. + expect(code).not.toContain('asset.headers.get("content-type")'); + }); + + // A Class A app deploys through `runFullDeploy`, which DOES honor + // `routing.notFound` when it builds the wrangler asset config. This wrapper is + // the code that then sits in front of the asset binding, so it has to agree — + // otherwise it fetches the generator's `404.html` and throws it away. + it('honors routing.notFound: 404-page in the generated wrapper', async () => { + const root = createTanStackRoot({ routing: { notFound: '404-page' } }); + vi.spyOn(process, 'cwd').mockReturnValue(root); + + const { voidPlugin } = await import('../../src/index.ts'); + const plugins = voidPlugin(); + const wrapperPlugin = plugins.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); + + const code = readFileSync(join(root, '.void', 'tanstack-start-trigger-wrapper.ts'), 'utf-8'); + expect(code).toContain('asset.headers.get("content-type")'); + expect(code).toContain('new Response(asset.body, asset)'); + }); +}); + +// 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); + vi.spyOn(process, 'cwd').mockReturnValue(root); + const { voidPlugin } = await import('../../src/index.ts'); + return voidPlugin(); + } + + function wrapperOf(plugins: Array): Plugin { + const plugin = plugins.find((p) => p.name === 'void:framework-build-wrapper'); + if (!plugin) { + throw new Error('Expected Class A wrapper plugin.'); + } + return plugin; + } + + it('writes routing.notFound into the built worker asset config', async () => { + const plugins = await loadPlugins({ routing: { notFound: '404-page' } }); + callConfig(wrapperOf(plugins), 'build'); + + const merged = mergeWorkerConfig(plugins); + expect(merged.assets).toEqual({ not_found_handling: '404-page' }); + }); + + it('invents no asset policy when routing.notFound is unset', async () => { + const plugins = await loadPlugins(); + callConfig(wrapperOf(plugins), 'build'); + + expect(mergeWorkerConfig(plugins).assets).toBeUndefined(); + }); + + it('leaves the dev asset router alone', async () => { + const plugins = await loadPlugins({ routing: { notFound: '404-page' } }); + callConfig(wrapperOf(plugins), 'serve'); + + expect(mergeWorkerConfig(plugins).assets).toBeUndefined(); + }); + + // 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'); + + 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/*'], + }); }); }); diff --git a/packages/void/test/unit/preset.test.ts b/packages/void/test/unit/preset.test.ts index fa9caec6d..fe148d789 100644 --- a/packages/void/test/unit/preset.test.ts +++ b/packages/void/test/unit/preset.test.ts @@ -4,7 +4,9 @@ import { join, resolve } from 'pathslash'; import { describe, expect, it, beforeEach, afterEach } from 'vite-plus/test'; import { detectPreset, + findBackendSources, formatProjectCommand, + hasBackendFiles, resolveProjectCommand, resolveWranglerArgv, resolveWranglerCommand, @@ -216,6 +218,117 @@ describe('detectPreset', () => { }); }); +// SSG detection (step 2) runs BEFORE the `hasBackendFiles` check (step 3), so an +// SSG repo that also has `routes/` / `middleware/` / `crons/` / `queues/` / +// `pages/` / an SSR entry returns a pure static preset and the backend is +// dropped with no diagnostic at all. `strictBackend` makes the ambiguous case +// loud — but only on the UNCONFIGURED auto-detect path, because `--dir` and a +// configured `inference.appType` are the user stating their intent. +describe('detectPreset — strictBackend', () => { + const vitepressPkg = { devDependencies: { vitepress: '^1.0.0' } }; + + it('throws when an SSG project also has routes/', () => { + const root = setupProject({ pkg: vitepressPkg, dirs: ['.vitepress', 'routes'] }); + expect(() => detectPreset(root, { strictBackend: true })).toThrow('vitepress'); + }); + + it('names the backend directories it found', () => { + const root = setupProject({ + pkg: vitepressPkg, + dirs: ['.vitepress', 'routes', 'middleware', 'crons'], + }); + let message = ''; + try { + detectPreset(root, { strictBackend: true }); + } catch (err) { + message = err instanceof Error ? err.message : String(err); + } + expect(message).toContain('routes/'); + expect(message).toContain('middleware/'); + expect(message).toContain('crons/'); + // ...and tells the user both ways out, so the error is actionable. + expect(message).toContain('"appType": "static"'); + expect(message).toContain('"appType": "void"'); + expect(message).toContain('"build"'); + }); + + it('detects an SSR entry as a backend source too', () => { + const root = setupProject({ + pkg: vitepressPkg, + dirs: ['.vitepress'], + files: { 'src/main.ssr.ts': 'export default {};' }, + }); + expect(() => detectPreset(root, { strictBackend: true })).toThrow('main.ssr.ts'); + }); + + it('does NOT throw for an SSG project with no backend', () => { + const root = setupProject({ pkg: vitepressPkg, dirs: ['.vitepress'] }); + expect(detectPreset(root, { strictBackend: true })).toEqual({ + buildCommand: 'vitepress build', + outputDir: resolve(root, '.vitepress/dist'), + appType: 'static', + }); + }); + + it('does NOT throw without the flag (auto-detect is opt-in)', () => { + const root = setupProject({ pkg: vitepressPkg, dirs: ['.vitepress', 'routes'] }); + expect(detectPreset(root)).toEqual({ + buildCommand: 'vitepress build', + outputDir: resolve(root, '.vitepress/dist'), + appType: 'static', + }); + }); + + it('does NOT throw for an explicit --dir (the user said what they want)', () => { + const root = setupProject({ pkg: vitepressPkg, dirs: ['.vitepress', 'routes'] }); + // `--dir` short-circuits at step 1, before SSG detection is even reached — + // and `resolveStaticDeployPreset` never passes strictBackend on that path. + expect(detectPreset(root, { dir: '.vitepress/dist', strictBackend: true })).toEqual({ + buildCommand: null, + outputDir: resolve(root, '.vitepress/dist'), + appType: 'static', + }); + }); + + it('does NOT throw when a non-SSG project has backend files', () => { + // Step 3 already returns null for these; the guard must not change that. + const root = setupProject({ + pkg: { dependencies: { vite: '^6.0.0' } }, + dirs: ['routes'], + }); + expect(detectPreset(root, { strictBackend: true })).toBeNull(); + }); +}); + +describe('findBackendSources', () => { + it('lists every backend source relative to the root', () => { + const root = setupProject({ + dirs: ['routes', 'pages', 'middleware', 'crons', 'queues'], + files: { 'src/main.ssr.tsx': 'export default {};' }, + }); + expect(findBackendSources(root)).toEqual([ + 'routes/', + 'pages/', + 'middleware/', + 'crons/', + 'queues/', + 'src/main.ssr.tsx', + ]); + }); + + it('is empty for a project with no backend, and agrees with hasBackendFiles', () => { + const root = setupProject({ pkg: { devDependencies: { vitepress: '^1.0.0' } } }); + expect(findBackendSources(root)).toEqual([]); + expect(hasBackendFiles(root)).toBe(false); + }); + + it('agrees with hasBackendFiles when a backend exists', () => { + const root = setupProject({ dirs: ['queues'] }); + expect(findBackendSources(root)).toEqual(['queues/']); + expect(hasBackendFiles(root)).toBe(true); + }); +}); + describe('project Vite commands', () => { it('formats Vite commands with vp when Vite+ is installed', () => { const root = setupProject({