@duraxis/cli 0.4.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +9 -23
- package/dist/admin.command-Dt5MnwJw.js +299 -0
- package/dist/admin.command-Dt5MnwJw.js.map +1 -0
- package/dist/commands/doctor.command.d.ts +1 -2
- package/dist/commands/minimal-admin.d.ts +4 -0
- package/dist/{config-CjMUqEhV.js → config-BKscNXeW.js} +53 -14
- package/dist/config-BKscNXeW.js.map +1 -0
- package/dist/config.d.ts +4 -6
- package/dist/file-plan-D-Sj3yv0.js +130 -0
- package/dist/file-plan-D-Sj3yv0.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/init/initialization-planner.d.ts +6 -3
- package/dist/init/nest-integration.d.ts +2 -0
- package/dist/init/static-config.d.ts +16 -0
- package/dist/{init.command-B2kKoyfi.js → init.command-DrO29773.js} +12 -17
- package/dist/init.command-DrO29773.js.map +1 -0
- package/dist/initialization-planner-B41PNGWc.js +315 -0
- package/dist/initialization-planner-B41PNGWc.js.map +1 -0
- package/dist/{migration.command-N7ahyx92.js → migration.command-dhRbN4UI.js} +4 -4
- package/dist/{migration.command-N7ahyx92.js.map → migration.command-dhRbN4UI.js.map} +1 -1
- package/dist/minimal-admin-B4ur_cON.js +232 -0
- package/dist/minimal-admin-B4ur_cON.js.map +1 -0
- package/dist/nest-integration-KCc7ZaG6.js +93 -0
- package/dist/nest-integration-KCc7ZaG6.js.map +1 -0
- package/dist/package-manager-Ca5ArUf-.js +269 -0
- package/dist/package-manager-Ca5ArUf-.js.map +1 -0
- package/dist/project-detector-BQWeQZ8Q.js +174 -0
- package/dist/project-detector-BQWeQZ8Q.js.map +1 -0
- package/dist/static-config-g_7qN12_.js +109 -0
- package/dist/static-config-g_7qN12_.js.map +1 -0
- package/dist/templates/project.d.ts +3 -1
- package/package.json +6 -6
- package/dist/admin.command-Chb6x9mF.js +0 -413
- package/dist/admin.command-Chb6x9mF.js.map +0 -1
- package/dist/config-CjMUqEhV.js.map +0 -1
- package/dist/init/managed-project.d.ts +0 -9
- package/dist/init.command-B2kKoyfi.js.map +0 -1
- package/dist/package-manager-BBRBhsIe.js +0 -972
- package/dist/package-manager-BBRBhsIe.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.command-N7ahyx92.js","names":[],"sources":["../src/artifacts.ts","../src/commands/migration.command.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { access, mkdir, readdir, readFile, writeFile, unlink, rename } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport ts from \"typescript\";\nimport {\n checksum,\n canonicalJSON,\n createSnapshot,\n validateSnapshot,\n validateMigrationId,\n validateArtifacts,\n type DuraxisMigration,\n type MigrationArtifact,\n type SchemaSnapshot,\n type SchemaPlan,\n diffSchemas,\n} from \"@duraxis/migrations\";\nimport type { CollectionDefinition } from \"@duraxis/core\";\nimport {\n importFile,\n readJSON,\n requireMigrationConfig,\n type DuraxisConnectionConfig,\n} from \"./config.js\";\n\nexport function artifactChecksum(source: string): string {\n const options: ts.TranspileOptions = {\n compilerOptions: {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n removeComments: true,\n newLine: ts.NewLineKind.LineFeed,\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n useDefineForClassFields: false,\n },\n };\n\n const first = ts.transpileModule(source, options).outputText;\n\n return checksum(ts.transpileModule(first, options).outputText);\n}\n\nexport interface LocalArtifacts {\n readonly artifacts: readonly MigrationArtifact[];\n readonly files: readonly string[];\n readonly snapshots: string;\n readonly directory: string;\n}\n\nexport async function loadArtifacts(\n config: DuraxisConnectionConfig,\n root: string,\n ownsLock = false,\n omitLatest = false,\n): Promise<LocalArtifacts> {\n requireMigrationConfig(config);\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n if (!ownsLock)\n try {\n await access(join(directory, \".duraxis-artifacts.lock\"));\n throw new Error(\n \"Artifact update in progress or stale guard; inspect artifacts before removing the guard\",\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\n .sort();\n\n const artifacts: MigrationArtifact[] = [];\n\n const ids = new Set<string>();\n\n for (const file of files) {\n const id = file.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n validateMigrationId(id);\n\n if (ids.has(id)) throw new Error(`Duplicate migration filename: ${id}`);\n\n ids.add(id);\n\n if (omitLatest && file == files.at(-1)) continue;\n\n const source = await readFile(join(directory, file), \"utf8\");\n const module = (await importFile(join(directory, file))) as { default: DuraxisMigration };\n\n if (module.default?.id != id) throw new Error(`Migration ID does not match filename: ${file}`);\n\n const snapshot = await readJSON<SchemaSnapshot>(join(snapshots, `${id}.json`));\n\n validateSnapshot(snapshot);\n\n artifacts.push({ migration: module.default, checksum: artifactChecksum(source), snapshot });\n }\n\n const expected = new Set([...ids].map((id) => `${id}.json`));\n\n for (const file of await readdir(snapshots))\n if (file.endsWith(\".json\") && file != \"baseline.json\" && !expected.has(file))\n throw new Error(`Orphaned snapshot: ${file}`);\n\n const initial = await readJSON<SchemaSnapshot>(join(snapshots, \"baseline.json\"));\n\n validateSnapshot(initial);\n\n if (\n initial.migrationId !== null ||\n initial.parentMigrationId !== null ||\n initial.collections.length\n )\n throw new Error(\"Invalid empty baseline snapshot\");\n\n validateArtifacts(artifacts);\n\n return { artifacts, files, snapshots, directory };\n}\nexport function migrationId(name: string, previous?: string): string {\n if (name.includes(\"..\") || /[\\\\/]/.test(name))\n throw new Error(\"Migration names cannot contain paths\");\n\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n if (!slug || slug.length > 64) throw new Error(\"Invalid migration name\");\n\n const stamp = new Date().toISOString().replace(/\\D/g, \"\");\n\n const previousStamp = previous?.slice(0, 17);\n\n const prefix =\n previousStamp && previousStamp >= stamp\n ? (BigInt(previousStamp) + 1n).toString().padStart(17, \"0\")\n : stamp;\n\n return `${prefix}_${slug}`;\n}\n\nfunction literal(value: unknown): string {\n return JSON.stringify(value, null, 2)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nexport function renderMigration(id: string, plan?: SchemaPlan): string {\n if (!plan)\n return `import { defineMigration } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n throw new Error(\"Unfinished migration: implement up and provide its expected snapshot\");\\n },\\n});\\n`;\n\n const inverse = diffSchemas(plan.after, plan.before);\n\n const reversible =\n !plan.operations.some(\n (operation) => operation.kind == \"collection\" && operation.after == null,\n ) && inverse.operations.every((operation) => operation.risk != \"requires-data-transformation\");\n\n return `import { defineMigration, applySchemaPlan } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n await applySchemaPlan(context, ${literal(plan)});\\n },\\n${\n reversible\n ? ` async down(context) {\\n${inverse.operations\n .filter((operation) => operation.kind == \"collection\" && operation.after == null)\n .map(\n (operation) =>\n ` for await (const row of context.scan(${JSON.stringify(operation.collection)})) throw new Error(\"Cannot drop a populated collection during generated rollback\");\\n`,\n )\n .join(\"\")} await applySchemaPlan(context, ${literal(inverse)});\\n },\\n`\n : \" // Irreversible automatically: write an explicit data-safe down() if needed.\\n\"\n } });\\n`;\n}\n\nexport async function withArtifactLock<T>(\n directory: string,\n callback: () => Promise<T>,\n): Promise<T> {\n await mkdir(directory, { recursive: true });\n\n const lock = join(directory, \".duraxis-artifacts.lock\");\n\n await writeFile(\n lock,\n canonicalJSON({\n pid: process.pid,\n purpose: \"artifact update; inspect files before removing a stale guard\",\n }),\n { flag: \"wx\" },\n );\n\n try {\n return await callback();\n } finally {\n await unlink(lock);\n }\n}\n\nexport async function writePair(\n migrationPath: string,\n source: string,\n snapshotPath: string,\n snapshot: SchemaSnapshot,\n): Promise<void> {\n await mkdir(resolve(snapshotPath, \"..\"), { recursive: true });\n await writeFile(migrationPath, source, { flag: \"wx\" });\n\n try {\n await writeFile(snapshotPath, JSON.stringify(snapshot, null, 2) + \"\\n\", { flag: \"wx\" });\n } catch (error) {\n await unlink(migrationPath);\n throw error;\n }\n}\n\nexport async function removePair(migrationPath: string, snapshotPath: string): Promise<void> {\n const suffix = `.removing-${randomBytes(6).toString(\"hex\")}`;\n await rename(migrationPath, migrationPath + suffix);\n\n try {\n await rename(snapshotPath, snapshotPath + suffix);\n } catch (error) {\n await rename(migrationPath + suffix, migrationPath);\n throw error;\n }\n\n await unlink(migrationPath + suffix);\n await unlink(snapshotPath + suffix);\n}\n\nexport function snapshotFor(\n id: string,\n parent: string | null,\n schema: readonly CollectionDefinition[],\n): SchemaSnapshot {\n return createSnapshot(id, parent, schema);\n}\n","import { access, writeFile, unlink } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { exportSchema } from \"@duraxis/orm\";\nimport {\n MigrationRunner,\n validateArtifacts,\n createSnapshot,\n diffSchemas,\n schemaHash,\n type SchemaSnapshot,\n type SchemaPlan,\n} from \"@duraxis/migrations\";\nimport {\n CommitOutcomeUnknownError,\n ResourceExhaustedError,\n OperationCancelledError,\n type CollectionDefinition,\n type DuraxisDatabase,\n} from \"@duraxis/core\";\nimport {\n loadConfig,\n readJSON,\n requireMigrationConfig,\n type DuraxisConnectionConfig,\n} from \"../config.js\";\nimport {\n artifactChecksum,\n loadArtifacts,\n migrationId,\n renderMigration,\n withArtifactLock,\n writePair,\n removePair,\n} from \"../artifacts.js\";\n\nimport type { CLIIO } from \"../cli.js\";\nimport type { ParsedCommand } from \"../registry/argument-parser.js\";\nclass MigrationCleanupError extends Error {\n public constructor(cause: unknown) {\n super(\n \"Migration database cleanup failed; inspect storage health and migration status before retrying\",\n { cause },\n );\n this.name = \"DuraxisMigrationCleanupError\";\n }\n}\nasync function withDatabase<T>(\n config: DuraxisConnectionConfig,\n callback: (database: DuraxisDatabase) => Promise<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const database = await config.createDatabase();\n let closing: Promise<void> | undefined;\n const close = () => (closing ??= database.close({ closeStorage: true }));\n const cancel = () => {\n // Observe rejection while the callback unwinds; finally awaits the same close\n // promise and reports cleanup failures rather than discarding them.\n void close().catch(() => undefined);\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n try {\n signal?.throwIfAborted();\n const result = await callback(database);\n signal?.throwIfAborted();\n return result;\n } finally {\n signal?.removeEventListener(\"abort\", cancel);\n try {\n await close();\n } catch (cause) {\n throw new MigrationCleanupError(cause);\n }\n }\n}\n\nfunction summary(plan: SchemaPlan): string {\n return plan.operations.length\n ? plan.operations\n .map(\n (operation) =>\n `${operation.before == null ? \"+\" : operation.after == null ? \"-\" : \"~\"} ${operation.kind} ${operation.collection}/${operation.name} (${operation.risk})`,\n )\n .join(\"\\n\")\n : \"No schema differences.\";\n}\n\nexport async function executeMigration(parsed: ParsedCommand, io: CLIIO): Promise<number> {\n const cwd = io.cwd ?? process.cwd();\n const out = io.out ?? console.log;\n const errorOut = io.error ?? console.error;\n const { values, positionals } = parsed;\n const command = parsed.definition.name;\n const name = positionals[0];\n const jsonErrors = values.json ?? false;\n try {\n io.signal?.throwIfAborted();\n const { config, root, path } = await loadConfig(cwd, values.config, values.database);\n\n io.signal?.throwIfAborted();\n const ownedDatabase = <T>(callback: (database: DuraxisDatabase) => Promise<T>) =>\n withDatabase(config, callback, io.signal);\n requireMigrationConfig(config);\n if (\n [\"migration:generate\", \"migration:baseline\"].includes(command) &&\n config.entities === undefined\n )\n throw new Error(\n \"This command requires a configured ORM entity schema source. Use migration:create for Core-only manual migrations.\",\n );\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n const print = (value: unknown, text: string) => {\n io.signal?.throwIfAborted();\n out(values.json ? JSON.stringify(value, null, 2) : text);\n };\n\n let schemaExporter = exportSchema;\n let Runner = MigrationRunner;\n if (config.moduleFormat === \"cjs\") {\n const require = (await import(\"node:module\")).createRequire(path);\n const migrations: unknown = require(\"@duraxis/migrations\");\n const isMigrationModule = (\n value: unknown,\n ): value is Pick<typeof import(\"@duraxis/migrations\"), \"MigrationRunner\"> =>\n value !== null &&\n typeof value === \"object\" &&\n \"MigrationRunner\" in value &&\n typeof value.MigrationRunner === \"function\";\n if (!isMigrationModule(migrations))\n throw new Error(\"Installed migrations package does not export MigrationRunner\");\n Runner = migrations.MigrationRunner;\n const module: unknown =\n config.entities === undefined ? { exportSchema } : require(\"@duraxis/orm\");\n const isOrmModule = (\n value: unknown,\n ): value is Pick<typeof import(\"@duraxis/orm\"), \"exportSchema\"> =>\n value !== null &&\n typeof value === \"object\" &&\n \"exportSchema\" in value &&\n typeof value.exportSchema === \"function\";\n if (!isOrmModule(module))\n throw new Error(\"Installed ORM package does not export exportSchema\");\n schemaExporter = module.exportSchema;\n }\n\n const entities = async () =>\n schemaExporter(\n typeof config.entities == \"function\" ? await config.entities() : (config.entities ?? []),\n );\n\n if (command == \"migration:snapshot\") {\n if (!values.schema)\n throw new Error(\"Provide --schema with a JSON array of expected collection definitions\");\n\n await withArtifactLock(directory, async () => {\n const { readdir } = await import(\"node:fs/promises\");\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\n .sort();\n\n const latest = files.at(-1);\n\n if (!latest) throw new Error(\"No manual migration found\");\n\n const id = latest.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n const parent = files.at(-2)?.replace(/\\.(ts|mts|js|mjs)$/, \"\") ?? null;\n\n if (parent) {\n const previous = await readJSON<SchemaSnapshot>(join(snapshots, `${parent}.json`));\n if (previous.migrationId != parent) throw new Error(\"Invalid predecessor snapshot\");\n }\n\n const definitions = await readJSON<readonly CollectionDefinition[]>(\n resolve(cwd, values.schema!),\n );\n\n await writeFile(\n join(snapshots, `${id}.json`),\n JSON.stringify(createSnapshot(id, parent, definitions), null, 2) + \"\\n\",\n { flag: \"wx\" },\n );\n });\n\n print(\n { status: \"snapshot-saved\" },\n \"Saved intended manual snapshot. migrate:up verifies the actual result atomically.\",\n );\n\n return 0;\n }\n\n if ([\"migration:create\", \"migration:generate\", \"migration:baseline\"].includes(command)) {\n if (!name) throw new Error(\"A migration name is required\");\n\n if (command == \"migration:baseline\" && !values.yes)\n throw new Error(\"Baseline adoption requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true);\n const previous = local.artifacts.at(-1);\n\n const id = migrationId(name, previous?.migration.id);\n const migrationPath = join(directory, `${id}.${config.migrations.format ?? \"ts\"}`);\n\n if (command == \"migration:create\") {\n await writeFile(migrationPath, renderMigration(id), { flag: \"wx\" });\n print(\n { id, unfinished: true },\n `Created ${id}. Implement up(), then use migration:snapshot --schema <collections.json>.`,\n );\n return;\n }\n\n const desired = await entities();\n\n const before = previous?.snapshot.collections ?? [];\n const plan = diffSchemas(before, desired);\n\n if (command == \"migration:baseline\" && local.artifacts.length) {\n if (local.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const initial = local.artifacts[0]!;\n const creation = diffSchemas([], desired);\n\n if (\n initial.snapshot.schemaHash != schemaHash(desired) ||\n initial.checksum != artifactChecksum(renderMigration(initial.migration.id, creation))\n )\n throw new Error(\n \"Existing baseline must be an unmodified generated initial-schema migration matching entities\",\n );\n await ownedDatabase((database) => new Runner(database, local.artifacts).baseline());\n\n print(\n { baseline: initial.migration.id, registered: true },\n `Registered existing baseline ${initial.migration.id}`,\n );\n return;\n }\n\n if (!plan.operations.length) {\n print({ operations: [] }, \"No schema differences.\");\n return;\n }\n\n if (plan.operations.some((operation) => operation.risk == \"requires-data-transformation\"))\n throw new Error(\n \"Automatic generation requires a manual data transformation. Use migration:create and provide a snapshot.\",\n );\n\n if (\n plan.operations.some((operation) => operation.risk == \"destructive\") &&\n !values[\"allow-destructive\"]\n )\n throw new Error(\"Destructive generation requires --allow-destructive\");\n\n const snapshot = createSnapshot(id, previous?.migration.id ?? null, desired);\n\n if (command == \"migration:baseline\") {\n await ownedDatabase(async (database) => {\n const actual = await database.getCollectionDefinitions();\n const names = new Set(desired.map((schema) => schema.name));\n\n if (\n schemaHash(actual.filter((schema) => names.has(schema.name))) != snapshot.schemaHash\n )\n throw new Error(\"Persisted managed schema is incompatible with baseline\");\n\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n const loaded = await loadArtifacts(config, root, true);\n\n await new Runner(database, loaded.artifacts).baseline();\n });\n } else\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n print({ id, operations: plan.operations }, `Created ${id}\\n${summary(plan)}`);\n });\n\n return 0;\n }\n\n if (command == \"migration:remove\") {\n if (!values.yes)\n throw new Error(\"Removing the latest unpublished local migration requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true, true);\n\n const latestFile = local.files.at(-1);\n\n const latest = latestFile?.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n if (!latest) throw new Error(\"No local migration to remove\");\n\n await ownedDatabase(async (database) => {\n const status = await new Runner(database, local.artifacts).status();\n\n if (status.applied.some((entry) => entry.id == latest))\n throw new Error(\"Cannot remove an applied migration\");\n\n const snapshotPath = join(snapshots, `${latest}.json`);\n\n try {\n await access(snapshotPath);\n } catch (error) {\n if (!(error instanceof Error && \"code\" in error && error.code === \"ENOENT\"))\n throw error;\n\n await unlink(join(directory, latestFile!));\n\n return;\n }\n\n await removePair(join(directory, latestFile!), snapshotPath);\n });\n\n print(\n { removed: latest },\n `Removed ${latest}. This checks only the configured database; never remove shared or released migrations.`,\n );\n });\n\n return 0;\n }\n\n const local = await loadArtifacts(config, root);\n const checkEntitySchema = async (): Promise<boolean> => {\n if (config.entities === undefined) return false;\n const difference = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n if (difference.operations.length)\n throw new Error(`Unrepresented entity changes:\\n${summary(difference)}`);\n return true;\n };\n\n if (command == \"migrate:diff\" && !values.persisted) {\n if (config.entities === undefined)\n throw new Error(\n \"Local schema diff requires an entity schema source; use --persisted to validate the applied catalog\",\n );\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n print(plan, summary(plan));\n\n return 0;\n }\n\n if (command == \"migrate:check\" && values.offline) {\n validateArtifacts(local.artifacts);\n\n const entitySchemaChecked = await checkEntitySchema();\n print(\n { valid: true, mode: \"offline\", entitySchemaChecked },\n entitySchemaChecked\n ? \"Local files, snapshots, and entity schema are valid. Database history was not checked.\"\n : \"Local files and snapshots are valid. No entity schema source configured; database history was not checked.\",\n );\n\n return 0;\n }\n\n if (command == \"migrate:up\" && values[\"dry-run\"]) {\n const steps = values.steps === undefined ? undefined : Number(values.steps);\n\n if (steps !== undefined && (!Number.isSafeInteger(steps) || steps < 0))\n throw new Error(\"Invalid steps\");\n\n if (\n values.to &&\n (!local.artifacts.some((artifact) => artifact.migration.id == values.to) ||\n steps !== undefined)\n )\n throw new Error(\"Invalid target or conflicting --steps\");\n\n const candidates = local.artifacts\n .filter((artifact) => !values.to || artifact.migration.id <= values.to)\n .slice(0, steps ?? Infinity)\n .map((artifact) => artifact.migration.id);\n\n print(\n { dryRun: true, appliedStateChecked: false, candidates },\n `Static preview only; database was not opened and applied state was not checked. Migration callbacks were not executed.\\n${candidates.join(\"\\n\")}`,\n );\n\n return 0;\n }\n\n await ownedDatabase(async (database) => {\n const runner = new Runner(database, local.artifacts);\n\n const options = {\n ...(values.steps === undefined ? {} : { steps: Number(values.steps) }),\n ...(values.to ? { to: values.to } : {}),\n allowDestructive: values[\"allow-destructive\"] ?? false,\n };\n\n if (command == \"migrate:up\") {\n const applied = await runner.up(options);\n\n print({ applied }, `Applied ${applied.length} migration(s).\\n${applied.join(\"\\n\")}`);\n } else if (command == \"migrate:down\") {\n if (!values.yes)\n throw new Error(\"Rollback requires --yes; review backups and down() first\");\n\n const reverted = await runner.down({ ...options, allowDestructive: true });\n\n print({ reverted }, `Reverted ${reverted.length} migration(s).`);\n } else if (command == \"migrate:status\") {\n const status = await runner.status();\n\n print(\n status,\n `Duraxis migration status\\nDatabase: ${values.database ?? \"default\"}\\n\\nApplied:\\n${status.applied.map((entry) => ` ${entry.id}`).join(\"\\n\")}\\nPending:\\n${status.pending.map((id) => ` ${id}`).join(\"\\n\")}\\nSchema drift: none\\n${status.applied.length} applied, ${status.pending.length} pending`,\n );\n } else if (command == \"migrate:diff\") {\n const plan = await runner.drift();\n\n print(plan, summary(plan));\n } else if (command == \"migrate:check\") {\n await runner.status();\n\n const entitySchemaChecked = await checkEntitySchema();\n print(\n { valid: true, entitySchemaChecked },\n entitySchemaChecked\n ? \"Migration files, snapshots, history, schema, and entities are valid.\"\n : \"Migration files, snapshots, history and persisted schema are valid. No entity schema source configured.\",\n );\n }\n });\n\n return 0;\n } catch (error) {\n if (io.signal?.aborted || error instanceof MigrationCleanupError) throw error;\n const message =\n error instanceof CommitOutcomeUnknownError\n ? `Commit outcome is unknown for transaction ${error.transactionId}. Reconcile migration status before retrying; do not repeat external side effects.`\n : error instanceof ResourceExhaustedError\n ? error.message\n : error instanceof OperationCancelledError\n ? \"Duraxis operation cancelled or deadline exceeded. Check configured resource deadlines and storage health.\"\n : error instanceof Error\n ? error.message\n : String(error);\n\n errorOut(jsonErrors ? JSON.stringify({ error: message }) : message);\n\n return 1;\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgB,iBAAiB,QAAwB;CACvD,MAAM,UAA+B,EACnC,iBAAiB;EACf,QAAQ,GAAG,aAAa;EACxB,QAAQ,GAAG,WAAW;EACtB,gBAAgB;EAChB,SA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ACrF,OAAO,IAAI,WAAW,gBAAgB;IACpC,IAAI,CAAC,OAAO,KACV,MAAM,IAAI,MAAM,0DAA0D;IAE5E,MAAM,WAAW,MAAM,OAAO,KAAK;KAAE,GAAG;KAAS,kBAAkB;IAAK,CAAC;IAEzE,MAAM,EAAE,SAAS,GAAG,YAAY,SAAS,OAAO,eAAe;GACjE,OAAO,IAAI,WAAW,kBAAkB;IACtC,MAAM,SAAS,MAAM,OAAO,OAAO;IAEnC,MACE,QACA,uCAAuC,OAAO,YAAY,UAAU,gBAAgB,OAAO,QAAQ,KAAK,UAAU,KAAK,MAAM,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,cAAc,OAAO,QAAQ,KAAK,OAAO,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,wBAAwB,OAAO,QAAQ,OAAO,YAAY,OAAO,QAAQ,OAAO,SAC/R;GACF,OAAO,IAAI,WAAW,gBAAgB;IACpC,MAAM,OAAO,MAAM,OAAO,MAAM;IAEhC,MAAM,MAAM,QAAQ,IAAI,CAAC;GAC3B,OAAO,IAAI,WAAW,iBAAiB;IACrC,MAAM,OAAO,OAAO;IAEpB,MAAM,sBAAsB,MAAM,kBAAkB;IACpD,MACE;KAAE,OAAO;KAAM;IAAoB,GACnC,sBACI,yEACA,yGACN;GACF;EACF,CAAC;EAED,OAAO;CACT,SAAS,OAAO;EACd,IAAI,GAAG,QAAQ,WAAW,iBAAiB,uBAAuB,MAAM;EACxE,MAAM,UACJ,iBAAiB,4BACb,6CAA6C,MAAM,cAAc,sFACjE,iBAAiB,yBACf,MAAM,UACN,iBAAiB,0BACf,8GACA,iBAAiB,QACf,MAAM,UACN,OAAO,KAAK;EAExB,SAAS,aAAa,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC,IAAI,OAAO;EAElE,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"migration.command-dhRbN4UI.js","names":[],"sources":["../src/artifacts.ts","../src/commands/migration.command.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { access, mkdir, readdir, readFile, writeFile, unlink, rename } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport ts from \"typescript\";\nimport {\n checksum,\n canonicalJSON,\n createSnapshot,\n validateSnapshot,\n validateMigrationId,\n validateArtifacts,\n type DuraxisMigration,\n type MigrationArtifact,\n type SchemaSnapshot,\n type SchemaPlan,\n diffSchemas,\n} from \"@duraxis/migrations\";\nimport type { CollectionDefinition } from \"@duraxis/core\";\nimport {\n importFile,\n readJSON,\n requireMigrationConfig,\n type DuraxisConnectionConfig,\n} from \"./config.js\";\n\nexport function artifactChecksum(source: string): string {\n const options: ts.TranspileOptions = {\n compilerOptions: {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n removeComments: true,\n newLine: ts.NewLineKind.LineFeed,\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n useDefineForClassFields: false,\n },\n };\n\n const first = ts.transpileModule(source, options).outputText;\n\n return checksum(ts.transpileModule(first, options).outputText);\n}\n\nexport interface LocalArtifacts {\n readonly artifacts: readonly MigrationArtifact[];\n readonly files: readonly string[];\n readonly snapshots: string;\n readonly directory: string;\n}\n\nexport async function loadArtifacts(\n config: DuraxisConnectionConfig,\n root: string,\n ownsLock = false,\n omitLatest = false,\n): Promise<LocalArtifacts> {\n requireMigrationConfig(config);\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n if (!ownsLock)\n try {\n await access(join(directory, \".duraxis-artifacts.lock\"));\n throw new Error(\n \"Artifact update in progress or stale guard; inspect artifacts before removing the guard\",\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\n .sort();\n\n const artifacts: MigrationArtifact[] = [];\n\n const ids = new Set<string>();\n\n for (const file of files) {\n const id = file.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n validateMigrationId(id);\n\n if (ids.has(id)) throw new Error(`Duplicate migration filename: ${id}`);\n\n ids.add(id);\n\n if (omitLatest && file == files.at(-1)) continue;\n\n const source = await readFile(join(directory, file), \"utf8\");\n const module = (await importFile(join(directory, file))) as { default: DuraxisMigration };\n\n if (module.default?.id != id) throw new Error(`Migration ID does not match filename: ${file}`);\n\n const snapshot = await readJSON<SchemaSnapshot>(join(snapshots, `${id}.json`));\n\n validateSnapshot(snapshot);\n\n artifacts.push({ migration: module.default, checksum: artifactChecksum(source), snapshot });\n }\n\n const expected = new Set([...ids].map((id) => `${id}.json`));\n\n for (const file of await readdir(snapshots))\n if (file.endsWith(\".json\") && file != \"baseline.json\" && !expected.has(file))\n throw new Error(`Orphaned snapshot: ${file}`);\n\n const initial = await readJSON<SchemaSnapshot>(join(snapshots, \"baseline.json\"));\n\n validateSnapshot(initial);\n\n if (\n initial.migrationId !== null ||\n initial.parentMigrationId !== null ||\n initial.collections.length\n )\n throw new Error(\"Invalid empty baseline snapshot\");\n\n validateArtifacts(artifacts);\n\n return { artifacts, files, snapshots, directory };\n}\nexport function migrationId(name: string, previous?: string): string {\n if (name.includes(\"..\") || /[\\\\/]/.test(name))\n throw new Error(\"Migration names cannot contain paths\");\n\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n if (!slug || slug.length > 64) throw new Error(\"Invalid migration name\");\n\n const stamp = new Date().toISOString().replace(/\\D/g, \"\");\n\n const previousStamp = previous?.slice(0, 17);\n\n const prefix =\n previousStamp && previousStamp >= stamp\n ? (BigInt(previousStamp) + 1n).toString().padStart(17, \"0\")\n : stamp;\n\n return `${prefix}_${slug}`;\n}\n\nfunction literal(value: unknown): string {\n return JSON.stringify(value, null, 2)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nexport function renderMigration(id: string, plan?: SchemaPlan): string {\n if (!plan)\n return `import { defineMigration } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n throw new Error(\"Unfinished migration: implement up and provide its expected snapshot\");\\n },\\n});\\n`;\n\n const inverse = diffSchemas(plan.after, plan.before);\n\n const reversible =\n !plan.operations.some(\n (operation) => operation.kind == \"collection\" && operation.after == null,\n ) && inverse.operations.every((operation) => operation.risk != \"requires-data-transformation\");\n\n return `import { defineMigration, applySchemaPlan } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n await applySchemaPlan(context, ${literal(plan)});\\n },\\n${\n reversible\n ? ` async down(context) {\\n${inverse.operations\n .filter((operation) => operation.kind == \"collection\" && operation.after == null)\n .map(\n (operation) =>\n ` for await (const row of context.scan(${JSON.stringify(operation.collection)})) throw new Error(\"Cannot drop a populated collection during generated rollback\");\\n`,\n )\n .join(\"\")} await applySchemaPlan(context, ${literal(inverse)});\\n },\\n`\n : \" // Irreversible automatically: write an explicit data-safe down() if needed.\\n\"\n } });\\n`;\n}\n\nexport async function withArtifactLock<T>(\n directory: string,\n callback: () => Promise<T>,\n): Promise<T> {\n await mkdir(directory, { recursive: true });\n\n const lock = join(directory, \".duraxis-artifacts.lock\");\n\n await writeFile(\n lock,\n canonicalJSON({\n pid: process.pid,\n purpose: \"artifact update; inspect files before removing a stale guard\",\n }),\n { flag: \"wx\" },\n );\n\n try {\n return await callback();\n } finally {\n await unlink(lock);\n }\n}\n\nexport async function writePair(\n migrationPath: string,\n source: string,\n snapshotPath: string,\n snapshot: SchemaSnapshot,\n): Promise<void> {\n await mkdir(resolve(snapshotPath, \"..\"), { recursive: true });\n await writeFile(migrationPath, source, { flag: \"wx\" });\n\n try {\n await writeFile(snapshotPath, JSON.stringify(snapshot, null, 2) + \"\\n\", { flag: \"wx\" });\n } catch (error) {\n await unlink(migrationPath);\n throw error;\n }\n}\n\nexport async function removePair(migrationPath: string, snapshotPath: string): Promise<void> {\n const suffix = `.removing-${randomBytes(6).toString(\"hex\")}`;\n await rename(migrationPath, migrationPath + suffix);\n\n try {\n await rename(snapshotPath, snapshotPath + suffix);\n } catch (error) {\n await rename(migrationPath + suffix, migrationPath);\n throw error;\n }\n\n await unlink(migrationPath + suffix);\n await unlink(snapshotPath + suffix);\n}\n\nexport function snapshotFor(\n id: string,\n parent: string | null,\n schema: readonly CollectionDefinition[],\n): SchemaSnapshot {\n return createSnapshot(id, parent, schema);\n}\n","import { access, writeFile, unlink } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { exportSchema } from \"@duraxis/orm\";\nimport {\n MigrationRunner,\n validateArtifacts,\n createSnapshot,\n diffSchemas,\n schemaHash,\n type SchemaSnapshot,\n type SchemaPlan,\n} from \"@duraxis/migrations\";\nimport {\n CommitOutcomeUnknownError,\n ResourceExhaustedError,\n OperationCancelledError,\n type CollectionDefinition,\n type DuraxisDatabase,\n} from \"@duraxis/core\";\nimport {\n loadConfig,\n readJSON,\n requireMigrationConfig,\n type DuraxisConnectionConfig,\n} from \"../config.js\";\nimport {\n artifactChecksum,\n loadArtifacts,\n migrationId,\n renderMigration,\n withArtifactLock,\n writePair,\n removePair,\n} from \"../artifacts.js\";\n\nimport type { CLIIO } from \"../cli.js\";\nimport type { ParsedCommand } from \"../registry/argument-parser.js\";\nclass MigrationCleanupError extends Error {\n public constructor(cause: unknown) {\n super(\n \"Migration database cleanup failed; inspect storage health and migration status before retrying\",\n { cause },\n );\n this.name = \"DuraxisMigrationCleanupError\";\n }\n}\nasync function withDatabase<T>(\n config: DuraxisConnectionConfig,\n callback: (database: DuraxisDatabase) => Promise<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const database = await config.createDatabase();\n let closing: Promise<void> | undefined;\n const close = () => (closing ??= database.close({ closeStorage: true }));\n const cancel = () => {\n // Observe rejection while the callback unwinds; finally awaits the same close\n // promise and reports cleanup failures rather than discarding them.\n void close().catch(() => undefined);\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n try {\n signal?.throwIfAborted();\n const result = await callback(database);\n signal?.throwIfAborted();\n return result;\n } finally {\n signal?.removeEventListener(\"abort\", cancel);\n try {\n await close();\n } catch (cause) {\n throw new MigrationCleanupError(cause);\n }\n }\n}\n\nfunction summary(plan: SchemaPlan): string {\n return plan.operations.length\n ? plan.operations\n .map(\n (operation) =>\n `${operation.before == null ? \"+\" : operation.after == null ? \"-\" : \"~\"} ${operation.kind} ${operation.collection}/${operation.name} (${operation.risk})`,\n )\n .join(\"\\n\")\n : \"No schema differences.\";\n}\n\nexport async function executeMigration(parsed: ParsedCommand, io: CLIIO): Promise<number> {\n const cwd = io.cwd ?? process.cwd();\n const out = io.out ?? console.log;\n const errorOut = io.error ?? console.error;\n const { values, positionals } = parsed;\n const command = parsed.definition.name;\n const name = positionals[0];\n const jsonErrors = values.json ?? false;\n try {\n io.signal?.throwIfAborted();\n const { config, root, path } = await loadConfig(cwd, values.config, values.database);\n\n io.signal?.throwIfAborted();\n const ownedDatabase = <T>(callback: (database: DuraxisDatabase) => Promise<T>) =>\n withDatabase(config, callback, io.signal);\n requireMigrationConfig(config);\n if (\n [\"migration:generate\", \"migration:baseline\"].includes(command) &&\n config.entities === undefined\n )\n throw new Error(\n \"This command requires a configured ORM entity schema source. Use migration:create for Core-only manual migrations.\",\n );\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n const print = (value: unknown, text: string) => {\n io.signal?.throwIfAborted();\n out(values.json ? JSON.stringify(value, null, 2) : text);\n };\n\n let schemaExporter = exportSchema;\n let Runner = MigrationRunner;\n if (config.moduleFormat === \"cjs\") {\n const require = (await import(\"node:module\")).createRequire(path);\n const migrations: unknown = require(\"@duraxis/migrations\");\n const isMigrationModule = (\n value: unknown,\n ): value is Pick<typeof import(\"@duraxis/migrations\"), \"MigrationRunner\"> =>\n value !== null &&\n typeof value === \"object\" &&\n \"MigrationRunner\" in value &&\n typeof value.MigrationRunner === \"function\";\n if (!isMigrationModule(migrations))\n throw new Error(\"Installed migrations package does not export MigrationRunner\");\n Runner = migrations.MigrationRunner;\n const module: unknown =\n config.entities === undefined ? { exportSchema } : require(\"@duraxis/orm\");\n const isOrmModule = (\n value: unknown,\n ): value is Pick<typeof import(\"@duraxis/orm\"), \"exportSchema\"> =>\n value !== null &&\n typeof value === \"object\" &&\n \"exportSchema\" in value &&\n typeof value.exportSchema === \"function\";\n if (!isOrmModule(module))\n throw new Error(\"Installed ORM package does not export exportSchema\");\n schemaExporter = module.exportSchema;\n }\n\n const entities = async () =>\n schemaExporter(\n typeof config.entities == \"function\" ? await config.entities() : (config.entities ?? []),\n );\n\n if (command == \"migration:snapshot\") {\n if (!values.schema)\n throw new Error(\"Provide --schema with a JSON array of expected collection definitions\");\n\n await withArtifactLock(directory, async () => {\n const { readdir } = await import(\"node:fs/promises\");\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\n .sort();\n\n const latest = files.at(-1);\n\n if (!latest) throw new Error(\"No manual migration found\");\n\n const id = latest.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n const parent = files.at(-2)?.replace(/\\.(ts|mts|js|mjs)$/, \"\") ?? null;\n\n if (parent) {\n const previous = await readJSON<SchemaSnapshot>(join(snapshots, `${parent}.json`));\n if (previous.migrationId != parent) throw new Error(\"Invalid predecessor snapshot\");\n }\n\n const definitions = await readJSON<readonly CollectionDefinition[]>(\n resolve(cwd, values.schema!),\n );\n\n await writeFile(\n join(snapshots, `${id}.json`),\n JSON.stringify(createSnapshot(id, parent, definitions), null, 2) + \"\\n\",\n { flag: \"wx\" },\n );\n });\n\n print(\n { status: \"snapshot-saved\" },\n \"Saved intended manual snapshot. migrate:up verifies the actual result atomically.\",\n );\n\n return 0;\n }\n\n if ([\"migration:create\", \"migration:generate\", \"migration:baseline\"].includes(command)) {\n if (!name) throw new Error(\"A migration name is required\");\n\n if (command == \"migration:baseline\" && !values.yes)\n throw new Error(\"Baseline adoption requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true);\n const previous = local.artifacts.at(-1);\n\n const id = migrationId(name, previous?.migration.id);\n const migrationPath = join(directory, `${id}.${config.migrations.format ?? \"ts\"}`);\n\n if (command == \"migration:create\") {\n await writeFile(migrationPath, renderMigration(id), { flag: \"wx\" });\n print(\n { id, unfinished: true },\n `Created ${id}. Implement up(), then use migration:snapshot --schema <collections.json>.`,\n );\n return;\n }\n\n const desired = await entities();\n\n const before = previous?.snapshot.collections ?? [];\n const plan = diffSchemas(before, desired);\n\n if (command == \"migration:baseline\" && local.artifacts.length) {\n if (local.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const initial = local.artifacts[0]!;\n const creation = diffSchemas([], desired);\n\n if (\n initial.snapshot.schemaHash != schemaHash(desired) ||\n initial.checksum != artifactChecksum(renderMigration(initial.migration.id, creation))\n )\n throw new Error(\n \"Existing baseline must be an unmodified generated initial-schema migration matching entities\",\n );\n await ownedDatabase((database) => new Runner(database, local.artifacts).baseline());\n\n print(\n { baseline: initial.migration.id, registered: true },\n `Registered existing baseline ${initial.migration.id}`,\n );\n return;\n }\n\n if (!plan.operations.length) {\n print({ operations: [] }, \"No schema differences.\");\n return;\n }\n\n if (plan.operations.some((operation) => operation.risk == \"requires-data-transformation\"))\n throw new Error(\n \"Automatic generation requires a manual data transformation. Use migration:create and provide a snapshot.\",\n );\n\n if (\n plan.operations.some((operation) => operation.risk == \"destructive\") &&\n !values[\"allow-destructive\"]\n )\n throw new Error(\"Destructive generation requires --allow-destructive\");\n\n const snapshot = createSnapshot(id, previous?.migration.id ?? null, desired);\n\n if (command == \"migration:baseline\") {\n await ownedDatabase(async (database) => {\n const actual = await database.getCollectionDefinitions();\n const names = new Set(desired.map((schema) => schema.name));\n\n if (\n schemaHash(actual.filter((schema) => names.has(schema.name))) != snapshot.schemaHash\n )\n throw new Error(\"Persisted managed schema is incompatible with baseline\");\n\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n const loaded = await loadArtifacts(config, root, true);\n\n await new Runner(database, loaded.artifacts).baseline();\n });\n } else\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n print({ id, operations: plan.operations }, `Created ${id}\\n${summary(plan)}`);\n });\n\n return 0;\n }\n\n if (command == \"migration:remove\") {\n if (!values.yes)\n throw new Error(\"Removing the latest unpublished local migration requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true, true);\n\n const latestFile = local.files.at(-1);\n\n const latest = latestFile?.replace(/\\.(ts|mts|js|mjs)$/, \"\");\n\n if (!latest) throw new Error(\"No local migration to remove\");\n\n await ownedDatabase(async (database) => {\n const status = await new Runner(database, local.artifacts).status();\n\n if (status.applied.some((entry) => entry.id == latest))\n throw new Error(\"Cannot remove an applied migration\");\n\n const snapshotPath = join(snapshots, `${latest}.json`);\n\n try {\n await access(snapshotPath);\n } catch (error) {\n if (!(error instanceof Error && \"code\" in error && error.code === \"ENOENT\"))\n throw error;\n\n await unlink(join(directory, latestFile!));\n\n return;\n }\n\n await removePair(join(directory, latestFile!), snapshotPath);\n });\n\n print(\n { removed: latest },\n `Removed ${latest}. This checks only the configured database; never remove shared or released migrations.`,\n );\n });\n\n return 0;\n }\n\n const local = await loadArtifacts(config, root);\n const checkEntitySchema = async (): Promise<boolean> => {\n if (config.entities === undefined) return false;\n const difference = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n if (difference.operations.length)\n throw new Error(`Unrepresented entity changes:\\n${summary(difference)}`);\n return true;\n };\n\n if (command == \"migrate:diff\" && !values.persisted) {\n if (config.entities === undefined)\n throw new Error(\n \"Local schema diff requires an entity schema source; use --persisted to validate the applied catalog\",\n );\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n print(plan, summary(plan));\n\n return 0;\n }\n\n if (command == \"migrate:check\" && values.offline) {\n validateArtifacts(local.artifacts);\n\n const entitySchemaChecked = await checkEntitySchema();\n print(\n { valid: true, mode: \"offline\", entitySchemaChecked },\n entitySchemaChecked\n ? \"Local files, snapshots, and entity schema are valid. Database history was not checked.\"\n : \"Local files and snapshots are valid. No entity schema source configured; database history was not checked.\",\n );\n\n return 0;\n }\n\n if (command == \"migrate:up\" && values[\"dry-run\"]) {\n const steps = values.steps === undefined ? undefined : Number(values.steps);\n\n if (steps !== undefined && (!Number.isSafeInteger(steps) || steps < 0))\n throw new Error(\"Invalid steps\");\n\n if (\n values.to &&\n (!local.artifacts.some((artifact) => artifact.migration.id == values.to) ||\n steps !== undefined)\n )\n throw new Error(\"Invalid target or conflicting --steps\");\n\n const candidates = local.artifacts\n .filter((artifact) => !values.to || artifact.migration.id <= values.to)\n .slice(0, steps ?? Infinity)\n .map((artifact) => artifact.migration.id);\n\n print(\n { dryRun: true, appliedStateChecked: false, candidates },\n `Static preview only; database was not opened and applied state was not checked. Migration callbacks were not executed.\\n${candidates.join(\"\\n\")}`,\n );\n\n return 0;\n }\n\n await ownedDatabase(async (database) => {\n const runner = new Runner(database, local.artifacts);\n\n const options = {\n ...(values.steps === undefined ? {} : { steps: Number(values.steps) }),\n ...(values.to ? { to: values.to } : {}),\n allowDestructive: values[\"allow-destructive\"] ?? false,\n };\n\n if (command == \"migrate:up\") {\n const applied = await runner.up(options);\n\n print({ applied }, `Applied ${applied.length} migration(s).\\n${applied.join(\"\\n\")}`);\n } else if (command == \"migrate:down\") {\n if (!values.yes)\n throw new Error(\"Rollback requires --yes; review backups and down() first\");\n\n const reverted = await runner.down({ ...options, allowDestructive: true });\n\n print({ reverted }, `Reverted ${reverted.length} migration(s).`);\n } else if (command == \"migrate:status\") {\n const status = await runner.status();\n\n print(\n status,\n `Duraxis migration status\\nDatabase: ${values.database ?? \"default\"}\\n\\nApplied:\\n${status.applied.map((entry) => ` ${entry.id}`).join(\"\\n\")}\\nPending:\\n${status.pending.map((id) => ` ${id}`).join(\"\\n\")}\\nSchema drift: none\\n${status.applied.length} applied, ${status.pending.length} pending`,\n );\n } else if (command == \"migrate:diff\") {\n const plan = await runner.drift();\n\n print(plan, summary(plan));\n } else if (command == \"migrate:check\") {\n await runner.status();\n\n const entitySchemaChecked = await checkEntitySchema();\n print(\n { valid: true, entitySchemaChecked },\n entitySchemaChecked\n ? \"Migration files, snapshots, history, schema, and entities are valid.\"\n : \"Migration files, snapshots, history and persisted schema are valid. No entity schema source configured.\",\n );\n }\n });\n\n return 0;\n } catch (error) {\n if (io.signal?.aborted || error instanceof MigrationCleanupError) throw error;\n const message =\n error instanceof CommitOutcomeUnknownError\n ? `Commit outcome is unknown for transaction ${error.transactionId}. Reconcile migration status before retrying; do not repeat external side effects.`\n : error instanceof ResourceExhaustedError\n ? error.message\n : error instanceof OperationCancelledError\n ? \"Duraxis operation cancelled or deadline exceeded. Check configured resource deadlines and storage health.\"\n : error instanceof Error\n ? error.message\n : String(error);\n\n errorOut(jsonErrors ? JSON.stringify({ error: message }) : message);\n\n return 1;\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgB,iBAAiB,QAAwB;CACvD,MAAM,UAA+B,EACnC,iBAAiB;EACf,QAAQ,GAAG,aAAa;EACxB,QAAQ,GAAG,WAAW;EACtB,gBAAgB;EAChB,SAAS,GAAG,YAAY;EACxB,wBAAwB;EACxB,uBAAuB;EACvB,yBAAyB;CAC3B,EACF;CAEA,MAAM,QAAQ,GAAG,gBAAgB,QAAQ,OAAO,CAAC,CAAC;CAElD,OAAO,SAAS,GAAG,gBAAgB,OAAO,OAAO,CAAC,CAAC,UAAU;AAC/D;AASA,eAAsB,cACpB,QACA,MACA,WAAW,OACX,aAAa,OACY;CACzB,uBAAuB,MAAM;CAC7B,MAAM,YAAY,QAAQ,MAAM,OAAO,WAAW,SAAS;CAC3D,MAAM,YAAY,QAAQ,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AQ,KAAK,UAAU,KAAK,MAAM,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,cAAc,OAAO,QAAQ,KAAK,OAAO,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,wBAAwB,OAAO,QAAQ,OAAO,YAAY,OAAO,QAAQ,OAAO,SAC/R;GACF,OAAO,IAAI,WAAW,gBAAgB;IACpC,MAAM,OAAO,MAAM,OAAO,MAAM;IAEhC,MAAM,MAAM,QAAQ,IAAI,CAAC;GAC3B,OAAO,IAAI,WAAW,iBAAiB;IACrC,MAAM,OAAO,OAAO;IAEpB,MAAM,sBAAsB,MAAM,kBAAkB;IACpD,MACE;KAAE,OAAO;KAAM;IAAoB,GACnC,sBACI,yEACA,yGACN;GACF;EACF,CAAC;EAED,OAAO;CACT,SAAS,OAAO;EACd,IAAI,GAAG,QAAQ,WAAW,iBAAiB,uBAAuB,MAAM;EACxE,MAAM,UACJ,iBAAiB,4BACb,6CAA6C,MAAM,cAAc,sFACjE,iBAAiB,yBACf,MAAM,UACN,iBAAiB,0BACf,8GACA,iBAAiB,QACf,MAAM,UACN,OAAO,KAAK;EAExB,SAAS,aAAa,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC,IAAI,OAAO;EAElE,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { inspectStaticConfig, property, replaceExpression, setLiteralProperty } from "./static-config-g_7qN12_.js";
|
|
2
|
+
import { a as extensions, i as entitySource, n as requiredPackages, o as initializationOptions, r as configurationSource } from "./initialization-planner-B41PNGWc.js";
|
|
3
|
+
import { addFile, describePlan, executeFiles } from "./file-plan-D-Sj3yv0.js";
|
|
4
|
+
import { a as configuredRegistry, i as resolveDependencies, n as runProcess, r as RegistryClient, t as installCommands } from "./package-manager-Ca5ArUf-.js";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
7
|
+
import ts from "typescript";
|
|
8
|
+
import { validateConnectionName } from "@duraxis/core";
|
|
9
|
+
// src/commands/minimal-admin.ts
|
|
10
|
+
async function minimalAdmin(parsed, io, project, path, redact) {
|
|
11
|
+
const source = await readFile(path, "utf8");
|
|
12
|
+
const { values, positionals, definition } = parsed;
|
|
13
|
+
let inspected;
|
|
14
|
+
try {
|
|
15
|
+
inspected = inspectStaticConfig(source, path);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (definition.name === "config:show") return {
|
|
18
|
+
unresolved: true,
|
|
19
|
+
files: [path],
|
|
20
|
+
message: "Executable configuration was not evaluated. Use --evaluate explicitly for trusted application code."
|
|
21
|
+
};
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
const selected = values.database ?? inspected.defaultConnection;
|
|
25
|
+
const object = inspected.connections.get(selected);
|
|
26
|
+
if (!object) throw new Error("Unknown named database");
|
|
27
|
+
validateConnectionName(selected);
|
|
28
|
+
for (const name of inspected.connections.keys()) validateConnectionName(name);
|
|
29
|
+
const files = {
|
|
30
|
+
root: project.root,
|
|
31
|
+
files: [],
|
|
32
|
+
directories: [],
|
|
33
|
+
warnings: [],
|
|
34
|
+
dependencies: {},
|
|
35
|
+
devDependencies: {},
|
|
36
|
+
commands: []
|
|
37
|
+
};
|
|
38
|
+
const finish = async () => {
|
|
39
|
+
if (values["dry-run"]) return {
|
|
40
|
+
status: "planned",
|
|
41
|
+
...describePlan(files)
|
|
42
|
+
};
|
|
43
|
+
await executeFiles(files, async () => {
|
|
44
|
+
for (const [command, ...args] of files.commands) await (io.runProcess ?? runProcess)({
|
|
45
|
+
command,
|
|
46
|
+
args,
|
|
47
|
+
cwd: project.root,
|
|
48
|
+
signal: io.signal
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
return {
|
|
52
|
+
status: "updated",
|
|
53
|
+
files: files.files.map((file) => file.path),
|
|
54
|
+
warnings: files.warnings
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
const configPath = relative(project.root, path).replaceAll("\\", "/");
|
|
58
|
+
if (definition.name === "config:show") return {
|
|
59
|
+
configuration: redact(inspected.value),
|
|
60
|
+
connection: selected,
|
|
61
|
+
databaseOpened: false,
|
|
62
|
+
trustedCodeEvaluated: false
|
|
63
|
+
};
|
|
64
|
+
if (definition.name === "connection:list") return {
|
|
65
|
+
default: inspected.defaultConnection,
|
|
66
|
+
connections: [...inspected.connections.keys()].map((name) => ({ name }))
|
|
67
|
+
};
|
|
68
|
+
if (definition.name === "config:validate" || definition.name === "storage:check") {
|
|
69
|
+
if (inspected.ast.parseDiagnostics.length) throw new Error("Invalid configuration syntax");
|
|
70
|
+
for (const [name, connection] of inspected.connections) {
|
|
71
|
+
if (!property(connection, "driver")) throw new Error(`Missing driver for ${name}`);
|
|
72
|
+
if (property(connection, "migrations")?.initializer.kind === ts.SyntaxKind.TrueKeyword) {
|
|
73
|
+
const schema = property(connection, "schema")?.initializer;
|
|
74
|
+
if (schema && ts.isObjectLiteralExpression(schema) && property(schema, "mode")?.initializer && ts.isStringLiteral(property(schema, "mode").initializer) && property(schema, "mode").initializer.text === "create") throw new Error("Migrations require schema validation");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
valid: true,
|
|
79
|
+
databaseOpened: false,
|
|
80
|
+
trustedCodeEvaluated: false,
|
|
81
|
+
message: "Static structure validated. Driver factories and environment expressions remain unevaluated; use --evaluate for trusted runtime validation."
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
if (definition.name === "config:set") {
|
|
85
|
+
const [key, text] = positionals;
|
|
86
|
+
if (!key || text === void 0 || /[\r\n\0]/.test(text)) throw new Error("Usage: config:set <key> <value>; control characters are forbidden");
|
|
87
|
+
if (![
|
|
88
|
+
"namespace",
|
|
89
|
+
"schemaMode",
|
|
90
|
+
"bucket",
|
|
91
|
+
"prefix",
|
|
92
|
+
"region",
|
|
93
|
+
"endpoint",
|
|
94
|
+
"storageDirectory"
|
|
95
|
+
].includes(key)) throw new Error("Unsupported key; edit advanced configuration manually. Secrets must use environment references.");
|
|
96
|
+
if (key === "namespace" && (!/^[A-Za-z0-9_/-]{1,128}$/.test(text) || text.split("/").some((part) => !part || part === ".."))) throw new Error("Invalid namespace");
|
|
97
|
+
if (key === "bucket" && !/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(text)) throw new Error("Invalid bucket");
|
|
98
|
+
if (key === "endpoint") {
|
|
99
|
+
const url = new URL(text);
|
|
100
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error("Endpoint must not contain secrets");
|
|
101
|
+
}
|
|
102
|
+
let updated;
|
|
103
|
+
if (key === "namespace" || key === "schemaMode") {
|
|
104
|
+
const field = key === "namespace" ? "database" : "schema";
|
|
105
|
+
const innerKey = key === "namespace" ? "namespace" : "mode";
|
|
106
|
+
if (key === "schemaMode" && ![
|
|
107
|
+
"create",
|
|
108
|
+
"validate",
|
|
109
|
+
"validate-managed"
|
|
110
|
+
].includes(text)) throw new Error("Invalid schemaMode");
|
|
111
|
+
const migrations = property(object, "migrations")?.initializer;
|
|
112
|
+
if (key === "schemaMode" && text === "create" && migrations && migrations.kind !== ts.SyntaxKind.FalseKeyword) throw new Error("Migrations require validation schema mode");
|
|
113
|
+
const target = property(object, field);
|
|
114
|
+
if (target && !ts.isObjectLiteralExpression(target.initializer)) throw new Error("Dynamic configuration requires manual editing");
|
|
115
|
+
updated = target ? setLiteralProperty(source, target.initializer, innerKey, JSON.stringify(text), inspected.ast) : setLiteralProperty(source, object, field, `{ ${innerKey}: ${JSON.stringify(text)} }`, inspected.ast);
|
|
116
|
+
} else {
|
|
117
|
+
const driver = property(object, "driver")?.initializer;
|
|
118
|
+
if (!driver || !ts.isArrowFunction(driver)) throw new Error("Custom driver factories require manual editing");
|
|
119
|
+
const body = driver.body;
|
|
120
|
+
if (!ts.isNewExpression(body) && !ts.isCallExpression(body) || body.arguments?.length !== 1 || !ts.isObjectLiteralExpression(body.arguments[0])) throw new Error("Custom driver options require manual editing");
|
|
121
|
+
let options = body.arguments[0];
|
|
122
|
+
if (key === "region" || key === "endpoint") {
|
|
123
|
+
const client = property(options, "client")?.initializer;
|
|
124
|
+
if (!client || !ts.isObjectLiteralExpression(client)) throw new Error("Custom client options require manual editing");
|
|
125
|
+
options = client;
|
|
126
|
+
}
|
|
127
|
+
const target = property(options, key === "storageDirectory" ? "directory" : key);
|
|
128
|
+
if (key === "storageDirectory") (await import("./initialization-planner-B41PNGWc.js").then((n) => n.s)).assertStorageDirectory(project.root, text, project.sourceDir, !!property(object, "migrations"));
|
|
129
|
+
let expression = target?.initializer;
|
|
130
|
+
if (expression && ts.isCallExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === "resolvePath" && expression.arguments.length === 1) expression = expression.arguments[0];
|
|
131
|
+
if (expression && ts.isBinaryExpression(expression) && expression.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken && ts.isStringLiteral(expression.right)) expression = expression.right;
|
|
132
|
+
if (expression && ts.isPropertyAccessExpression(expression) && expression.expression.getText(inspected.ast) === "env" && (key === "endpoint" || key === "prefix" || key === "bucket")) updated = replaceExpression(source, expression, `${expression.getText(inspected.ast)} ?? ${JSON.stringify(text)}`, inspected.ast);
|
|
133
|
+
else {
|
|
134
|
+
if (!expression || !ts.isStringLiteral(expression)) throw new Error("Only literal driver settings or generated environment fallbacks can be changed safely; edit this expression manually");
|
|
135
|
+
updated = replaceExpression(source, expression, JSON.stringify(text), inspected.ast);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
await addFile(files, configPath, updated, true);
|
|
139
|
+
return finish();
|
|
140
|
+
}
|
|
141
|
+
if (definition.name === "connection:add") {
|
|
142
|
+
const name = validateConnectionName(positionals[0] ?? "");
|
|
143
|
+
if (inspected.connections.has(name)) throw new Error("Connection already exists");
|
|
144
|
+
if ([...inspected.connections.keys()].some((existing) => existing.toUpperCase().replace(/-/g, "_") === name.toUpperCase().replace(/-/g, "_"))) throw new Error("Connection names collide after environment variable normalization");
|
|
145
|
+
for (const [existingName, existing] of inspected.connections) {
|
|
146
|
+
const automatic = property(existing, "autoLoadEntities")?.initializer;
|
|
147
|
+
const directories = automatic && ts.isObjectLiteralExpression(automatic) ? property(automatic, "directories")?.initializer : void 0;
|
|
148
|
+
const scoped = directories && ts.isArrayLiteralExpression(directories) && directories.elements.length > 0 && directories.elements.every(ts.isStringLiteral);
|
|
149
|
+
if (automatic && automatic.kind !== ts.SyntaxKind.FalseKeyword && !scoped && !property(existing, "entities")) throw new Error(`Narrow connection ${existingName} discovery to explicit directories before adding another connection; this prevents cross-connection entity leakage. No files were written.`);
|
|
150
|
+
}
|
|
151
|
+
const options = await initializationOptions(project, {
|
|
152
|
+
...values,
|
|
153
|
+
namespace: values.namespace ?? name,
|
|
154
|
+
language: values.language ?? (/\.[cm]?ts$/.test(path) ? "typescript" : "javascript"),
|
|
155
|
+
"source-dir": dirname(configPath),
|
|
156
|
+
framework: values.framework ?? (project.nestjs ? "nestjs" : "standalone")
|
|
157
|
+
});
|
|
158
|
+
if ((options.language === "typescript" ? !/\.[cm]?ts$/.test(path) : !/\.[cm]?js$/.test(path)) || options.moduleFormat !== project.moduleFormat) throw new Error("Named connections must use the existing configuration language and module format");
|
|
159
|
+
if (options.driver === "disk" && !values["storage-directory"]) throw new Error("Named Disk connections require an explicit distinct --storage-directory");
|
|
160
|
+
if (options.driver === "disk") {
|
|
161
|
+
const { staticDriverInfo } = await import("./static-config-g_7qN12_.js");
|
|
162
|
+
for (const existing of inspected.connections.values()) {
|
|
163
|
+
const info = staticDriverInfo(inspected, existing);
|
|
164
|
+
if (info.driver === "disk" && info.directory && resolve(project.root, info.directory) === resolve(project.root, options.storageDirectory)) throw new Error("Named Disk connections require distinct storage directories to avoid ownership conflicts");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
let alias = "DuraxisAddedStorage";
|
|
168
|
+
while (source.includes(alias)) alias += "Next";
|
|
169
|
+
const generated = configurationSource({
|
|
170
|
+
defaultConnection: name,
|
|
171
|
+
connections: { [name]: options }
|
|
172
|
+
}, alias);
|
|
173
|
+
const addition = inspectStaticConfig(generated, path);
|
|
174
|
+
const connection = addition.connections.get(name);
|
|
175
|
+
let updated;
|
|
176
|
+
const named = property(inspected.object, "connections");
|
|
177
|
+
if (named) updated = setLiteralProperty(source, named.initializer, JSON.stringify(name), connection.getText(addition.ast), inspected.ast);
|
|
178
|
+
else updated = replaceExpression(source, inspected.object, `{ defaultConnection: "default", connections: { default: ${inspected.object.getText(inspected.ast)}, ${JSON.stringify(name)}: ${connection.getText(addition.ast)} } }`, inspected.ast);
|
|
179
|
+
updated = addition.ast.statements.filter((statement) => {
|
|
180
|
+
if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) return statement.moduleSpecifier.text !== "@duraxis/core";
|
|
181
|
+
if (!ts.isVariableStatement(statement)) return false;
|
|
182
|
+
return !statement.declarationList.declarations.some((declaration) => {
|
|
183
|
+
const call = declaration.initializer;
|
|
184
|
+
return call && ts.isCallExpression(call) && call.expression.getText(addition.ast) === "require" && call.arguments[0] && ts.isStringLiteral(call.arguments[0]) && call.arguments[0].text === "@duraxis/core";
|
|
185
|
+
});
|
|
186
|
+
}).map((statement) => statement.getText(addition.ast)).join("\n") + "\n" + updated;
|
|
187
|
+
await addFile(files, configPath, updated, true);
|
|
188
|
+
if (options.migrations) {
|
|
189
|
+
const base = `duraxis/${name}`;
|
|
190
|
+
files.directories.push(`${base}/migrations`, `${base}/snapshots`);
|
|
191
|
+
const { createSnapshot } = await import("@duraxis/migrations");
|
|
192
|
+
await addFile(files, `${base}/snapshots/baseline.json`, JSON.stringify(createSnapshot(null, null, []), null, 2) + "\n");
|
|
193
|
+
}
|
|
194
|
+
const needed = requiredPackages(options);
|
|
195
|
+
const existing = {
|
|
196
|
+
...project.dependencies,
|
|
197
|
+
...project.devDependencies
|
|
198
|
+
};
|
|
199
|
+
const resolved = options.install ? await resolveDependencies(needed, existing, new RegistryClient(await configuredRegistry(project, values.registry), io.fetch, io.signal), values.prerelease) : Object.fromEntries(needed.map((name) => [name, existing[name] ?? "latest"]));
|
|
200
|
+
files.dependencies = Object.fromEntries(Object.entries(resolved).filter(([name]) => !existing[name]));
|
|
201
|
+
files.commands = options.install ? installCommands(options.manager, files.dependencies, {}) : [];
|
|
202
|
+
if (Object.keys(files.dependencies).length) await addFile(files, "package.json", JSON.stringify({
|
|
203
|
+
...project.manifest,
|
|
204
|
+
dependencies: {
|
|
205
|
+
...project.dependencies,
|
|
206
|
+
...files.dependencies
|
|
207
|
+
}
|
|
208
|
+
}, null, 2) + "\n", true);
|
|
209
|
+
return finish();
|
|
210
|
+
}
|
|
211
|
+
if (definition.name === "generate:entity" || definition.name === "generate:module") {
|
|
212
|
+
const name = positionals[0];
|
|
213
|
+
if (!name || !/^[A-Z][A-Za-z0-9]{0,63}$/.test(name)) throw new Error("Use a PascalCase identifier (letters and digits only)");
|
|
214
|
+
const format = extensions(project);
|
|
215
|
+
const base = `${dirname(configPath)}/features/${selected}`;
|
|
216
|
+
if (definition.name === "generate:entity") {
|
|
217
|
+
if (!property(object, "autoLoadEntities") && !property(object, "entities")) throw new Error("Entity generation requires ORM integration");
|
|
218
|
+
await addFile(files, `${base}/${name.replace(/[A-Z]/g, (letter, index) => `${index ? "-" : ""}${letter.toLowerCase()}`)}.entity.${format.source}`, entitySource(name, name.toLowerCase() + "s", project.language, project.moduleFormat));
|
|
219
|
+
} else {
|
|
220
|
+
if (!project.nestjs) throw new Error("Module generation requires NestJS integration");
|
|
221
|
+
if (project.language !== "typescript") throw new Error("JavaScript feature modules require explicit application registration; use DuraxisModule.forFeature([])");
|
|
222
|
+
const entityFile = `${name.replace(/[A-Z]/g, (letter, index) => `${index ? "-" : ""}${letter.toLowerCase()}`)}.entity`;
|
|
223
|
+
const hasEntity = await (await import("./project-detector-BQWeQZ8Q.js")).exists(join(project.root, `${base}/${entityFile}.${format.source}`));
|
|
224
|
+
await addFile(files, `${base}/${name.toLowerCase()}.module.ts`, `import { Module } from "@nestjs/common";\nimport { DuraxisModule } from "@duraxis/nestjs";\n${hasEntity ? `import { ${name} } from "./${entityFile}.${format.runtime}";\n` : ""}\n@Module({ imports: [DuraxisModule.forFeature([${hasEntity ? name : ""}], ${JSON.stringify(selected)})], exports: [DuraxisModule] })\nexport class ${name}Module {}\n`);
|
|
225
|
+
}
|
|
226
|
+
return finish();
|
|
227
|
+
}
|
|
228
|
+
throw new Error(`Unsupported operation for executable configuration: ${definition.name}`);
|
|
229
|
+
}
|
|
230
|
+
export { minimalAdmin };
|
|
231
|
+
|
|
232
|
+
//# sourceMappingURL=minimal-admin-B4ur_cON.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"minimal-admin-B4ur_cON.js","names":["connectionName"],"sources":["../src/commands/minimal-admin.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join, relative, dirname, resolve } from \"node:path\";\nimport ts from \"typescript\";\nimport type { CLIIO } from \"../cli.js\";\nimport type { ParsedCommand } from \"../registry/argument-parser.js\";\nimport type { ProjectContext } from \"../init/project-detector.js\";\nimport {\n inspectStaticConfig,\n property,\n replaceExpression,\n setLiteralProperty,\n} from \"../init/static-config.js\";\nimport { validateConnectionName as connectionName } from \"@duraxis/core\";\nimport { initializationOptions } from \"../init/initialization-options.js\";\nimport { entitySource, extensions, configurationSource } from \"../templates/project.js\";\nimport { addFile, executeFiles, describePlan, type FilePlan } from \"../filesystem/file-plan.js\";\nimport { requiredPackages } from \"../init/initialization-planner.js\";\nimport { resolveDependencies } from \"../dependencies/dependency-resolver.js\";\nimport { RegistryClient } from \"../dependencies/registry-client.js\";\nimport { configuredRegistry } from \"../dependencies/configured-registry.js\";\nimport { installCommands, runProcess } from \"../dependencies/package-manager.js\";\n\nexport async function minimalAdmin(\n parsed: ParsedCommand,\n io: CLIIO,\n project: ProjectContext,\n path: string,\n redact: (value: unknown) => unknown,\n): Promise<unknown> {\n const source = await readFile(path, \"utf8\");\n const { values, positionals, definition } = parsed;\n let inspected: ReturnType<typeof inspectStaticConfig>;\n try {\n inspected = inspectStaticConfig(source, path);\n } catch (error) {\n if (definition.name === \"config:show\")\n return {\n unresolved: true,\n files: [path],\n message:\n \"Executable configuration was not evaluated. Use --evaluate explicitly for trusted application code.\",\n };\n throw error;\n }\n const selected = values.database ?? inspected.defaultConnection;\n const object = inspected.connections.get(selected);\n if (!object) throw new Error(\"Unknown named database\");\n connectionName(selected);\n for (const name of inspected.connections.keys()) connectionName(name);\n const files: FilePlan = {\n root: project.root,\n files: [],\n directories: [],\n warnings: [],\n dependencies: {},\n devDependencies: {},\n commands: [],\n };\n const finish = async () => {\n if (values[\"dry-run\"]) return { status: \"planned\", ...describePlan(files) };\n await executeFiles(files, async () => {\n for (const [command, ...args] of files.commands)\n await (io.runProcess ?? runProcess)({\n command: command!,\n args,\n cwd: project.root,\n signal: io.signal,\n });\n });\n return {\n status: \"updated\",\n files: files.files.map((file) => file.path),\n warnings: files.warnings,\n };\n };\n const configPath = relative(project.root, path).replaceAll(\"\\\\\", \"/\");\n if (definition.name === \"config:show\")\n return {\n configuration: redact(inspected.value),\n connection: selected,\n databaseOpened: false,\n trustedCodeEvaluated: false,\n };\n if (definition.name === \"connection:list\")\n return {\n default: inspected.defaultConnection,\n connections: [...inspected.connections.keys()].map((name) => ({ name })),\n };\n if (definition.name === \"config:validate\" || definition.name === \"storage:check\") {\n const errors = (inspected.ast as unknown as { parseDiagnostics: readonly unknown[] })\n .parseDiagnostics;\n if (errors.length) throw new Error(\"Invalid configuration syntax\");\n for (const [name, connection] of inspected.connections) {\n if (!property(connection, \"driver\")) throw new Error(`Missing driver for ${name}`);\n if (property(connection, \"migrations\")?.initializer.kind === ts.SyntaxKind.TrueKeyword) {\n const schema = property(connection, \"schema\")?.initializer;\n if (\n schema &&\n ts.isObjectLiteralExpression(schema) &&\n property(schema, \"mode\")?.initializer &&\n ts.isStringLiteral(property(schema, \"mode\")!.initializer) &&\n (property(schema, \"mode\")!.initializer as ts.StringLiteral).text === \"create\"\n )\n throw new Error(\"Migrations require schema validation\");\n }\n }\n return {\n valid: true,\n databaseOpened: false,\n trustedCodeEvaluated: false,\n message:\n \"Static structure validated. Driver factories and environment expressions remain unevaluated; use --evaluate for trusted runtime validation.\",\n };\n }\n if (definition.name === \"config:set\") {\n const [key, text] = positionals;\n if (!key || text === undefined || /[\\r\\n\\0]/.test(text))\n throw new Error(\"Usage: config:set <key> <value>; control characters are forbidden\");\n const supported = [\n \"namespace\",\n \"schemaMode\",\n \"bucket\",\n \"prefix\",\n \"region\",\n \"endpoint\",\n \"storageDirectory\",\n ];\n if (!supported.includes(key))\n throw new Error(\n \"Unsupported key; edit advanced configuration manually. Secrets must use environment references.\",\n );\n if (\n key === \"namespace\" &&\n (!/^[A-Za-z0-9_/-]{1,128}$/.test(text) ||\n text.split(\"/\").some((part) => !part || part === \"..\"))\n )\n throw new Error(\"Invalid namespace\");\n if (key === \"bucket\" && !/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(text))\n throw new Error(\"Invalid bucket\");\n if (key === \"endpoint\") {\n const url = new URL(text);\n if (\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n )\n throw new Error(\"Endpoint must not contain secrets\");\n }\n let updated: string;\n if (key === \"namespace\" || key === \"schemaMode\") {\n const field = key === \"namespace\" ? \"database\" : \"schema\";\n const innerKey = key === \"namespace\" ? \"namespace\" : \"mode\";\n if (key === \"schemaMode\" && ![\"create\", \"validate\", \"validate-managed\"].includes(text))\n throw new Error(\"Invalid schemaMode\");\n const migrations = property(object, \"migrations\")?.initializer;\n if (\n key === \"schemaMode\" &&\n text === \"create\" &&\n migrations &&\n migrations.kind !== ts.SyntaxKind.FalseKeyword\n )\n throw new Error(\"Migrations require validation schema mode\");\n const target = property(object, field);\n if (target && !ts.isObjectLiteralExpression(target.initializer))\n throw new Error(\"Dynamic configuration requires manual editing\");\n updated = target\n ? setLiteralProperty(\n source,\n target.initializer as ts.ObjectLiteralExpression,\n innerKey,\n JSON.stringify(text),\n inspected.ast,\n )\n : setLiteralProperty(\n source,\n object,\n field,\n `{ ${innerKey}: ${JSON.stringify(text)} }`,\n inspected.ast,\n );\n } else {\n const driver = property(object, \"driver\")?.initializer;\n if (!driver || !ts.isArrowFunction(driver))\n throw new Error(\"Custom driver factories require manual editing\");\n const body = driver.body;\n if (\n (!ts.isNewExpression(body) && !ts.isCallExpression(body)) ||\n body.arguments?.length !== 1 ||\n !ts.isObjectLiteralExpression(body.arguments[0]!)\n )\n throw new Error(\"Custom driver options require manual editing\");\n let options = body.arguments[0] as ts.ObjectLiteralExpression;\n if (key === \"region\" || key === \"endpoint\") {\n const client = property(options, \"client\")?.initializer;\n if (!client || !ts.isObjectLiteralExpression(client))\n throw new Error(\"Custom client options require manual editing\");\n options = client;\n }\n const driverKey = key === \"storageDirectory\" ? \"directory\" : key;\n const target = property(options, driverKey);\n if (key === \"storageDirectory\")\n (await import(\"../init/initialization-options.js\")).assertStorageDirectory(\n project.root,\n text,\n project.sourceDir,\n !!property(object, \"migrations\"),\n );\n let expression = target?.initializer;\n if (\n expression &&\n ts.isCallExpression(expression) &&\n ts.isIdentifier(expression.expression) &&\n expression.expression.text === \"resolvePath\" &&\n expression.arguments.length === 1\n )\n expression = expression.arguments[0];\n if (\n expression &&\n ts.isBinaryExpression(expression) &&\n expression.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken &&\n ts.isStringLiteral(expression.right)\n )\n expression = expression.right;\n if (\n expression &&\n ts.isPropertyAccessExpression(expression) &&\n expression.expression.getText(inspected.ast) === \"env\" &&\n (key === \"endpoint\" || key === \"prefix\" || key === \"bucket\")\n ) {\n updated = replaceExpression(\n source,\n expression,\n `${expression.getText(inspected.ast)} ?? ${JSON.stringify(text)}`,\n inspected.ast,\n );\n } else {\n if (!expression || !ts.isStringLiteral(expression))\n throw new Error(\n \"Only literal driver settings or generated environment fallbacks can be changed safely; edit this expression manually\",\n );\n updated = replaceExpression(source, expression, JSON.stringify(text), inspected.ast);\n }\n }\n await addFile(files, configPath, updated, true);\n return finish();\n }\n if (definition.name === \"connection:add\") {\n const name = connectionName(positionals[0] ?? \"\");\n if (inspected.connections.has(name)) throw new Error(\"Connection already exists\");\n if (\n [...inspected.connections.keys()].some(\n (existing) =>\n existing.toUpperCase().replace(/-/g, \"_\") === name.toUpperCase().replace(/-/g, \"_\"),\n )\n )\n throw new Error(\"Connection names collide after environment variable normalization\");\n for (const [existingName, existing] of inspected.connections) {\n const automatic = property(existing, \"autoLoadEntities\")?.initializer;\n const directories =\n automatic && ts.isObjectLiteralExpression(automatic)\n ? property(automatic, \"directories\")?.initializer\n : undefined;\n const scoped =\n directories &&\n ts.isArrayLiteralExpression(directories) &&\n directories.elements.length > 0 &&\n directories.elements.every(ts.isStringLiteral);\n if (\n automatic &&\n automatic.kind !== ts.SyntaxKind.FalseKeyword &&\n !scoped &&\n !property(existing, \"entities\")\n )\n throw new Error(\n `Narrow connection ${existingName} discovery to explicit directories before adding another connection; this prevents cross-connection entity leakage. No files were written.`,\n );\n }\n const options = await initializationOptions(project, {\n ...values,\n namespace: values.namespace ?? name,\n language: values.language ?? (/\\.[cm]?ts$/.test(path) ? \"typescript\" : \"javascript\"),\n \"source-dir\": dirname(configPath),\n framework: values.framework ?? (project.nestjs ? \"nestjs\" : \"standalone\"),\n });\n if (\n (options.language === \"typescript\" ? !/\\.[cm]?ts$/.test(path) : !/\\.[cm]?js$/.test(path)) ||\n options.moduleFormat !== project.moduleFormat\n )\n throw new Error(\n \"Named connections must use the existing configuration language and module format\",\n );\n if (options.driver === \"disk\" && !values[\"storage-directory\"])\n throw new Error(\"Named Disk connections require an explicit distinct --storage-directory\");\n if (options.driver === \"disk\") {\n const { staticDriverInfo } = await import(\"../init/static-config.js\");\n for (const existing of inspected.connections.values()) {\n const info = staticDriverInfo(inspected, existing);\n if (\n info.driver === \"disk\" &&\n info.directory &&\n resolve(project.root, info.directory) === resolve(project.root, options.storageDirectory)\n )\n throw new Error(\n \"Named Disk connections require distinct storage directories to avoid ownership conflicts\",\n );\n }\n }\n let alias = \"DuraxisAddedStorage\";\n while (source.includes(alias)) alias += \"Next\";\n const generated = configurationSource(\n { defaultConnection: name, connections: { [name]: options } },\n alias,\n );\n const addition = inspectStaticConfig(generated, path);\n const connection = addition.connections.get(name)!;\n let updated: string;\n const named = property(inspected.object, \"connections\");\n if (named)\n updated = setLiteralProperty(\n source,\n named.initializer as ts.ObjectLiteralExpression,\n JSON.stringify(name),\n connection.getText(addition.ast),\n inspected.ast,\n );\n else\n updated = replaceExpression(\n source,\n inspected.object,\n `{ defaultConnection: \"default\", connections: { default: ${inspected.object.getText(inspected.ast)}, ${JSON.stringify(name)}: ${connection.getText(addition.ast)} } }`,\n inspected.ast,\n );\n const imports = addition.ast.statements.filter((statement) => {\n if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier))\n return statement.moduleSpecifier.text !== \"@duraxis/core\";\n if (!ts.isVariableStatement(statement)) return false;\n return !statement.declarationList.declarations.some((declaration) => {\n const call = declaration.initializer;\n return (\n call &&\n ts.isCallExpression(call) &&\n call.expression.getText(addition.ast) === \"require\" &&\n call.arguments[0] &&\n ts.isStringLiteral(call.arguments[0]) &&\n call.arguments[0].text === \"@duraxis/core\"\n );\n });\n });\n updated =\n imports.map((statement) => statement.getText(addition.ast)).join(\"\\n\") + \"\\n\" + updated;\n await addFile(files, configPath, updated, true);\n if (options.migrations) {\n const base = `duraxis/${name}`;\n files.directories.push(`${base}/migrations`, `${base}/snapshots`);\n const { createSnapshot } = await import(\"@duraxis/migrations\");\n await addFile(\n files,\n `${base}/snapshots/baseline.json`,\n JSON.stringify(createSnapshot(null, null, []), null, 2) + \"\\n\",\n );\n }\n const needed = requiredPackages(options);\n const existing = { ...project.dependencies, ...project.devDependencies };\n const resolved = options.install\n ? await resolveDependencies(\n needed,\n existing,\n new RegistryClient(\n await configuredRegistry(project, values.registry),\n io.fetch,\n io.signal,\n ),\n values.prerelease,\n )\n : Object.fromEntries(needed.map((name) => [name, existing[name] ?? \"latest\"]));\n files.dependencies = Object.fromEntries(\n Object.entries(resolved).filter(([name]) => !existing[name]),\n );\n files.commands = options.install\n ? installCommands(options.manager, files.dependencies, {})\n : [];\n if (Object.keys(files.dependencies).length)\n await addFile(\n files,\n \"package.json\",\n JSON.stringify(\n { ...project.manifest, dependencies: { ...project.dependencies, ...files.dependencies } },\n null,\n 2,\n ) + \"\\n\",\n true,\n );\n return finish();\n }\n if (definition.name === \"generate:entity\" || definition.name === \"generate:module\") {\n const name = positionals[0];\n if (!name || !/^[A-Z][A-Za-z0-9]{0,63}$/.test(name))\n throw new Error(\"Use a PascalCase identifier (letters and digits only)\");\n const format = extensions(project);\n const base = `${dirname(configPath)}/features/${selected}`;\n if (definition.name === \"generate:entity\") {\n if (!property(object, \"autoLoadEntities\") && !property(object, \"entities\"))\n throw new Error(\"Entity generation requires ORM integration\");\n await addFile(\n files,\n `${base}/${name.replace(/[A-Z]/g, (letter, index: number) => `${index ? \"-\" : \"\"}${letter.toLowerCase()}`)}.entity.${format.source}`,\n entitySource(name, name.toLowerCase() + \"s\", project.language, project.moduleFormat),\n );\n } else {\n if (!project.nestjs) throw new Error(\"Module generation requires NestJS integration\");\n if (project.language !== \"typescript\")\n throw new Error(\n \"JavaScript feature modules require explicit application registration; use DuraxisModule.forFeature([])\",\n );\n const entityFile = `${name.replace(/[A-Z]/g, (letter, index: number) => `${index ? \"-\" : \"\"}${letter.toLowerCase()}`)}.entity`;\n const hasEntity = await (\n await import(\"../init/project-detector.js\")\n ).exists(join(project.root, `${base}/${entityFile}.${format.source}`));\n await addFile(\n files,\n `${base}/${name.toLowerCase()}.module.ts`,\n `import { Module } from \"@nestjs/common\";\\nimport { DuraxisModule } from \"@duraxis/nestjs\";\\n${hasEntity ? `import { ${name} } from \"./${entityFile}.${format.runtime}\";\\n` : \"\"}\\n@Module({ imports: [DuraxisModule.forFeature([${hasEntity ? name : \"\"}], ${JSON.stringify(selected)})], exports: [DuraxisModule] })\\nexport class ${name}Module {}\\n`,\n );\n }\n return finish();\n }\n throw new Error(`Unsupported operation for executable configuration: ${definition.name}`);\n}\n"],"mappings":";;;;;;;;;AAsBA,eAAsB,aACpB,QACA,IACA,SACA,MACA,QACkB;CAClB,MAAM,SAAS,MAAM,SAAS,MAAM,MAAM;CAC1C,MAAM,EAAE,QAAQ,aAAa,eAAe;CAC5C,IAAI;CACJ,IAAI;EACF,YAAY,oBAAoB,QAAQ,IAAI;CAC9C,SAAS,OAAO;EACd,IAAI,WAAW,SAAS,eACtB,OAAO;GACL,YAAY;GACZ,OAAO,CAAC,IAAI;GACZ,SACE;EACJ;EACF,MAAM;CACR;CACA,MAAM,WAAW,OAAO,YAAY,UAAU;CAC9C,MAAM,SAAS,UAAU,YAAY,IAAI,QAAQ;CACjD,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,wBAAwB;CACrD,uBAAe,QAAQ;CACvB,KAAK,MAAM,QAAQ,UAAU,YAAY,KAAK,GAAG,uBAAe,IAAI;CACpE,MAAM,QAAkB;EACtB,MAAM,QAAQ;EACd,OAAO,CAAC;EACR,aAAa,CAAC;EACd,UAAU,CAAC;EACX,cAAc,CAAC;EACf,iBAAiB,CAAC;EAClB,UAAU,CAAC;CACb;CACA,MAAM,SAAS,YAAY;EACzB,IAAI,OAAO,YAAY,OAAO;GAAE,QAAQ;GAAW,GAAG,aAAa,KAAK;EAAE;EAC1E,MAAM,aAAa,OAAO,YAAY;GACpC,KAAK,MAAM,CAAC,SAAS,GAAG,SAAS,MAAM,UACrC,OAAO,GAAG,cAAc,WAAA,CAAY;IACzB;IACT;IACA,KAAK,QAAQ;IACb,QAAQ,GAAG;GACb,CAAC;EACL,CAAC;EACD,OAAO;GACL,QAAQ;GACR,OAAO,MAAM,MAAM,KAAK,SAAS,KAAK,IAAI;GAC1C,UAAU,MAAM;EAClB;CACF;CACA,MAAM,aAAa,SAAS,QAAQ,MAAM,IAAI,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,aAAa,WAAW,GAAG,OAAO,QAAQ,QAAQ,GAAG,kDAAkD,YAAY,OAAO,GAAG,KAAK,KAAK,UAAU,QAAQ,EAAE,gDAAgD,KAAK,YAC9U;EACF;EACA,OAAO,OAAO;CAChB;CACA,MAAM,IAAI,MAAM,uDAAuD,WAAW,MAAM;AAC1F"}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
// src/init/nest-integration.ts
|
|
4
|
+
/** Surgical AST-guided edits preserve every unrelated byte, including comments. */
|
|
5
|
+
function integrateNestModule(source, path, configPath) {
|
|
6
|
+
const ast = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
|
|
7
|
+
let moduleName;
|
|
8
|
+
let duraxisName;
|
|
9
|
+
let configName;
|
|
10
|
+
let reference = posix.relative(posix.dirname(path), configPath).replace(/\.[cm]?ts$/, ".js");
|
|
11
|
+
if (!reference.startsWith(".")) reference = `./${reference}`;
|
|
12
|
+
const identifiers = /* @__PURE__ */ new Set();
|
|
13
|
+
const collect = (node) => {
|
|
14
|
+
if (ts.isIdentifier(node)) identifiers.add(node.text);
|
|
15
|
+
ts.forEachChild(node, collect);
|
|
16
|
+
};
|
|
17
|
+
collect(ast);
|
|
18
|
+
const unique = (base) => {
|
|
19
|
+
let result = base;
|
|
20
|
+
for (let i = 2; identifiers.has(result); i++) result = `${base}${i}`;
|
|
21
|
+
identifiers.add(result);
|
|
22
|
+
return result;
|
|
23
|
+
};
|
|
24
|
+
for (const statement of ast.statements) {
|
|
25
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
26
|
+
const specifier = statement.moduleSpecifier.text;
|
|
27
|
+
const bindings = statement.importClause?.namedBindings;
|
|
28
|
+
if (statement.importClause?.isTypeOnly) continue;
|
|
29
|
+
if (bindings && ts.isNamespaceImport(bindings)) {
|
|
30
|
+
if (specifier === "@nestjs/common") moduleName = `${bindings.name.text}.Module`;
|
|
31
|
+
if (specifier === "@duraxis/nestjs") duraxisName = `${bindings.name.text}.DuraxisModule`;
|
|
32
|
+
}
|
|
33
|
+
if (bindings && ts.isNamedImports(bindings)) for (const item of bindings.elements) {
|
|
34
|
+
if (item.isTypeOnly) continue;
|
|
35
|
+
if (specifier === "@nestjs/common" && (item.propertyName ?? item.name).text === "Module") moduleName = item.name.text;
|
|
36
|
+
if (specifier === "@duraxis/nestjs" && (item.propertyName ?? item.name).text === "DuraxisModule") duraxisName = item.name.text;
|
|
37
|
+
}
|
|
38
|
+
if (specifier === reference && statement.importClause?.name) configName = statement.importClause.name.text;
|
|
39
|
+
}
|
|
40
|
+
let commonjs = false;
|
|
41
|
+
for (const statement of ast.statements) {
|
|
42
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
43
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
44
|
+
const call = declaration.initializer;
|
|
45
|
+
if (!call || !ts.isCallExpression(call) || call.expression.getText(ast) !== "require" || call.arguments.length !== 1 || !ts.isStringLiteral(call.arguments[0])) continue;
|
|
46
|
+
const specifier = call.arguments[0].text;
|
|
47
|
+
commonjs = !/\.[cm]?ts$/.test(path);
|
|
48
|
+
if (ts.isIdentifier(declaration.name) && specifier === reference) configName = declaration.name.text;
|
|
49
|
+
if (ts.isObjectBindingPattern(declaration.name)) for (const element of declaration.name.elements) {
|
|
50
|
+
if (specifier === "@nestjs/common" && (element.propertyName ?? element.name).getText(ast) === "Module") moduleName = element.name.getText(ast);
|
|
51
|
+
if (specifier === "@duraxis/nestjs" && (element.propertyName ?? element.name).getText(ast) === "DuraxisModule") duraxisName = element.name.getText(ast);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (!moduleName) throw new Error(`Cannot safely integrate ${path}: import Module from @nestjs/common using a named import`);
|
|
56
|
+
const roots = ast.statements.filter(ts.isClassDeclaration).filter((node) => node.name?.text === "AppModule");
|
|
57
|
+
if (roots.length !== 1) throw new Error(`Cannot safely integrate ${path}: expected one AppModule class`);
|
|
58
|
+
let decorator = (ts.getDecorators(roots[0]) ?? []).map((item) => item.expression).find((expression) => ts.isCallExpression(expression) && expression.expression.getText(ast) === moduleName);
|
|
59
|
+
if (!decorator) for (const statement of ast.statements) {
|
|
60
|
+
if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) continue;
|
|
61
|
+
const apply = statement.expression;
|
|
62
|
+
if (apply.arguments.length === 1 && apply.arguments[0].getText(ast) === "AppModule" && ts.isCallExpression(apply.expression) && apply.expression.expression.getText(ast) === moduleName) decorator = apply.expression;
|
|
63
|
+
}
|
|
64
|
+
if (!decorator || !ts.isCallExpression(decorator) || decorator.arguments.length !== 1 || !ts.isObjectLiteralExpression(decorator.arguments[0])) throw new Error(`Cannot safely integrate ${path}: @Module metadata must be an inline object`);
|
|
65
|
+
const metadata = decorator.arguments[0];
|
|
66
|
+
const properties = metadata.properties.filter((property) => property.name && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) && property.name.text === "imports");
|
|
67
|
+
if (metadata.properties.some(ts.isSpreadAssignment)) throw new Error(`Cannot safely integrate ${path}: spread module metadata may override imports`);
|
|
68
|
+
if (properties.length > 1) throw new Error(`Cannot safely integrate ${path}: duplicate imports property`);
|
|
69
|
+
const property = properties[0];
|
|
70
|
+
let array;
|
|
71
|
+
if (property) {
|
|
72
|
+
if (!ts.isPropertyAssignment(property) || !ts.isArrayLiteralExpression(property.initializer)) throw new Error(`Cannot safely integrate ${path}: imports must be an inline array`);
|
|
73
|
+
array = property.initializer;
|
|
74
|
+
if (duraxisName && array.elements.some((element) => ts.isCallExpression(element) && ts.isPropertyAccessExpression(element.expression) && element.expression.expression.getText(ast) === duraxisName && ["forRoot", "forRootAsync"].includes(element.expression.name.text))) throw new Error(`Existing Duraxis root registration in ${path}; preserve its configuration and integrate the new configuration explicitly`);
|
|
75
|
+
}
|
|
76
|
+
const imports = [];
|
|
77
|
+
if (!duraxisName) {
|
|
78
|
+
duraxisName = unique("DuraxisModule");
|
|
79
|
+
imports.push(commonjs ? `const { DuraxisModule${duraxisName === "DuraxisModule" ? "" : `: ${duraxisName}`} } = require("@duraxis/nestjs");` : `import { DuraxisModule${duraxisName === "DuraxisModule" ? "" : ` as ${duraxisName}`} } from "@duraxis/nestjs";`);
|
|
80
|
+
}
|
|
81
|
+
if (!configName) {
|
|
82
|
+
configName = unique("duraxisConfig");
|
|
83
|
+
imports.push(commonjs ? `const ${configName} = require(${JSON.stringify(reference)});` : `import ${configName} from ${JSON.stringify(reference)};`);
|
|
84
|
+
}
|
|
85
|
+
const registration = `${duraxisName}.forRoot(${configName})`;
|
|
86
|
+
const offset = array ? array.elements.end : metadata.properties.end;
|
|
87
|
+
const addition = array ? `${array.elements.length && !array.elements.hasTrailingComma ? "," : ""}\n ${registration},` : `${metadata.properties.length && !metadata.properties.hasTrailingComma ? "," : ""}\n imports: [${registration}],`;
|
|
88
|
+
const importOffset = ast.statements.filter(ts.isImportDeclaration).at(-1)?.end ?? 0;
|
|
89
|
+
return source.slice(0, importOffset) + (imports.length ? "\n" + imports.join("\n") + "\n" : "") + source.slice(importOffset, offset) + addition + source.slice(offset);
|
|
90
|
+
}
|
|
91
|
+
export { integrateNestModule };
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=nest-integration-KCc7ZaG6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nest-integration-KCc7ZaG6.js","names":[],"sources":["../src/init/nest-integration.ts"],"sourcesContent":["import ts from \"typescript\";\nimport { posix } from \"node:path\";\n\n/** Surgical AST-guided edits preserve every unrelated byte, including comments. */\nexport function integrateNestModule(source: string, path: string, configPath: string): string {\n const ast = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);\n let moduleName: string | undefined;\n let duraxisName: string | undefined;\n let configName: string | undefined;\n let reference = posix.relative(posix.dirname(path), configPath).replace(/\\.[cm]?ts$/, \".js\");\n if (!reference.startsWith(\".\")) reference = `./${reference}`;\n const identifiers = new Set<string>();\n const collect = (node: ts.Node) => {\n if (ts.isIdentifier(node)) identifiers.add(node.text);\n ts.forEachChild(node, collect);\n };\n collect(ast);\n const unique = (base: string) => {\n let result = base;\n for (let i = 2; identifiers.has(result); i++) result = `${base}${i}`;\n identifiers.add(result);\n return result;\n };\n for (const statement of ast.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))\n continue;\n const specifier = statement.moduleSpecifier.text;\n const bindings = statement.importClause?.namedBindings;\n if (statement.importClause?.isTypeOnly) continue;\n if (bindings && ts.isNamespaceImport(bindings)) {\n if (specifier === \"@nestjs/common\") moduleName = `${bindings.name.text}.Module`;\n if (specifier === \"@duraxis/nestjs\") duraxisName = `${bindings.name.text}.DuraxisModule`;\n }\n if (bindings && ts.isNamedImports(bindings))\n for (const item of bindings.elements) {\n if (item.isTypeOnly) continue;\n if (specifier === \"@nestjs/common\" && (item.propertyName ?? item.name).text === \"Module\")\n moduleName = item.name.text;\n if (\n specifier === \"@duraxis/nestjs\" &&\n (item.propertyName ?? item.name).text === \"DuraxisModule\"\n )\n duraxisName = item.name.text;\n }\n if (specifier === reference && statement.importClause?.name)\n configName = statement.importClause.name.text;\n }\n let commonjs = false;\n for (const statement of ast.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n const call = declaration.initializer;\n if (\n !call ||\n !ts.isCallExpression(call) ||\n call.expression.getText(ast) !== \"require\" ||\n call.arguments.length !== 1 ||\n !ts.isStringLiteral(call.arguments[0]!)\n )\n continue;\n const specifier = (call.arguments[0] as ts.StringLiteral).text;\n commonjs = !/\\.[cm]?ts$/.test(path);\n if (ts.isIdentifier(declaration.name) && specifier === reference)\n configName = declaration.name.text;\n if (ts.isObjectBindingPattern(declaration.name))\n for (const element of declaration.name.elements) {\n if (\n specifier === \"@nestjs/common\" &&\n (element.propertyName ?? element.name).getText(ast) === \"Module\"\n )\n moduleName = element.name.getText(ast);\n if (\n specifier === \"@duraxis/nestjs\" &&\n (element.propertyName ?? element.name).getText(ast) === \"DuraxisModule\"\n )\n duraxisName = element.name.getText(ast);\n }\n }\n }\n if (!moduleName)\n throw new Error(\n `Cannot safely integrate ${path}: import Module from @nestjs/common using a named import`,\n );\n const roots = ast.statements\n .filter(ts.isClassDeclaration)\n .filter((node) => node.name?.text === \"AppModule\");\n if (roots.length !== 1)\n throw new Error(`Cannot safely integrate ${path}: expected one AppModule class`);\n const decorators = ts.getDecorators(roots[0]!) ?? [];\n let decorator = decorators\n .map((item) => item.expression)\n .find(\n (expression) =>\n ts.isCallExpression(expression) && expression.expression.getText(ast) === moduleName,\n );\n if (!decorator) {\n for (const statement of ast.statements) {\n if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression))\n continue;\n const apply = statement.expression;\n if (\n apply.arguments.length === 1 &&\n apply.arguments[0]!.getText(ast) === \"AppModule\" &&\n ts.isCallExpression(apply.expression) &&\n apply.expression.expression.getText(ast) === moduleName\n )\n decorator = apply.expression;\n }\n }\n if (\n !decorator ||\n !ts.isCallExpression(decorator) ||\n decorator.arguments.length !== 1 ||\n !ts.isObjectLiteralExpression(decorator.arguments[0]!)\n )\n throw new Error(`Cannot safely integrate ${path}: @Module metadata must be an inline object`);\n const metadata = decorator.arguments[0]! as ts.ObjectLiteralExpression;\n const properties = metadata.properties.filter(\n (property) =>\n property.name &&\n (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&\n property.name.text === \"imports\",\n );\n if (metadata.properties.some(ts.isSpreadAssignment))\n throw new Error(`Cannot safely integrate ${path}: spread module metadata may override imports`);\n if (properties.length > 1)\n throw new Error(`Cannot safely integrate ${path}: duplicate imports property`);\n const property = properties[0];\n let array: ts.ArrayLiteralExpression | undefined;\n if (property) {\n if (!ts.isPropertyAssignment(property) || !ts.isArrayLiteralExpression(property.initializer))\n throw new Error(`Cannot safely integrate ${path}: imports must be an inline array`);\n array = property.initializer;\n if (\n duraxisName &&\n array.elements.some(\n (element) =>\n ts.isCallExpression(element) &&\n ts.isPropertyAccessExpression(element.expression) &&\n element.expression.expression.getText(ast) === duraxisName &&\n [\"forRoot\", \"forRootAsync\"].includes(element.expression.name.text),\n )\n ) {\n // Preserve an existing application-specific registration; never open a second connection implicitly.\n throw new Error(\n `Existing Duraxis root registration in ${path}; preserve its configuration and integrate the new configuration explicitly`,\n );\n }\n }\n const imports: string[] = [];\n if (!duraxisName) {\n duraxisName = unique(\"DuraxisModule\");\n imports.push(\n commonjs\n ? `const { DuraxisModule${duraxisName === \"DuraxisModule\" ? \"\" : `: ${duraxisName}`} } = require(\"@duraxis/nestjs\");`\n : `import { DuraxisModule${duraxisName === \"DuraxisModule\" ? \"\" : ` as ${duraxisName}`} } from \"@duraxis/nestjs\";`,\n );\n }\n if (!configName) {\n configName = unique(\"duraxisConfig\");\n imports.push(\n commonjs\n ? `const ${configName} = require(${JSON.stringify(reference)});`\n : `import ${configName} from ${JSON.stringify(reference)};`,\n );\n }\n const registration = `${duraxisName}.forRoot(${configName})`;\n const offset = array ? array.elements.end : metadata.properties.end;\n const addition = array\n ? `${array.elements.length && !array.elements.hasTrailingComma ? \",\" : \"\"}\\n ${registration},`\n : `${metadata.properties.length && !metadata.properties.hasTrailingComma ? \",\" : \"\"}\\n imports: [${registration}],`;\n const importOffset = ast.statements.filter(ts.isImportDeclaration).at(-1)?.end ?? 0;\n return (\n source.slice(0, importOffset) +\n (imports.length ? \"\\n\" + imports.join(\"\\n\") + \"\\n\" : \"\") +\n source.slice(importOffset, offset) +\n addition +\n source.slice(offset)\n );\n}\n"],"mappings":";;;;AAIA,SAAgB,oBAAoB,QAAgB,MAAc,YAA4B;CAC5F,MAAM,MAAM,GAAG,iBAAiB,MAAM,QAAQ,GAAG,aAAa,QAAQ,IAAI;CAC1E,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,YAAY,MAAM,SAAS,MAAM,QAAQ,IAAI,GAAG,UAAU,CAAC,CAAC,QAAQ,cAAc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