diff --git a/docs/guide/database/d1.md b/docs/guide/database/d1.md index d529cec20..165ad3baa 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/cli/cf-config-migrate.ts b/packages/void/src/cli/cf-config-migrate.ts index 78f031027..1e19d2ddb 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 8f1c96fc9..9444047f7 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/local-d1.ts b/packages/void/src/local-d1.ts index 9d94ffca7..bbdfe2557 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 f80e2c2ac..943b45a08 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -166,6 +166,20 @@ export function toNativeCloudflareConfig( return { ...config, worker: config.worker }; } +export type D1PreviewIds = Array<[binding: string, id: string]>; + +export function applyLocalD1PreviewIds( + worker: Pick, + ids: D1PreviewIds, +): void { + for (const [name, id] of ids) { + const binding = worker.env?.[name]; + if (binding?.type === 'd1') { + binding.id = id; + } + } +} + /** * Give Container Durable Objects a regular binding in the dev server. Their unsafe * binding from `migrateBuiltWranglerConfig()` exists only for the Worker upload, and @@ -209,6 +223,10 @@ export function nativeAuxiliaryWorkers( workers: Array | undefined, root: string, readLocalQueueBindings?: () => ReadonlyArray | undefined, + d1?: { + configure: (worker: CloudflareConfig['worker'], settings: WorkerConfig) => void; + restoreEntryPreviewIds: (entryConfig: WorkerConfig) => void; + }, ): PluginConfig['auxiliaryWorkers'] { return workers?.map(({ configPath, config, ...options }) => ({ ...options, @@ -221,28 +239,26 @@ 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 patch = - typeof config === 'function' - ? config(base, { - entryWorkerConfig: convertToWranglerConfig({ - worker, - containers: [], - }), - }) - : 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 e65093381..c2177baa7 100644 --- a/packages/void/src/plugin-cloudflare-preview.ts +++ b/packages/void/src/plugin-cloudflare-preview.ts @@ -1,13 +1,23 @@ -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, restoreLocalD1Binding } from './plugin-cloudflare-config.ts'; -import type { LocalQueueProducers } from './plugin-cloudflare-config.ts'; +import { + addLocalQueueProducers, + applyLocalD1PreviewIds, + restoreLocalD1Binding, +} 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, @@ -42,6 +52,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 66ccc7289..77fbf7906 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, @@ -18,13 +19,15 @@ import { restoreLocalContainerBindings, restoreLocalD1Binding, toNativeCloudflareConfig, + applyLocalD1PreviewIds, } from './plugin-cloudflare-config.ts'; import type { AuxiliaryWorkerConfig, 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'; @@ -73,10 +76,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) { @@ -85,6 +112,7 @@ export function cloudflare(options: { let base = ( options.configPath ? readGeneratedWranglerConfigFile(options.configPath) : {} ) as WorkerConfig; + const raw = base; if (process.env.CLOUDFLARE_ENV && base.env) { const selected = base.env[process.env.CLOUDFLARE_ENV]; if (!selected) { @@ -104,6 +132,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. @@ -175,6 +204,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); @@ -298,6 +333,21 @@ export function cloudflare(options: { options.auxiliaryWorkers, root, () => localQueueBindings, + { + configure: configureD1, + 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; + } + } + }, + }, ), 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 149bc5d4a..121e7ac57 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/cf-config-migrate.test.ts b/packages/void/test/unit/cf-config-migrate.test.ts index 1b1da84c4..cd13a5ad6 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/local-d1.test.ts b/packages/void/test/unit/local-d1.test.ts index f8de40eab..6849df633 100644 --- a/packages/void/test/unit/local-d1.test.ts +++ b/packages/void/test/unit/local-d1.test.ts @@ -50,6 +50,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 }); } @@ -88,6 +89,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( @@ -263,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( @@ -303,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(); }); }); diff --git a/packages/void/test/unit/plugin-cloudflare-config.test.ts b/packages/void/test/unit/plugin-cloudflare-config.test.ts index 020f01bec..a636f1331 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,19 @@ 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, [['DB', 'preview-id']]); + + expect(worker.env).toEqual({ + DB: { type: 'd1', id: 'preview-id' }, + OTHER: { type: 'd1', id: 'other-id' }, + }); +});