From 24785a8d46557e94c94a75a06b93cd2280497e89 Mon Sep 17 00:00:00 2001 From: konaito <81353953+konaito@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:08:05 +0900 Subject: [PATCH 1/3] fix(dev): accept a D1 preview_database_id and use it locally A D1 binding with preview_database_id stopped the dev server and builds with "cf cannot migrate Cloudflare setting d1_databases.0". The cf converter reports the option as unsupported, and Void did not handle it. Deployments keep using database_id. The dev server now binds the preview ID, which local void db commands already use, so migrations and the app read the same local database. --- packages/void/src/cli/cf-config-migrate.ts | 29 +++++++++- packages/void/src/config.ts | 1 + packages/void/src/plugin-cloudflare-config.ts | 34 +++++++++++ packages/void/src/plugin-cloudflare.ts | 5 ++ .../void/test/unit/cf-config-migrate.test.ts | 24 ++++++++ .../unit/plugin-cloudflare-config.test.ts | 58 ++++++++++++++++++- 6 files changed, 148 insertions(+), 3 deletions(-) diff --git a/packages/void/src/cli/cf-config-migrate.ts b/packages/void/src/cli/cf-config-migrate.ts index 78f031027c..1e19d2ddbc 100644 --- a/packages/void/src/cli/cf-config-migrate.ts +++ b/packages/void/src/cli/cf-config-migrate.ts @@ -44,15 +44,40 @@ function normalizeQueueConcurrency(raw: JsonObject) { return result; } +/** + * A deployment uses `database_id`. Void selects the local D1 database, including a + * `preview_database_id`, itself (see `local-d1.ts` and `applyLocalD1PreviewIds()`). + */ +function withoutD1PreviewIds(raw: JsonObject) { + if (!Array.isArray(raw.d1_databases)) { + return raw; + } + return { + ...raw, + d1_databases: raw.d1_databases.map((value: unknown) => { + const database = record(value); + if (!database || !('preview_database_id' in database)) { + return value; + } + const { preview_database_id: _local, ...rest } = database; + return rest; + }), + }; +} + +function normalizeBindings(raw: JsonObject) { + return withoutD1PreviewIds(normalizeQueueConcurrency(raw)); +} + /** Remove build-only fields and settings translated into cf's typed config below. */ function migrationInput(raw: JsonObject): JsonObject { - const result = normalizeQueueConcurrency(raw); + const result = normalizeBindings(raw); const environments = record(result.env); if (environments) { result.env = Object.fromEntries( Object.entries(environments).map(([name, value]) => [ name, - record(value) ? normalizeQueueConcurrency(value as JsonObject) : value, + record(value) ? normalizeBindings(value as JsonObject) : value, ]), ); } diff --git a/packages/void/src/config.ts b/packages/void/src/config.ts index b1c5dcdfd6..6ff18a4958 100644 --- a/packages/void/src/config.ts +++ b/packages/void/src/config.ts @@ -143,6 +143,7 @@ export type CloudflareConfig = Record & { binding: string; database_name?: string; database_id?: string; + preview_database_id?: string; migrations_dir?: string; migrations_table?: string; }> diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index 8472275a4f..dc674b58ba 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -157,6 +157,40 @@ export function toNativeCloudflareConfig(raw: WorkerConfig, root: string): Cloud return { ...config, worker: config.worker }; } +/** + * Give the dev server the same local D1 database as `void db` commands. Like Wrangler, they + * use a binding's `preview_database_id` locally; the deployable config keeps `database_id`. + * The first settings that declare a binding decide its local ID, so a selected environment + * comes before the top-level settings. + */ +export function applyLocalD1PreviewIds( + worker: Pick, + settings: ReadonlyArray<{ d1_databases?: unknown } | undefined>, +): void { + const env = worker.env; + if (!env) { + return; + } + const declared = new Set(); + for (const databases of settings.map((item) => item?.d1_databases)) { + if (!Array.isArray(databases)) { + continue; + } + for (const database of databases as Array | null>) { + const name = database?.binding; + if (typeof name !== 'string' || declared.has(name)) { + continue; + } + declared.add(name); + const binding = env[name]; + const previewId = database?.preview_database_id; + if (binding?.type === 'd1' && typeof previewId === 'string' && previewId.length > 0) { + binding.id = previewId; + } + } + } +} + /** * Give Container Durable Objects a regular binding in the dev server. Their unsafe * binding from `migrateBuiltWranglerConfig()` exists only for the Worker upload, and diff --git a/packages/void/src/plugin-cloudflare.ts b/packages/void/src/plugin-cloudflare.ts index 6b672d4102..cff5616225 100644 --- a/packages/void/src/plugin-cloudflare.ts +++ b/packages/void/src/plugin-cloudflare.ts @@ -17,6 +17,7 @@ import { nativeAuxiliaryWorkers, restoreLocalContainerBindings, toNativeCloudflareConfig, + applyLocalD1PreviewIds, } from './plugin-cloudflare-config.ts'; import type { AuxiliaryWorkerConfig, @@ -82,6 +83,8 @@ export function cloudflare(options: { let base = ( options.configPath ? readGeneratedWranglerConfigFile(options.configPath) : {} ) as WorkerConfig; + // The translation below drops local-only D1 preview IDs. Keep the settings that have them. + const localD1Settings: Array<{ d1_databases?: unknown }> = []; if (process.env.CLOUDFLARE_ENV && base.env) { const selected = base.env[process.env.CLOUDFLARE_ENV]; if (!selected) { @@ -90,6 +93,7 @@ export function cloudflare(options: { ); } const original = base; + localD1Settings.push(selected, original); base = convertToWranglerConfig(toNativeCloudflareConfig(base, root)); base.main = selected.main ?? original.main; base.migrations = selected.migrations ?? original.migrations; @@ -112,6 +116,7 @@ export function cloudflare(options: { } } else if (environment.command === 'serve') { restoreLocalContainerBindings(pluginNative.worker); + applyLocalD1PreviewIds(pluginNative.worker, [...localD1Settings, workerConfig]); localQueueBindings = addLocalQueueProducers( pluginNative.worker, options.localQueueProducers, diff --git a/packages/void/test/unit/cf-config-migrate.test.ts b/packages/void/test/unit/cf-config-migrate.test.ts index 1b1da84c40..cd13a5ad61 100644 --- a/packages/void/test/unit/cf-config-migrate.test.ts +++ b/packages/void/test/unit/cf-config-migrate.test.ts @@ -68,6 +68,30 @@ it('rejects unresolved blocking follow-ups instead of silently dropping settings ).toThrow('cf cannot migrate Cloudflare setting config.routes.0'); }); +it.each([false, true])( + 'deploys a D1 binding with a preview ID under its database_id (named=%s)', + (named) => { + const d1_databases = [ + { + binding: 'DB', + database_name: 'app-db', + database_id: 'production-id', + preview_database_id: 'preview-id', + }, + ]; + const migrated = migrateBuiltWranglerConfig( + { + name: 'void-migrate-test', + compatibility_date: '2026-09-29', + ...(named ? { env: { staging: { d1_databases } } } : { d1_databases }), + }, + named ? 'staging' : 'production', + ); + + expect(migrated.worker?.env?.DB).toMatchObject({ type: 'd1', id: 'production-id' }); + }, +); + it.each( [undefined, null, 7].flatMap((maxConcurrency) => [false, true].map((named) => ({ maxConcurrency, named })), diff --git a/packages/void/test/unit/plugin-cloudflare-config.test.ts b/packages/void/test/unit/plugin-cloudflare-config.test.ts index 020f01bec6..254130e3fc 100644 --- a/packages/void/test/unit/plugin-cloudflare-config.test.ts +++ b/packages/void/test/unit/plugin-cloudflare-config.test.ts @@ -1,5 +1,8 @@ import { afterEach, expect, it, vi } from 'vite-plus/test'; -import { addLocalQueueProducers } from '../../src/plugin-cloudflare-config.ts'; +import { + addLocalQueueProducers, + applyLocalD1PreviewIds, +} from '../../src/plugin-cloudflare-config.ts'; afterEach(() => { vi.restoreAllMocks(); @@ -24,3 +27,56 @@ it('warns once for an inferred binding shared by queue files', () => { ), ); }); + +it('gives the dev server the preview D1 database that void db commands use', () => { + const worker = { + env: { + DB: { type: 'd1' as const, id: 'production-id' }, + OTHER: { type: 'd1' as const, id: 'other-id' }, + }, + }; + + applyLocalD1PreviewIds(worker, [ + { + d1_databases: [ + { binding: 'DB', database_id: 'production-id', preview_database_id: 'preview-id' }, + { binding: 'OTHER', database_id: 'other-id' }, + ], + }, + ]); + + expect(worker.env).toEqual({ + DB: { type: 'd1', id: 'preview-id' }, + OTHER: { type: 'd1', id: 'other-id' }, + }); +}); + +it('takes the local D1 ID from the first settings that declare the binding', () => { + const worker = { + env: { + DB: { type: 'd1' as const, id: 'staging-id' }, + PLAIN: { type: 'd1' as const, id: 'plain-staging-id' }, + }, + }; + + applyLocalD1PreviewIds(worker, [ + { + d1_databases: [ + { binding: 'DB', database_id: 'staging-id', preview_database_id: 'staging-preview' }, + { binding: 'PLAIN', database_id: 'plain-staging-id' }, + ], + }, + { + d1_databases: [ + { binding: 'DB', database_id: 'production-id', preview_database_id: 'preview-id' }, + { binding: 'PLAIN', database_id: 'plain-id', preview_database_id: 'plain-preview' }, + ], + }, + undefined, + ]); + + expect(worker.env).toEqual({ + DB: { type: 'd1', id: 'staging-preview' }, + PLAIN: { type: 'd1', id: 'plain-staging-id' }, + }); +}); From a0063cf900291322d8c1f71eae238e3dbfc091d2 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Sat, 5 Dec 2026 12:07:51 +0900 Subject: [PATCH 2/3] Keep local D1 identities consistent across Workers and previews. --- docs/guide/database/d1.md | 2 +- packages/void/src/local-d1.ts | 50 +++++--- packages/void/src/plugin-cloudflare-config.ts | 54 +++------ .../void/src/plugin-cloudflare-preview.ts | 28 ++++- packages/void/src/plugin-cloudflare.ts | 59 ++++++++- .../integration/plugin-cloudflare-v2.test.ts | 112 ++++++++++++++++++ packages/void/test/unit/local-d1.test.ts | 23 ++++ .../unit/plugin-cloudflare-config.test.ts | 39 +----- 8 files changed, 269 insertions(+), 98 deletions(-) diff --git a/docs/guide/database/d1.md b/docs/guide/database/d1.md index d529cec203..165ad3baa6 100644 --- a/docs/guide/database/d1.md +++ b/docs/guide/database/d1.md @@ -9,7 +9,7 @@ outline: deep ## Local Database -The dev server and local `void db` commands share the same database. If `cloudflare.d1_databases` in `void.config.ts` declares the D1 binding, Void uses its ID. A `preview_database_id` takes precedence during local development. +The dev server, local preview, and local `void db` commands share the same database. If you set a `preview_database_id` on a binding in `cloudflare.d1_databases`, Void uses it locally and keeps `database_id` for deployment. When using `CLOUDFLARE_ENV`, declare the D1 binding in that environment. To store local data outside `.void`, set `voidPlugin({ persistTo: 'local-state' })` in your Vite config. Start the dev server once to record that directory before running database commands. After changing the Vite config, start it again to refresh it. Frameworks that manage their own Cloudflare runtime use `.wrangler/state`. diff --git a/packages/void/src/local-d1.ts b/packages/void/src/local-d1.ts index 9d94ffca77..bbdfe25571 100644 --- a/packages/void/src/local-d1.ts +++ b/packages/void/src/local-d1.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { isRecord } from '@void/deploy-core'; import { isAbsolute, join, resolve } from 'pathslash'; import { readRootWranglerConfig } from './cli/wrangler.ts'; import { getMiniflareDatabasePath } from './migrations/runner.ts'; @@ -28,22 +29,25 @@ export type LocalD1Target = { databasePath: string; }; -function readConfiguredDatabaseId(root: string, bindingName: string): string | undefined { - let rootConfig: ReturnType; - try { - rootConfig = readRootWranglerConfig(root); - } catch (error) { - throw new Error(`db: cannot read malformed Wrangler configuration in ${root}.`, { - cause: error, - }); - } - if (!rootConfig) { - return undefined; +/** D1 bindings are not inherited by a named Wrangler environment. */ +export function configuredD1Databases( + config: { env?: unknown; d1_databases?: unknown }, + configPath: string, + options: { allowMissingEnvironment?: boolean } = {}, +): Array> { + const environment = process.env.CLOUDFLARE_ENV; + let settings = config; + if (environment && isRecord(config.env)) { + const selected = config.env[environment]; + if (isRecord(selected)) { + settings = selected; + } else if (!options.allowMissingEnvironment) { + throw new Error(`Cloudflare environment ${environment} is not configured.`); + } } - const { configPath, config } = rootConfig; - const rawDatabases = config.d1_databases; + const rawDatabases = settings.d1_databases; if (rawDatabases === undefined) { - return undefined; + return []; } if (!Array.isArray(rawDatabases)) { throw new Error(`db: cannot read ${configPath}: "d1_databases" must be an array.`); @@ -63,7 +67,23 @@ function readConfiguredDatabaseId(root: string, bindingName: string): string | u ); } - const matches = (rawDatabases as Array>).filter( + return rawDatabases as Array>; +} + +function readConfiguredDatabaseId(root: string, bindingName: string): string | undefined { + let rootConfig: ReturnType; + try { + rootConfig = readRootWranglerConfig(root); + } catch (error) { + throw new Error(`db: cannot read malformed Wrangler configuration in ${root}.`, { + cause: error, + }); + } + if (!rootConfig) { + return undefined; + } + const { configPath, config } = rootConfig; + const matches = configuredD1Databases(config, configPath).filter( (entry) => entry.binding === bindingName, ); if (matches.length > 1) { diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index 171a7ea202..794fd11283 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -166,36 +166,16 @@ export function toNativeCloudflareConfig( return { ...config, worker: config.worker }; } -/** - * Give the dev server the same local D1 database as `void db` commands. Like Wrangler, they - * use a binding's `preview_database_id` locally; the deployable config keeps `database_id`. - * The first settings that declare a binding decide its local ID, so a selected environment - * comes before the top-level settings. - */ +export type D1PreviewIds = Array<[binding: string, id: string]>; + export function applyLocalD1PreviewIds( worker: Pick, - settings: ReadonlyArray<{ d1_databases?: unknown } | undefined>, + ids: D1PreviewIds, ): void { - const env = worker.env; - if (!env) { - return; - } - const declared = new Set(); - for (const databases of settings.map((item) => item?.d1_databases)) { - if (!Array.isArray(databases)) { - continue; - } - for (const database of databases as Array | null>) { - const name = database?.binding; - if (typeof name !== 'string' || declared.has(name)) { - continue; - } - declared.add(name); - const binding = env[name]; - const previewId = database?.preview_database_id; - if (binding?.type === 'd1' && typeof previewId === 'string' && previewId.length > 0) { - binding.id = previewId; - } + for (const [name, id] of ids) { + const binding = worker.env?.[name]; + if (binding?.type === 'd1') { + binding.id = id; } } } @@ -231,6 +211,10 @@ export function nativeAuxiliaryWorkers( workers: Array | undefined, root: string, readLocalQueueBindings?: () => ReadonlyArray | undefined, + d1?: { + configure: (worker: CloudflareConfig['worker'], settings: WorkerConfig) => void; + entryDatabases: () => WorkerConfig['d1_databases']; + }, ): PluginConfig['auxiliaryWorkers'] { return workers?.map(({ configPath, config, ...options }) => ({ ...options, @@ -252,19 +236,19 @@ export function nativeAuxiliaryWorkers( } worker = { ...entryWorkerConfig, env }; } + const entryDatabases = typeof config === 'function' ? d1?.entryDatabases() : undefined; const patch = typeof config === 'function' ? config(base, { - entryWorkerConfig: convertToWranglerConfig({ - worker, - containers: [], - }), + entryWorkerConfig: { + ...convertToWranglerConfig({ worker, containers: [] }), + ...(entryDatabases ? { d1_databases: entryDatabases } : {}), + }, }) : config; - const native = toNativeCloudflareConfig( - mergeCloudflareConfig(patch ?? {}, base), - path ? dirname(path) : root, - ); + const settings = mergeCloudflareConfig(patch ?? {}, base); + const native = toNativeCloudflareConfig(settings, path ? dirname(path) : root); + d1?.configure(native.worker, settings); return native.worker; }, })); diff --git a/packages/void/src/plugin-cloudflare-preview.ts b/packages/void/src/plugin-cloudflare-preview.ts index 07713d7bd2..b749d40faa 100644 --- a/packages/void/src/plugin-cloudflare-preview.ts +++ b/packages/void/src/plugin-cloudflare-preview.ts @@ -1,13 +1,19 @@ -import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; -import { getRootConfigPath, getWorkerConfigPath } from '@cloudflare/build-output-utils'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { + getRootConfigPath, + getWorkerConfigPath, + readBuildOutput, +} from '@cloudflare/build-output-utils'; import type { CloudflareConfig } from '@cloudflare/vite-plugin'; import { dirname, join } from 'pathslash'; import type { Plugin } from 'vite'; -import { addLocalQueueProducers } from './plugin-cloudflare-config.ts'; -import type { LocalQueueProducers } from './plugin-cloudflare-config.ts'; +import { addLocalQueueProducers, applyLocalD1PreviewIds } from './plugin-cloudflare-config.ts'; +import type { D1PreviewIds, LocalQueueProducers } from './plugin-cloudflare-config.ts'; import { writeFileAtomic } from './shared/atomic-write.ts'; import { loadLocalEnv } from './shared/env.ts'; +export const D1_PREVIEW_FILE = 'void-d1-preview.json'; + /** Give preview local bindings without changing the deployable build or storing their values. */ export function withLocalPreviewBindings( plugins: Array, @@ -41,6 +47,20 @@ export function withLocalPreviewBindings( try { const output = dirname(getRootConfigPath(root)); cpSync(output, dirname(getRootConfigPath(directory)), { recursive: true }); + const d1Overrides = join(output, D1_PREVIEW_FILE); + if (existsSync(d1Overrides)) { + const ids = new Map( + JSON.parse(readFileSync(d1Overrides, 'utf8')) as Array<[string, D1PreviewIds]>, + ); + const { workers } = await readBuildOutput(directory); + for (const { config, configPath } of Object.values(workers)) { + const overrides = config.name && ids.get(config.name); + if (overrides) { + applyLocalD1PreviewIds(config, overrides); + writeFileAtomic(configPath, JSON.stringify(config)); + } + } + } const path = getWorkerConfigPath(directory); const worker = JSON.parse(readFileSync(path, 'utf8')) as Pick< CloudflareConfig['worker'], diff --git a/packages/void/src/plugin-cloudflare.ts b/packages/void/src/plugin-cloudflare.ts index 50664108bb..28aaaa2d70 100644 --- a/packages/void/src/plugin-cloudflare.ts +++ b/packages/void/src/plugin-cloudflare.ts @@ -10,6 +10,7 @@ import type { PluginConfig } from '@cloudflare/vite-plugin'; import { dirname, isAbsolute, join, relative, resolve } from 'pathslash'; import type { BuildEnvironment, Plugin } from 'vite'; import { readGeneratedWranglerConfigFile } from './cli/generated-wrangler-config.ts'; +import { configuredD1Databases } from './local-d1.ts'; import { voidWarn } from './log.ts'; import { addLocalQueueProducers, @@ -24,7 +25,8 @@ import type { LocalQueueProducers, WorkerConfig, } from './plugin-cloudflare-config.ts'; -import { withLocalPreviewBindings } from './plugin-cloudflare-preview.ts'; +import type { D1PreviewIds } from './plugin-cloudflare-config.ts'; +import { D1_PREVIEW_FILE, withLocalPreviewBindings } from './plugin-cloudflare-preview.ts'; import { isVitestServer } from './plugin-dev-config.ts'; import { writeFileAtomic } from './shared/atomic-write.ts'; import { CLOUDFLARE_DEPLOY_BUILD_ENV } from './shared/env.ts'; @@ -71,10 +73,34 @@ export function cloudflare(options: { let pluginNative: ReturnType; let localQueueBindings: Array | undefined; let localQueueWarnings: Array | undefined; + const previewIdsByWorker = new Map(); + let serving = false; + function configureD1(worker: typeof native.worker, settings: WorkerConfig) { + const ids: D1PreviewIds = []; + for (const { binding, preview_database_id } of configuredD1Databases(settings, root, { + allowMissingEnvironment: true, + })) { + if ( + typeof binding === 'string' && + typeof preview_database_id === 'string' && + preview_database_id + ) { + ids.push([binding, preview_database_id]); + } + } + if (ids.length) { + previewIdsByWorker.set(worker.name, ids); + if (serving) { + applyLocalD1PreviewIds(worker, ids); + } + } + } const outputDirectories = new Map(); const bridge: Plugin = { name: 'void:cloudflare-config', config(_userConfig, environment) { + serving = environment.command === 'serve'; + previewIdsByWorker.clear(); localQueueBindings = undefined; localQueueWarnings = undefined; if (environment.isPreview) { @@ -83,8 +109,7 @@ export function cloudflare(options: { let base = ( options.configPath ? readGeneratedWranglerConfigFile(options.configPath) : {} ) as WorkerConfig; - // The translation below drops local-only D1 preview IDs. Keep the settings that have them. - const localD1Settings: Array<{ d1_databases?: unknown }> = []; + const raw = base; if (process.env.CLOUDFLARE_ENV && base.env) { const selected = base.env[process.env.CLOUDFLARE_ENV]; if (!selected) { @@ -93,7 +118,6 @@ export function cloudflare(options: { ); } const original = base; - localD1Settings.push(selected, original); base = convertToWranglerConfig(toNativeCloudflareConfig(base, root, environment.command)); base.main = selected.main ?? original.main; base.migrations = selected.migrations ?? original.migrations; @@ -105,6 +129,7 @@ export function cloudflare(options: { workerConfig = mergeCloudflareConfig(options.config(base), base); native = toNativeCloudflareConfig(workerConfig, root, environment.command); pluginNative = structuredClone(native); + configureD1(pluginNative.worker, process.env.CLOUDFLARE_ENV && raw.env ? raw : workerConfig); if (environment.command === 'build' && (native.containers?.length ?? 0) > 0) { // Void builds images during deployment preparation. Managed builds consume // the Worker bundle and must not acquire a local Docker prerequisite. @@ -116,7 +141,6 @@ export function cloudflare(options: { } } else if (environment.command === 'serve') { restoreLocalContainerBindings(pluginNative.worker); - applyLocalD1PreviewIds(pluginNative.worker, [...localD1Settings, workerConfig]); localQueueBindings = addLocalQueueProducers( pluginNative.worker, options.localQueueProducers, @@ -176,6 +200,12 @@ export function cloudflare(options: { mkdirSync(getWorkerAssetsDir(root), { recursive: true }); } const built = await readBuildOutput(root); + if (previewIdsByWorker.size) { + writeFileAtomic( + join(dirname(getRootConfigPath(root)), D1_PREVIEW_FILE), + JSON.stringify([...previewIdsByWorker]), + ); + } const worker = built.workers.default; const environment = options.viteEnvironment.name ?? 'ssr'; const destination = outputDirectories.get(environment); @@ -299,6 +329,25 @@ export function cloudflare(options: { options.auxiliaryWorkers, root, () => localQueueBindings, + { + configure: configureD1, + entryDatabases() { + const ids = previewIdsByWorker.get(native.worker.name); + if (!ids) { + return; + } + // Public auxiliary callbacks can share the entry's D1 declaration. + // Keep both the deploy ID and the local override in that fresh copy. + const databases = convertToWranglerConfig(native).d1_databases; + for (const [name, id] of ids) { + const binding = databases?.find((db) => db.binding === name); + if (binding) { + binding.preview_database_id = id; + } + } + return databases; + }, + }, ), types: { generate: false }, config() { diff --git a/packages/void/test/integration/plugin-cloudflare-v2.test.ts b/packages/void/test/integration/plugin-cloudflare-v2.test.ts index 149bc5d4a8..121e7ac573 100644 --- a/packages/void/test/integration/plugin-cloudflare-v2.test.ts +++ b/packages/void/test/integration/plugin-cloudflare-v2.test.ts @@ -22,6 +22,7 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { prepareNativeWorkerDeploy } from '../../src/cli/cf-worker-deploy-output.ts'; import { verifyGeneratedDeployConfig } from '../../src/cli/deploy-artifact-validation.ts'; import { prepareCfBuildOutput } from '../../src/deploy.ts'; +import { getMiniflareDatabasePath, runMigrations } from '../../src/migrations/runner.ts'; import { nativeAuxiliaryWorkers, toNativeCloudflareConfig, @@ -46,6 +47,117 @@ afterEach(() => { }); describe('Cloudflare v2 compatibility', () => { + it('uses local D1 IDs in dev and preview for entry and auxiliary Workers', async () => { + const root = project(); + const configPath = join(root, 'worker-config.json'); + const migrations = join(root, 'migrations'); + mkdirSync(migrations); + const persistRoot = join(root, '.void'); + const query = + "return Response.json(await env.DB.prepare('SELECT name FROM users').first('name'));"; + writeFileSync( + join(root, 'entry.js'), + `export default { async fetch(req, env) { if (new URL(req.url).pathname.startsWith('/lookup/')) return env.HELPER.fetch(req); ${query} } };`, + ); + writeFileSync( + join(root, 'helper.js'), + `export default { async fetch(req, env) { if (new URL(req.url).pathname === '/lookup/shared') return Response.json(await env.SHARED.prepare('SELECT name FROM users').first('name')); ${query} } };`, + ); + for (const name of ['entry', 'helper']) { + writeFileSync( + join(migrations, '0001_users.sql'), + `CREATE TABLE users (name TEXT); +INSERT INTO users VALUES ('${name}');`, + ); + await runMigrations(migrations, getMiniflareDatabasePath(persistRoot, name + '-preview')); + } + let usePreviewIds = true; + const database = (name: string) => ({ + binding: 'DB', + database_name: name, + database_id: name + '-deploy', + ...(usePreviewIds ? { preview_database_id: name + '-preview' } : {}), + }); + const config = (): InlineConfig => { + writeFileSync( + configPath, + JSON.stringify({ + name: 'entry', + main: './entry.js', + compatibility_date: '2026-02-24', + d1_databases: [database('entry')], + services: [{ binding: 'HELPER', service: 'helper' }], + }), + ); + return { + root, + configFile: false, + logLevel: 'silent', + plugins: cloudflare({ + configPath, + config: () => ({}), + inspectorPort: false, + persistState: { path: persistRoot }, + viteEnvironment: { name: 'ssr' }, + auxiliaryWorkers: [ + { + config: (_, { entryWorkerConfig }) => ({ + name: 'helper', + main: './helper.js', + compatibility_date: '2026-02-24', + d1_databases: [ + database('helper'), + { ...entryWorkerConfig.d1_databases![0], binding: 'SHARED' }, + ], + }), + }, + ], + }), + }; + }; + async function checkResponses(base: string) { + for (const [path, name] of [ + ['/', 'entry'], + ['/lookup/auxiliary', 'helper'], + ['/lookup/shared', 'entry'], + ]) { + const response = await fetch(new URL(path, base)); + expect(response.status).toBe(200); + expect(await response.json()).toBe(name); + } + } + const dev = await createServer({ ...config(), server: { port: 0 } }); + try { + await dev.listen(); + await checkResponses(dev.resolvedUrls!.local[0]); + } finally { + await dev.close(); + } + await (await createBuilder(config())).buildApp(); + const server = await preview({ ...config(), preview: { port: 0 } }); + try { + await checkResponses(server.resolvedUrls!.local[0]); + } finally { + await server.close(); + } + const upload = await prepareCfBuildOutput(root); + expect(upload).not.toBeNull(); + try { + const { workers } = await readBuildOutput(upload!.directory); + expect(workers.default.config.env?.DB).toMatchObject({ id: 'entry-deploy' }); + expect(workers.helper.config.env?.SHARED).toMatchObject({ id: 'entry-deploy' }); + expect(workers.helper.config.env?.DB).toMatchObject({ id: 'helper-deploy' }); + expect( + existsSync(join(dirname(getRootConfigPath(upload!.directory)), 'void-d1-preview.json')), + ).toBe(false); + } finally { + await upload?.dispose(); + } + usePreviewIds = false; + await (await createBuilder(config())).buildApp(); + expect(existsSync(join(dirname(getRootConfigPath(root)), 'void-d1-preview.json'))).toBe(false); + }, 15_000); + it('includes split Worker modules in a Wrangler deployment', async () => { const root = project(); writeFileSync( diff --git a/packages/void/test/unit/local-d1.test.ts b/packages/void/test/unit/local-d1.test.ts index 0a80997860..fb119a504b 100644 --- a/packages/void/test/unit/local-d1.test.ts +++ b/packages/void/test/unit/local-d1.test.ts @@ -46,6 +46,7 @@ async function runGeneratedMigrationPlugin(plugins: ReturnType { vi.restoreAllMocks(); + vi.unstubAllEnvs(); for (const root of roots.splice(0, roots.length)) { rmSync(root, { recursive: true, force: true }); } @@ -84,6 +85,28 @@ describe('local D1 identity', () => { }); }); + it('selects the named environment without inheriting top-level D1 bindings', () => { + const root = createRoot(); + vi.stubEnv('CLOUDFLARE_ENV', 'staging'); + for (const [stagingD1, expected] of [ + [[{ binding: 'DB', database_id: 'staging', preview_database_id: 'preview' }], 'preview'], + [[{ binding: 'DB', database_id: 'staging' }], 'staging'], + [[{ binding: 'OTHER', database_id: 'secondary' }], 'local'], + [undefined, 'local'], + ] as const) { + writeFileSync( + join(root, 'wrangler.jsonc'), + JSON.stringify({ + d1_databases: [ + { binding: 'DB', database_id: 'production', preview_database_id: 'top-preview' }, + ], + env: { staging: { d1_databases: stagingD1 } }, + }), + ); + expect(getLocalD1Target(root).databaseId).toBe(expected); + } + }); + it('fails instead of choosing among duplicate configured bindings', () => { const root = createRoot(); writeFileSync( diff --git a/packages/void/test/unit/plugin-cloudflare-config.test.ts b/packages/void/test/unit/plugin-cloudflare-config.test.ts index 254130e3fc..a636f13314 100644 --- a/packages/void/test/unit/plugin-cloudflare-config.test.ts +++ b/packages/void/test/unit/plugin-cloudflare-config.test.ts @@ -36,47 +36,10 @@ it('gives the dev server the preview D1 database that void db commands use', () }, }; - applyLocalD1PreviewIds(worker, [ - { - d1_databases: [ - { binding: 'DB', database_id: 'production-id', preview_database_id: 'preview-id' }, - { binding: 'OTHER', database_id: 'other-id' }, - ], - }, - ]); + applyLocalD1PreviewIds(worker, [['DB', 'preview-id']]); expect(worker.env).toEqual({ DB: { type: 'd1', id: 'preview-id' }, OTHER: { type: 'd1', id: 'other-id' }, }); }); - -it('takes the local D1 ID from the first settings that declare the binding', () => { - const worker = { - env: { - DB: { type: 'd1' as const, id: 'staging-id' }, - PLAIN: { type: 'd1' as const, id: 'plain-staging-id' }, - }, - }; - - applyLocalD1PreviewIds(worker, [ - { - d1_databases: [ - { binding: 'DB', database_id: 'staging-id', preview_database_id: 'staging-preview' }, - { binding: 'PLAIN', database_id: 'plain-staging-id' }, - ], - }, - { - d1_databases: [ - { binding: 'DB', database_id: 'production-id', preview_database_id: 'preview-id' }, - { binding: 'PLAIN', database_id: 'plain-id', preview_database_id: 'plain-preview' }, - ], - }, - undefined, - ]); - - expect(worker.env).toEqual({ - DB: { type: 'd1', id: 'staging-preview' }, - PLAIN: { type: 'd1', id: 'plain-staging-id' }, - }); -}); From 65dc2671ef357abe1ea309f1ce7baeeb8c2515fb Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Sat, 5 Dec 2026 12:12:07 +0900 Subject: [PATCH 3/3] Keep implicit primary bindings intact in auxiliary callbacks. --- packages/void/src/plugin-cloudflare-config.ts | 34 +++++++++---------- packages/void/src/plugin-cloudflare.ts | 22 +++++------- packages/void/test/unit/local-d1.test.ts | 13 +++++-- 3 files changed, 36 insertions(+), 33 deletions(-) diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index 60cce04731..943b45a080 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -225,7 +225,7 @@ export function nativeAuxiliaryWorkers( readLocalQueueBindings?: () => ReadonlyArray | undefined, d1?: { configure: (worker: CloudflareConfig['worker'], settings: WorkerConfig) => void; - entryDatabases: () => WorkerConfig['d1_databases']; + restoreEntryPreviewIds: (entryConfig: WorkerConfig) => void; }, ): PluginConfig['auxiliaryWorkers'] { return workers?.map(({ configPath, config, ...options }) => ({ @@ -239,25 +239,23 @@ export function nativeAuxiliaryWorkers( : readGeneratedWranglerConfigFile(path) : {} ) as WorkerConfig; - let worker = entryWorkerConfig; - const localBindings = readLocalQueueBindings?.(); - if (localBindings && typeof config === 'function') { - const env = { ...entryWorkerConfig.env }; - for (const name of localBindings) { - delete env[name]; + let patch: Partial | void; + if (typeof config === 'function') { + let worker = entryWorkerConfig; + const localBindings = readLocalQueueBindings?.(); + if (localBindings) { + const env = { ...worker.env }; + for (const name of localBindings) { + delete env[name]; + } + worker = { ...worker, env }; } - worker = { ...entryWorkerConfig, env }; + const entry = convertToWranglerConfig({ worker, containers: [] }); + d1?.restoreEntryPreviewIds(entry); + patch = config(base, { entryWorkerConfig: entry }); + } else { + patch = config; } - const entryDatabases = typeof config === 'function' ? d1?.entryDatabases() : undefined; - const patch = - typeof config === 'function' - ? config(base, { - entryWorkerConfig: { - ...convertToWranglerConfig({ worker, containers: [] }), - ...(entryDatabases ? { d1_databases: entryDatabases } : {}), - }, - }) - : config; const settings = mergeCloudflareConfig(patch ?? {}, base); const native = toNativeCloudflareConfig(settings, path ? dirname(path) : root); d1?.configure(native.worker, settings); diff --git a/packages/void/src/plugin-cloudflare.ts b/packages/void/src/plugin-cloudflare.ts index d1cf759891..77fbf7906d 100644 --- a/packages/void/src/plugin-cloudflare.ts +++ b/packages/void/src/plugin-cloudflare.ts @@ -335,21 +335,17 @@ export function cloudflare(options: { () => localQueueBindings, { configure: configureD1, - entryDatabases() { - const ids = previewIdsByWorker.get(native.worker.name); - if (!ids) { - return; - } - // Public auxiliary callbacks can share the entry's D1 declaration. - // Keep both the deploy ID and the local override in that fresh copy. - const databases = convertToWranglerConfig(native).d1_databases; - for (const [name, id] of ids) { - const binding = databases?.find((db) => db.binding === name); - if (binding) { - binding.preview_database_id = id; + restoreEntryPreviewIds(entryConfig) { + // Auxiliary callbacks may forward the entry's D1 declaration. Keep + // both IDs without replacing unrelated bindings' local defaults. + for (const [name, id] of previewIdsByWorker.get(native.worker.name) ?? []) { + const entry = entryConfig.d1_databases?.find((db) => db.binding === name); + const deployed = native.worker.env?.[name]; + if (entry && deployed?.type === 'd1') { + entry.database_id = deployed.id; + entry.preview_database_id = id; } } - return databases; }, }, ), diff --git a/packages/void/test/unit/local-d1.test.ts b/packages/void/test/unit/local-d1.test.ts index 34372037cf..6849df6331 100644 --- a/packages/void/test/unit/local-d1.test.ts +++ b/packages/void/test/unit/local-d1.test.ts @@ -286,7 +286,7 @@ describe('local D1 identity', () => { writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module', name: 'd1-repro' })); writeFileSync( join(root, 'void.config.ts'), - "export default { cloudflare: { d1_databases: [{ binding: 'DB', database_name: 'repro' }] } };\n", + "export default { cloudflare: { d1_databases: [{ binding: 'DB', database_name: 'repro' },{ binding: 'OTHER', database_name:'other', database_id:'other-prod', preview_database_id:'other-preview' }] } };\n", ); mkdirSync(join(root, 'src'), { recursive: true }); writeFileSync( @@ -326,11 +326,20 @@ describe('local D1 identity', () => { return seenD1; }; + const other = expect.objectContaining({ + binding: 'OTHER', + database_id: 'other-prod', + preview_database_id: 'other-preview', + }); expect(await resolveEntryD1('serve')).toEqual([ expect.objectContaining({ binding: 'DB', database_name: 'repro', database_id: 'DB' }), + other, ]); const buildD1 = await resolveEntryD1('build'); - expect(buildD1).toEqual([expect.objectContaining({ binding: 'DB', database_name: 'repro' })]); + expect(buildD1).toEqual([ + expect.objectContaining({ binding: 'DB', database_name: 'repro' }), + other, + ]); expect(buildD1?.[0]?.database_id).toBeUndefined(); }); });