diff --git a/docs/reference/cli/generate.md b/docs/reference/cli/generate.md index 463481456..a0e994727 100644 --- a/docs/reference/cli/generate.md +++ b/docs/reference/cli/generate.md @@ -33,6 +33,8 @@ Column names must be unique. The names `id`, `created_at`, and `updated_at` are Model names must start with a lowercase letter and can contain lowercase letters, digits, and underscores (e.g. `posts`, `user_roles`). Choose a name that can be used as a TypeScript variable. Existing files are never overwritten. +If the model's schema file already exists, the command exits with an error before creating any files. Edit the schema and use `void db generate` to create a migration for column changes. + ## `void gen migration` {#void-gen-migration} ``` diff --git a/packages/void/src/cli/gen.ts b/packages/void/src/cli/gen.ts index 47ba3d941..0ad19ac1a 100644 --- a/packages/void/src/cli/gen.ts +++ b/packages/void/src/cli/gen.ts @@ -1,5 +1,14 @@ import { spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { + appendFileSync, + existsSync, + lstatSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { join, dirname, relative } from 'pathslash'; import { readConfig, getDatabaseDialect } from '../config.ts'; import type { DatabaseDialect } from '../config.ts'; @@ -7,7 +16,7 @@ import { PLACEHOLDER_DB_URL, writeDrizzleConfig } from '../drizzle/config.ts'; import { snapshotDrizzleOutputs } from '../drizzle/generate.ts'; import { collectMigrations, readJournal } from '../migrations/collect.ts'; import { assertJournalCoherence } from '../migrations/validate.ts'; -import { readProjectPaths } from '../project-paths.ts'; +import { readProjectPaths, resolveProjectPaths } from '../project-paths.ts'; import { hasOwnKey } from '../shared/has-own-key.ts'; import type { GenArgs } from './gen-args.ts'; import { log, select, isCancel, cancel } from './interactive-prompts.ts'; @@ -412,14 +421,20 @@ async function runModel(root: string, name: string, columns: Array): `gen: Model name '${name}' is reserved in TypeScript. Choose a different name.`, ); } - const validator = await resolveValidator(root); - - const dialect = getDatabaseDialect(readConfig(root)); - const paths = readProjectPaths(root); + const config = readConfig(root, { fsCache: false }); + const paths = resolveProjectPaths(root, config); const schemaDir = paths.schemaDir; const barrelPath = paths.schemaFile; const modelPath = join(schemaDir, `${name}.ts`); + const modelFile = relative(root, modelPath); + const modelExistsMessage = `gen: Model '${name}' already exists at ${modelFile}. Edit the schema and update any affected routes.`; + if (lstatSync(modelPath, { throwIfNoEntry: false })) { + throw new Error(modelExistsMessage); + } + + const validator = await resolveValidator(root); + const dialect = getDatabaseDialect(config); // 1. Generate Drizzle table definition const { id, createdAt, updatedAt } = GENERATED_MODEL_COLUMNS; @@ -472,33 +487,72 @@ async function runModel(root: string, name: string, columns: Array): } mkdirSync(schemaDir, { recursive: true }); - writeIfNotExists(modelPath, content); - - // 2. Update or create barrel export - const exportLine = `export * from "./schema/${name}";`; - if (existsSync(barrelPath)) { - const existing = readFileSync(barrelPath, 'utf8'); - if (!existing.includes(exportLine)) { - writeFileSync(barrelPath, existing.trimEnd() + '\n' + exportLine + '\n'); + const exportLine = `export * from "./schema/${name}";\n`; + const routesDir = join(paths.routesDir, 'api', name); + const indexPath = join(routesDir, 'index.ts'); + let createdIndex = false; + let createdModel = false; + let originalBarrel: string | undefined; + let appended = ''; + // Different models share one barrel. A failed scaffold must not roll back another's export. + const { default: lockfile } = await import('proper-lockfile'); + const release = await lockfile.lock(schemaDir, { + retries: { retries: 10, minTimeout: 50, maxTimeout: 1000 }, + }); + try { + try { + writeFileSync(modelPath, content, { flag: 'wx' }); + createdModel = true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') { + throw new Error(modelExistsMessage, { cause: error }); + } + throw error; + } + originalBarrel = existsSync(barrelPath) ? readFileSync(barrelPath, 'utf8') : undefined; + if (!originalBarrel?.includes(exportLine.trimEnd())) { + const separator = originalBarrel && !originalBarrel.endsWith('\n') ? '\n' : ''; + appendFileSync(barrelPath, separator + exportLine); + appended = separator + exportLine; } - } else { - writeFileSync(barrelPath, exportLine + '\n'); - } - // 3. Regenerate .void, including every file that .void/tsconfig.json lists - const { prepareProject } = await import('../codegen/prepare.ts'); - await prepareProject(root); + const { prepareProject } = await import('../codegen/prepare.ts'); + await prepareProject(root); - log.step(`Created ${relative(root, modelPath)}`); - log.step(`Updated ${relative(root, barrelPath)}`); - - // 4. Routes: routes/api//index.ts - const routeIndexPath = join(paths.routesDir, 'api', name, 'index.ts'); - writeIfNotExists(routeIndexPath, generateIndexRoute(name, columns, validator)); + createdIndex = writeIfNotExists(indexPath, generateIndexRoute(name, columns, validator)); + writeIfNotExists(join(routesDir, '[id].ts'), generateIdRoute(name, validator)); + } catch (error) { + if (createdIndex) { + rmSync(indexPath); + } + if (appended && existsSync(barrelPath)) { + const current = readFileSync(barrelPath, 'utf8'); + if (current === (originalBarrel ?? '') + appended) { + if (originalBarrel === undefined) { + rmSync(barrelPath); + } else { + writeFileSync(barrelPath, originalBarrel); + } + } else { + // Preserve edits made to the barrel while project preparation was running. + const lines = current.split('\n'); + const index = lines.indexOf(exportLine.trimEnd()); + if (index !== -1) { + lines.splice(index, 1); + writeFileSync(barrelPath, lines.join('\n')); + } + } + } + if (createdModel && existsSync(modelPath) && readFileSync(modelPath, 'utf8') === content) { + rmSync(modelPath); + } + throw error; + } finally { + await release(); + } - // 5. Route: routes/api//[id].ts - const routeIdPath = join(paths.routesDir, 'api', name, '[id].ts'); - writeIfNotExists(routeIdPath, generateIdRoute(name, validator)); + log.step(`Created ${modelFile}`); + log.step(`Updated ${relative(root, barrelPath)}`); printSuccess('Model scaffolding complete. Run `void db push` to apply.'); } diff --git a/packages/void/src/config-loader.ts b/packages/void/src/config-loader.ts index 1773f538e..83338dc67 100644 --- a/packages/void/src/config-loader.ts +++ b/packages/void/src/config-loader.ts @@ -8,6 +8,7 @@ export const LEGACY_CONFIG_FILE = 'void.json'; export const TYPED_CONFIG_FILE = 'void.config.ts'; export type LoadedVoidConfig = { source: string; value: unknown }; +export type VoidConfigLoadOptions = { fsCache?: boolean }; /** The file to name in messages about a project's settings. Only legacy projects use JSON. */ export function getConfigFileName(root: string): string { @@ -16,7 +17,7 @@ export function getConfigFileName(root: string): string { /** Evaluate a TypeScript config without requiring Void to be installed in the target project. */ // oxlint-disable-next-line quality/no-unknown-returns -- Callers validate the project's default export after loading it. -export function loadTypedVoidConfigFile(path: string): unknown { +export function loadTypedVoidConfigFile(path: string, options?: VoidConfigLoadOptions): unknown { const sourceEntry = fileURLToPath(new URL('./config-entry.ts', import.meta.url)); const configEntry = existsSync(sourceEntry) ? sourceEntry @@ -27,7 +28,10 @@ export function loadTypedVoidConfigFile(path: string): unknown { // config. It lives in the project's own node_modules, never in a shared temporary directory. const nodeModules = join(dirname(path), 'node_modules'); const jiti = createJiti(import.meta.url, { - fsCache: existsSync(nodeModules) ? join(nodeModules, '.cache', 'void', 'config') : false, + fsCache: + options?.fsCache !== false && existsSync(nodeModules) + ? join(nodeModules, '.cache', 'void', 'config') + : false, moduleCache: false, interopDefault: false, alias: { 'void/config': configEntry }, @@ -40,7 +44,10 @@ export function loadTypedVoidConfigFile(path: string): unknown { } /** Load project-authored configuration before runtime validation. */ -export function loadVoidConfig(root: string): LoadedVoidConfig | null { +export function loadVoidConfig( + root: string, + options?: VoidConfigLoadOptions, +): LoadedVoidConfig | null { const typedPath = join(root, TYPED_CONFIG_FILE); const jsonPath = join(root, LEGACY_CONFIG_FILE); const hasTyped = existsSync(typedPath); @@ -56,7 +63,7 @@ export function loadVoidConfig(root: string): LoadedVoidConfig | null { if (hasTyped) { try { - return { source: TYPED_CONFIG_FILE, value: loadTypedVoidConfigFile(typedPath) }; + return { source: TYPED_CONFIG_FILE, value: loadTypedVoidConfigFile(typedPath, options) }; } catch (error) { const base = `config: Could not load ${TYPED_CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`; const hint = aliasHint(error, TYPED_CONFIG_FILE); diff --git a/packages/void/src/config.ts b/packages/void/src/config.ts index 9444047f7..75ee59d8d 100644 --- a/packages/void/src/config.ts +++ b/packages/void/src/config.ts @@ -5,6 +5,7 @@ import { VOID_AUTH_PROVIDERS, isVoidAuthProvider } from './auth/providers.ts'; import type { VoidAuthProvider } from './auth/providers.ts'; import type { DevRedirectRule, HeaderRule } from './cli/types.ts'; import { loadVoidConfig } from './config-loader.ts'; +import type { VoidConfigLoadOptions } from './config-loader.ts'; import type { HeadConfig } from './pages/head.ts'; import { validateSourceDir } from './project-paths.ts'; import { MimeError, parseAddress } from './runtime/email/mime.ts'; @@ -429,8 +430,8 @@ const MIGRATION_ERRORS = { } satisfies Record; /** Read and validate the project's typed config, with legacy JSON compatibility. */ -export function readConfig(root: string): VoidConfig { - const loaded = loadVoidConfig(root); +export function readConfig(root: string, options?: VoidConfigLoadOptions): VoidConfig { + const loaded = loadVoidConfig(root, options); return loaded ? validateConfig(loaded.value, loaded.source) : {}; } diff --git a/packages/void/test/unit/gen.test.ts b/packages/void/test/unit/gen.test.ts index 5dbf6e867..8ba9cb189 100644 --- a/packages/void/test/unit/gen.test.ts +++ b/packages/void/test/unit/gen.test.ts @@ -194,6 +194,100 @@ afterEach(() => { }); describe('gen model', () => { + it.each([undefined, 'export const existing = 1;\n\n'])( + 'can retry after project preparation fails with initial barrel %j', + async (barrel) => { + writePkg({ zod: '^4.0.0' }); + mkdirSync(join(TMP, 'db'), { recursive: true }); + if (barrel !== undefined) { + writeFileSync(join(TMP, 'db/schema.ts'), barrel); + } + mkdirSync(join(TMP, 'routes'), { recursive: true }); + const health = join(TMP, 'routes/health.ts'); + writeFileSync(health, 'export const HEAD = () => null;'); + const args = parseGenArgs(['model', 'posts', 'title:string']); + + await expect(runGenCommand(TMP, args)).rejects.toThrow(/HEAD/); + expect(existsSync(join(TMP, 'db/schema/posts.ts'))).toBe(false); + if (barrel === undefined) { + expect(existsSync(join(TMP, 'db/schema.ts'))).toBe(false); + } else { + expect(read('db/schema.ts')).toBe(barrel); + } + writeFileSync(health, 'export const GET = () => null;'); + await runGenCommand(TMP, args); + expect(read('db/schema.ts')).toContain('export * from "./schema/posts";'); + expect(read('routes/api/posts/index.ts')).toContain('title'); + expect(read('routes/api/posts/[id].ts')).toContain('export const GET'); + }, + ); + + it('preserves a concurrently scaffolded model when route creation fails', async () => { + writePkg({ zod: '^4.0.0' }); + mkdirSync(join(TMP, 'routes/api'), { recursive: true }); + const blocker = join(TMP, 'routes/api/posts'); + writeFileSync(blocker, 'Keep this file'); + const posts = parseGenArgs(['model', 'posts']); + const comments = parseGenArgs(['model', 'comments']); + const results = await Promise.allSettled([ + runGenCommand(TMP, posts), + runGenCommand(TMP, comments), + ]); + expect(results.map(({ status }) => status)).toEqual(['rejected', 'fulfilled']); + expect(read('db/schema.ts')).toBe('export * from "./schema/comments";\n'); + expect(read('db/schema/comments.ts')).toContain('export const comments'); + expect(read('routes/api/posts')).toBe('Keep this file'); + expect(existsSync(join(TMP, 'db/schema/posts.ts'))).toBe(false); + rmSync(blocker); + await runGenCommand(TMP, posts); + expect(read('db/schema.ts')).toContain('export * from "./schema/posts";'); + }); + + it.each([ + { description: 'a missing collection route', sourceDir: '', hasRoute: false }, + { description: 'an existing collection route', sourceDir: 'src', hasRoute: true }, + ])( + 'rejects a model rerun with $description before prompting or writing', + async ({ sourceDir, hasRoute }) => { + const schemaPath = join(TMP, sourceDir, 'db/schema/posts.ts'); + const routePath = join(TMP, sourceDir, 'routes/api/posts/index.ts'); + const schema = 'export const posts = { title: "original" };\n'; + const route = '// Existing collection route\n'; + mkdirSync(dirname(schemaPath), { recursive: true }); + mkdirSync(join(TMP, 'node_modules')); + writeFileSync(schemaPath, schema); + writeFileSync( + join(TMP, 'void.config.ts'), + `export default ${JSON.stringify(sourceDir ? { sourceDir } : {})};\n`, + ); + if (hasRoute) { + mkdirSync(dirname(routePath), { recursive: true }); + writeFileSync(routePath, route); + } + const filesBefore = new Set(readdirSync(TMP, { encoding: 'utf8', recursive: true })); + mockSelect.mockResolvedValueOnce('none'); + vi.mocked(outro).mockClear(); + + await expect( + runGenCommand(TMP, { + subcommand: 'model', + name: 'posts', + columns: [{ name: 'body', type: 'text', nullable: false }], + }), + ).rejects.toThrow( + /Model 'posts' already exists at .+\. Edit the schema and update any affected routes\./, + ); + + expect(mockSelect).not.toHaveBeenCalled(); + expect(outro).not.toHaveBeenCalled(); + expect(new Set(readdirSync(TMP, { encoding: 'utf8', recursive: true }))).toEqual(filesBefore); + expect(readFileSync(schemaPath, 'utf8')).toBe(schema); + if (hasRoute) { + expect(readFileSync(routePath, 'utf8')).toBe(route); + } + }, + ); + it.each(['class', 'await', 'arguments'])( 'rejects reserved name %s before scaffolding', async (name) => {