diff --git a/docs/guide/database.md b/docs/guide/database.md index f4438ad3b..e2e2ceb66 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,6 +264,12 @@ 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. + ```ts // db/seed.ts import { defineSeed } from 'void/seed'; diff --git a/packages/void/package.json b/packages/void/package.json index 040acf123..ed0ebeac4 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -379,6 +379,8 @@ "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:", "ignore": "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 7a5058214..472d16d2d 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -11,7 +11,6 @@ import { import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; -import { createJiti } from 'jiti'; import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; import { readConfig, @@ -52,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'; @@ -776,45 +776,53 @@ 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 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; - // 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') { @@ -2470,8 +2479,11 @@ async function runSeedModule( } } -async function loadSeedFunction(seedPath: string): Promise>> { - const mod = await importLocalModule(seedPath); +async function loadSeedFunction( + seedPath: string, + importModule: SeedModuleImporter, +): Promise>> { + const mod = await importModule(seedPath); const seed = typeof mod.default === 'function' ? mod.default @@ -2486,7 +2498,10 @@ async function loadSeedFunction(seedPath: string): Promise>; } -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); @@ -2495,14 +2510,14 @@ async function loadSeedSchema(root: string): Promise> { } if (location.type === 'file') { - const mod = await importLocalModule(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(file))); + const parts = await Promise.all(files.map((file) => importModule(file))); return Object.assign( {}, ...parts.map((mod) => @@ -2530,16 +2545,6 @@ function collectSchemaModuleFiles(dir: string): Array { return files.sort(); } -async function importLocalModule(modulePath: string): Promise> { - // Native import() cannot resolve the extensionless re-exports that `void gen model` writes. - const jiti = createJiti(import.meta.url, { - fsCache: false, - moduleCache: false, - interopDefault: false, - }); - return jiti.import>(modulePath); -} - /** 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 c0c0913cb..6f131e3ec 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -1,9 +1,9 @@ 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'; 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(); @@ -108,6 +108,23 @@ async function readMessages(root: string): Promise { let runDbCommand: typeof import('../../src/cli/db.ts').runDbCommand; @@ -235,24 +252,429 @@ 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 }, - ); + runSeedInNode(root); + 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"); + 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/*': ['./fixtures/*.d.ts', './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"); - expect(result.status, result.stderr).toBe(0); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from alias' }]); + }, + 30_000, + ); + + 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.${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' }), + ); + runSeedInNode(root); + 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('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', + 'linked workspace package', + 'linked TypeScript package', + 'local CommonJS helper', + ])( + 'resolves a dynamic #internal import from %s', + async (importer) => { + const installed = importer !== 'local CommonJS helper'; + 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 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: './' + entry, + imports: { '#internal': './internal.js' }, + }), + ); + 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); + } + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: installed ? 'package' : 'app' }]); + }, + 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');" }, + }); + await runDbCommand(root, { action: 'seed' }); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ extends: './.void/tsconfig.json' }), + ); + 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(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({ + 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('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 9625ae931..911f174ad 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -858,6 +858,12 @@ 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 gray-matter: specifier: ^4.0.3 version: 4.0.3