From 21641601c6cefed7ae5891576ee3270286702af1 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 10:38:34 +0530 Subject: [PATCH 01/10] fix(cli): resolve tsconfig aliases in database seeds --- docs/guide/database.md | 2 + packages/void/src/cli/db.ts | 21 ++++-- packages/void/test/unit/db-seed.test.ts | 94 +++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 6 deletions(-) diff --git a/docs/guide/database.md b/docs/guide/database.md index f4438ad3b..f29e17c6b 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,6 +264,8 @@ Use `db/seed.ts` for a programmatic seed or `db/seed.sql` for SQL. JavaScript an Use `db/seed.ts` when you want to generate seed data in code. Export a default function or a named `seed` function. +Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. + ```ts // db/seed.ts import { defineSeed } from 'void/seed'; diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 7a5058214..68071b8ca 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -776,7 +776,7 @@ async function runSeed( const seed = resolveSeedTarget(root, file); const sql = seed.kind === 'sql' ? readFileSync(seed.path, 'utf-8') : undefined; await confirmReset(root, dialect, yes); - const seedFn = sql === undefined ? await loadSeedFunction(seed.path) : undefined; + const seedFn = sql === undefined ? await loadSeedFunction(root, seed.path) : undefined; // Reset first (drop + re-run migrations). The drop is confirmed above, so do not ask again. const migrationCount = await resetDatabase(root, dialect, true); @@ -2470,8 +2470,11 @@ async function runSeedModule( } } -async function loadSeedFunction(seedPath: string): Promise>> { - const mod = await importLocalModule(seedPath); +async function loadSeedFunction( + root: string, + seedPath: string, +): Promise>> { + const mod = await importLocalModule(root, seedPath); const seed = typeof mod.default === 'function' ? mod.default @@ -2495,14 +2498,14 @@ async function loadSeedSchema(root: string): Promise> { } if (location.type === 'file') { - const mod = await importLocalModule(location.path); + const mod = await importLocalModule(root, location.path); return Object.fromEntries( Object.entries(mod).filter(([name]) => name !== 'default' && name !== '__esModule'), ); } const files = collectSchemaModuleFiles(location.path); - const parts = await Promise.all(files.map((file) => importLocalModule(file))); + const parts = await Promise.all(files.map((file) => importLocalModule(root, file))); return Object.assign( {}, ...parts.map((mod) => @@ -2530,12 +2533,18 @@ function collectSchemaModuleFiles(dir: string): Array { return files.sort(); } -async function importLocalModule(modulePath: string): Promise> { +async function importLocalModule( + root: string, + modulePath: string, +): Promise> { // Native import() cannot resolve the extensionless re-exports that `void gen model` writes. + const tsconfigPath = join(root, 'tsconfig.json'); const jiti = createJiti(import.meta.url, { fsCache: false, moduleCache: false, interopDefault: false, + // Anchor aliases to the app rather than the installed CLI or the current directory. + tsconfigPaths: existsSync(tsconfigPath) ? tsconfigPath : false, }); return jiti.import>(modulePath); } diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index c0c0913cb..c46f711c8 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -253,6 +253,100 @@ await runDbCommand(${JSON.stringify(root)}, { action: 'seed' });`, expect(await readMessages(root)).toEqual([{ id: 1, text: 'from barrel' }]); }, 30_000); + it.each([ + { layout: 'file', importSchema: true }, + { layout: 'directory', importSchema: true }, + { layout: 'file', importSchema: false }, + { layout: 'directory', importSchema: false }, + ])( + 'resolves tsconfig paths in a schema $layout with seed imports: $importSchema', + async ({ layout, importSchema }) => { + const root = createProjectRoot({ + migration: `CREATE TABLE users (id TEXT PRIMARY KEY); +CREATE TABLE messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + text TEXT NOT NULL REFERENCES users(id) +); +`, + seedFile: { + name: 'seed.ts', + content: `import { defineSeed } from 'void/seed'; +${importSchema ? "import { messages } from '@schema';\nimport { value } from '@seed-data/message';" : ''} + +export default defineSeed(async ({ db, schema }) => { + ${importSchema ? '' : "const { value } = await import('@seed-data/message');"} + await db.insert(schema.userTable).values({ id: value }); + await db.insert(${importSchema ? 'messages' : 'schema.messages'}).values({ text: value }); +}); +`, + }, + }); + mkdirSync(join(root, '.void')); + mkdirSync(join(root, 'config')); + mkdirSync(join(root, 'fixtures')); + writeFileSync( + join(root, '.void', 'better-auth-schema.ts'), + `import { sqliteTable, text } from 'void/schema-d1'; +export const userTable = sqliteTable('users', { id: text().primaryKey() }); +`, + ); + writeFileSync(join(root, 'fixtures', 'message.ts'), "export const value = 'from alias';\n"); + const compilerOptions = { + ...(layout === 'directory' ? { baseUrl: '..' } : {}), + paths: { + '@auth-schema': ['./.void/better-auth-schema.ts'], + '@schema': ['./db/schema'], + '@seed-data/*': ['./missing/*', './fixtures/*'], + }, + }; + writeFileSync( + join(root, 'config', 'tsconfig.base.json'), + JSON.stringify({ compilerOptions }), + ); + writeFileSync( + join(root, 'tsconfig.json'), + `{ + // Support both root paths and paths inherited from another directory. + ${layout === 'directory' ? '"extends": "./config/tsconfig.base.json"' : `"compilerOptions": ${JSON.stringify(compilerOptions)}`}, +} +`, + ); + const schemaDir = layout === 'directory' ? join(root, 'db', 'schema') : join(root, 'db'); + mkdirSync(schemaDir, { recursive: true }); + writeFileSync( + join(schemaDir, layout === 'directory' ? 'index.ts' : 'schema.ts'), + `import { integer, sqliteTable, text } from 'void/schema-d1'; +import { userTable } from '@auth-schema'; +export { userTable }; + +export const messages = sqliteTable('messages', { + id: integer().primaryKey({ autoIncrement: true }), + text: text().notNull().references(() => userTable.id), +}); +`, + ); + // Loading CLI modules must not evaluate the app's Vite config. + writeFileSync(join(root, 'vite.config.ts'), "throw new Error('Vite config was loaded');\n"); + + // Use plain Node so Vitest cannot resolve the imports for the seed loader. + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from alias' }]); + }, + 30_000, + ); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { From e86f6fd95db76467a381dae160435e4b4a378215 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 11:10:19 +0530 Subject: [PATCH 02/10] fix(cli): exclude declaration aliases from seed imports --- packages/void/package.json | 1 + packages/void/src/cli/db.ts | 157 ++++++++++++++++-------- packages/void/test/unit/db-seed.test.ts | 76 +++++++++++- pnpm-lock.yaml | 3 + 4 files changed, 186 insertions(+), 51 deletions(-) diff --git a/packages/void/package.json b/packages/void/package.json index 040acf123..a6669fec2 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -379,6 +379,7 @@ "drizzle-valibot": "^0.4.2", "drizzle-zod": "^0.8.3", "email-validator": "^2.0.4", + "get-tsconfig": "^4.14.3", "gray-matter": "^4.0.3", "hono": "catalog:", "ignore": "catalog:", diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 68071b8ca..0a66ad262 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, + mkdtempSync, readFileSync, readdirSync, renameSync, @@ -9,8 +10,10 @@ import { writeFileSync, } from 'node:fs'; import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; import { pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; +import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; import { createJiti } from 'jiti'; import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; import { @@ -776,45 +779,50 @@ async function runSeed( const seed = resolveSeedTarget(root, file); const sql = seed.kind === 'sql' ? readFileSync(seed.path, 'utf-8') : undefined; await confirmReset(root, dialect, yes); - const seedFn = sql === undefined ? await loadSeedFunction(root, seed.path) : undefined; + const loader = sql === undefined ? createSeedModuleLoader(root) : undefined; + try { + const seedFn = loader ? await loadSeedFunction(seed.path, loader.importModule) : undefined; - // Reset first (drop + re-run migrations). The drop is confirmed above, so do not ask again. - const migrationCount = await resetDatabase(root, dialect, true); - log.step(`Reset database. Applied ${formatCount(migrationCount, 'migration')}.`); + // Reset first (drop + re-run migrations). The drop is confirmed above, so do not ask again. + const migrationCount = await resetDatabase(root, dialect, true); + log.step(`Reset database. Applied ${formatCount(migrationCount, 'migration')}.`); - if (sql !== undefined) { - if (dialect === 'postgresql') { - await withPgClient(root, async (client) => { - await client.query(sql); - }); - printSuccess(`Seeded from ${seed.displayPath}.`); + if (sql !== undefined) { + if (dialect === 'postgresql') { + await withPgClient(root, async (client) => { + await client.query(sql); + }); + printSuccess(`Seeded from ${seed.displayPath}.`); - return; - } + return; + } - if (dialect === 'mysql') { - await withMySqlClient(root, async (client) => { - await client.query(sql); - }); - printSuccess(`Seeded from ${seed.displayPath}.`); + if (dialect === 'mysql') { + await withMySqlClient(root, async (client) => { + await client.query(sql); + }); + printSuccess(`Seeded from ${seed.displayPath}.`); - return; - } + return; + } - const { openSqliteDatabase } = await import('../migrations/runner.ts'); - const { databasePath: dbPath } = getLocalD1Target(root); - const db = await openSqliteDatabase(dbPath); - try { - db.exec(sql); - } finally { - db.close(); + const { openSqliteDatabase } = await import('../migrations/runner.ts'); + const { databasePath: dbPath } = getLocalD1Target(root); + const db = await openSqliteDatabase(dbPath); + try { + db.exec(sql); + } finally { + db.close(); + } + } else { + await runSeedModule(root, seedFn!, dialect, loader!.importModule); } - } else { - await runSeedModule(root, seedFn!, dialect); - } - log.info(dim("Restart your dev server if it's running.")); - printSuccess(`Seeded from ${seed.displayPath}.`); + log.info(dim("Restart your dev server if it's running.")); + printSuccess(`Seeded from ${seed.displayPath}.`); + } finally { + loader?.close(); + } } /** @@ -2426,8 +2434,9 @@ async function runSeedModule( root: string, seed: SeedFn>, dialect: DatabaseDialect, + importModule: SeedModuleImporter, ): Promise { - const schema = await loadSeedSchema(root); + const schema = await loadSeedSchema(root, importModule); const casing = getDatabaseCasing(readConfig(root)); if (dialect === 'postgresql') { @@ -2471,10 +2480,10 @@ async function runSeedModule( } async function loadSeedFunction( - root: string, seedPath: string, + importModule: SeedModuleImporter, ): Promise>> { - const mod = await importLocalModule(root, seedPath); + const mod = await importModule(seedPath); const seed = typeof mod.default === 'function' ? mod.default @@ -2489,7 +2498,10 @@ async function loadSeedFunction( return seed as SeedFn>; } -async function loadSeedSchema(root: string): Promise> { +async function loadSeedSchema( + root: string, + importModule: SeedModuleImporter, +): Promise> { const { discoverSchema } = await import('../drizzle/discover.ts'); const paths = readProjectPaths(root); const location = discoverSchema(root, paths); @@ -2498,14 +2510,14 @@ async function loadSeedSchema(root: string): Promise> { } if (location.type === 'file') { - const mod = await importLocalModule(root, location.path); + const mod = await importModule(location.path); return Object.fromEntries( Object.entries(mod).filter(([name]) => name !== 'default' && name !== '__esModule'), ); } const files = collectSchemaModuleFiles(location.path); - const parts = await Promise.all(files.map((file) => importLocalModule(root, file))); + const parts = await Promise.all(files.map((file) => importModule(file))); return Object.assign( {}, ...parts.map((mod) => @@ -2533,20 +2545,65 @@ function collectSchemaModuleFiles(dir: string): Array { return files.sort(); } -async function importLocalModule( - root: string, - modulePath: string, -): Promise> { - // Native import() cannot resolve the extensionless re-exports that `void gen model` writes. +type SeedModuleImporter = (path: string) => Promise>; + +function createSeedModuleLoader(root: string): { + importModule: SeedModuleImporter; + close: () => void; +} { const tsconfigPath = join(root, 'tsconfig.json'); - const jiti = createJiti(import.meta.url, { - fsCache: false, - moduleCache: false, - interopDefault: false, - // Anchor aliases to the app rather than the installed CLI or the current directory. - tsconfigPaths: existsSync(tsconfigPath) ? tsconfigPath : false, - }); - return jiti.import>(modulePath); + let directory: string | undefined; + const close = () => { + if (directory) { + rmSync(directory, { recursive: true, force: true }); + } + }; + try { + const project = existsSync(tsconfigPath) ? getTsconfig(tsconfigPath) : null; + const options = project?.config.compilerOptions; + let runtimeTsconfig: string | false = false; + if (project && options) { + const paths: Record> = {}; + for (const [alias, targets] of Object.entries(options.paths ?? {})) { + const runtimeTargets = targets.filter((target) => !/\.d\.[cm]?ts$/.test(target)); + if (runtimeTargets.length === 0) { + continue; + } + // Resolve each mapping independently, retaining the declaring config's + // path base and the wildcard itself when converting targets to absolute paths. + const matcher = createPathsMatcher({ + ...project, + config: { compilerOptions: { ...options, paths: { [alias]: runtimeTargets } } }, + }); + paths[alias] = matcher!(alias); + } + // Jiti accepts a config filename, not parsed options. Keep this disposable + // runtime config through execution: dynamic imports create child loaders. + directory = mkdtempSync(join(tmpdir(), 'void-seed-')); + runtimeTsconfig = join(directory, 'tsconfig.json'); + writeFileSync( + runtimeTsconfig, + JSON.stringify({ + compilerOptions: { + ...(options.baseUrl !== undefined + ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } + : {}), + paths, + }, + }), + ); + } + const jiti = createJiti(import.meta.url, { + fsCache: false, + moduleCache: false, + interopDefault: false, + tsconfigPaths: runtimeTsconfig, + }); + return { importModule: (path) => jiti.import>(path), close }; + } catch (error) { + close(); + throw error; + } } /** The schema and casing that `void/db` gives drizzle, or undefined when neither is set. */ diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index c46f711c8..8f09b4d46 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import * as output from '../../src/cli/output.ts'; +import { createProjectTsconfig } from '../../src/codegen/project-tsconfig.ts'; import { getMiniflareDatabasePath } from '../../src/migrations/runner.ts'; const mockIntro = vi.fn(); @@ -291,12 +292,16 @@ export const userTable = sqliteTable('users', { id: text().primaryKey() }); `, ); writeFileSync(join(root, 'fixtures', 'message.ts'), "export const value = 'from alias';\n"); + writeFileSync( + join(root, 'fixtures', 'message.d.ts'), + 'export declare const value: string;\n', + ); const compilerOptions = { ...(layout === 'directory' ? { baseUrl: '..' } : {}), paths: { '@auth-schema': ['./.void/better-auth-schema.ts'], '@schema': ['./db/schema'], - '@seed-data/*': ['./missing/*', './fixtures/*'], + '@seed-data/*': ['./fixtures/*.d.ts', './missing/*', './fixtures/*'], }, }; writeFileSync( @@ -347,6 +352,75 @@ export const messages = sqliteTable('messages', { 30_000, ); + it('keeps runtime helpers when extending generated declaration aliases', async () => { + const root = createProjectRoot({ + schema: `import { integer, sqliteTable, text } from 'void/schema-d1'; +export const messages = sqliteTable('messages', { + id: integer().primaryKey({ autoIncrement: true }), + text: text().notNull(), +}); +`, + seedFile: { + name: 'seed.ts', + content: `import { defineSeed } from 'void/seed'; +import { routeUrl } from 'void/routes'; +import { messages } from '@schema'; +export default defineSeed(async ({ db }) => { + await db.insert(messages).values({ text: routeUrl('/messages/[id]', { params: { id: 'hello world' } }) }); +}); +`, + }, + }); + mkdirSync(join(root, '.void')); + const config = createProjectTsconfig(root, true, true, true); + config.compilerOptions!.paths!['void/seed'] = ['./seed.d.mts']; + config.compilerOptions!.paths!['void/schema-d1'] = ['./schema.d.cts']; + writeFileSync(join(root, '.void', 'tsconfig.json'), JSON.stringify(config)); + writeFileSync( + join(root, '.void', 'routes.d.ts'), + 'export declare function routeUrl(): string;\n', + ); + writeFileSync(join(root, '.void', 'db.d.ts'), 'export {};\n'); + writeFileSync( + join(root, '.void', 'seed.d.mts'), + 'export declare function defineSeed(): void;\n', + ); + writeFileSync(join(root, '.void', 'schema.d.cts'), 'export {};\n'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ extends: './.void/tsconfig.json' }), + ); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); + }, 30_000); + + it('loads CommonJS JavaScript seeds', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.js', + content: `module.exports = async function seed({ db }) { + const { sql } = require('drizzle-orm'); + await db.run(sql\`INSERT INTO messages (text) VALUES ('from CommonJS')\`); +}; +`, + }, + }); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'commonjs' })); + await runDbCommand(root, { action: 'seed' }); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from CommonJS' }]); + }); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9625ae931..bb68029c0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -858,6 +858,9 @@ importers: email-validator: specifier: ^2.0.4 version: 2.0.4 + get-tsconfig: + specifier: ^4.14.3 + version: 4.14.3 gray-matter: specifier: ^4.0.3 version: 4.0.3 From 86ea48491f03c0c9363d2f5714f163c1d1e95cbe Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 15:21:51 +0530 Subject: [PATCH 03/10] fix(cli): resolve aliases in JavaScript database seeds --- docs/guide/database.md | 4 +- packages/void/src/cli/db.ts | 70 +++++++-- packages/void/test/unit/db-seed.test.ts | 199 +++++++++++++++++++----- 3 files changed, 223 insertions(+), 50 deletions(-) diff --git a/docs/guide/database.md b/docs/guide/database.md index f29e17c6b..5d28f4800 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,7 +264,9 @@ Use `db/seed.ts` for a programmatic seed or `db/seed.sql` for SQL. JavaScript an Use `db/seed.ts` when you want to generate seed data in code. Export a default function or a named `seed` function. -Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. +Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. This works in TypeScript and JavaScript files, including dynamic `import()` calls. + +If your tsconfig extends `.void/tsconfig.json`, run `void prepare` before seeding a fresh checkout. ```ts // db/seed.ts diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 0a66ad262..dfb16079f 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -9,13 +9,13 @@ import { rmSync, writeFileSync, } from 'node:fs'; -import { createRequire } from 'node:module'; +import { createRequire, isBuiltin, registerHooks } from 'node:module'; import { tmpdir } from 'node:os'; import { pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; import { createJiti } from 'jiti'; -import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; +import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'pathslash'; import { readConfig, getDatabaseCasing, @@ -2553,7 +2553,9 @@ function createSeedModuleLoader(root: string): { } { const tsconfigPath = join(root, 'tsconfig.json'); let directory: string | undefined; + let hooks: ReturnType | undefined; const close = () => { + hooks?.deregister(); if (directory) { rmSync(directory, { recursive: true, force: true }); } @@ -2562,6 +2564,7 @@ function createSeedModuleLoader(root: string): { const project = existsSync(tsconfigPath) ? getTsconfig(tsconfigPath) : null; const options = project?.config.compilerOptions; let runtimeTsconfig: string | false = false; + let matchPaths: ReturnType = null; if (project && options) { const paths: Record> = {}; for (const [alias, targets] of Object.entries(options.paths ?? {})) { @@ -2581,17 +2584,16 @@ function createSeedModuleLoader(root: string): { // runtime config through execution: dynamic imports create child loaders. directory = mkdtempSync(join(tmpdir(), 'void-seed-')); runtimeTsconfig = join(directory, 'tsconfig.json'); - writeFileSync( - runtimeTsconfig, - JSON.stringify({ - compilerOptions: { - ...(options.baseUrl !== undefined - ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } - : {}), - paths, - }, - }), - ); + const config = { + compilerOptions: { + ...(options.baseUrl !== undefined + ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } + : {}), + paths, + }, + }; + writeFileSync(runtimeTsconfig, JSON.stringify(config)); + matchPaths = createPathsMatcher({ path: runtimeTsconfig, config }); } const jiti = createJiti(import.meta.url, { fsCache: false, @@ -2599,9 +2601,51 @@ function createSeedModuleLoader(root: string): { interopDefault: false, tsconfigPaths: runtimeTsconfig, }); + // Jiti delegates .mjs and ESM .js to Node. Apply the same paths there, + // including imports made by ESM helpers and dynamic imports during the seed. + if (matchPaths) { + const jitiUrl = import.meta.resolve('jiti'); + const modules = new Set(); + hooks = registerHooks({ + resolve(specifier, context, nextResolve) { + // Only follow Jiti's native imports and their descendants. CLI imports + // made while resetting the database must keep their own resolution. + if (context.parentURL !== jitiUrl && !modules.has(context.parentURL ?? '')) { + return nextResolve(specifier, context); + } + if ( + !isBuiltin(specifier) && + !isAbsolute(specifier) && + !specifier.startsWith('.') && + !/^[\w+.-]+:/.test(specifier) + ) { + for (const target of matchPaths(specifier)) { + const resolved = jiti.esmResolve(target, { try: true }); + if (resolved) { + const result = nextResolve(resolved, context); + modules.add(result.url); + return result; + } + } + } + const result = nextResolve(specifier, context); + modules.add(result.url); + return result; + }, + }); + } return { importModule: (path) => jiti.import>(path), close }; } catch (error) { close(); + if ( + !existsSync(join(root, '.void', 'tsconfig.json')) && + error instanceof Error && + /File ['"].*[/\\]\.void[/\\]tsconfig\.json['"] not found/.test(error.message) + ) { + throw new Error('db: Missing .void/tsconfig.json. Run `void prepare` before seeding.', { + cause: error, + }); + } throw error; } } diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 8f09b4d46..5c70f4a48 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -1,5 +1,5 @@ import { spawnSync } from 'node:child_process'; -import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; @@ -352,58 +352,185 @@ export const messages = sqliteTable('messages', { 30_000, ); - it('keeps runtime helpers when extending generated declaration aliases', async () => { - const root = createProjectRoot({ - schema: `import { integer, sqliteTable, text } from 'void/schema-d1'; + it.each(['ts', 'mjs', 'js'])( + 'keeps runtime helpers in %s seeds when extending generated declaration aliases', + async (extension) => { + const root = createProjectRoot({ + schema: `import { integer, sqliteTable, text } from 'void/schema-d1'; export const messages = sqliteTable('messages', { id: integer().primaryKey({ autoIncrement: true }), text: text().notNull(), }); `, - seedFile: { - name: 'seed.ts', - content: `import { defineSeed } from 'void/seed'; + seedFile: { + name: `seed.${extension}`, + content: `import { defineSeed } from 'void/seed'; import { routeUrl } from 'void/routes'; import { messages } from '@schema'; export default defineSeed(async ({ db }) => { await db.insert(messages).values({ text: routeUrl('/messages/[id]', { params: { id: 'hello world' } }) }); }); `, - }, + }, + }); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' })); + mkdirSync(join(root, 'node_modules')); + symlinkSync( + join(import.meta.dirname, '../..'), + join(root, 'node_modules', 'void'), + process.platform === 'win32' ? 'junction' : 'dir', + ); + mkdirSync(join(root, '.void')); + const config = createProjectTsconfig(root, true, true, true); + config.compilerOptions!.paths!['void/seed'] = ['./seed.d.mts']; + config.compilerOptions!.paths!['void/schema-d1'] = ['./schema.d.cts']; + writeFileSync(join(root, '.void', 'tsconfig.json'), JSON.stringify(config)); + writeFileSync( + join(root, '.void', 'routes.d.ts'), + 'export declare function routeUrl(): string;\n', + ); + writeFileSync(join(root, '.void', 'db.d.ts'), 'export {};\n'); + writeFileSync( + join(root, '.void', 'seed.d.mts'), + 'export declare function defineSeed(): void;\n', + ); + writeFileSync(join(root, '.void', 'schema.d.cts'), 'export {};\n'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ extends: './.void/tsconfig.json' }), + ); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); + }, + 30_000, + ); + + it.each( + ['ts', 'mjs', 'js'].flatMap((extension) => + ['static', 'dynamic'].map((importMode) => ({ extension, importMode })), + ), + )( + 'resolves $importMode aliases in $extension seeds before matching packages', + async ({ extension, importMode }) => { + const root = createProjectRoot({ + seedFile: { + name: `seed.${extension}`, + content: `import { sql } from 'drizzle-orm'; +${importMode === 'static' ? "import { value } from 'seed-fixture';" : ''} +export default async function seed({ db }) { + ${importMode === 'dynamic' ? "const { value } = await import('seed-fixture');" : ''} + await db.run(sql\`INSERT INTO messages (text) VALUES (\${value})\`); +} +`, + }, + }); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' })); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { + baseUrl: '.', + paths: { + 'seed-fixture': ['./missing', './fixtures/message.mjs'], + 'seed-*': ['./fixtures/*.d.ts', './fixtures/*.js'], + 'better-sqlite3': ['./fixtures/not-a-driver.js'], + }, + }, + }), + ); + mkdirSync(join(root, 'fixtures')); + writeFileSync( + join(root, 'fixtures', 'message.mjs'), + `import { basename } from 'node:path'; +import { value as prefix } from 'seed-value'; +export const value = prefix + (await import('seed-value')).value; +if (basename(import.meta.url) !== 'message.mjs') throw new Error('Wrong module URL'); +`, + ); + writeFileSync(join(root, 'fixtures', 'value.js'), "export const value = 'local';\n"); + writeFileSync(join(root, 'fixtures', 'value.d.ts'), 'export declare const value: string;\n'); + writeFileSync( + join(root, 'fixtures', 'not-a-driver.js'), + "throw new Error('CLI database imports used seed aliases');\n", + ); + for (const name of ['seed-fixture', 'seed-value']) { + const directory = join(root, 'node_modules', name); + mkdirSync(directory, { recursive: true }); + writeFileSync( + join(directory, 'package.json'), + JSON.stringify({ name, type: 'module', exports: './index.js' }), + ); + writeFileSync(join(directory, 'index.js'), "export const value = 'package';\n"); + } + writeFileSync( + join(root, 'db', 'broken.mjs'), + "import 'seed-fixture';\nexport const value = 1;\n", + ); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import { createRequire } from 'node:module'; +const { runDbCommand } = await import(process.argv[1]); +await runDbCommand(process.argv[2], { action: 'seed' }); +const require = createRequire(process.argv[2] + '/package.json'); +if (!require.resolve('seed-fixture').includes('node_modules')) throw new Error('Seed alias hook leaked'); +let error; +try { await runDbCommand(process.argv[2], { action: 'seed', file: 'db/broken.mjs' }); } +catch (cause) { error = cause; } +if (!error?.message.includes('must export')) throw new Error('Invalid seed was accepted'); +if (!require.resolve('seed-fixture').includes('node_modules')) throw new Error('Failed seed leaked its alias hook');`, + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'locallocal' }]); + }, + 30_000, + ); + + it('suggests void prepare for a missing generated tsconfig before resetting data', async () => { + const root = createProjectRoot({ + seedFile: { name: 'seed.sql', content: "INSERT INTO messages (text) VALUES ('keep me');" }, }); - mkdirSync(join(root, '.void')); - const config = createProjectTsconfig(root, true, true, true); - config.compilerOptions!.paths!['void/seed'] = ['./seed.d.mts']; - config.compilerOptions!.paths!['void/schema-d1'] = ['./schema.d.cts']; - writeFileSync(join(root, '.void', 'tsconfig.json'), JSON.stringify(config)); - writeFileSync( - join(root, '.void', 'routes.d.ts'), - 'export declare function routeUrl(): string;\n', - ); - writeFileSync(join(root, '.void', 'db.d.ts'), 'export {};\n'); - writeFileSync( - join(root, '.void', 'seed.d.mts'), - 'export declare function defineSeed(): void;\n', - ); - writeFileSync(join(root, '.void', 'schema.d.cts'), 'export {};\n'); + await runDbCommand(root, { action: 'seed' }); writeFileSync( join(root, 'tsconfig.json'), JSON.stringify({ extends: './.void/tsconfig.json' }), ); - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', - new URL('../../src/cli/db.ts', import.meta.url).href, - root, - ], - { encoding: 'utf8', timeout: 20_000 }, + writeFileSync(join(root, 'db', 'seed.ts'), 'export default async function seed() {}\n'); + + await expect(runDbCommand(root, { action: 'seed', file: 'db/seed.ts' })).rejects.toThrow( + /void prepare/, ); - expect(result.status, result.stderr).toBe(0); - expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); - }, 30_000); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'keep me' }]); + }); + + it('preserves errors for unrelated missing tsconfig bases', async () => { + const root = createProjectRoot({ + seedFile: { name: 'seed.ts', content: 'export default async function seed() {}\n' }, + }); + writeFileSync(join(root, 'tsconfig.json'), JSON.stringify({ extends: './missing.json' })); + + await expect(runDbCommand(root, { action: 'seed' })).rejects.toThrow( + "File './missing.json' not found.", + ); + }); it('loads CommonJS JavaScript seeds', async () => { const root = createProjectRoot({ From 2e7a421fbd798de89b0af9d427ba4406d952a1d5 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 15:36:37 +0530 Subject: [PATCH 04/10] fix(cli): scope native seed imports to application modules --- packages/void/src/cli/db.ts | 40 +++++--- packages/void/test/unit/db-seed.test.ts | 129 ++++++++++++++++-------- 2 files changed, 115 insertions(+), 54 deletions(-) diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index dfb16079f..c4112c5f3 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -5,13 +5,14 @@ import { mkdtempSync, readFileSync, readdirSync, + realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; import { createRequire, isBuiltin, registerHooks } from 'node:module'; import { tmpdir } from 'node:os'; -import { pathToFileURL } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; import { createJiti } from 'jiti'; @@ -2604,15 +2605,34 @@ function createSeedModuleLoader(root: string): { // Jiti delegates .mjs and ESM .js to Node. Apply the same paths there, // including imports made by ESM helpers and dynamic imports during the seed. if (matchPaths) { - const jitiUrl = import.meta.resolve('jiti'); - const modules = new Set(); + const appUrl = pathToFileURL(realpathSync(root) + '/').href; hooks = registerHooks({ resolve(specifier, context, nextResolve) { - // Only follow Jiti's native imports and their descendants. CLI imports - // made while resetting the database must keep their own resolution. - if (context.parentURL !== jitiUrl && !modules.has(context.parentURL ?? '')) { + // Use the importer's location for both ESM and CommonJS. Installed + // dependencies resolve their imports in their own package scope. + const parent = context.parentURL; + if ( + !parent?.startsWith(appUrl) || + parent.slice(appUrl.length - 1).includes('/node_modules/') + ) { return nextResolve(specifier, context); } + // Generated schema barrels re-export extensionless TypeScript paths. + if (specifier.startsWith('./') || specifier.startsWith('../')) { + try { + return nextResolve(specifier, context); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_UNSUPPORTED_DIR_IMPORT') { + const target = new URL(specifier, parent); + const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); + if (resolved) { + return nextResolve(resolved + target.search + target.hash, context); + } + } + throw error; + } + } if ( !isBuiltin(specifier) && !isAbsolute(specifier) && @@ -2622,15 +2642,11 @@ function createSeedModuleLoader(root: string): { for (const target of matchPaths(specifier)) { const resolved = jiti.esmResolve(target, { try: true }); if (resolved) { - const result = nextResolve(resolved, context); - modules.add(result.url); - return result; + return nextResolve(resolved, context); } } } - const result = nextResolve(specifier, context); - modules.add(result.url); - return result; + return nextResolve(specifier, context); }, }); } diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 5c70f4a48..18b48be69 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -1,7 +1,6 @@ import { spawnSync } from 'node:child_process'; import { existsSync, mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import * as output from '../../src/cli/output.ts'; import { createProjectTsconfig } from '../../src/codegen/project-tsconfig.ts'; @@ -109,6 +108,22 @@ async function readMessages(root: string): Promise { let runDbCommand: typeof import('../../src/cli/db.ts').runDbCommand; @@ -236,21 +251,7 @@ export const messages = sqliteTable("messages", { }); `, ); - const dbModule = pathToFileURL(join(import.meta.dirname, '../../src/cli/db.ts')).href; - - // Plain Node, because Vitest's module runner resolves extensionless imports. - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - `const { runDbCommand } = await import(${JSON.stringify(dbModule)}); -await runDbCommand(${JSON.stringify(root)}, { action: 'seed' });`, - ], - { encoding: 'utf8', timeout: 20_000 }, - ); - - expect(result.status, result.stderr).toBe(0); + runSeedInNode(root); expect(await readMessages(root)).toEqual([{ id: 1, text: 'from barrel' }]); }, 30_000); @@ -333,20 +334,7 @@ export const messages = sqliteTable('messages', { // Loading CLI modules must not evaluate the app's Vite config. writeFileSync(join(root, 'vite.config.ts'), "throw new Error('Vite config was loaded');\n"); - // Use plain Node so Vitest cannot resolve the imports for the seed loader. - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', - new URL('../../src/cli/db.ts', import.meta.url).href, - root, - ], - { encoding: 'utf8', timeout: 20_000 }, - ); - - expect(result.status, result.stderr).toBe(0); + runSeedInNode(root); expect(await readMessages(root)).toEqual([{ id: 1, text: 'from alias' }]); }, 30_000, @@ -399,18 +387,7 @@ export default defineSeed(async ({ db }) => { join(root, 'tsconfig.json'), JSON.stringify({ extends: './.void/tsconfig.json' }), ); - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', - new URL('../../src/cli/db.ts', import.meta.url).href, - root, - ], - { encoding: 'utf8', timeout: 20_000 }, - ); - expect(result.status, result.stderr).toBe(0); + runSeedInNode(root); expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); }, 30_000, @@ -504,6 +481,74 @@ if (!require.resolve('seed-fixture').includes('node_modules')) throw new Error(' 30_000, ); + it('dynamically imports a generated schema barrel from an mjs seed', async () => { + const root = createProjectRoot({ + schema: 'export * from "./schema/messages";', + seedFile: { + name: 'seed.mjs', + content: `export default async function ({ db }) { + const { messages } = await import('@schema'); + await db.insert(messages).values({ text: 'from barrel' }); +}`, + }, + }); + mkdirSync(join(root, 'db/schema')); + writeFileSync( + join(root, 'db/schema/messages.ts'), + `import { sqliteTable, text } from 'drizzle-orm/sqlite-core'; +export const messages = sqliteTable('messages', { text: text().notNull() });`, + ); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@schema': ['./db/schema.ts'] } } }), + ); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from barrel' }]); + }, 30_000); + + it.each(['installed package', 'local CommonJS helper'])( + 'resolves a dynamic #internal import from %s', + async (importer) => { + const installed = importer === 'installed package'; + const root = createProjectRoot({ + seedFile: { + name: installed ? 'seed.mjs' : 'seed.ts', + content: `import { sql } from 'drizzle-orm'; +${installed ? "import { readValue } from 'seed-package';" : "const { readValue } = require('./helper.cjs');"} +export default async function ({ db }) { + const value = await readValue(); + await db.run(sql\`INSERT INTO messages (text) VALUES (\${value})\`); +}`, + }, + }); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '#internal': ['./app.mjs'] } } }), + ); + writeFileSync(join(root, 'app.mjs'), "export default 'app';"); + const helper = "async () => (await import('#internal')).default"; + if (installed) { + const directory = join(root, 'node_modules/seed-package'); + mkdirSync(directory, { recursive: true }); + writeFileSync( + join(directory, 'package.json'), + JSON.stringify({ + type: 'module', + exports: './index.js', + imports: { '#internal': './internal.js' }, + }), + ); + writeFileSync(join(directory, 'index.js'), 'export const readValue = ' + helper); + writeFileSync(join(directory, 'internal.js'), "export default 'package';"); + } else { + writeFileSync(join(root, 'db/helper.cjs'), 'exports.readValue = ' + helper); + } + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: installed ? 'package' : 'app' }]); + }, + 30_000, + ); + it('suggests void prepare for a missing generated tsconfig before resetting data', async () => { const root = createProjectRoot({ seedFile: { name: 'seed.sql', content: "INSERT INTO messages (text) VALUES ('keep me');" }, From f46892910acecb04c563a39629646a2ca29daade Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Wed, 18 Nov 2026 19:49:10 +0900 Subject: [PATCH 05/10] Keep database seed imports in their package scope. --- docs/guide/database.md | 4 +- packages/void/package.json | 1 + packages/void/src/cli/db-seed-loader.ts | 202 ++++++++++++++++++++++++ packages/void/src/cli/db.ts | 137 +--------------- packages/void/test/unit/db-seed.test.ts | 96 ++++++++++- pnpm-lock.yaml | 3 + 6 files changed, 306 insertions(+), 137 deletions(-) create mode 100644 packages/void/src/cli/db-seed-loader.ts diff --git a/docs/guide/database.md b/docs/guide/database.md index 5d28f4800..e2e2ceb66 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,7 +264,9 @@ Use `db/seed.ts` for a programmatic seed or `db/seed.sql` for SQL. JavaScript an Use `db/seed.ts` when you want to generate seed data in code. Export a default function or a named `seed` function. -Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. This works in TypeScript and JavaScript files, including dynamic `import()` calls. +On Node.js, seed files and schema modules use the aliases in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. This includes dynamic `import()` calls and seeds selected with `--file`. Dependencies keep their own package imports, including linked workspace packages. + +Running the CLI directly under Bun uses Bun's own resolver. Use `npx void db seed` if a seed outside your project needs the project's aliases or a workspace package uses a conflicting alias. If your tsconfig extends `.void/tsconfig.json`, run `void prepare` before seeding a fresh checkout. diff --git a/packages/void/package.json b/packages/void/package.json index a6669fec2..ed0ebeac4 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -379,6 +379,7 @@ "drizzle-valibot": "^0.4.2", "drizzle-zod": "^0.8.3", "email-validator": "^2.0.4", + "esbuild": "^0.28.2", "get-tsconfig": "^4.14.3", "gray-matter": "^4.0.3", "hono": "catalog:", diff --git a/packages/void/src/cli/db-seed-loader.ts b/packages/void/src/cli/db-seed-loader.ts new file mode 100644 index 000000000..eb34b17af --- /dev/null +++ b/packages/void/src/cli/db-seed-loader.ts @@ -0,0 +1,202 @@ +import { existsSync, readFileSync, realpathSync } from 'node:fs'; +import nodeModule, { type ResolveHookSync } from 'node:module'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { buildSync, transformSync } from 'esbuild'; +import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; +import { createJiti } from 'jiti'; +import { basename, dirname, extname, isAbsolute, join, toSlash } from 'pathslash'; + +export type SeedModuleImporter = (path: string) => Promise>; + +function seedPaths(root: string) { + const path = join(root, 'tsconfig.json'); + if (!existsSync(path)) { + return null; + } + try { + const project = getTsconfig(path); + const options = project?.config.compilerOptions; + if (!project || !options) { + return null; + } + const paths = Object.fromEntries( + Object.entries(options.paths ?? {}) + .map( + ([name, targets]) => + [name, targets.filter((target) => !/\.d\.[cm]?ts$/.test(target))] as const, + ) + .filter(([, targets]) => targets.length > 0), + ); + if (!Object.keys(paths).length && options.baseUrl === undefined) { + return null; + } + return createPathsMatcher({ ...project, config: { compilerOptions: { ...options, paths } } }); + } catch (error) { + if ( + !existsSync(join(root, '.void/tsconfig.json')) && + error instanceof Error && + /File ['"].*[/\\]\.void[/\\]tsconfig\.json['"] not found/.test(error.message) + ) { + throw new Error('db: Missing .void/tsconfig.json. Run `void prepare` before seeding.', { + cause: error, + }); + } + throw error; + } +} + +function seedScope(root: string, seed: string) { + const directories = new Map([ + [toSlash(realpathSync(root)), true], + [dirname(realpathSync(seed)), true], + ]); + function ownsDirectory(directory: string): boolean { + const known = directories.get(directory); + if (known !== undefined) { + return known; + } + const parent = dirname(directory); + const owned = + parent !== directory && + basename(directory) !== 'node_modules' && + !existsSync(join(directory, 'package.json')) && + ownsDirectory(parent); + directories.set(directory, owned); + return owned; + } + return (url: string) => url.startsWith('file:') && ownsDirectory(dirname(fileURLToPath(url))); +} + +export function createSeedModuleLoader( + root: string, + seed: string, +): { + importModule: SeedModuleImporter; + close: () => void; +} { + const match = seedPaths(root); + const jiti = createJiti(import.meta.url, { + fsCache: false, + moduleCache: false, + interopDefault: false, + tsconfigPaths: false, + }); + if (!match || typeof nodeModule.registerHooks !== 'function') { + return { importModule: (path) => jiti.import>(path), close: () => {} }; + } + const owns = seedScope(root, seed); + const modules = new Set(); + + const resolveImport: ResolveHookSync = (specifier, context, nextResolve) => { + const parent = context.parentURL!; + if (specifier.startsWith('./') || specifier.startsWith('../')) { + try { + return nextResolve(specifier, context); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if ( + code === 'MODULE_NOT_FOUND' || + code === 'ERR_MODULE_NOT_FOUND' || + code === 'ERR_UNSUPPORTED_DIR_IMPORT' + ) { + const target = new URL(specifier, parent); + const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); + if (resolved) { + return { shortCircuit: true, url: resolved + target.search + target.hash }; + } + } + throw error; + } + } + if ( + owns(parent) && + !isAbsolute(specifier) && + !specifier.startsWith('.') && + !/^[\w+.-]+:/.test(specifier) + ) { + for (const target of match(specifier)) { + const resolved = jiti.esmResolve(target, { try: true }); + if (resolved) { + return { shortCircuit: true, url: resolved }; + } + } + } + return nextResolve(specifier, context); + }; + const hooks = nodeModule.registerHooks({ + resolve(specifier, context, nextResolve) { + const parent = context.parentURL; + if (!parent || !modules.has(parent) || nodeModule.isBuiltin(specifier)) { + return nextResolve(specifier, context); + } + const local = owns(parent) || /\.[cm]?ts$/.test(fileURLToPath(parent)); + const result = local + ? resolveImport(specifier, context, nextResolve) + : nextResolve(specifier, context); + if (result.url.startsWith('file:')) { + modules.add(result.url); + if ( + local && + extname(fileURLToPath(result.url)) === '.json' && + !context.importAttributes?.type + ) { + return { ...result, importAttributes: { ...context.importAttributes, type: 'json' } }; + } + } + return result; + }, + load(url, context, nextLoad) { + if (!modules.has(url)) { + return nextLoad(url, context); + } + const sourcefile = fileURLToPath(url); + if (sourcefile.endsWith('.js') && context.format === 'commonjs' && owns(url)) { + const source = readFileSync(sourcefile, 'utf8'); + const { metafile } = buildSync({ + stdin: { sourcefile, contents: source }, + write: false, + metafile: true, + platform: 'node', + target: 'node24', + }); + if (Object.values(metafile.inputs)[0]?.format === 'esm') { + return { format: 'module', source, shortCircuit: true }; + } + } + if (!/\.[cm]?ts$/.test(sourcefile)) { + return nextLoad(url, context); + } + const commonjs = sourcefile.endsWith('.cts'); + const { code } = transformSync(readFileSync(sourcefile, 'utf8'), { + sourcefile, + loader: 'ts', + target: 'node24', + platform: 'node', + format: commonjs ? 'cjs' : 'esm', + sourcemap: 'inline', + ...(commonjs + ? {} + : { + define: { + require: 'import.meta.require', + __filename: 'import.meta.filename', + __dirname: 'import.meta.dirname', + }, + banner: + "import.meta.require = globalThis.process.getBuiltinModule('node:module').createRequire(import.meta.url);", + }), + }); + return { format: commonjs ? 'commonjs' : 'module', source: code, shortCircuit: true }; + }, + }); + return { + async importModule(path) { + const url = pathToFileURL(realpathSync(path)).href; + modules.add(url); + const mod = await import(url); + const cjs = mod['module.exports']; + return cjs && typeof cjs === 'object' ? cjs : mod; + }, + close: () => hooks.deregister(), + }; +} diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index c4112c5f3..472d16d2d 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -2,21 +2,16 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, - mkdtempSync, readFileSync, readdirSync, - realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; -import { createRequire, isBuiltin, registerHooks } from 'node:module'; -import { tmpdir } from 'node:os'; -import { fileURLToPath, pathToFileURL } from 'node:url'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; -import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; -import { createJiti } from 'jiti'; -import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'pathslash'; +import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; import { readConfig, getDatabaseCasing, @@ -56,6 +51,7 @@ import { quoteSqlIdentifier, quoteSqlString, } from './db-export-sequences.ts'; +import type { SeedModuleImporter } from './db-seed-loader.ts'; import { formatTimestamp } from './gen.ts'; import { printSuccess, dim, formatCount, formatUrl, getErrorMessage, pc } from './output.ts'; import { readDeploymentPlatform, readProjectConfig } from './project.ts'; @@ -780,7 +776,10 @@ async function runSeed( const seed = resolveSeedTarget(root, file); const sql = seed.kind === 'sql' ? readFileSync(seed.path, 'utf-8') : undefined; await confirmReset(root, dialect, yes); - const loader = sql === undefined ? createSeedModuleLoader(root) : undefined; + const loader = + sql === undefined + ? (await import('./db-seed-loader.ts')).createSeedModuleLoader(root, seed.path) + : undefined; try { const seedFn = loader ? await loadSeedFunction(seed.path, loader.importModule) : undefined; @@ -2546,126 +2545,6 @@ function collectSchemaModuleFiles(dir: string): Array { return files.sort(); } -type SeedModuleImporter = (path: string) => Promise>; - -function createSeedModuleLoader(root: string): { - importModule: SeedModuleImporter; - close: () => void; -} { - const tsconfigPath = join(root, 'tsconfig.json'); - let directory: string | undefined; - let hooks: ReturnType | undefined; - const close = () => { - hooks?.deregister(); - if (directory) { - rmSync(directory, { recursive: true, force: true }); - } - }; - try { - const project = existsSync(tsconfigPath) ? getTsconfig(tsconfigPath) : null; - const options = project?.config.compilerOptions; - let runtimeTsconfig: string | false = false; - let matchPaths: ReturnType = null; - if (project && options) { - const paths: Record> = {}; - for (const [alias, targets] of Object.entries(options.paths ?? {})) { - const runtimeTargets = targets.filter((target) => !/\.d\.[cm]?ts$/.test(target)); - if (runtimeTargets.length === 0) { - continue; - } - // Resolve each mapping independently, retaining the declaring config's - // path base and the wildcard itself when converting targets to absolute paths. - const matcher = createPathsMatcher({ - ...project, - config: { compilerOptions: { ...options, paths: { [alias]: runtimeTargets } } }, - }); - paths[alias] = matcher!(alias); - } - // Jiti accepts a config filename, not parsed options. Keep this disposable - // runtime config through execution: dynamic imports create child loaders. - directory = mkdtempSync(join(tmpdir(), 'void-seed-')); - runtimeTsconfig = join(directory, 'tsconfig.json'); - const config = { - compilerOptions: { - ...(options.baseUrl !== undefined - ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } - : {}), - paths, - }, - }; - writeFileSync(runtimeTsconfig, JSON.stringify(config)); - matchPaths = createPathsMatcher({ path: runtimeTsconfig, config }); - } - const jiti = createJiti(import.meta.url, { - fsCache: false, - moduleCache: false, - interopDefault: false, - tsconfigPaths: runtimeTsconfig, - }); - // Jiti delegates .mjs and ESM .js to Node. Apply the same paths there, - // including imports made by ESM helpers and dynamic imports during the seed. - if (matchPaths) { - const appUrl = pathToFileURL(realpathSync(root) + '/').href; - hooks = registerHooks({ - resolve(specifier, context, nextResolve) { - // Use the importer's location for both ESM and CommonJS. Installed - // dependencies resolve their imports in their own package scope. - const parent = context.parentURL; - if ( - !parent?.startsWith(appUrl) || - parent.slice(appUrl.length - 1).includes('/node_modules/') - ) { - return nextResolve(specifier, context); - } - // Generated schema barrels re-export extensionless TypeScript paths. - if (specifier.startsWith('./') || specifier.startsWith('../')) { - try { - return nextResolve(specifier, context); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_UNSUPPORTED_DIR_IMPORT') { - const target = new URL(specifier, parent); - const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); - if (resolved) { - return nextResolve(resolved + target.search + target.hash, context); - } - } - throw error; - } - } - if ( - !isBuiltin(specifier) && - !isAbsolute(specifier) && - !specifier.startsWith('.') && - !/^[\w+.-]+:/.test(specifier) - ) { - for (const target of matchPaths(specifier)) { - const resolved = jiti.esmResolve(target, { try: true }); - if (resolved) { - return nextResolve(resolved, context); - } - } - } - return nextResolve(specifier, context); - }, - }); - } - return { importModule: (path) => jiti.import>(path), close }; - } catch (error) { - close(); - if ( - !existsSync(join(root, '.void', 'tsconfig.json')) && - error instanceof Error && - /File ['"].*[/\\]\.void[/\\]tsconfig\.json['"] not found/.test(error.message) - ) { - throw new Error('db: Missing .void/tsconfig.json. Run `void prepare` before seeding.', { - cause: error, - }); - } - throw error; - } -} - /** The schema and casing that `void/db` gives drizzle, or undefined when neither is set. */ function getDrizzleSchemaOptions( schema: Record, diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 18b48be69..6f131e3ec 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -109,15 +109,16 @@ async function readMessages(root: string): Promise { - const installed = importer === 'installed package'; + const installed = importer !== 'local CommonJS helper'; const root = createProjectRoot({ seedFile: { name: installed ? 'seed.mjs' : 'seed.ts', @@ -528,17 +534,31 @@ export default async function ({ db }) { writeFileSync(join(root, 'app.mjs'), "export default 'app';"); const helper = "async () => (await import('#internal')).default"; if (installed) { - const directory = join(root, 'node_modules/seed-package'); + const linked = importer.startsWith('linked'); + const entry = importer === 'linked TypeScript package' ? 'index.ts' : 'index.js'; + const directory = join( + root, + linked ? 'packages/seed-package' : 'node_modules/seed-package', + ); mkdirSync(directory, { recursive: true }); + if (linked) { + mkdirSync(join(root, 'node_modules')); + symlinkSync(directory, join(root, 'node_modules/seed-package'), 'junction'); + } writeFileSync( join(directory, 'package.json'), JSON.stringify({ type: 'module', - exports: './index.js', + exports: './' + entry, imports: { '#internal': './internal.js' }, }), ); - writeFileSync(join(directory, 'index.js'), 'export const readValue = ' + helper); + if (entry === 'index.ts') { + writeFileSync(join(directory, entry), "export { readValue } from './helper';"); + writeFileSync(join(directory, 'helper.ts'), 'export const readValue = ' + helper); + } else { + writeFileSync(join(directory, entry), 'export const readValue = ' + helper); + } writeFileSync(join(directory, 'internal.js'), "export default 'package';"); } else { writeFileSync(join(root, 'db/helper.cjs'), 'exports.readValue = ' + helper); @@ -549,6 +569,45 @@ export default async function ({ db }) { 30_000, ); + it.each([ + { name: 'seed.mjs', external: false }, + { name: 'seed.js', external: false }, + { name: 'seed.mjs', external: true }, + ])( + 'loads a TypeScript enum via a dynamic alias from $name (external: $external)', + async ({ name, external }) => { + const root = createProjectRoot({ + seedFile: { name: 'seed.sql', content: '' }, + schema: + "import { sqliteTable, text } from 'drizzle-orm/sqlite-core'; export const messages = sqliteTable('messages', {text: text().notNull()});", + }); + writeFileSync(join(root, 'package.json'), '{"type":"module"}'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { paths: { '@fixture': ['./fixture.ts'] } }, + }), + ); + writeFileSync(join(root, 'fixture.ts'), "export enum Label { Local = 'local' }"); + const seedDir = external + ? mkdtempSync(join(root, '../.tmp-external-seed-')) + : join(root, 'db'); + if (external) { + roots.push(seedDir); + } + const seedPath = join(seedDir, name); + writeFileSync( + seedPath, + `export default async ({ db, schema }) => { + const { Label } = await import('@fixture'); + await db.insert(schema.messages).values({text: Label.Local}); +};`, + ); + runSeedInNode(root, seedPath); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'local' }]); + }, + ); + it('suggests void prepare for a missing generated tsconfig before resetting data', async () => { const root = createProjectRoot({ seedFile: { name: 'seed.sql', content: "INSERT INTO messages (text) VALUES ('keep me');" }, @@ -593,6 +652,29 @@ export default async function ({ db }) { expect(await readMessages(root)).toEqual([{ id: 1, text: 'from CommonJS' }]); }); + it('keeps ESM syntax in a JavaScript seed and its helpers in a CommonJS app', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.js', + content: `import {value} from './helper.js'; +import { sql } from 'drizzle-orm'; +export default async ({db})=>{ await db.run(sql\`INSERT INTO messages (text) VALUES (\${value})\`); };`, + }, + }); + writeFileSync(join(root, 'package.json'), '{"type":"commonjs"}'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@data': ['./data.json'] } } }), + ); + writeFileSync(join(root, 'data.json'), '{"text":"from json"}'); + writeFileSync( + join(root, 'db/helper.js'), + "export const value = (await import('@data')).default.text;", + ); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from json' }]); + }); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bb68029c0..911f174ad 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -858,6 +858,9 @@ importers: email-validator: specifier: ^2.0.4 version: 2.0.4 + esbuild: + specifier: ^0.28.2 + version: 0.28.2 get-tsconfig: specifier: ^4.14.3 version: 4.14.3 From 6e817b71f442ef5b95e934209a4ad016cdd19fc2 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 14:59:49 +0800 Subject: [PATCH 06/10] Satisfy lint rules in the seed module loader. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/db-seed-loader.ts | 86 ++++++++++++++++++------- 1 file changed, 61 insertions(+), 25 deletions(-) diff --git a/packages/void/src/cli/db-seed-loader.ts b/packages/void/src/cli/db-seed-loader.ts index eb34b17af..707dce9b7 100644 --- a/packages/void/src/cli/db-seed-loader.ts +++ b/packages/void/src/cli/db-seed-loader.ts @@ -1,5 +1,6 @@ import { existsSync, readFileSync, realpathSync } from 'node:fs'; -import nodeModule, { type ResolveHookSync } from 'node:module'; +import nodeModule from 'node:module'; +import type { ResolveHookSync } from 'node:module'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { buildSync, transformSync } from 'esbuild'; import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; @@ -8,6 +9,44 @@ import { basename, dirname, extname, isAbsolute, join, toSlash } from 'pathslash export type SeedModuleImporter = (path: string) => Promise>; +export interface SeedModuleLoader { + importModule: SeedModuleImporter; + /** Remove the module hooks once the seed has finished. */ + close: () => void; +} + +const DECLARATION_SUFFIXES = ['.d.ts', '.d.mts', '.d.cts']; +const TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts']; +const MISSING_MODULE_CODES = new Set([ + 'MODULE_NOT_FOUND', + 'ERR_MODULE_NOT_FOUND', + 'ERR_UNSUPPORTED_DIR_IMPORT', +]); + +function isDeclarationFile(path: string): boolean { + return DECLARATION_SUFFIXES.some((suffix) => path.endsWith(suffix)); +} + +function isTypeScriptFile(path: string): boolean { + return TYPESCRIPT_SUFFIXES.some((suffix) => path.endsWith(suffix)); +} + +/** Whether a specifier starts with a URL scheme such as `node:`, `data:`, or `file:`. */ +function hasUrlScheme(specifier: string): boolean { + const colon = specifier.indexOf(':'); + if (colon <= 0) { + return false; + } + for (const char of specifier.slice(0, colon)) { + const isLetter = (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z'); + const isDigit = char >= '0' && char <= '9'; + if (!isLetter && !isDigit && char !== '+' && char !== '.' && char !== '-' && char !== '_') { + return false; + } + } + return true; +} + function seedPaths(root: string) { const path = join(root, 'tsconfig.json'); if (!existsSync(path)) { @@ -23,7 +62,7 @@ function seedPaths(root: string) { Object.entries(options.paths ?? {}) .map( ([name, targets]) => - [name, targets.filter((target) => !/\.d\.[cm]?ts$/.test(target))] as const, + [name, targets.filter((target) => !isDeclarationFile(target))] as const, ) .filter(([, targets]) => targets.length > 0), ); @@ -32,10 +71,12 @@ function seedPaths(root: string) { } return createPathsMatcher({ ...project, config: { compilerOptions: { ...options, paths } } }); } catch (error) { + // get-tsconfig reports a missing `extends` target as "File '' not found." if ( - !existsSync(join(root, '.void/tsconfig.json')) && error instanceof Error && - /File ['"].*[/\\]\.void[/\\]tsconfig\.json['"] not found/.test(error.message) + error.message.includes('not found') && + toSlash(error.message).includes('/.void/tsconfig.json') && + !existsSync(join(root, '.void/tsconfig.json')) ) { throw new Error('db: Missing .void/tsconfig.json. Run `void prepare` before seeding.', { cause: error, @@ -67,13 +108,7 @@ function seedScope(root: string, seed: string) { return (url: string) => url.startsWith('file:') && ownsDirectory(dirname(fileURLToPath(url))); } -export function createSeedModuleLoader( - root: string, - seed: string, -): { - importModule: SeedModuleImporter; - close: () => void; -} { +export function createSeedModuleLoader(root: string, seed: string): SeedModuleLoader { const match = seedPaths(root); const jiti = createJiti(import.meta.url, { fsCache: false, @@ -81,24 +116,24 @@ export function createSeedModuleLoader( interopDefault: false, tsconfigPaths: false, }); - if (!match || typeof nodeModule.registerHooks !== 'function') { + if (!match) { return { importModule: (path) => jiti.import>(path), close: () => {} }; } const owns = seedScope(root, seed); const modules = new Set(); - const resolveImport: ResolveHookSync = (specifier, context, nextResolve) => { - const parent = context.parentURL!; + const resolveImport = ( + specifier: string, + parent: string, + context: Parameters[1], + nextResolve: Parameters[2], + ): ReturnType => { if (specifier.startsWith('./') || specifier.startsWith('../')) { try { return nextResolve(specifier, context); } catch (error) { const code = (error as NodeJS.ErrnoException).code; - if ( - code === 'MODULE_NOT_FOUND' || - code === 'ERR_MODULE_NOT_FOUND' || - code === 'ERR_UNSUPPORTED_DIR_IMPORT' - ) { + if (code !== undefined && MISSING_MODULE_CODES.has(code)) { const target = new URL(specifier, parent); const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); if (resolved) { @@ -112,7 +147,7 @@ export function createSeedModuleLoader( owns(parent) && !isAbsolute(specifier) && !specifier.startsWith('.') && - !/^[\w+.-]+:/.test(specifier) + !hasUrlScheme(specifier) ) { for (const target of match(specifier)) { const resolved = jiti.esmResolve(target, { try: true }); @@ -129,9 +164,9 @@ export function createSeedModuleLoader( if (!parent || !modules.has(parent) || nodeModule.isBuiltin(specifier)) { return nextResolve(specifier, context); } - const local = owns(parent) || /\.[cm]?ts$/.test(fileURLToPath(parent)); + const local = owns(parent) || isTypeScriptFile(fileURLToPath(parent)); const result = local - ? resolveImport(specifier, context, nextResolve) + ? resolveImport(specifier, parent, context, nextResolve) : nextResolve(specifier, context); if (result.url.startsWith('file:')) { modules.add(result.url); @@ -163,7 +198,7 @@ export function createSeedModuleLoader( return { format: 'module', source, shortCircuit: true }; } } - if (!/\.[cm]?ts$/.test(sourcefile)) { + if (!isTypeScriptFile(sourcefile)) { return nextLoad(url, context); } const commonjs = sourcefile.endsWith('.cts'); @@ -193,9 +228,10 @@ export function createSeedModuleLoader( async importModule(path) { const url = pathToFileURL(realpathSync(path)).href; modules.add(url); - const mod = await import(url); + const mod = (await import(url)) as Record; + // A CommonJS module imported natively exposes its whole `module.exports` under this key. const cjs = mod['module.exports']; - return cjs && typeof cjs === 'object' ? cjs : mod; + return cjs && typeof cjs === 'object' ? (cjs as Record) : mod; }, close: () => hooks.deregister(), }; From a33334700cb73d4e08f2616bc69f3485490e4624 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 15:12:46 +0800 Subject: [PATCH 07/10] Keep package resolution in seeds that use tsconfig aliases. Fall back to jiti when node:module has no registerHooks (Bun), resolve extensionless subpaths into packages without exports, load .tsx helpers, and skip .json files for path targets as TypeScript does. Co-Authored-By: Claude Opus 5.5 --- docs/guide/database.md | 6 +-- packages/void/src/cli/db-seed-loader.ts | 40 +++++++++----- packages/void/test/unit/db-seed.test.ts | 70 ++++++++++++++++++++++++- 3 files changed, 96 insertions(+), 20 deletions(-) diff --git a/docs/guide/database.md b/docs/guide/database.md index e2e2ceb66..3f1c16c74 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,11 +264,7 @@ Use `db/seed.ts` for a programmatic seed or `db/seed.sql` for SQL. JavaScript an Use `db/seed.ts` when you want to generate seed data in code. Export a default function or a named `seed` function. -On Node.js, seed files and schema modules use the aliases in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. This includes dynamic `import()` calls and seeds selected with `--file`. Dependencies keep their own package imports, including linked workspace packages. - -Running the CLI directly under Bun uses Bun's own resolver. Use `npx void db seed` if a seed outside your project needs the project's aliases or a workspace package uses a conflicting alias. - -If your tsconfig extends `.void/tsconfig.json`, run `void prepare` before seeding a fresh checkout. +Seed files and schema modules can import the path aliases in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`, including through dynamic `import()`. If your tsconfig extends `.void/tsconfig.json`, run `void prepare` before seeding a fresh checkout. ```ts // db/seed.ts diff --git a/packages/void/src/cli/db-seed-loader.ts b/packages/void/src/cli/db-seed-loader.ts index 707dce9b7..541c4a63e 100644 --- a/packages/void/src/cli/db-seed-loader.ts +++ b/packages/void/src/cli/db-seed-loader.ts @@ -16,7 +16,7 @@ export interface SeedModuleLoader { } const DECLARATION_SUFFIXES = ['.d.ts', '.d.mts', '.d.cts']; -const TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts']; +const TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts', '.tsx']; const MISSING_MODULE_CODES = new Set([ 'MODULE_NOT_FOUND', 'ERR_MODULE_NOT_FOUND', @@ -31,6 +31,11 @@ function isTypeScriptFile(path: string): boolean { return TYPESCRIPT_SUFFIXES.some((suffix) => path.endsWith(suffix)); } +function isMissingModule(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException).code; + return code !== undefined && MISSING_MODULE_CODES.has(code); +} + /** Whether a specifier starts with a URL scheme such as `node:`, `data:`, or `file:`. */ function hasUrlScheme(specifier: string): boolean { const colon = specifier.indexOf(':'); @@ -116,7 +121,9 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo interopDefault: false, tsconfigPaths: false, }); - if (!match) { + // Bun has no `registerHooks`; there jiti loads the seed and Bun applies the tsconfig paths itself. + const { registerHooks } = nodeModule as Partial; + if (!match || typeof registerHooks !== 'function') { return { importModule: (path) => jiti.import>(path), close: () => {} }; } const owns = seedScope(root, seed); @@ -132,8 +139,7 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo try { return nextResolve(specifier, context); } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code !== undefined && MISSING_MODULE_CODES.has(code)) { + if (isMissingModule(error)) { const target = new URL(specifier, parent); const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); if (resolved) { @@ -143,22 +149,30 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo throw error; } } - if ( - owns(parent) && - !isAbsolute(specifier) && - !specifier.startsWith('.') && - !hasUrlScheme(specifier) - ) { + const bare = !isAbsolute(specifier) && !specifier.startsWith('.') && !hasUrlScheme(specifier); + if (bare && owns(parent)) { for (const target of match(specifier)) { const resolved = jiti.esmResolve(target, { try: true }); + // TypeScript adds code extensions to a path target, never `.json`. + if (resolved && (!resolved.endsWith('.json') || target.endsWith('.json'))) { + return { shortCircuit: true, url: resolved }; + } + } + } + try { + return nextResolve(specifier, context); + } catch (error) { + // Allow extensionless subpaths into packages without `exports`, such as `lodash/range`. + if (bare && isMissingModule(error)) { + const resolved = jiti.esmResolve(specifier, { parentURL: parent, try: true }); if (resolved) { return { shortCircuit: true, url: resolved }; } } + throw error; } - return nextResolve(specifier, context); }; - const hooks = nodeModule.registerHooks({ + const hooks = registerHooks({ resolve(specifier, context, nextResolve) { const parent = context.parentURL; if (!parent || !modules.has(parent) || nodeModule.isBuiltin(specifier)) { @@ -204,7 +218,7 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo const commonjs = sourcefile.endsWith('.cts'); const { code } = transformSync(readFileSync(sourcefile, 'utf8'), { sourcefile, - loader: 'ts', + loader: sourcefile.endsWith('.tsx') ? 'tsx' : 'ts', target: 'node24', platform: 'node', format: commonjs ? 'cjs' : 'esm', diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 55926f0c9..4ebdfe19d 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -48,6 +48,14 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ const roots: Array = []; +const messagesSchema = `import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; + +export const messages = sqliteTable("messages", { + id: integer("id").primaryKey({ autoIncrement: true }), + text: text("text").notNull(), +}); +`; + function createProjectRoot(options: { seedFile: { name: string; content: string }; extraSeedFile?: { name: string; content: string }; @@ -117,13 +125,13 @@ async function readMessages(root: string): Promise{ await db.run(sql\`INSERT INTO messages (text) VAL expect(await readMessages(root)).toEqual([{ id: 1, text: 'from json' }]); }); + it('loads seeds when the runtime has no module hooks', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.ts', + content: `export default async ({ db, schema }) => { + await db.insert(schema.messages).values({ text: 'without hooks' }); +};`, + }, + schema: messagesSchema, + }); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@schema': ['./db/schema.ts'] } } }), + ); + // Bun's node:module has no registerHooks. + runSeedInNode( + root, + undefined, + "(await import('node:module')).default.registerHooks = undefined; ", + ); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'without hooks' }]); + }); + + it('keeps package resolution for extensionless subpaths, .tsx helpers, and .json neighbours', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.ts', + content: `import legacy from 'legacy/plugin/value'; +import named from 'named'; +import { text } from './text'; +export default async ({ db, schema }) => { + await db.insert(schema.messages).values({ text: [legacy, named, text].join(',') }); +};`, + }, + schema: messagesSchema, + }); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { baseUrl: '.', paths: { '@schema': ['./db/schema.ts'] } }, + }), + ); + mkdirSync(join(root, 'node_modules/legacy/plugin'), { recursive: true }); + writeFileSync(join(root, 'node_modules/legacy/package.json'), '{"name":"legacy"}'); + writeFileSync(join(root, 'node_modules/legacy/plugin/value.js'), "module.exports = 'legacy';"); + mkdirSync(join(root, 'node_modules/named'), { recursive: true }); + writeFileSync( + join(root, 'node_modules/named/package.json'), + '{"name":"named","type":"module","exports":"./index.js"}', + ); + writeFileSync(join(root, 'node_modules/named/index.js'), "export default 'package';"); + // TypeScript never maps the baseUrl candidate `named` to this file. + writeFileSync(join(root, 'named.json'), '"json"'); + writeFileSync(join(root, 'db/text.tsx'), "export const text: string = 'tsx';"); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'legacy,package,tsx' }]); + }); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { From 6e26ff751fc2acee962819e27dc98942886487b4 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 15:29:26 +0800 Subject: [PATCH 08/10] Keep jiti's import interop in seeds that use tsconfig aliases. App modules get named exports from JSON files and CommonJS modules, ESM-syntax JavaScript in a CommonJS app keeps require and __dirname, and extensionless absolute paths resolve as relative ones do. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/db-seed-loader.ts | 119 ++++++++++++++++++------ packages/void/test/unit/db-seed.test.ts | 54 +++++++++++ 2 files changed, 143 insertions(+), 30 deletions(-) diff --git a/packages/void/src/cli/db-seed-loader.ts b/packages/void/src/cli/db-seed-loader.ts index 541c4a63e..9beae8e94 100644 --- a/packages/void/src/cli/db-seed-loader.ts +++ b/packages/void/src/cli/db-seed-loader.ts @@ -113,6 +113,62 @@ function seedScope(root: string, seed: string) { return (url: string) => url.startsWith('file:') && ownsDirectory(dirname(fileURLToPath(url))); } +/** Compile an app module to ESM that still has `require`, `__filename`, and `__dirname`. */ +function compileToEsm(sourcefile: string, loader: 'js' | 'ts' | 'tsx'): string { + return transformSync(readFileSync(sourcefile, 'utf8'), { + sourcefile, + loader, + target: 'node24', + platform: 'node', + format: 'esm', + sourcemap: 'inline', + define: { + require: 'import.meta.require', + __filename: 'import.meta.filename', + __dirname: 'import.meta.dirname', + }, + banner: + "import.meta.require = globalThis.process.getBuiltinModule('node:module').createRequire(import.meta.url);", + }).code; +} + +/** ESM that re-exports every named value, which Node's static CommonJS and JSON imports lack. */ +function namedExports(value: unknown): string { + const names = + value !== null && (typeof value === 'object' || typeof value === 'function') + ? Object.keys(value).filter((name) => name !== 'default' && name !== '__esModule') + : []; + return names + .map((name, index) => { + const key = JSON.stringify(name); + return `const __voidExport${index} = __voidValue[${key}];\nexport { __voidExport${index} as ${key} };`; + }) + .join('\n'); +} + +/** A JSON module that also has a named export for each top-level key, as jiti gave seeds. */ +function jsonModule(url: string): string { + const value: unknown = JSON.parse(readFileSync(fileURLToPath(url), 'utf8')); + return `const __voidValue = ${JSON.stringify(value)}; +export default __voidValue; +${namedExports(value)}`; +} + +/** + * A CommonJS module whose named exports are read from its `module.exports`, as jiti gave seeds. + * Node only finds the names it can detect in the source, so `import { range } from 'lodash'` + * would fail to link. The module runs here, and the wrapper gets the cached instance. + */ +function commonjsModule(url: string): string { + const filename = JSON.stringify(fileURLToPath(url)); + const value: unknown = nodeModule.createRequire(url)(fileURLToPath(url)); + return `import { createRequire } from 'node:module'; +const __voidValue = createRequire(import.meta.url)(${filename}); +export default __voidValue && __voidValue.__esModule ? __voidValue.default : __voidValue; +export { __voidValue as 'module.exports' }; +${namedExports(value)}`; +} + export function createSeedModuleLoader(root: string, seed: string): SeedModuleLoader { const match = seedPaths(root); const jiti = createJiti(import.meta.url, { @@ -128,6 +184,8 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo } const owns = seedScope(root, seed); const modules = new Set(); + // Modules that an app module imports with `import`, which get jiti's named-export interop. + const imported = new Set(); const resolveImport = ( specifier: string, @@ -135,10 +193,16 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo context: Parameters[1], nextResolve: Parameters[2], ): ReturnType => { - if (specifier.startsWith('./') || specifier.startsWith('../')) { + const file = + specifier.startsWith('./') || + specifier.startsWith('../') || + specifier.startsWith('/') || + specifier.startsWith('file:'); + if (file) { try { return nextResolve(specifier, context); } catch (error) { + // Add the extension that jiti added for an extensionless path, such as `./users`. if (isMissingModule(error)) { const target = new URL(specifier, parent); const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); @@ -184,12 +248,8 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo : nextResolve(specifier, context); if (result.url.startsWith('file:')) { modules.add(result.url); - if ( - local && - extname(fileURLToPath(result.url)) === '.json' && - !context.importAttributes?.type - ) { - return { ...result, importAttributes: { ...context.importAttributes, type: 'json' } }; + if (local && !context.conditions.includes('require')) { + imported.add(result.url); } } return result; @@ -209,33 +269,32 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo target: 'node24', }); if (Object.values(metafile.inputs)[0]?.format === 'esm') { - return { format: 'module', source, shortCircuit: true }; + return { format: 'module', source: compileToEsm(sourcefile, 'js'), shortCircuit: true }; } } + const interop = imported.has(url) && !context.conditions.includes('require'); + if (interop && extname(sourcefile) === '.json' && !context.importAttributes.type) { + return { format: 'module', source: jsonModule(url), shortCircuit: true }; + } if (!isTypeScriptFile(sourcefile)) { - return nextLoad(url, context); + const result = nextLoad(url, context); + return interop && result.format === 'commonjs' + ? { format: 'module', source: commonjsModule(url), shortCircuit: true } + : result; } - const commonjs = sourcefile.endsWith('.cts'); - const { code } = transformSync(readFileSync(sourcefile, 'utf8'), { - sourcefile, - loader: sourcefile.endsWith('.tsx') ? 'tsx' : 'ts', - target: 'node24', - platform: 'node', - format: commonjs ? 'cjs' : 'esm', - sourcemap: 'inline', - ...(commonjs - ? {} - : { - define: { - require: 'import.meta.require', - __filename: 'import.meta.filename', - __dirname: 'import.meta.dirname', - }, - banner: - "import.meta.require = globalThis.process.getBuiltinModule('node:module').createRequire(import.meta.url);", - }), - }); - return { format: commonjs ? 'commonjs' : 'module', source: code, shortCircuit: true }; + if (sourcefile.endsWith('.cts')) { + const { code } = transformSync(readFileSync(sourcefile, 'utf8'), { + sourcefile, + loader: 'ts', + target: 'node24', + platform: 'node', + format: 'cjs', + sourcemap: 'inline', + }); + return { format: 'commonjs', source: code, shortCircuit: true }; + } + const loader = sourcefile.endsWith('.tsx') ? 'tsx' : 'ts'; + return { format: 'module', source: compileToEsm(sourcefile, loader), shortCircuit: true }; }, }); return { diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 4ebdfe19d..9e77fcf4a 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -749,6 +749,60 @@ export default async ({ db, schema }) => { expect(await readMessages(root)).toEqual([{ id: 1, text: 'legacy,package,tsx' }]); }); + it('keeps CommonJS interop for TypeScript seeds', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.ts', + content: `import { text } from './fixture.json'; +import { value } from 'dynamic-cjs'; +import { label } from './helper'; +import { join } from 'node:path'; +export default async ({ db, schema }) => { + const helper = await import(join(import.meta.dirname, 'helper')); + await db.insert(schema.messages).values({ text: [text, value, label, helper.label].join(',') }); +};`, + }, + schema: messagesSchema, + }); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@schema': ['./db/schema.ts'] } } }), + ); + writeFileSync(join(root, 'db/fixture.json'), '{"text":"json"}'); + writeFileSync(join(root, 'db/helper.ts'), "export const label = 'helper';"); + mkdirSync(join(root, 'node_modules/dynamic-cjs'), { recursive: true }); + writeFileSync(join(root, 'node_modules/dynamic-cjs/package.json'), '{"name":"dynamic-cjs"}'); + // Node's CommonJS export detection cannot see these names. + writeFileSync( + join(root, 'node_modules/dynamic-cjs/index.js'), + "Object.assign(module.exports, Object.fromEntries([['value', 'cjs']]));", + ); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'json,cjs,helper,helper' }]); + }); + + it('keeps require and __dirname in ESM-syntax JavaScript seeds of a CommonJS app', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.js', + content: `import { basename } from 'node:path'; +export default async ({ db, schema }) => { + const { text } = require('./fixture.json'); + await db.insert(schema.messages).values({ text: [text, basename(__dirname)].join(',') }); +};`, + }, + schema: messagesSchema, + }); + writeFileSync(join(root, 'package.json'), '{"type":"commonjs"}'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@schema': ['./db/schema.ts'] } } }), + ); + writeFileSync(join(root, 'db/fixture.json'), '{"text":"json"}'); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'json,db' }]); + }); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { From 9b7b35b8e6fed1687667a17bc1b56f3d6e73d37c Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 15:38:41 +0800 Subject: [PATCH 09/10] Drop the CommonJS export wrapper from seed imports. Running a CommonJS module inside the load hook changed evaluation order, could hit Node's require(esm) race guard, and changed what packages in node_modules received. CommonJS imports keep Node's export detection. JSON named exports now skip a byte order mark, __proto__, and malformed keys, and Windows drive paths get the extension fallback. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/db-seed-loader.ts | 99 ++++++++++++++----------- packages/void/test/unit/db-seed.test.ts | 19 +++-- 2 files changed, 63 insertions(+), 55 deletions(-) diff --git a/packages/void/src/cli/db-seed-loader.ts b/packages/void/src/cli/db-seed-loader.ts index 9beae8e94..22cd3fa23 100644 --- a/packages/void/src/cli/db-seed-loader.ts +++ b/packages/void/src/cli/db-seed-loader.ts @@ -132,41 +132,47 @@ function compileToEsm(sourcefile: string, loader: 'js' | 'ts' | 'tsx'): string { }).code; } -/** ESM that re-exports every named value, which Node's static CommonJS and JSON imports lack. */ -function namedExports(value: unknown): string { - const names = - value !== null && (typeof value === 'object' || typeof value === 'function') - ? Object.keys(value).filter((name) => name !== 'default' && name !== '__esModule') - : []; - return names - .map((name, index) => { - const key = JSON.stringify(name); - return `const __voidExport${index} = __voidValue[${key}];\nexport { __voidExport${index} as ${key} };`; - }) - .join('\n'); -} - -/** A JSON module that also has a named export for each top-level key, as jiti gave seeds. */ -function jsonModule(url: string): string { - const value: unknown = JSON.parse(readFileSync(fileURLToPath(url), 'utf8')); - return `const __voidValue = ${JSON.stringify(value)}; -export default __voidValue; -${namedExports(value)}`; +/** Whether a string has no lone surrogate, which an export name cannot contain. */ +function isWellFormed(value: string): boolean { + for (let index = 0; index < value.length; index++) { + const code = value.charCodeAt(index); + if (code >= 0xd8_00 && code <= 0xdb_ff) { + const next = value.charCodeAt(index + 1); + if (!(next >= 0xdc_00 && next <= 0xdf_ff)) { + return false; + } + index++; + } else if (code >= 0xdc_00 && code <= 0xdf_ff) { + return false; + } + } + return true; } /** - * A CommonJS module whose named exports are read from its `module.exports`, as jiti gave seeds. - * Node only finds the names it can detect in the source, so `import { range } from 'lodash'` - * would fail to link. The module runs here, and the wrapper gets the cached instance. + * A JSON module that also has a named export for each top-level key, as jiti gave seeds, so + * `import { rows } from './fixtures.json'` keeps working. The default export matches Node's. */ -function commonjsModule(url: string): string { - const filename = JSON.stringify(fileURLToPath(url)); - const value: unknown = nodeModule.createRequire(url)(fileURLToPath(url)); - return `import { createRequire } from 'node:module'; -const __voidValue = createRequire(import.meta.url)(${filename}); -export default __voidValue && __voidValue.__esModule ? __voidValue.default : __voidValue; -export { __voidValue as 'module.exports' }; -${namedExports(value)}`; +function jsonModule(url: string): string { + let text = readFileSync(fileURLToPath(url), 'utf8'); + if (text.startsWith('\uFEFF')) { + text = text.slice(1); + } + const value: unknown = JSON.parse(text); + const names = + value !== null && typeof value === 'object' && !Array.isArray(value) + ? Object.keys(value).filter( + (name) => name !== 'default' && name !== '__proto__' && isWellFormed(name), + ) + : []; + return [ + `const __voidValue = JSON.parse(${JSON.stringify(text)});`, + 'export default __voidValue;', + ...names.map((name, index) => { + const key = JSON.stringify(name); + return `const __voidExport${index} = __voidValue[${key}];\nexport { __voidExport${index} as ${key} };`; + }), + ].join('\n'); } export function createSeedModuleLoader(root: string, seed: string): SeedModuleLoader { @@ -184,7 +190,7 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo } const owns = seedScope(root, seed); const modules = new Set(); - // Modules that an app module imports with `import`, which get jiti's named-export interop. + // Modules that an app module imports with `import`. A JSON one gets jiti's named exports. const imported = new Set(); const resolveImport = ( @@ -193,18 +199,20 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo context: Parameters[1], nextResolve: Parameters[2], ): ReturnType => { - const file = + const absolute = isAbsolute(specifier); + if ( + absolute || specifier.startsWith('./') || specifier.startsWith('../') || - specifier.startsWith('/') || - specifier.startsWith('file:'); - if (file) { + specifier.startsWith('file:') + ) { try { return nextResolve(specifier, context); } catch (error) { // Add the extension that jiti added for an extensionless path, such as `./users`. - if (isMissingModule(error)) { - const target = new URL(specifier, parent); + // Node's ESM resolver also rejects a Windows drive path, which jiti accepted. + if (isMissingModule(error) || absolute) { + const target = absolute ? pathToFileURL(specifier) : new URL(specifier, parent); const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); if (resolved) { return { shortCircuit: true, url: resolved + target.search + target.hash }; @@ -213,7 +221,7 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo throw error; } } - const bare = !isAbsolute(specifier) && !specifier.startsWith('.') && !hasUrlScheme(specifier); + const bare = !specifier.startsWith('.') && !hasUrlScheme(specifier); if (bare && owns(parent)) { for (const target of match(specifier)) { const resolved = jiti.esmResolve(target, { try: true }); @@ -272,15 +280,16 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo return { format: 'module', source: compileToEsm(sourcefile, 'js'), shortCircuit: true }; } } - const interop = imported.has(url) && !context.conditions.includes('require'); - if (interop && extname(sourcefile) === '.json' && !context.importAttributes.type) { + if ( + extname(sourcefile) === '.json' && + imported.has(url) && + !context.conditions.includes('require') && + !context.importAttributes.type + ) { return { format: 'module', source: jsonModule(url), shortCircuit: true }; } if (!isTypeScriptFile(sourcefile)) { - const result = nextLoad(url, context); - return interop && result.format === 'commonjs' - ? { format: 'module', source: commonjsModule(url), shortCircuit: true } - : result; + return nextLoad(url, context); } if (sourcefile.endsWith('.cts')) { const { code } = transformSync(readFileSync(sourcefile, 'utf8'), { diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 9e77fcf4a..6d5436e69 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -749,17 +749,17 @@ export default async ({ db, schema }) => { expect(await readMessages(root)).toEqual([{ id: 1, text: 'legacy,package,tsx' }]); }); - it('keeps CommonJS interop for TypeScript seeds', async () => { + it('keeps named JSON imports and extensionless absolute imports in TypeScript seeds', async () => { const root = createProjectRoot({ seedFile: { name: 'seed.ts', content: `import { text } from './fixture.json'; -import { value } from 'dynamic-cjs'; import { label } from './helper'; +import data from './data.cjs'; import { join } from 'node:path'; export default async ({ db, schema }) => { const helper = await import(join(import.meta.dirname, 'helper')); - await db.insert(schema.messages).values({ text: [text, value, label, helper.label].join(',') }); + await db.insert(schema.messages).values({ text: [text, label, data.label, helper.label].join(',') }); };`, }, schema: messagesSchema, @@ -768,17 +768,16 @@ export default async ({ db, schema }) => { join(root, 'tsconfig.json'), JSON.stringify({ compilerOptions: { paths: { '@schema': ['./db/schema.ts'] } } }), ); - writeFileSync(join(root, 'db/fixture.json'), '{"text":"json"}'); + // Editors on Windows may save JSON with a byte order mark. + writeFileSync(join(root, 'db/fixture.json'), '\uFEFF{"text":"json"}'); writeFileSync(join(root, 'db/helper.ts'), "export const label = 'helper';"); - mkdirSync(join(root, 'node_modules/dynamic-cjs'), { recursive: true }); - writeFileSync(join(root, 'node_modules/dynamic-cjs/package.json'), '{"name":"dynamic-cjs"}'); - // Node's CommonJS export detection cannot see these names. + // CommonJS that requires a module the seed has already imported. writeFileSync( - join(root, 'node_modules/dynamic-cjs/index.js'), - "Object.assign(module.exports, Object.fromEntries([['value', 'cjs']]));", + join(root, 'db/data.cjs'), + "module.exports = { label: require('./helper.ts').label };", ); runSeedInNode(root); - expect(await readMessages(root)).toEqual([{ id: 1, text: 'json,cjs,helper,helper' }]); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'json,helper,helper,helper' }]); }); it('keeps require and __dirname in ESM-syntax JavaScript seeds of a CommonJS app', async () => { From 81a4e33b35d66a031599696878aeafbb71c2bf25 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 15:55:40 +0800 Subject: [PATCH 10/10] Share JSON values and package extensions in seed imports. A JSON file that app code imports uses the value require() caches, so both share one object, and every module in the seed graph gets the extension lookup jiti gave it. Aliases still apply only to app modules. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/db-seed-loader.ts | 21 +++++++++---------- packages/void/test/unit/db-seed.test.ts | 27 ++++++++++++++++++++----- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/packages/void/src/cli/db-seed-loader.ts b/packages/void/src/cli/db-seed-loader.ts index 22cd3fa23..cac87044b 100644 --- a/packages/void/src/cli/db-seed-loader.ts +++ b/packages/void/src/cli/db-seed-loader.ts @@ -151,14 +151,12 @@ function isWellFormed(value: string): boolean { /** * A JSON module that also has a named export for each top-level key, as jiti gave seeds, so - * `import { rows } from './fixtures.json'` keeps working. The default export matches Node's. + * `import { rows } from './fixtures.json'` keeps working. The value is the one `require()` caches, + * so an import and a require of the file share one object, as they did with jiti. */ function jsonModule(url: string): string { - let text = readFileSync(fileURLToPath(url), 'utf8'); - if (text.startsWith('\uFEFF')) { - text = text.slice(1); - } - const value: unknown = JSON.parse(text); + const filename = fileURLToPath(url); + const value: unknown = nodeModule.createRequire(url)(filename); const names = value !== null && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value).filter( @@ -166,7 +164,8 @@ function jsonModule(url: string): string { ) : []; return [ - `const __voidValue = JSON.parse(${JSON.stringify(text)});`, + "import { createRequire } from 'node:module';", + `const __voidValue = createRequire(import.meta.url)(${JSON.stringify(filename)});`, 'export default __voidValue;', ...names.map((name, index) => { const key = JSON.stringify(name); @@ -196,6 +195,7 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo const resolveImport = ( specifier: string, parent: string, + local: boolean, context: Parameters[1], nextResolve: Parameters[2], ): ReturnType => { @@ -235,7 +235,7 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo return nextResolve(specifier, context); } catch (error) { // Allow extensionless subpaths into packages without `exports`, such as `lodash/range`. - if (bare && isMissingModule(error)) { + if (bare && local && isMissingModule(error)) { const resolved = jiti.esmResolve(specifier, { parentURL: parent, try: true }); if (resolved) { return { shortCircuit: true, url: resolved }; @@ -250,10 +250,9 @@ export function createSeedModuleLoader(root: string, seed: string): SeedModuleLo if (!parent || !modules.has(parent) || nodeModule.isBuiltin(specifier)) { return nextResolve(specifier, context); } + // Aliases apply only to app modules; every module in the seed graph gets jiti's extensions. const local = owns(parent) || isTypeScriptFile(fileURLToPath(parent)); - const result = local - ? resolveImport(specifier, parent, context, nextResolve) - : nextResolve(specifier, context); + const result = resolveImport(specifier, parent, local, context, nextResolve); if (result.url.startsWith('file:')) { modules.add(result.url); if (local && !context.conditions.includes('require')) { diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 6d5436e69..15fcb705e 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -749,17 +749,18 @@ export default async ({ db, schema }) => { expect(await readMessages(root)).toEqual([{ id: 1, text: 'legacy,package,tsx' }]); }); - it('keeps named JSON imports and extensionless absolute imports in TypeScript seeds', async () => { + it('keeps JSON and extensionless imports in TypeScript seeds', async () => { const root = createProjectRoot({ seedFile: { name: 'seed.ts', - content: `import { text } from './fixture.json'; + content: `import fixture, { text } from './fixture.json'; +import { value as pkg } from 'extensionless-esm'; import { label } from './helper'; import data from './data.cjs'; import { join } from 'node:path'; export default async ({ db, schema }) => { const helper = await import(join(import.meta.dirname, 'helper')); - await db.insert(schema.messages).values({ text: [text, label, data.label, helper.label].join(',') }); + await db.insert(schema.messages).values({ text: [text, label, data.label, helper.label, pkg, data.fixture === fixture].join(',') }); };`, }, schema: messagesSchema, @@ -774,10 +775,26 @@ export default async ({ db, schema }) => { // CommonJS that requires a module the seed has already imported. writeFileSync( join(root, 'db/data.cjs'), - "module.exports = { label: require('./helper.ts').label };", + "module.exports = { label: require('./helper.ts').label, fixture: require('./fixture.json') };", + ); + // A package whose ESM omits the extension of its own files, which jiti accepted. + mkdirSync(join(root, 'node_modules/extensionless-esm'), { recursive: true }); + writeFileSync( + join(root, 'node_modules/extensionless-esm/package.json'), + '{"name":"extensionless-esm","type":"module","exports":"./index.js"}', + ); + writeFileSync( + join(root, 'node_modules/extensionless-esm/index.js'), + "export { value } from './value';", + ); + writeFileSync( + join(root, 'node_modules/extensionless-esm/value.js'), + "export const value = 'package';", ); runSeedInNode(root); - expect(await readMessages(root)).toEqual([{ id: 1, text: 'json,helper,helper,helper' }]); + expect(await readMessages(root)).toEqual([ + { id: 1, text: 'json,helper,helper,helper,package,true' }, + ]); }); it('keeps require and __dirname in ESM-syntax JavaScript seeds of a CommonJS app', async () => {