diff --git a/docs/guide/database.md b/docs/guide/database.md index f4438ad3b..3f1c16c74 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 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 import { defineSeed } from 'void/seed'; diff --git a/packages/void/package.json b/packages/void/package.json index ae781040a..cdab2a1f0 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -378,6 +378,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..22cd3fa23 --- /dev/null +++ b/packages/void/src/cli/db-seed-loader.ts @@ -0,0 +1,320 @@ +import { existsSync, readFileSync, realpathSync } from 'node:fs'; +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'; +import { createJiti } from 'jiti'; +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', '.tsx']; +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)); +} + +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(':'); + 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)) { + 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) => !isDeclarationFile(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) { + // get-tsconfig reports a missing `extends` target as "File '' not found." + if ( + error instanceof Error && + 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, + }); + } + 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))); +} + +/** 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; +} + +/** 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 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 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 { + const match = seedPaths(root); + const jiti = createJiti(import.meta.url, { + fsCache: false, + moduleCache: false, + interopDefault: false, + tsconfigPaths: false, + }); + // 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); + const modules = new Set(); + // Modules that an app module imports with `import`. A JSON one gets jiti's named exports. + const imported = new Set(); + + const resolveImport = ( + specifier: string, + parent: string, + context: Parameters[1], + nextResolve: Parameters[2], + ): ReturnType => { + const absolute = isAbsolute(specifier); + if ( + absolute || + specifier.startsWith('./') || + specifier.startsWith('../') || + specifier.startsWith('file:') + ) { + try { + return nextResolve(specifier, context); + } catch (error) { + // Add the extension that jiti added for an extensionless path, such as `./users`. + // 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 }; + } + } + throw error; + } + } + const bare = !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; + } + }; + const hooks = 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) || isTypeScriptFile(fileURLToPath(parent)); + const result = local + ? resolveImport(specifier, parent, context, nextResolve) + : nextResolve(specifier, context); + if (result.url.startsWith('file:')) { + modules.add(result.url); + if (local && !context.conditions.includes('require')) { + imported.add(result.url); + } + } + 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: compileToEsm(sourcefile, 'js'), shortCircuit: true }; + } + } + 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)) { + return nextLoad(url, context); + } + 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 { + async importModule(path) { + const url = pathToFileURL(realpathSync(path)).href; + modules.add(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 as Record) : mod; + }, + close: () => hooks.deregister(), + }; +} diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 89f43d566..a4e134065 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 { Buffer } from './node-buffer.ts'; import { printSuccess, dim, formatCount, formatUrl, getErrorMessage, pc } from './output.ts'; @@ -776,49 +776,59 @@ async function runSeed( const seed = resolveSeedTarget(root, file); const seedSql = seed.kind === 'sql' ? readFileSync(seed.path, 'utf8') : undefined; await confirmReset(root, dialect, yes); - const preparedSeed = - seedSql === undefined - ? { kind: 'module' as const, run: await loadSeedFunction(seed.path) } - : { kind: 'sql' as const, sql: seedSql }; - // 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 (preparedSeed.kind === 'sql') { - const { sql } = preparedSeed; - if (dialect === 'postgresql') { - await withPgClient(root, async (client) => { - await client.query(sql); - }); - printSuccess(`Seeded from ${seed.displayPath}.`); - - return; + if (seedSql !== undefined) { + await resetBeforeSeed(root, dialect); + await runSqlSeed(root, dialect, seedSql); + if (dialect === 'sqlite') { + log.info(dim("Restart your dev server if it's running.")); } + printSuccess(`Seeded from ${seed.displayPath}.`); + return; + } - if (dialect === 'mysql') { - await withMySqlClient(root, async (client) => { - await client.query(sql); - }); - printSuccess(`Seeded from ${seed.displayPath}.`); + const { createSeedModuleLoader } = await import('./db-seed-loader.ts'); + const loader = createSeedModuleLoader(root, seed.path); + try { + const run = await loadSeedFunction(seed.path, loader.importModule); + await resetBeforeSeed(root, dialect); + await runSeedModule(root, run, dialect, loader.importModule); + } finally { + loader.close(); + } + log.info(dim("Restart your dev server if it's running.")); + printSuccess(`Seeded from ${seed.displayPath}.`); +} - return; - } +/** Drop and re-run migrations before a seed. The drop is already confirmed, so do not ask again. */ +async function resetBeforeSeed(root: string, dialect: DatabaseDialect): Promise { + const migrationCount = await resetDatabase(root, dialect, true); + log.step(`Reset database. Applied ${formatCount(migrationCount, 'migration')}.`); +} - 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, preparedSeed.run, dialect); +async function runSqlSeed(root: string, dialect: DatabaseDialect, sql: string): Promise { + if (dialect === 'postgresql') { + await withPgClient(root, async (client) => { + await client.query(sql); + }); + return; } - log.info(dim("Restart your dev server if it's running.")); - printSuccess(`Seeded from ${seed.displayPath}.`); + if (dialect === 'mysql') { + await withMySqlClient(root, async (client) => { + await client.query(sql); + }); + 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(); + } } /** @@ -2463,8 +2473,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') { @@ -2507,8 +2518,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 @@ -2523,7 +2537,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); @@ -2532,14 +2549,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))); const schema: Record = {}; Object.assign( schema, @@ -2569,16 +2586,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 ad53ec098..6d5436e69 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -1,11 +1,11 @@ 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 { packageFixturePath } from '../../../../test/fixture-dir.ts'; // oxlint-disable-next-line import/no-namespace -- The test replaces or spies on members of the module object. 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(); @@ -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 }; @@ -116,6 +124,23 @@ async function readMessages(root: string): Promise { let runDbCommand: typeof import('../../src/cli/db.ts').runDbCommand; @@ -243,24 +268,540 @@ 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('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('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 { 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(',') }); +};`, + }, + schema: messagesSchema, + }); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@schema': ['./db/schema.ts'] } } }), + ); + // 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';"); + // CommonJS that requires a module the seed has already imported. + writeFileSync( + join(root, 'db/data.cjs'), + "module.exports = { label: require('./helper.ts').label };", + ); + runSeedInNode(root); + 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 () => { + 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: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65ebe33fc..f05671059 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -882,6 +882,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