Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<persist-root>/v3/d1/miniflare-D1DatabaseObject/<hash>.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 <url>` 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.
Expand Down
57 changes: 41 additions & 16 deletions packages/void/src/plugin-framework-triggers.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -562,7 +562,7 @@ function astroMiddlewareClaims(): Map<string, AstroMiddlewareClaim> {

/**
* 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);
Expand All @@ -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<typeof readRootWranglerConfig>;
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;
}

/**
Expand All @@ -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
Expand All @@ -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;
Expand Down
73 changes: 54 additions & 19 deletions packages/void/src/plugin-framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -373,28 +379,53 @@ 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);
},
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)};`]
: []),
Expand All @@ -404,19 +435,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}
`;
},
},
Expand Down
44 changes: 33 additions & 11 deletions packages/void/test/integration/astro.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Env>;
`;

// 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' },
Expand Down Expand Up @@ -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'),
Expand Down
Loading