From 5a26cb148bc69679a88a270f207ffb278d5b2b1d Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Sat, 28 Nov 2026 15:26:17 +0900 Subject: [PATCH 1/2] fix(astro): apply the request scope and dev triggers to entries that call handle() An Astro app with a Worker entry of its own hands requests to Astro with `handle()` from `@astrojs/cloudflare/handler`: the entry that Astro's adapter guide shows. Void wraps only the adapter's server entry, so such an app ran without the wrapper: - With PostgreSQL or MySQL, a request ran outside Void's request scope and void/db opened a connection for every query: four for a request with four queries, where the adapter's own entry opens one. `astro dev` and the built Worker both did this, without a warning. - In dev, next to the app's own middleware, `/__void/scheduled` and `/__void/queue` were not answered: the request went on to Astro, which returned 404. #434 listed this as a known limit and warned about it. The plugin that wraps the server entry now also resolves `@astrojs/cloudflare/handler` to a module that wraps `handle()` the same way. The server entry imports `handle` by a relative path, which the plugin does not see, so each request is still wrapped once. An entry that reaches Astro another way, such as `cf()` from `@astrojs/cloudflare/fetch`, still skips the wrapper. The dev warning for an app with its own middleware and its own entry now says which two calls work, and appears only when the entry's source names neither module. astro.test.ts runs its PostgreSQL tests with both entries, so its shard estimate goes up. Co-Authored-By: Claude Fable 5.2 --- packages/void/AGENTS.md | 2 +- .../void/src/plugin-framework-triggers.ts | 57 +++++--- packages/void/src/plugin-framework.ts | 55 +++++--- packages/void/test/integration/astro.test.ts | 44 +++++-- .../plugin-vite-environment.test.ts | 122 ++++++++++++------ .../unit/plugin-framework-triggers.test.ts | 38 +++++- test/integration-timings.ts | 2 +- 7 files changed, 223 insertions(+), 97 deletions(-) diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 2df952b68..ac23e335b 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -140,7 +140,7 @@ generated entries must preserve the module-boundary rules below. - **Local D1 identity**: `local-d1.ts` selects the configured D1 binding from root JSON/JSONC config, preferring `preview_database_id` over `database_id` for local development. Development, schema checks, auth migrations, and every local database command use this same identity and persistence directory. `voidPlugin({ persistTo })` records its canonical path in `.void/local-d1.json`; CLI commands reread binding IDs and reject stale Vite-config state until `void dev` refreshes it. - **D1 read replication**: preserve all three `database.readReplication` states through native and hosted deployment. True enables replication, false disables it, and omitted skips replication configuration (new databases default to off). Native deploy reconciles either explicit boolean on already-provisioned databases too. - **Migration DB path**: Miniflare stores D1 data at a deterministic path computed from the `database_id` using HMAC-SHA256. The `getMiniflareDatabasePath()` function in `migrations/runner.ts` replicates this algorithm so migrations target `/v3/d1/miniflare-D1DatabaseObject/.sqlite` (for example `.void/v3/...` in default/class-A mode and `.wrangler/state/v3/...` in class-B/C framework mode). -- **Drizzle-first database**: Schema is defined in `db/schema.ts` (Drizzle table definitions). `void/db` exports a dialect-aware Drizzle instance for D1, PostgreSQL, or MySQL. `@schema` is an auto-configured alias for `db/schema.ts`. Migrations live in `db/migrations/`. CLI commands: `void db push` (prototype), `void db generate` (create migration files), `void db migrate` (apply locally). When auth is enabled, `void db generate` adds `.void/better-auth-schema.ts` to Drizzle Kit's schema inputs. Direct Cloudflare deploy applies PostgreSQL or MySQL migrations from the shell-provided production `DATABASE_URL`; PostgreSQL is transactional, while MySQL DDL is not. `drizzle-orm` and `drizzle-kit` ship with void. For PostgreSQL and MySQL, `void/db` is one drizzle instance whose client looks up the current request's pool on every call. workerd ties a socket to the request that opened it, so a query built or prepared at module scope must run on the pool of the request that executes it, and building one must not create a pool (global scope has no request to own it). mysql2 starts its idle timer only when it builds a pool with `maxIdle` below `connectionLimit`, and that timer runs until the pool ends, so the MySQL pools set neither: each connection closes from its pool `release` event after 1 second idle (60 seconds for `createDb`). Inside a request, reading `db` builds that request's pool first, so a missing connection string throws its own error rather than drizzle's "Failed query". The client answers drizzle's pool checks (`instanceof Pool`, `'getConnection' in`) through `getPrototypeOf` and `has`, cached per isolate, so a transaction still holds one connection. Astro's adapter entry runs inside `withRuntimeEnv` for these dialects, like the Class A wrapper. +- **Drizzle-first database**: Schema is defined in `db/schema.ts` (Drizzle table definitions). `void/db` exports a dialect-aware Drizzle instance for D1, PostgreSQL, or MySQL. `@schema` is an auto-configured alias for `db/schema.ts`. Migrations live in `db/migrations/`. CLI commands: `void db push` (prototype), `void db generate` (create migration files), `void db migrate` (apply locally). When auth is enabled, `void db generate` adds `.void/better-auth-schema.ts` to Drizzle Kit's schema inputs. Direct Cloudflare deploy applies PostgreSQL or MySQL migrations from the shell-provided production `DATABASE_URL`; PostgreSQL is transactional, while MySQL DDL is not. `drizzle-orm` and `drizzle-kit` ship with void. For PostgreSQL and MySQL, `void/db` is one drizzle instance whose client looks up the current request's pool on every call. workerd ties a socket to the request that opened it, so a query built or prepared at module scope must run on the pool of the request that executes it, and building one must not create a pool (global scope has no request to own it). mysql2 starts its idle timer only when it builds a pool with `maxIdle` below `connectionLimit`, and that timer runs until the pool ends, so the MySQL pools set neither: each connection closes from its pool `release` event after 1 second idle (60 seconds for `createDb`). Inside a request, reading `db` builds that request's pool first, so a missing connection string throws its own error rather than drizzle's "Failed query". The client answers drizzle's pool checks (`instanceof Pool`, `'getConnection' in`) through `getPrototypeOf` and `has`, cached per isolate, so a transaction still holds one connection. Astro's adapter entry runs inside `withRuntimeEnv` for these dialects, like the Class A wrapper, and so does the adapter's `handle()`, which an app's own Worker entry calls: Void wraps both `@astrojs/cloudflare/entrypoints/server` and `@astrojs/cloudflare/handler`. An entry that reaches Astro another way (`cf()` from `@astrojs/cloudflare/fetch`) runs without the wrapper. - **Database provisioning adapters**: `void db connect ` saves an external database URL to `.env` and syncs a linked Void project; `--local-only` skips the sync. `void db connect --provider neon` provisions through the built-in Neon adapter using `NEON_API_KEY`. Third-party packages or local modules can export a `DatabaseProviderAdapter` built with `void/database-provider`; runtime database code remains provider-neutral. - **Environment model**: `env.ts` is the checked-in schema; root `.env` is the only dotenv file and is local-only. Production server keys use the remote secret store, while fixed-prefix `VITE_*` keys are public build-time values. The server runtime reads the same embedded public values for boot validation and SSR. Client folding must observe the final shared `config.env`; Vite runs `configResolved` hooks concurrently. Never add `.env.*` precedence, `.secret()`/`.public()` modifiers, or plaintext Worker vars for schema-declared server keys. - **Framework env schema**: `env` has no schema in a Worker whose own modules have not loaded `env.ts`, whatever the Vite plugin loaded in its process, so it returns raw values. The Class A wrapper (TanStack Start, React Router, vinext) imports `env.ts` ahead of the framework entry and awaits `_prepareEnv(env)` on every request, in dev and build. Unlike `_validateEnvOnce`, it never rejects: a read of a key that failed throws that key's error, async validators included, so requests that do not read it and a build-time prerender without production secrets still run. Both keep one result per key, reuse a validation for the same raw values, and keep the results with the env object they received. Reads through another object (the `cloudflare:workers` env that a D1 app's framework reads outside a request scope, the remote dev copy) get the latest validation's result while they hold the raw value it came from; never copy results to that object, which can come to hold other values. A validation in which a validator threw serves its reads but runs again on the next call. Results live on the process-global registry because `void deploy` bundles cron and queue jobs apart from the app, with a copy of `void/env` of their own: the jobs call `registry.prepare`, the `_prepareEnv` of the copy that registered the schema (key in `shared/env-registry.ts`). SvelteKit, Nuxt, Analog and Astro Workers do not load `env.ts` yet. diff --git a/packages/void/src/plugin-framework-triggers.ts b/packages/void/src/plugin-framework-triggers.ts index e66f5ab12..81fdc7101 100644 --- a/packages/void/src/plugin-framework-triggers.ts +++ b/packages/void/src/plugin-framework-triggers.ts @@ -1,5 +1,5 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { dirname, join } from 'pathslash'; +import { dirname, join, resolve } from 'pathslash'; import { normalizePath } from 'vite'; import type { Plugin } from 'vite'; import { Buffer } from './cli/node-buffer.ts'; @@ -562,7 +562,7 @@ function astroMiddlewareClaims(): Map { /** * Whether the Astro app has middleware that Void did not write. Void cannot add its dev trigger - * middleware then, so the wrapper around Astro's Cloudflare server entry answers the triggers. + * middleware then, so the wrapper around the adapter's request handler answers the triggers. */ export function hasOwnAstroMiddleware(root: string): boolean { const middlewarePath = join(root, ASTRO_MIDDLEWARE_RELATIVE); @@ -573,18 +573,42 @@ export function hasOwnAstroMiddleware(root: string): boolean { return existsSync(join(root, 'src', 'middleware', 'index.ts')); } -/** The Worker entry from the app's Cloudflare config, unless it is Astro's server entry. */ -function customAstroWorkerEntry(root: string): string | undefined { - let main: unknown; +/** + * The adapter modules that Void's wrapper covers (`void:astro-server-entry`): the server entry, + * and the one whose `handle()` an app's own Worker entry calls. + */ +const ASTRO_WRAPPED_MODULES = [ + '@astrojs/cloudflare/entrypoints/server', + '@astrojs/cloudflare/handler', +]; + +/** + * The app's own Worker entry from its Cloudflare config, when its source names neither module + * that Void wraps, so its requests reach Astro another way. An entry that cannot be read counts + * too, and so does one that leaves the call to another module of the app. + */ +function unwrappedAstroWorkerEntry(root: string): string | undefined { + let rootConfig: ReturnType; try { - main = readRootWranglerConfig(root)?.config.main; + rootConfig = readRootWranglerConfig(root); } catch { return undefined; } - return typeof main === 'string' && - !/^@astrojs\/cloudflare\/entrypoints\/server(?:\.js)?$/.test(main) - ? main - : undefined; + const main = rootConfig?.config.main; + if ( + !rootConfig || + typeof main !== 'string' || + /^@astrojs\/cloudflare\/entrypoints\/server(?:\.js)?$/.test(main) + ) { + return undefined; + } + let source: string; + try { + source = readFileSync(resolve(dirname(rootConfig.configPath), main), 'utf8'); + } catch { + return main; + } + return ASTRO_WRAPPED_MODULES.some((name) => source.includes(name)) ? undefined : main; } /** @@ -595,8 +619,9 @@ function customAstroWorkerEntry(root: string): string | undefined { * * Astro middleware lives at a single discoverable entry, so if the user * already has `src/middleware.ts` we don't overwrite it. The wrapper around - * Astro's Cloudflare server entry answers the triggers then. A custom Worker - * entry can skip that server entry, so we warn when the app sets one. + * the adapter's request handler answers the triggers then, also for a custom + * Worker entry that calls `handle()`. An entry that reaches Astro another way + * skips the wrapper, so we warn about one. * * If we wrote the file we remove it when the last dev server using it closes, * so the user's source tree stays clean. `src/middleware.ts` belongs to the @@ -610,13 +635,13 @@ export function astroDevTriggerInjectPlugin(root: string): Plugin { /** Whether the dev server being set up now holds the middleware Void wrote. */ const ensureFile = (): boolean => { if (hasOwnAstroMiddleware(root)) { - const entry = customAstroWorkerEntry(root); + const entry = unwrappedAstroWorkerEntry(root); if (entry) { voidWarn( `Your Astro app has its own middleware and its own Worker entry (${entry}).\n` + - ' In dev, /__void/scheduled and /__void/queue do not work if this entry calls\n' + - ' handle() from @astrojs/cloudflare/handler. To use them, call fetch() on the\n' + - ' default export of @astrojs/cloudflare/entrypoints/server instead.', + ' In dev, /__void/scheduled and /__void/queue work only when this entry serves\n' + + ' requests with handle() from @astrojs/cloudflare/handler, or with fetch() on\n' + + ' the default export of @astrojs/cloudflare/entrypoints/server.', ); } return false; diff --git a/packages/void/src/plugin-framework.ts b/packages/void/src/plugin-framework.ts index 3d4af6c5b..344349029 100644 --- a/packages/void/src/plugin-framework.ts +++ b/packages/void/src/plugin-framework.ts @@ -49,6 +49,8 @@ const voidDir = toSlash(import.meta.dirname); const ASTRO_SERVER_ENTRY = '@astrojs/cloudflare/entrypoints/server'; const ASTRO_SCOPED_SERVER_ENTRY = '\0void:astro-server-entry'; +const ASTRO_HANDLER = '@astrojs/cloudflare/handler'; +const ASTRO_SCOPED_HANDLER = '\0void:astro-handler'; /** * A define value as Vite writes it into code (its handleDefineValue): a string is code, anything @@ -356,7 +358,11 @@ export function createFrameworkPlugins(input: { }, }; - // Astro's Cloudflare adapter owns the Worker entry. Void wraps its default entry: + // Astro's Cloudflare adapter owns the Worker entry. Void wraps the two modules through which an + // app reaches the adapter's request handler: the adapter's server entry, which is the default + // Worker entry, and `@astrojs/cloudflare/handler`, whose `handle()` an app's own Worker entry + // calls. The server entry imports `handle` by a relative path, which this plugin does not see, + // so each request is wrapped once. // - For PostgreSQL and MySQL, each request runs inside Void's request scope // (`withRuntimeEnv`), as the Class A wrapper does, so void/db keeps one client per request // instead of one per query. D1 apps run without it: inside a request scope, void/db reads D1 @@ -377,24 +383,31 @@ export function createFrameworkPlugins(input: { astroDevTriggers = resolvedConfig.command === 'serve' && hasOwnAstroMiddleware(root); }, resolveId: { - filter: { id: /^@astrojs\/cloudflare\/entrypoints\/server(?:\.js)?$/ }, - handler(_id, importer) { + filter: { id: /^@astrojs\/cloudflare\/(?:entrypoints\/server(?:\.js)?|handler)$/ }, + handler(id, importer) { + const scoped = + id === ASTRO_HANDLER ? ASTRO_SCOPED_HANDLER : ASTRO_SCOPED_SERVER_ENTRY; if ( (!scopeAstroRequests && !astroDevTriggers) || - importer === ASTRO_SCOPED_SERVER_ENTRY || + // The wrapper's own import of the module it wraps. + importer === scoped || this.environment?.name === 'client' ) { return; } - return ASTRO_SCOPED_SERVER_ENTRY; + return scoped; }, }, load: { // \0 prefix is Vite's virtual module convention - filter: { id: /^\0void:astro-server-entry$/ }, - handler() { + filter: { id: /^\0void:astro-(?:server-entry|handler)$/ }, + handler(id) { + const wrapsHandle = id === ASTRO_SCOPED_HANDLER; + const source = JSON.stringify(wrapsHandle ? ASTRO_HANDLER : ASTRO_SERVER_ENTRY); const imports = [ - `import original from ${JSON.stringify(ASTRO_SERVER_ENTRY)};`, + wrapsHandle + ? `import { handle as original } from ${source};` + : `import original from ${source};`, ...(scopeAstroRequests ? [`import { withRuntimeEnv } from ${JSON.stringify(envModuleFile)};`] : []), @@ -404,19 +417,23 @@ export function createFrameworkPlugins(input: { ] : []), ]; - const handle = astroDevTriggers - ? 'async () => (await handleDevTrigger(request, env, ctx)) ?? original.fetch(request, env, ctx)' - : '() => original.fetch(request, env, ctx)'; + const callOriginal = wrapsHandle + ? 'original(request, env, ctx)' + : 'original.fetch(request, env, ctx)'; + const respond = astroDevTriggers + ? `async () => (await handleDevTrigger(request, env, ctx)) ?? ${callOriginal}` + : `() => ${callOriginal}`; + const body = (indent: string): string => + `${indent}const respond = ${respond};\n` + + `${indent}return ${scopeAstroRequests ? 'withRuntimeEnv(env, respond)' : 'respond()'};`; + // The wrapper's own `handle` takes the place of the one that `export *` passes on. + const wrapped = wrapsHandle + ? `export function handle(request, env, ctx) {\n${body(' ')}\n}` + : `export default {\n ...original,\n fetch(request, env, ctx) {\n${body(' ')}\n },\n};`; return `${imports.join('\n')} -export * from ${JSON.stringify(ASTRO_SERVER_ENTRY)}; +export * from ${source}; -export default { - ...original, - fetch(request, env, ctx) { - const handle = ${handle}; - return ${scopeAstroRequests ? 'withRuntimeEnv(env, handle)' : 'handle()'}; - }, -}; +${wrapped} `; }, }, diff --git a/packages/void/test/integration/astro.test.ts b/packages/void/test/integration/astro.test.ts index 4cd6c2d9b..7d9853558 100644 --- a/packages/void/test/integration/astro.test.ts +++ b/packages/void/test/integration/astro.test.ts @@ -137,8 +137,23 @@ describe('playground/astro dev', () => { }); }); -// Astro owns its Worker entry; Void runs it in a request scope for PostgreSQL. -describe('playground/astro with PostgreSQL', () => { +// The entry that Astro's adapter guide shows for an app with a Worker entry of its own. +const OWN_WORKER_ENTRY = `import { handle } from '@astrojs/cloudflare/handler'; + +export default { + fetch(request, env, ctx) { + return handle(request, env, ctx); + }, +} satisfies ExportedHandler; +`; + +// Astro owns its Worker entry; Void runs it in a request scope for PostgreSQL. An app's own Worker +// entry reaches Astro through the adapter's handle(), which gets the same request scope and dev +// triggers. +describe.each([ + ["the adapter's Worker entry", undefined], + ['its own Worker entry that calls handle()', OWN_WORKER_ENTRY], +])('playground/astro with PostgreSQL and %s', (_entry, ownWorkerEntry) => { const USERS = [ { id: 1, name: 'Ada', email: 'ada@example.com' }, { id: 2, name: 'Linus', email: 'linus@example.com' }, @@ -221,15 +236,22 @@ export const onRequest = defineMiddleware((_context, next) => next()); playground = createIsolatedPlayground(ROOT, PLAYGROUND); const root = playground.root; const configPath = join(root, 'void.config.ts'); - writeFileSync( - configPath, - readFileSync(configPath, 'utf8') - .replace('defineConfig({', "defineConfig({\n database: 'pg',") - .replace( - "compatibility_flags: ['nodejs_als']", - "compatibility_flags: ['nodejs_compat', 'nodejs_als']", - ), - ); + let config = readFileSync(configPath, 'utf8') + .replace('defineConfig({', "defineConfig({\n database: 'pg',") + .replace( + "compatibility_flags: ['nodejs_als']", + "compatibility_flags: ['nodejs_compat', 'nodejs_als']", + ); + if (ownWorkerEntry) { + expect(config).toContain("name: 'playground-astro',"); + config = config.replace( + "name: 'playground-astro',", + "name: 'playground-astro',\n main: './src/worker.ts',", + ); + mkdirSync(join(root, 'src'), { recursive: true }); + writeFileSync(join(root, 'src/worker.ts'), ownWorkerEntry); + } + writeFileSync(configPath, config); rmSync(join(root, 'db/migrations'), { recursive: true, force: true }); writeFileSync( join(root, 'db/schema.ts'), diff --git a/packages/void/test/integration/plugin-vite-environment.test.ts b/packages/void/test/integration/plugin-vite-environment.test.ts index 31b45a54e..0e142b83e 100644 --- a/packages/void/test/integration/plugin-vite-environment.test.ts +++ b/packages/void/test/integration/plugin-vite-environment.test.ts @@ -1390,16 +1390,43 @@ describe('Astro preview', () => { describe('Astro server entry', () => { const entry = '@astrojs/cloudflare/entrypoints/server'; const scopedEntry = '\0void:astro-server-entry'; + // An app's own Worker entry calls handle() from this module. + const handler = '@astrojs/cloudflare/handler'; + const scopedHandler = '\0void:astro-handler'; const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; + type Respond = (request: Request, env: unknown, ctx: unknown) => Promise; type WrapperModule = { named: string; - default: { - marker: string; - fetch(request: Request, env: unknown, ctx: unknown): Promise; - }; + default?: { marker: string; fetch: Respond }; + handle: Respond; }; + // The adapter modules that Void wraps, each with the id of its wrapper and the function of the + // wrapper that answers a request. + const wrapped = [ + { + name: 'the Cloudflare adapter entry', + source: entry, + scoped: scopedEntry, + respondWith: + (wrapper: WrapperModule): Respond => + (request, env, ctx) => + wrapper.default!.fetch(request, env, ctx), + }, + { + name: "the Cloudflare adapter's handle()", + source: handler, + scoped: scopedHandler, + respondWith: (wrapper: WrapperModule): Respond => wrapper.handle, + }, + ]; + + /** Each wrapped module with each database. */ + function casesFor(databases: ReadonlyArray) { + return wrapped.flatMap((module) => databases.map((database) => ({ ...module, database }))); + } + function createAstroRoot(database: 'pg' | 'mysql' | undefined): string { const root = realpathSync.native(createProjectRoot()); writeFileSync( @@ -1425,19 +1452,23 @@ describe('Astro server entry', () => { }); } - /** Import the wrapper with stand-ins for the adapter entry and the generated trigger dispatch. */ + /** + * Import a wrapper with stand-ins for the adapter module it wraps and the generated trigger + * dispatch. + */ async function importWrapper( root: string, code: string, adapter: string, dispatch: string, ): Promise { - writeFileSync(join(root, 'adapter-entry.mjs'), adapter); + writeFileSync(join(root, 'adapter-module.mjs'), adapter); writeFileSync(join(root, 'dispatch.mjs'), dispatch); writeFileSync( - join(root, 'entry.mjs'), + join(root, 'wrapper.mjs'), code - .replaceAll(JSON.stringify(entry), '"./adapter-entry.mjs"') + .replaceAll(JSON.stringify(entry), '"./adapter-module.mjs"') + .replaceAll(JSON.stringify(handler), '"./adapter-module.mjs"') .replace( /^import \{ withRuntimeEnv \} from .*;$/m, `import { withRuntimeEnv } from ${JSON.stringify(envUrl)};`, @@ -1447,7 +1478,7 @@ describe('Astro server entry', () => { 'import { handleDevTrigger } from "./dispatch.mjs";', ), ); - return (await import(pathToFileURL(join(root, 'entry.mjs')).href)) as WrapperModule; + return (await import(pathToFileURL(join(root, 'wrapper.mjs')).href)) as WrapperModule; } const loadedCode = (loaded: unknown): string => @@ -1469,7 +1500,7 @@ describe('Astro server entry', () => { ['pg', true], [undefined, true], ] as const)( - 'wraps the Cloudflare adapter entry in dev (database: %s, app middleware: %s)', + 'wraps the Cloudflare adapter entry and its handle() in dev (database: %s, app middleware: %s)', async (database, appMiddleware) => { const root = createAstroRoot(database); if (appMiddleware) { @@ -1480,13 +1511,19 @@ describe('Astro server entry', () => { const middleware = readFileSync(join(root, 'src/middleware.ts'), 'utf8'); expect(middleware.includes('Auto-generated by Void in dev')).toBe(!appMiddleware); const container = server.environments.ssr.pluginContainer; - const wrapped = database !== undefined || appMiddleware; - expect((await container.resolveId(entry))?.id === scopedEntry).toBe(wrapped); - if (wrapped) { - // The wrapper imports the adapter's own entry. - expect((await container.resolveId(entry, scopedEntry))?.id).not.toBe(scopedEntry); - const code = loadedCode(await container.load(scopedEntry)); - expect(code.includes('handleDevTrigger')).toBe(appMiddleware); + const isWrapped = database !== undefined || appMiddleware; + for (const { source, scoped } of wrapped) { + // The adapter's entry is the Worker entry; the app's own entry imports handle(). + const importer = source === handler ? join(root, 'src/worker.ts') : undefined; + expect((await container.resolveId(source, importer))?.id === scoped, source).toBe( + isWrapped, + ); + if (isWrapped) { + // The wrapper imports the adapter's own module. + expect((await container.resolveId(source, scoped))?.id, source).not.toBe(scoped); + const code = loadedCode(await container.load(scoped)); + expect(code.includes('handleDevTrigger'), source).toBe(appMiddleware); + } } } finally { await server.close(); @@ -1494,32 +1531,32 @@ describe('Astro server entry', () => { }, ); - it.each(['pg', 'mysql'] as const)( - 'runs the Cloudflare adapter entry in a Void request scope (database: %s)', - async (database) => { + it.each(casesFor(['pg', 'mysql'] as const))( + 'runs $name in a Void request scope (database: $database)', + async ({ scoped, respondWith, database }) => { const root = createAstroRoot(database); const server = await startDevServer(root); try { const container = server.environments.ssr.pluginContainer; const wrapper = await importWrapper( root, - loadedCode(await container.load(scopedEntry)), + loadedCode(await container.load(scoped)), `import { getRuntimeBinding, getRuntimeRequestResource } from ${JSON.stringify(envUrl)}; export const named = "kept"; -export default { - marker: "kept", - fetch(request, env, ctx) { - // Throws outside a request scope. - getRuntimeRequestResource({}, () => ({})); - return Response.json({ url: request.url, database: getRuntimeBinding("DATABASE_URL"), ctx }); - }, -}; +export function handle(request, env, ctx) { + // Throws outside a request scope. + getRuntimeRequestResource({}, () => ({})); + return Response.json({ url: request.url, database: getRuntimeBinding("DATABASE_URL"), ctx }); +} +export default { marker: "kept", fetch: handle }; `, 'export async function handleDevTrigger() {\n return null;\n}\n', ); - expect([wrapper.named, wrapper.default.marker]).toEqual(['kept', 'kept']); - const response = await wrapper.default.fetch( + // The module's other exports pass through, and so do the entry's other members. + expect(wrapper.named).toBe('kept'); + expect(wrapper.default?.marker).toBe(scoped === scopedEntry ? 'kept' : undefined); + const response = await respondWith(wrapper)( new Request('http://localhost/api'), { DATABASE_URL: 'postgres://request' }, { id: 'ctx' }, @@ -1537,15 +1574,15 @@ export default { // Void cannot add its middleware next to the app's own, so the wrapper answers the triggers. A // build never imports the dev-only dispatch. - it.each(['pg', undefined] as const)( - 'sends dev triggers to the generated dispatch before the adapter entry, only in dev (database: %s)', - async (database) => { + it.each(casesFor(['pg', undefined] as const))( + 'sends dev triggers to the generated dispatch before $name, only in dev (database: $database)', + async ({ source, scoped, respondWith, database }) => { const root = createAstroRoot(database); writeAppMiddleware(root); const server = await startDevServer(root); let code: string; try { - code = loadedCode(await server.environments.ssr.pluginContainer.load(scopedEntry)); + code = loadedCode(await server.environments.ssr.pluginContainer.load(scoped)); } finally { await server.close(); } @@ -1553,7 +1590,7 @@ export default { const wrapper = await importWrapper( root, code, - 'export default {\n fetch() {\n return new Response("astro");\n },\n};\n', + 'export function handle() {\n return new Response("astro");\n}\nexport default { fetch: handle };\n', `export async function handleDevTrigger(request, env, ctx) { const { pathname } = new URL(request.url); if (request.method !== "POST" || pathname !== "/__void/scheduled") return null; @@ -1561,7 +1598,8 @@ export default { } `, ); - const trigger = await wrapper.default.fetch( + const respond = respondWith(wrapper); + const trigger = await respond( new Request('http://localhost/__void/scheduled', { method: 'POST' }), { DB: 'binding' }, { id: 'ctx' }, @@ -1571,7 +1609,7 @@ export default { env: { DB: 'binding' }, ctx: { id: 'ctx' }, }); - const page = await wrapper.default.fetch(new Request('http://localhost/'), {}, {}); + const page = await respond(new Request('http://localhost/'), {}, {}); expect(await page.text()).toBe('astro'); const config = await resolveConfig( @@ -1587,12 +1625,12 @@ export default { source: string, importer: string | undefined, ) => unknown; - const resolved = await resolveId.call({ environment: { name: 'ssr' } }, entry, undefined); - // A D1 build keeps the adapter's own entry; a PostgreSQL build keeps only the request scope. - expect(resolved).toBe(database ? scopedEntry : undefined); + const resolved = await resolveId.call({ environment: { name: 'ssr' } }, source, undefined); + // A D1 build keeps the adapter's own module; a PostgreSQL build keeps only the request scope. + expect(resolved).toBe(database ? scoped : undefined); if (database) { const load = getHookHandler(plugin.load) as (id: string) => unknown; - const buildCode = loadedCode(await load(scopedEntry)); + const buildCode = loadedCode(await load(scoped)); expect(buildCode).toContain('withRuntimeEnv'); expect(buildCode).not.toContain('dev-triggers'); expect(buildCode).not.toContain('handleDevTrigger'); diff --git a/packages/void/test/unit/plugin-framework-triggers.test.ts b/packages/void/test/unit/plugin-framework-triggers.test.ts index fccd4b04b..9844fa92f 100644 --- a/packages/void/test/unit/plugin-framework-triggers.test.ts +++ b/packages/void/test/unit/plugin-framework-triggers.test.ts @@ -540,20 +540,43 @@ describe('astroDevTriggerInjectPlugin', () => { expect(code).toContain(`from "${frameworkTriggersDispatchPath(root)}"`); }); - // Next to the app's own middleware, the wrapper around Astro's server entry answers the - // triggers. A custom Worker entry can skip that server entry. + // Next to the app's own middleware, the wrapper around the adapter's request handler answers + // the triggers: its server entry, and handle(), which an app's own Worker entry calls. An entry + // that names neither reaches Astro another way. + const OWN_ENTRY = './src/worker.ts'; it.each([ - [undefined, false], - ['@astrojs/cloudflare/entrypoints/server', false], - ['./src/worker.ts', true], + ['no main', undefined, undefined, false], + ["the adapter's server entry", '@astrojs/cloudflare/entrypoints/server', undefined, false], + [ + 'an entry that calls handle()', + OWN_ENTRY, + "import { handle } from '@astrojs/cloudflare/handler';\n", + false, + ], + [ + "an entry that calls the server entry's fetch()", + OWN_ENTRY, + "import handler from '@astrojs/cloudflare/entrypoints/server';\n", + false, + ], + [ + 'an entry that runs Astro with cf()', + OWN_ENTRY, + "import { cf, finalize } from '@astrojs/cloudflare/fetch';\n", + true, + ], + ['an entry that cannot be read', OWN_ENTRY, undefined, true], ])( - 'skips an app with its own middleware and warns only for a custom Worker entry (main: %s)', - (main, warns) => { + 'skips an app with its own middleware and warns only for a Worker entry that skips the wrapper (main: %s)', + (_name, main, entry, warns) => { const root = createTempRoot(); mkdirSync(join(root, 'src'), { recursive: true }); const existing = '// user middleware\nexport const onRequest = () => {};\n'; writeFileSync(join(root, 'src', 'middleware.ts'), existing); writeFileSync(join(root, 'wrangler.jsonc'), JSON.stringify({ main })); + if (entry) { + writeFileSync(join(root, 'src', 'worker.ts'), entry); + } const log = vi.spyOn(console, 'log').mockImplementation(() => {}); callConfigureServer(astroDevTriggerInjectPlugin(root)); @@ -562,6 +585,7 @@ describe('astroDevTriggerInjectPlugin', () => { const output = log.mock.calls.map((call) => String(call[0])).join('\n'); if (warns) { expect(output).toContain('its own Worker entry (./src/worker.ts)'); + expect(output).toContain('handle() from @astrojs/cloudflare/handler'); expect(output).toContain('default export of @astrojs/cloudflare/entrypoints/server'); } else { expect(output).toBe(''); diff --git a/test/integration-timings.ts b/test/integration-timings.ts index 5fb8f49a4..3334c56de 100644 --- a/test/integration-timings.ts +++ b/test/integration-timings.ts @@ -11,7 +11,7 @@ export const integrationTimings: Readonly> = { 'packages/svelte/test/integration/svelte-pages-client.test.ts': 30_000, 'packages/void/test/e2e/cloudflare-deploy-live.test.ts': 6, 'packages/void/test/integration/analog.test.ts': 38_000, - 'packages/void/test/integration/astro.test.ts': 26_000, + 'packages/void/test/integration/astro.test.ts': 36_000, 'packages/void/test/integration/cli-help.test.ts': 1718, 'packages/void/test/integration/cli-runtime-check.test.ts': 900, 'packages/void/test/integration/cloudflare-deploy-build.test.ts': 6700, From dd0fde1ae9c77275c828b0ba7a62fe8a3ee8642c Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Sat, 28 Nov 2026 16:28:38 +0900 Subject: [PATCH 2/2] fix(astro): name handle()'s module for the dev dependency optimizer The wrapper that Void puts around `handle()` is a `\0` module, and Vite's dependency scan stops there: it never records `@astrojs/cloudflare/handler`, which the wrapper imports. The Worker's imports reveal it later, so on the first `astro dev` start of an app whose own entry is wrapped, the optimizer of the Worker environment ran a second time. Nothing reloaded, and later starts use the cache. Name the module in `optimizeDeps.include` of a Worker environment in dev, as the adapter names its server entry. The hook runs after the adapter's, which turns discovery off in the server that `astro build` and `astro sync` start to generate types. An include there would be prebundled for nothing, so that server is left alone. Co-Authored-By: Claude Fable 5.2 --- packages/void/src/plugin-framework.ts | 18 ++++++++++ .../plugin-vite-environment.test.ts | 33 ++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/packages/void/src/plugin-framework.ts b/packages/void/src/plugin-framework.ts index 344349029..d8ed32b5b 100644 --- a/packages/void/src/plugin-framework.ts +++ b/packages/void/src/plugin-framework.ts @@ -379,6 +379,24 @@ export function createFrameworkPlugins(input: { ? { name: 'void:astro-server-entry', enforce: 'pre', + // The dependency scan stops at a wrapper, a `\0` id, so it never records the module that + // the wrapper imports. The Worker's imports reveal it later, and the optimizer runs a + // second time on the first start. The adapter names its server entry for the optimizer; + // name `handle()`'s module as well. The hook runs after the adapter's, which turns + // discovery off in the server that `astro build` and `astro sync` start to generate + // types: an include would be prebundled there for nothing. + configEnvironment: { + order: 'post', + handler(_name, environment, { command }) { + if ( + command === 'serve' && + environment.resolve?.conditions?.includes('workerd') && + !environment.optimizeDeps?.noDiscovery + ) { + return { optimizeDeps: { include: [ASTRO_HANDLER] } }; + } + }, + }, configResolved(resolvedConfig) { astroDevTriggers = resolvedConfig.command === 'serve' && hasOwnAstroMiddleware(root); }, diff --git a/packages/void/test/integration/plugin-vite-environment.test.ts b/packages/void/test/integration/plugin-vite-environment.test.ts index 0e142b83e..2be24045d 100644 --- a/packages/void/test/integration/plugin-vite-environment.test.ts +++ b/packages/void/test/integration/plugin-vite-environment.test.ts @@ -13,7 +13,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { getWorkerBundleDir } from '@cloudflare/build-output-utils'; -import type { PluginOption } from 'vite'; +import type { Plugin, PluginOption } from 'vite'; import { createBuilder, createServer, normalizePath, resolveConfig } from 'vite'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { pagesPlugin as reactPagesPlugin } from '../../../react/src/plugin-pages.ts'; @@ -1637,4 +1637,35 @@ export default { marker: "kept", fetch: handle }; } }, ); + + // The dependency scan stops at the wrapper, so it cannot find the module that the wrapper + // imports. The stand-in configures the Worker environment as the adapter does, after Void's + // plugins: workerd conditions, and no discovery in the server that `astro build` and + // `astro sync` start to generate types. + it.each([ + ['serve', false, true], + ['serve', true, false], + ['build', false, false], + ] as const)( + "names handle()'s module for the dependency optimizer of a Worker environment that discovers dependencies (command: %s, discovery off: %s)", + async (command, noDiscovery, named) => { + const root = createAstroRoot(undefined); + const adapter: Plugin = { + name: 'adapter-stand-in', + config: () => ({ + environments: { ssr: { resolve: { conditions: ['workerd', 'worker'] } }, node: {} }, + }), + configEnvironment: (name) => + name === 'ssr' ? { optimizeDeps: { noDiscovery, include: [] } } : undefined, + }; + const config = await resolveConfig( + { root, configFile: false, logLevel: 'silent', plugins: [voidPlugin(), adapter] }, + command, + command === 'build' ? 'production' : 'development', + ); + expect(config.environments.ssr.optimizeDeps.include?.includes(handler)).toBe(named); + // An environment that does not run in workerd is left alone. + expect(config.environments.node.optimizeDeps.include ?? []).not.toContain(handler); + }, + ); });