@prisma-next/cli 0.4.0-dev.4 → 0.4.0-dev.6
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/README.md +8 -7
- package/dist/cli-errors-BUuJr6py.mjs +5 -0
- package/dist/{cli-errors-DStABy9d.d.mts → cli-errors-Dic2eADK.d.mts} +1 -0
- package/dist/cli.mjs +9 -9
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-tdnbk0OR.mjs → client-DUs1DH-1.mjs} +2 -2
- package/dist/{client-tdnbk0OR.mjs.map → client-DUs1DH-1.mjs.map} +1 -1
- package/dist/commands/contract-emit.mjs +1 -1
- package/dist/commands/contract-infer.mjs +1 -1
- package/dist/commands/db-init.mjs +5 -5
- package/dist/commands/db-schema.mjs +3 -3
- package/dist/commands/db-sign.mjs +4 -4
- package/dist/commands/db-update.mjs +5 -5
- package/dist/commands/db-verify.mjs +4 -4
- package/dist/commands/migration-apply.mjs +6 -6
- package/dist/commands/migration-apply.mjs.map +1 -1
- package/dist/commands/migration-emit.d.mts +38 -0
- package/dist/commands/migration-emit.d.mts.map +1 -0
- package/dist/commands/migration-emit.mjs +81 -0
- package/dist/commands/migration-emit.mjs.map +1 -0
- package/dist/commands/migration-new.mjs +5 -5
- package/dist/commands/migration-new.mjs.map +1 -1
- package/dist/commands/migration-plan.d.mts.map +1 -1
- package/dist/commands/migration-plan.mjs +13 -32
- package/dist/commands/migration-plan.mjs.map +1 -1
- package/dist/commands/migration-ref.d.mts +1 -1
- package/dist/commands/migration-ref.mjs +2 -2
- package/dist/commands/migration-show.d.mts +1 -1
- package/dist/commands/migration-show.mjs +4 -4
- package/dist/commands/migration-show.mjs.map +1 -1
- package/dist/commands/migration-status.mjs +1 -1
- package/dist/{contract-emit-Ctn6mH9H.mjs → contract-emit-7jqH6dq9.mjs} +5 -5
- package/dist/{contract-emit-Ctn6mH9H.mjs.map → contract-emit-7jqH6dq9.mjs.map} +1 -1
- package/dist/contract-emit-C2_J2U7A.mjs +4 -0
- package/dist/{contract-emit-CRoS1nx5.mjs → contract-emit-CKig_Lra.mjs} +4 -4
- package/dist/{contract-emit-CRoS1nx5.mjs.map → contract-emit-CKig_Lra.mjs.map} +1 -1
- package/dist/{contract-infer-Ba1SE57Q.mjs → contract-infer-BFlIbyl9.mjs} +3 -3
- package/dist/{contract-infer-Ba1SE57Q.mjs.map → contract-infer-BFlIbyl9.mjs.map} +1 -1
- package/dist/exports/control-api.mjs +2 -2
- package/dist/exports/index.mjs +1 -1
- package/dist/{framework-components-BAsliT4V.mjs → framework-components-Bsr1GaIj.mjs} +2 -2
- package/dist/{framework-components-BAsliT4V.mjs.map → framework-components-Bsr1GaIj.mjs.map} +1 -1
- package/dist/{init-Dx5uJ-6Q.mjs → init-DlFLMBaU.mjs} +2 -2
- package/dist/{init-Dx5uJ-6Q.mjs.map → init-DlFLMBaU.mjs.map} +1 -1
- package/dist/{inspect-live-schema-gYQiWfpl.mjs → inspect-live-schema-gjmUZ8xm.mjs} +4 -4
- package/dist/{inspect-live-schema-gYQiWfpl.mjs.map → inspect-live-schema-gjmUZ8xm.mjs.map} +1 -1
- package/dist/{migration-command-scaffold-x4n_ZhAh.mjs → migration-command-scaffold-CfllKppa.mjs} +4 -4
- package/dist/{migration-command-scaffold-x4n_ZhAh.mjs.map → migration-command-scaffold-CfllKppa.mjs.map} +1 -1
- package/dist/migration-emit-dRXV6QSz.mjs +72 -0
- package/dist/migration-emit-dRXV6QSz.mjs.map +1 -0
- package/dist/{migration-status-DyVDf5NI.mjs → migration-status-BwKCQB_a.mjs} +5 -5
- package/dist/{migration-status-DyVDf5NI.mjs.map → migration-status-BwKCQB_a.mjs.map} +1 -1
- package/dist/{migrations-DTZBYXm1.mjs → migrations-BIsjFjSV.mjs} +6 -15
- package/dist/migrations-BIsjFjSV.mjs.map +1 -0
- package/dist/{result-handler-oK_vA-Fn.mjs → result-handler-AFK4hxyX.mjs} +2 -2
- package/dist/result-handler-AFK4hxyX.mjs.map +1 -0
- package/dist/{validate-contract-deps-esa-VQ0h.mjs → validate-contract-deps-DBH6iTAD.mjs} +1 -1
- package/dist/{validate-contract-deps-esa-VQ0h.mjs.map → validate-contract-deps-DBH6iTAD.mjs.map} +1 -1
- package/dist/{verify-DlFQ2FOw.mjs → verify-C56CuQc7.mjs} +2 -2
- package/dist/{verify-DlFQ2FOw.mjs.map → verify-C56CuQc7.mjs.map} +1 -1
- package/package.json +19 -19
- package/src/cli.ts +4 -4
- package/src/commands/migration-apply.ts +2 -2
- package/src/commands/migration-emit.ts +132 -0
- package/src/commands/migration-new.ts +3 -3
- package/src/commands/migration-plan.ts +15 -57
- package/src/commands/migration-show.ts +1 -1
- package/src/commands/migration-status.ts +1 -1
- package/src/lib/migration-emit.ts +113 -0
- package/src/utils/cli-errors.ts +5 -0
- package/src/utils/formatters/help.ts +1 -1
- package/src/utils/formatters/migrations.ts +6 -20
- package/dist/cli-errors-BDCYR5ap.mjs +0 -4
- package/dist/commands/migration-verify.d.mts +0 -16
- package/dist/commands/migration-verify.d.mts.map +0 -1
- package/dist/commands/migration-verify.mjs +0 -110
- package/dist/commands/migration-verify.mjs.map +0 -1
- package/dist/contract-emit-CGpb33vs.mjs +0 -4
- package/dist/migrations-DTZBYXm1.mjs.map +0 -1
- package/dist/result-handler-oK_vA-Fn.mjs.map +0 -1
- package/src/commands/migration-verify.ts +0 -180
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import "../config-loader-C4VXKl8f.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { n as ContractValidationError } from "../client-
|
|
4
|
-
import { d as setCommandExamples, l as sanitizeErrorMessage, m as parseGlobalFlags, t as handleResult, u as setCommandDescriptions } from "../result-handler-
|
|
2
|
+
import { a as errorContractValidationFailed, m as errorRunnerFailed, n as ERROR_CODE_DESTRUCTIVE_CHANGES, p as errorMigrationPlanningFailed, s as errorDestructiveChanges, t as CliStructuredError, v as errorUnexpected } from "../cli-errors-BUuJr6py.mjs";
|
|
3
|
+
import { n as ContractValidationError } from "../client-DUs1DH-1.mjs";
|
|
4
|
+
import { d as setCommandExamples, l as sanitizeErrorMessage, m as parseGlobalFlags, t as handleResult, u as setCommandDescriptions } from "../result-handler-AFK4hxyX.mjs";
|
|
5
5
|
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
6
|
-
import {
|
|
7
|
-
import { n as prepareMigrationContext, t as addMigrationCommandOptions } from "../migration-command-scaffold-
|
|
6
|
+
import { a as formatMigrationPlanOutput, i as formatMigrationJson, n as formatMigrationApplyOutput } from "../migrations-BIsjFjSV.mjs";
|
|
7
|
+
import { n as prepareMigrationContext, t as addMigrationCommandOptions } from "../migration-command-scaffold-CfllKppa.mjs";
|
|
8
8
|
import { Command } from "commander";
|
|
9
9
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
10
10
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-C4VXKl8f.mjs";
|
|
2
|
-
import { _ as
|
|
3
|
-
import { n as ContractValidationError, t as createControlClient } from "../client-
|
|
4
|
-
import { _ as formatStyledHeader, a as maskConnectionUrl, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, s as resolveContractPath, t as handleResult, u as setCommandDescriptions } from "../result-handler-
|
|
2
|
+
import { _ as errorTargetMismatch, a as errorContractValidationFailed, c as errorDriverRequired, d as errorMarkerMissing, h as errorRuntime, l as errorFileNotFound, o as errorDatabaseConnectionRequired, t as CliStructuredError, u as errorHashMismatch, v as errorUnexpected } from "../cli-errors-BUuJr6py.mjs";
|
|
3
|
+
import { n as ContractValidationError, t as createControlClient } from "../client-DUs1DH-1.mjs";
|
|
4
|
+
import { _ as formatStyledHeader, a as maskConnectionUrl, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, s as resolveContractPath, t as handleResult, u as setCommandDescriptions } from "../result-handler-AFK4hxyX.mjs";
|
|
5
5
|
import { t as createProgressAdapter } from "../progress-adapter-B-YvmcDu.mjs";
|
|
6
6
|
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
7
|
-
import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "../verify-
|
|
7
|
+
import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "../verify-C56CuQc7.mjs";
|
|
8
8
|
import { Command } from "commander";
|
|
9
9
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
10
10
|
import { relative, resolve } from "pathe";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-C4VXKl8f.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { t as createControlClient } from "../client-
|
|
4
|
-
import { _ as formatStyledHeader, a as maskConnectionUrl, c as resolveMigrationPaths, d as setCommandExamples, f as targetSupportsMigrations, i as loadAllBundles, m as parseGlobalFlags, n as addGlobalOptions, o as readContractEnvelope, p as toPathDecisionResult, t as handleResult, u as setCommandDescriptions } from "../result-handler-
|
|
2
|
+
import { c as errorDriverRequired, g as errorTargetMigrationNotSupported, h as errorRuntime, o as errorDatabaseConnectionRequired, t as CliStructuredError, v as errorUnexpected } from "../cli-errors-BUuJr6py.mjs";
|
|
3
|
+
import { t as createControlClient } from "../client-DUs1DH-1.mjs";
|
|
4
|
+
import { _ as formatStyledHeader, a as maskConnectionUrl, c as resolveMigrationPaths, d as setCommandExamples, f as targetSupportsMigrations, i as loadAllBundles, m as parseGlobalFlags, n as addGlobalOptions, o as readContractEnvelope, p as toPathDecisionResult, t as handleResult, u as setCommandDescriptions } from "../result-handler-AFK4hxyX.mjs";
|
|
5
5
|
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
6
|
-
import { t as formatMigrationApplyCommandOutput } from "../migrations-
|
|
6
|
+
import { t as formatMigrationApplyCommandOutput } from "../migrations-BIsjFjSV.mjs";
|
|
7
7
|
import { Command } from "commander";
|
|
8
8
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
9
9
|
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
@@ -95,7 +95,7 @@ async function executeMigrationApplyCommand(options, flags, ui, startTime) {
|
|
|
95
95
|
let migrations;
|
|
96
96
|
try {
|
|
97
97
|
migrations = await loadAllBundles(migrationsDir);
|
|
98
|
-
if (migrations.drafts.length > 0 && !flags.quiet) ui.warn(`${migrations.drafts.length} draft migration(s) found: ${migrations.drafts.map((d) => d.dirName).join(", ")}. Run 'prisma-next migration
|
|
98
|
+
if (migrations.drafts.length > 0 && !flags.quiet) ui.warn(`${migrations.drafts.length} draft migration(s) found: ${migrations.drafts.map((d) => d.dirName).join(", ")}. Run 'prisma-next migration emit --dir <path>' to attest before applying.`);
|
|
99
99
|
} catch (error) {
|
|
100
100
|
if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
|
|
101
101
|
throw error;
|
|
@@ -155,7 +155,7 @@ async function executeMigrationApplyCommand(options, flags, ui, startTime) {
|
|
|
155
155
|
const matchingDraft = migrations.drafts.find((d) => d.manifest.to === destinationHash);
|
|
156
156
|
return notOk(errorRuntime("Current contract has no planned migration path", {
|
|
157
157
|
why: matchingDraft ? `A draft migration exists at "${matchingDraft.dirName}" but has not been attested` : `Current contract hash "${destinationHash}" is not present in the migration history at ${migrationsRelative}`,
|
|
158
|
-
fix: matchingDraft ? `Run 'prisma-next migration
|
|
158
|
+
fix: matchingDraft ? `Run 'prisma-next migration emit --dir "${migrationsRelative}/${matchingDraft.dirName}"' to attest, then re-run apply.` : "Run `prisma-next migration plan` to create a migration for the current contract, then re-run apply.",
|
|
159
159
|
meta: {
|
|
160
160
|
destinationHash,
|
|
161
161
|
knownNodes: [...migrations.graph.nodes]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration-apply.mjs","names":["destinationHash: string","refName: string | undefined","details: Array<{ label: string; value: string }>","migrations: MigrationBundleSet","pendingMigrations: MigrationApplyStep[]"],"sources":["../../src/commands/migration-apply.ts"],"sourcesContent":["import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findPathWithDecision } from '@prisma-next/migration-tools/dag';\nimport { readRefs, resolveRef } from '@prisma-next/migration-tools/refs';\nimport type { AttestedMigrationBundle } from '@prisma-next/migration-tools/types';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\n\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { MigrationApplyFailure, MigrationApplyStep } from '../control-api/types';\nimport {\n CliStructuredError,\n type CliStructuredError as CliStructuredErrorType,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n loadAllBundles,\n type MigrationBundleSet,\n maskConnectionUrl,\n readContractEnvelope,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n targetSupportsMigrations,\n toPathDecisionResult,\n} from '../utils/command-helpers';\nimport { formatMigrationApplyCommandOutput } from '../utils/formatters/migrations';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationApplyCommandOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly ref?: string;\n}\n\nexport interface MigrationApplyResult {\n readonly ok: boolean;\n readonly migrationsApplied: number;\n readonly migrationsTotal: number;\n readonly markerHash: string;\n readonly applied: readonly {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly operationsExecuted: number;\n }[];\n readonly summary: string;\n readonly pathDecision?: {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationId: string | null;\n readonly from: string;\n readonly to: string;\n }[];\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nfunction mapMigrationToolsError(error: unknown): CliStructuredErrorType {\n if (MigrationToolsError.is(error)) {\n return errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code, ...(error.details ?? {}) },\n });\n }\n return errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\nfunction mapApplyFailure(failure: MigrationApplyFailure): CliStructuredErrorType {\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the issue and re-run `prisma-next migration apply` — previously applied migrations are preserved.',\n meta: failure.meta ?? {},\n });\n}\n\nfunction packageToStep(pkg: AttestedMigrationBundle): MigrationApplyStep {\n return {\n dirName: pkg.dirName,\n from: pkg.manifest.from,\n to: pkg.manifest.to,\n toContract: pkg.manifest.toContract,\n operations: pkg.ops,\n };\n}\n\nasync function executeMigrationApplyCommand(\n options: MigrationApplyCommandOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationApplyResult, CliStructuredErrorType>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, migrationsRelative, refsPath } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for migration apply (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: 'migration apply',\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: 'Config.driver is required for migration apply',\n }),\n );\n }\n\n if (!targetSupportsMigrations(config.target)) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n let destinationHash: string;\n let refName: string | undefined;\n\n if (options.ref) {\n refName = options.ref;\n try {\n const refs = await readRefs(refsPath);\n destinationHash = resolveRef(refs, refName);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n } else {\n try {\n const envelope = await readContractEnvelope(config);\n destinationHash = envelope.storageHash;\n } catch (error) {\n return notOk(\n errorRuntime('Current contract is unavailable', {\n why: `Failed to read contract: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to generate a valid contract.json, then retry apply.',\n }),\n );\n }\n }\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: migrationsRelative },\n ];\n if (typeof dbConnection === 'string') {\n details.push({\n label: 'database',\n value: maskConnectionUrl(dbConnection),\n });\n }\n if (refName) {\n details.push({ label: 'ref', value: refName });\n }\n const header = formatStyledHeader({\n command: 'migration apply',\n description: 'Apply planned migrations to the database',\n url: 'https://pris.ly/migration-apply',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Read migrations and build migration chain model (offline — no DB needed)\n let migrations: MigrationBundleSet;\n try {\n migrations = await loadAllBundles(migrationsDir);\n if (migrations.drafts.length > 0 && !flags.quiet) {\n ui.warn(\n `${migrations.drafts.length} draft migration(s) found: ${migrations.drafts.map((d) => d.dirName).join(', ')}. ` +\n \"Run 'prisma-next migration verify --dir <path>' to attest before applying.\",\n );\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n try {\n await client.connect(dbConnection);\n const marker = await client.readMarker();\n\n // --- No attested migrations on disk ---\n if (migrations.attested.length === 0) {\n if (marker?.storageHash) {\n return notOk(\n errorRuntime('Database has state but no migrations exist', {\n why: `The database marker hash \"${marker.storageHash}\" exists but no attested migrations were found in ${migrationsRelative}`,\n fix: 'Ensure the migrations directory is correct. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.',\n meta: { markerHash: marker.storageHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n // Non-empty contract + no migrations = user needs to plan first.\n if (destinationHash !== EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Current contract has no planned migrations', {\n why: `No attested migrations were found in ${migrationsRelative}, but current contract hash is \"${destinationHash}\"`,\n fix: 'Run `prisma-next migration plan` to create an attested migration for the current contract.',\n meta: { destinationHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n // Empty contract + no migrations = nothing to do.\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash: EMPTY_CONTRACT_HASH,\n applied: [],\n summary: 'No attested migrations found',\n timings: { total: Date.now() - startTime },\n });\n }\n\n // --- Validate marker state ---\n\n // The empty sentinel should never appear in a real marker row — if it does,\n // the marker was corrupted and replaying all migrations would be dangerous.\n if (marker?.storageHash === EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Database marker contains the empty sentinel hash', {\n why: `The marker row exists but contains the empty sentinel value \"${EMPTY_CONTRACT_HASH}\". This should never happen — the marker should contain the hash of the last applied contract.`,\n fix: 'The marker is corrupted. Run `prisma-next db sign` to overwrite it with the correct contract hash, or drop and recreate the database.',\n meta: { markerHash: EMPTY_CONTRACT_HASH },\n }),\n );\n }\n\n const markerHash = marker?.storageHash;\n\n if (markerHash !== undefined && !migrations.graph.nodes.has(markerHash)) {\n return notOk(\n errorRuntime('Database marker does not match any known migration', {\n why: `The database marker hash \"${markerHash}\" is not found in the migration history at ${migrationsRelative}`,\n fix: 'Ensure the migrations directory matches this database. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.',\n meta: { markerHash, knownNodes: [...migrations.graph.nodes] },\n }),\n );\n }\n\n if (!migrations.graph.nodes.has(destinationHash)) {\n const matchingDraft = migrations.drafts.find((d) => d.manifest.to === destinationHash);\n return notOk(\n errorRuntime('Current contract has no planned migration path', {\n why: matchingDraft\n ? `A draft migration exists at \"${matchingDraft.dirName}\" but has not been attested`\n : `Current contract hash \"${destinationHash}\" is not present in the migration history at ${migrationsRelative}`,\n fix: matchingDraft\n ? `Run 'prisma-next migration verify --dir ${migrationsRelative}/${matchingDraft.dirName}' to attest, then re-run apply.`\n : 'Run `prisma-next migration plan` to create a migration for the current contract, then re-run apply.',\n meta: { destinationHash, knownNodes: [...migrations.graph.nodes] },\n }),\n );\n }\n\n // --- Resolve path and apply ---\n\n // \"No marker\" means the database is fresh — start from the empty contract hash.\n const originHash = markerHash ?? EMPTY_CONTRACT_HASH;\n\n const decision = findPathWithDecision(migrations.graph, originHash, destinationHash, refName);\n if (!decision) {\n return notOk(\n errorRuntime('No migration path from current state to target', {\n why: `Cannot find a path from \"${originHash}\" to target \"${destinationHash}\"`,\n fix: 'Check the migration history for gaps or inconsistencies.',\n meta: { markerHash: originHash, destinationHash },\n }),\n );\n }\n\n const pendingPath = decision.selectedPath;\n const pathDecision = toPathDecisionResult(decision);\n\n if (pendingPath.length === 0) {\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash: originHash,\n applied: [],\n summary: 'Already up to date',\n pathDecision,\n timings: { total: Date.now() - startTime },\n });\n }\n\n const bundleByDir = new Map(migrations.attested.map((b) => [b.dirName, b]));\n const pendingMigrations: MigrationApplyStep[] = [];\n for (const migration of pendingPath) {\n const pkg = bundleByDir.get(migration.dirName);\n if (!pkg) {\n return notOk(\n errorRuntime(`Migration package not found: ${migration.dirName}`, {\n why: `The migration directory for path segment ${migration.from} → ${migration.to} was not found`,\n fix: 'Ensure all migration directories are present and intact.',\n }),\n );\n }\n pendingMigrations.push(packageToStep(pkg));\n }\n\n if (!flags.quiet && !flags.json) {\n for (const migration of pendingMigrations) {\n ui.step(`Pending ${migration.dirName}`);\n }\n }\n\n const applyResult = await client.migrationApply({\n originHash,\n destinationHash,\n pendingMigrations,\n });\n\n if (!applyResult.ok) {\n return notOk(mapApplyFailure(applyResult.failure));\n }\n\n const { value } = applyResult;\n\n return ok({\n ok: true,\n migrationsApplied: value.migrationsApplied,\n migrationsTotal: pendingPath.length,\n markerHash: value.markerHash,\n applied: value.applied,\n summary: value.summary,\n pathDecision,\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createMigrationApplyCommand(): Command {\n const command = new Command('apply');\n setCommandDescriptions(\n command,\n 'Apply planned migrations to the database',\n 'Applies previously planned migrations (created by `migration plan`) to a live database.\\n' +\n 'Compares the database marker against the migration history to determine which\\n' +\n 'migrations are pending, then executes them sequentially. Each migration runs\\n' +\n 'in its own transaction. Does not plan new migrations — run `migration plan` first.',\n );\n setCommandExamples(command, ['prisma-next migration apply --db $DATABASE_URL']);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--ref <name>', 'Target ref name from migrations/refs/')\n .action(async (options: MigrationApplyCommandOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const ui = new TerminalUI({\n color: flags.color,\n interactive: flags.interactive,\n });\n\n const result = await executeMigrationApplyCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (applyResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(applyResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationApplyCommandOutput(applyResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;AA2EA,SAAS,uBAAuB,OAAwC;AACtE,KAAI,oBAAoB,GAAG,MAAM,CAC/B,QAAO,aAAa,MAAM,S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AAY;GAC7B,YAAY,MAAM;GAClB,SAAS,MAAM;GACf,SAAS,MAAM;GACf;GACA,SAAS,EAAE,OAAO,KAAK,KAAK,GAAG,WAAW;GAC3C,CAAC;UACK,OAAO;AACd,MAAI,mBAAmB,GAAG,MAAM,CAC9B,QAAO,MAAM,MAAM;AAErB,SAAO,MACL,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAAE,EACtE,KAAK,4CAA4C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IACxG,CAAC,CACH;WACO;AACR,QAAM,OAAO,OAAO;;;AAIxB,SAAgB,8BAAuC;CACrD,MAAM,UAAU,IAAI,QAAQ,QAAQ;AACpC,wBACE,SACA,4CACA,2UAID;AACD,oBAAmB,SAAS,CAAC,iDAAiD,CAAC;AAC/E,kBAAiB,QAAQ,CACtB,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,gBAAgB,wCAAwC,CAC/D,OAAO,OAAO,YAA0C;EACvD,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,YAAY,KAAK,KAAK;EAE5B,MAAM,KAAK,IAAI,WAAW;GACxB,OAAO,MAAM;GACb,aAAa,MAAM;GACpB,CAAC;EAIF,MAAM,WAAW,aAFF,MAAM,6BAA6B,SAAS,OAAO,IAAI,UAAU,EAE1C,OAAO,KAAK,gBAAgB;AAChE,OAAI,MAAM,KACR,IAAG,OAAO,KAAK,UAAU,aAAa,MAAM,EAAE,CAAC;YACtC,CAAC,MAAM,MAChB,IAAG,IAAI,kCAAkC,aAAa,MAAM,CAAC;IAE/D;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
1
|
+
{"version":3,"file":"migration-apply.mjs","names":["destinationHash: string","refName: string | undefined","details: Array<{ label: string; value: string }>","migrations: MigrationBundleSet","pendingMigrations: MigrationApplyStep[]"],"sources":["../../src/commands/migration-apply.ts"],"sourcesContent":["import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findPathWithDecision } from '@prisma-next/migration-tools/dag';\nimport { readRefs, resolveRef } from '@prisma-next/migration-tools/refs';\nimport type { AttestedMigrationBundle } from '@prisma-next/migration-tools/types';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\n\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { MigrationApplyFailure, MigrationApplyStep } from '../control-api/types';\nimport {\n CliStructuredError,\n type CliStructuredError as CliStructuredErrorType,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n loadAllBundles,\n type MigrationBundleSet,\n maskConnectionUrl,\n readContractEnvelope,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n targetSupportsMigrations,\n toPathDecisionResult,\n} from '../utils/command-helpers';\nimport { formatMigrationApplyCommandOutput } from '../utils/formatters/migrations';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationApplyCommandOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly ref?: string;\n}\n\nexport interface MigrationApplyResult {\n readonly ok: boolean;\n readonly migrationsApplied: number;\n readonly migrationsTotal: number;\n readonly markerHash: string;\n readonly applied: readonly {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly operationsExecuted: number;\n }[];\n readonly summary: string;\n readonly pathDecision?: {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationId: string | null;\n readonly from: string;\n readonly to: string;\n }[];\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nfunction mapMigrationToolsError(error: unknown): CliStructuredErrorType {\n if (MigrationToolsError.is(error)) {\n return errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code, ...(error.details ?? {}) },\n });\n }\n return errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\nfunction mapApplyFailure(failure: MigrationApplyFailure): CliStructuredErrorType {\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the issue and re-run `prisma-next migration apply` — previously applied migrations are preserved.',\n meta: failure.meta ?? {},\n });\n}\n\nfunction packageToStep(pkg: AttestedMigrationBundle): MigrationApplyStep {\n return {\n dirName: pkg.dirName,\n from: pkg.manifest.from,\n to: pkg.manifest.to,\n toContract: pkg.manifest.toContract,\n operations: pkg.ops,\n };\n}\n\nasync function executeMigrationApplyCommand(\n options: MigrationApplyCommandOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationApplyResult, CliStructuredErrorType>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, migrationsRelative, refsPath } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for migration apply (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: 'migration apply',\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: 'Config.driver is required for migration apply',\n }),\n );\n }\n\n if (!targetSupportsMigrations(config.target)) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n let destinationHash: string;\n let refName: string | undefined;\n\n if (options.ref) {\n refName = options.ref;\n try {\n const refs = await readRefs(refsPath);\n destinationHash = resolveRef(refs, refName);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n } else {\n try {\n const envelope = await readContractEnvelope(config);\n destinationHash = envelope.storageHash;\n } catch (error) {\n return notOk(\n errorRuntime('Current contract is unavailable', {\n why: `Failed to read contract: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to generate a valid contract.json, then retry apply.',\n }),\n );\n }\n }\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: migrationsRelative },\n ];\n if (typeof dbConnection === 'string') {\n details.push({\n label: 'database',\n value: maskConnectionUrl(dbConnection),\n });\n }\n if (refName) {\n details.push({ label: 'ref', value: refName });\n }\n const header = formatStyledHeader({\n command: 'migration apply',\n description: 'Apply planned migrations to the database',\n url: 'https://pris.ly/migration-apply',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Read migrations and build migration chain model (offline — no DB needed)\n let migrations: MigrationBundleSet;\n try {\n migrations = await loadAllBundles(migrationsDir);\n if (migrations.drafts.length > 0 && !flags.quiet) {\n ui.warn(\n `${migrations.drafts.length} draft migration(s) found: ${migrations.drafts.map((d) => d.dirName).join(', ')}. ` +\n \"Run 'prisma-next migration emit --dir <path>' to attest before applying.\",\n );\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n try {\n await client.connect(dbConnection);\n const marker = await client.readMarker();\n\n // --- No attested migrations on disk ---\n if (migrations.attested.length === 0) {\n if (marker?.storageHash) {\n return notOk(\n errorRuntime('Database has state but no migrations exist', {\n why: `The database marker hash \"${marker.storageHash}\" exists but no attested migrations were found in ${migrationsRelative}`,\n fix: 'Ensure the migrations directory is correct. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.',\n meta: { markerHash: marker.storageHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n // Non-empty contract + no migrations = user needs to plan first.\n if (destinationHash !== EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Current contract has no planned migrations', {\n why: `No attested migrations were found in ${migrationsRelative}, but current contract hash is \"${destinationHash}\"`,\n fix: 'Run `prisma-next migration plan` to create an attested migration for the current contract.',\n meta: { destinationHash, migrationsDir: migrationsRelative },\n }),\n );\n }\n // Empty contract + no migrations = nothing to do.\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash: EMPTY_CONTRACT_HASH,\n applied: [],\n summary: 'No attested migrations found',\n timings: { total: Date.now() - startTime },\n });\n }\n\n // --- Validate marker state ---\n\n // The empty sentinel should never appear in a real marker row — if it does,\n // the marker was corrupted and replaying all migrations would be dangerous.\n if (marker?.storageHash === EMPTY_CONTRACT_HASH) {\n return notOk(\n errorRuntime('Database marker contains the empty sentinel hash', {\n why: `The marker row exists but contains the empty sentinel value \"${EMPTY_CONTRACT_HASH}\". This should never happen — the marker should contain the hash of the last applied contract.`,\n fix: 'The marker is corrupted. Run `prisma-next db sign` to overwrite it with the correct contract hash, or drop and recreate the database.',\n meta: { markerHash: EMPTY_CONTRACT_HASH },\n }),\n );\n }\n\n const markerHash = marker?.storageHash;\n\n if (markerHash !== undefined && !migrations.graph.nodes.has(markerHash)) {\n return notOk(\n errorRuntime('Database marker does not match any known migration', {\n why: `The database marker hash \"${markerHash}\" is not found in the migration history at ${migrationsRelative}`,\n fix: 'Ensure the migrations directory matches this database. If the database was managed with `db init` or `db update`, run `prisma-next db sign` to update the marker.',\n meta: { markerHash, knownNodes: [...migrations.graph.nodes] },\n }),\n );\n }\n\n if (!migrations.graph.nodes.has(destinationHash)) {\n const matchingDraft = migrations.drafts.find((d) => d.manifest.to === destinationHash);\n return notOk(\n errorRuntime('Current contract has no planned migration path', {\n why: matchingDraft\n ? `A draft migration exists at \"${matchingDraft.dirName}\" but has not been attested`\n : `Current contract hash \"${destinationHash}\" is not present in the migration history at ${migrationsRelative}`,\n fix: matchingDraft\n ? `Run 'prisma-next migration emit --dir \"${migrationsRelative}/${matchingDraft.dirName}\"' to attest, then re-run apply.`\n : 'Run `prisma-next migration plan` to create a migration for the current contract, then re-run apply.',\n meta: { destinationHash, knownNodes: [...migrations.graph.nodes] },\n }),\n );\n }\n\n // --- Resolve path and apply ---\n\n // \"No marker\" means the database is fresh — start from the empty contract hash.\n const originHash = markerHash ?? EMPTY_CONTRACT_HASH;\n\n const decision = findPathWithDecision(migrations.graph, originHash, destinationHash, refName);\n if (!decision) {\n return notOk(\n errorRuntime('No migration path from current state to target', {\n why: `Cannot find a path from \"${originHash}\" to target \"${destinationHash}\"`,\n fix: 'Check the migration history for gaps or inconsistencies.',\n meta: { markerHash: originHash, destinationHash },\n }),\n );\n }\n\n const pendingPath = decision.selectedPath;\n const pathDecision = toPathDecisionResult(decision);\n\n if (pendingPath.length === 0) {\n return ok({\n ok: true,\n migrationsApplied: 0,\n migrationsTotal: 0,\n markerHash: originHash,\n applied: [],\n summary: 'Already up to date',\n pathDecision,\n timings: { total: Date.now() - startTime },\n });\n }\n\n const bundleByDir = new Map(migrations.attested.map((b) => [b.dirName, b]));\n const pendingMigrations: MigrationApplyStep[] = [];\n for (const migration of pendingPath) {\n const pkg = bundleByDir.get(migration.dirName);\n if (!pkg) {\n return notOk(\n errorRuntime(`Migration package not found: ${migration.dirName}`, {\n why: `The migration directory for path segment ${migration.from} → ${migration.to} was not found`,\n fix: 'Ensure all migration directories are present and intact.',\n }),\n );\n }\n pendingMigrations.push(packageToStep(pkg));\n }\n\n if (!flags.quiet && !flags.json) {\n for (const migration of pendingMigrations) {\n ui.step(`Pending ${migration.dirName}`);\n }\n }\n\n const applyResult = await client.migrationApply({\n originHash,\n destinationHash,\n pendingMigrations,\n });\n\n if (!applyResult.ok) {\n return notOk(mapApplyFailure(applyResult.failure));\n }\n\n const { value } = applyResult;\n\n return ok({\n ok: true,\n migrationsApplied: value.migrationsApplied,\n migrationsTotal: pendingPath.length,\n markerHash: value.markerHash,\n applied: value.applied,\n summary: value.summary,\n pathDecision,\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migration apply: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createMigrationApplyCommand(): Command {\n const command = new Command('apply');\n setCommandDescriptions(\n command,\n 'Apply planned migrations to the database',\n 'Applies previously planned migrations (created by `migration plan`) to a live database.\\n' +\n 'Compares the database marker against the migration history to determine which\\n' +\n 'migrations are pending, then executes them sequentially. Each migration runs\\n' +\n 'in its own transaction. Does not plan new migrations — run `migration plan` first.',\n );\n setCommandExamples(command, ['prisma-next migration apply --db $DATABASE_URL']);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--ref <name>', 'Target ref name from migrations/refs/')\n .action(async (options: MigrationApplyCommandOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const ui = new TerminalUI({\n color: flags.color,\n interactive: flags.interactive,\n });\n\n const result = await executeMigrationApplyCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (applyResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(applyResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationApplyCommandOutput(applyResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;AA2EA,SAAS,uBAAuB,OAAwC;AACtE,KAAI,oBAAoB,GAAG,MAAM,CAC/B,QAAO,aAAa,MAAM,SAAS;EACjC,KAAK,MAAM;EACX,KAAK,MAAM;EACX,MAAM;GAAE,MAAM,MAAM;GAAM,GAAI,MA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AO,KAAK,KAAK,GAAG,WAAW;GAC3C,CAAC;UACK,OAAO;AACd,MAAI,mBAAmB,GAAG,MAAM,CAC9B,QAAO,MAAM,MAAM;AAErB,SAAO,MACL,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAAE,EACtE,KAAK,4CAA4C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IACxG,CAAC,CACH;WACO;AACR,QAAM,OAAO,OAAO;;;AAIxB,SAAgB,8BAAuC;CACrD,MAAM,UAAU,IAAI,QAAQ,QAAQ;AACpC,wBACE,SACA,4CACA,2UAID;AACD,oBAAmB,SAAS,CAAC,iDAAiD,CAAC;AAC/E,kBAAiB,QAAQ,CACtB,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,gBAAgB,wCAAwC,CAC/D,OAAO,OAAO,YAA0C;EACvD,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,YAAY,KAAK,KAAK;EAE5B,MAAM,KAAK,IAAI,WAAW;GACxB,OAAO,MAAM;GACb,aAAa,MAAM;GACpB,CAAC;EAIF,MAAM,WAAW,aAFF,MAAM,6BAA6B,SAAS,OAAO,IAAI,UAAU,EAE1C,OAAO,KAAK,gBAAgB;AAChE,OAAI,MAAM,KACR,IAAG,OAAO,KAAK,UAAU,aAAa,MAAM,EAAE,CAAC;YACtC,CAAC,MAAM,MAChB,IAAG,IAAI,kCAAkC,aAAa,MAAM,CAAC;IAE/D;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/global-flags.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Common options parsed by Commander.js for every command.
|
|
7
|
+
* Extend this for command-specific options instead of duplicating these fields.
|
|
8
|
+
*/
|
|
9
|
+
interface CommonCommandOptions {
|
|
10
|
+
readonly json?: string | boolean;
|
|
11
|
+
readonly quiet?: boolean;
|
|
12
|
+
readonly q?: boolean;
|
|
13
|
+
readonly verbose?: boolean;
|
|
14
|
+
readonly v?: boolean;
|
|
15
|
+
readonly trace?: boolean;
|
|
16
|
+
readonly color?: boolean;
|
|
17
|
+
readonly 'no-color'?: boolean;
|
|
18
|
+
readonly interactive?: boolean;
|
|
19
|
+
readonly 'no-interactive'?: boolean;
|
|
20
|
+
readonly yes?: boolean;
|
|
21
|
+
readonly y?: boolean;
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/commands/migration-emit.d.ts
|
|
25
|
+
interface MigrationEmitOptions extends CommonCommandOptions {
|
|
26
|
+
readonly dir: string;
|
|
27
|
+
readonly config?: string;
|
|
28
|
+
}
|
|
29
|
+
interface MigrationEmitResult {
|
|
30
|
+
readonly ok: boolean;
|
|
31
|
+
readonly dir: string;
|
|
32
|
+
readonly migrationId: string;
|
|
33
|
+
readonly summary: string;
|
|
34
|
+
}
|
|
35
|
+
declare function createMigrationEmitCommand(): Command;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { MigrationEmitOptions, MigrationEmitResult, createMigrationEmitCommand };
|
|
38
|
+
//# sourceMappingURL=migration-emit.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-emit.d.mts","names":[],"sources":["../../src/utils/global-flags.ts","../../src/commands/migration-emit.ts"],"sourcesContent":[],"mappings":";;;;AC8BA;AAuEA;;;UDxFiB,oBAAA;;;;;;;;;;;;;;;;UCYA,oBAAA,SAA6B;EDZ7B,SAAA,GAAA,EAAA,MAAA;;;UCiBA,mBAAA;EALA,SAAA,EAAA,EAAA,OAAA;EAKA,SAAA,GAAA,EAAA,MAAA;EAuED,SAAA,WAAA,EAAA,MAAA;;;iBAAA,0BAAA,CAAA,GAA8B"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { t as loadConfig } from "../config-loader-C4VXKl8f.mjs";
|
|
2
|
+
import { g as errorTargetMigrationNotSupported, h as errorRuntime, t as CliStructuredError, v as errorUnexpected } from "../cli-errors-BUuJr6py.mjs";
|
|
3
|
+
import { t as assertFrameworkComponentsCompatible } from "../framework-components-Bsr1GaIj.mjs";
|
|
4
|
+
import { _ as formatStyledHeader, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, r as getTargetMigrations, t as handleResult, u as setCommandDescriptions } from "../result-handler-AFK4hxyX.mjs";
|
|
5
|
+
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
6
|
+
import { r as formatMigrationEmitCommandOutput } from "../migrations-BIsjFjSV.mjs";
|
|
7
|
+
import { t as emitMigration } from "../migration-emit-dRXV6QSz.mjs";
|
|
8
|
+
import { Command } from "commander";
|
|
9
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
10
|
+
import { MigrationToolsError } from "@prisma-next/migration-tools/types";
|
|
11
|
+
|
|
12
|
+
//#region src/commands/migration-emit.ts
|
|
13
|
+
async function executeMigrationEmitCommand(options, flags, ui) {
|
|
14
|
+
const dir = options.dir;
|
|
15
|
+
if (!flags.json && !flags.quiet) {
|
|
16
|
+
const header = formatStyledHeader({
|
|
17
|
+
command: "migration emit",
|
|
18
|
+
description: "Emit ops.json from migration.ts and compute migrationId",
|
|
19
|
+
details: [{
|
|
20
|
+
label: "dir",
|
|
21
|
+
value: dir
|
|
22
|
+
}],
|
|
23
|
+
flags
|
|
24
|
+
});
|
|
25
|
+
ui.stderr(header);
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const config = await loadConfig(options.config);
|
|
29
|
+
const migrations = getTargetMigrations(config.target);
|
|
30
|
+
if (!migrations) throw errorTargetMigrationNotSupported({ why: `Target "${config.target.id}" does not support migrations` });
|
|
31
|
+
const frameworkComponents = assertFrameworkComponentsCompatible(config.family.familyId, config.target.targetId, [
|
|
32
|
+
config.target,
|
|
33
|
+
config.adapter,
|
|
34
|
+
...config.extensionPacks ?? []
|
|
35
|
+
]);
|
|
36
|
+
const { migrationId } = await emitMigration(dir, {
|
|
37
|
+
targetId: config.target.targetId,
|
|
38
|
+
migrations,
|
|
39
|
+
frameworkComponents
|
|
40
|
+
});
|
|
41
|
+
return ok({
|
|
42
|
+
ok: true,
|
|
43
|
+
dir,
|
|
44
|
+
migrationId,
|
|
45
|
+
summary: `Emitted ops.json and attested migrationId: ${migrationId}`
|
|
46
|
+
});
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (CliStructuredError.is(error)) return notOk(error);
|
|
49
|
+
if (MigrationToolsError.is(error)) return notOk(errorRuntime(error.message, {
|
|
50
|
+
why: error.why,
|
|
51
|
+
fix: error.fix,
|
|
52
|
+
meta: {
|
|
53
|
+
code: error.code,
|
|
54
|
+
...error.details ?? {}
|
|
55
|
+
}
|
|
56
|
+
}));
|
|
57
|
+
return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to emit migration: ${error instanceof Error ? error.message : String(error)}` }));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function createMigrationEmitCommand() {
|
|
61
|
+
const command = new Command("emit");
|
|
62
|
+
setCommandDescriptions(command, "Emit ops.json from migration.ts and compute migrationId", "Evaluates migration.ts in the package directory, resolves it to ops.json,\nthen computes and persists the content-addressed migrationId in manifest.json.");
|
|
63
|
+
setCommandExamples(command, ["prisma-next migration emit --dir migrations/20250101-add-users"]);
|
|
64
|
+
addGlobalOptions(command).requiredOption("--dir <path>", "Path to the migration package directory").option("--config <path>", "Path to prisma-next.config.ts").action(async (options) => {
|
|
65
|
+
const flags = parseGlobalFlags(options);
|
|
66
|
+
const ui = new TerminalUI({
|
|
67
|
+
color: flags.color,
|
|
68
|
+
interactive: flags.interactive
|
|
69
|
+
});
|
|
70
|
+
const exitCode = handleResult(await executeMigrationEmitCommand(options, flags, ui), flags, ui, (emitResult) => {
|
|
71
|
+
if (flags.json) ui.output(JSON.stringify(emitResult, null, 2));
|
|
72
|
+
else if (!flags.quiet) ui.log(formatMigrationEmitCommandOutput(emitResult, flags));
|
|
73
|
+
});
|
|
74
|
+
process.exit(exitCode);
|
|
75
|
+
});
|
|
76
|
+
return command;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
//#endregion
|
|
80
|
+
export { createMigrationEmitCommand };
|
|
81
|
+
//# sourceMappingURL=migration-emit.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-emit.mjs","names":[],"sources":["../../src/commands/migration-emit.ts"],"sourcesContent":["import { MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { emitMigration } from '../lib/migration-emit';\nimport {\n CliStructuredError,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n getTargetMigrations,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatMigrationEmitCommandOutput } from '../utils/formatters/migrations';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport { assertFrameworkComponentsCompatible } from '../utils/framework-components';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\nexport interface MigrationEmitOptions extends CommonCommandOptions {\n readonly dir: string;\n readonly config?: string;\n}\n\nexport interface MigrationEmitResult {\n readonly ok: boolean;\n readonly dir: string;\n readonly migrationId: string;\n readonly summary: string;\n}\n\nasync function executeMigrationEmitCommand(\n options: MigrationEmitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationEmitResult, CliStructuredError>> {\n const dir = options.dir;\n\n if (!flags.json && !flags.quiet) {\n const header = formatStyledHeader({\n command: 'migration emit',\n description: 'Emit ops.json from migration.ts and compute migrationId',\n details: [{ label: 'dir', value: dir }],\n flags,\n });\n ui.stderr(header);\n }\n\n try {\n const config = await loadConfig(options.config);\n const migrations = getTargetMigrations(config.target);\n if (!migrations) {\n throw errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n });\n }\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n [config.target, config.adapter, ...(config.extensionPacks ?? [])],\n );\n\n const { migrationId } = await emitMigration(dir, {\n targetId: config.target.targetId,\n migrations,\n frameworkComponents,\n });\n\n return ok({\n ok: true,\n dir,\n migrationId,\n summary: `Emitted ops.json and attested migrationId: ${migrationId}`,\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code, ...(error.details ?? {}) },\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to emit migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nexport function createMigrationEmitCommand(): Command {\n const command = new Command('emit');\n setCommandDescriptions(\n command,\n 'Emit ops.json from migration.ts and compute migrationId',\n 'Evaluates migration.ts in the package directory, resolves it to ops.json,\\n' +\n 'then computes and persists the content-addressed migrationId in manifest.json.',\n );\n setCommandExamples(command, ['prisma-next migration emit --dir migrations/20250101-add-users']);\n addGlobalOptions(command)\n .requiredOption('--dir <path>', 'Path to the migration package directory')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: MigrationEmitOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n const result = await executeMigrationEmitCommand(options, flags, ui);\n\n const exitCode = handleResult(result, flags, ui, (emitResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(emitResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationEmitCommandOutput(emitResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n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nC,wBACE,SACA,2DACA,4JAED;AACD,oBAAmB,SAAS,CAAC,iEAAiE,CAAC;AAC/F,kBAAiB,QAAQ,CACtB,eAAe,gBAAgB,0CAA0C,CACzE,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,YAAkC;EAC/C,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;EAIjF,MAAM,WAAW,aAFF,MAAM,4BAA4B,SAAS,OAAO,GAAG,EAE9B,OAAO,KAAK,eAAe;AAC/D,OAAI,MAAM,KACR,IAAG,OAAO,KAAK,UAAU,YAAY,MAAM,EAAE,CAAC;YACrC,CAAC,MAAM,MAChB,IAAG,IAAI,iCAAiC,YAAY,MAAM,CAAC;IAE7D;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-C4VXKl8f.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { _ as formatStyledHeader, c as resolveMigrationPaths, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "../result-handler-
|
|
2
|
+
import { h as errorRuntime, v as errorUnexpected } from "../cli-errors-BUuJr6py.mjs";
|
|
3
|
+
import { _ as formatStyledHeader, c as resolveMigrationPaths, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "../result-handler-AFK4hxyX.mjs";
|
|
4
4
|
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
@@ -16,7 +16,7 @@ import { scaffoldMigrationTs } from "@prisma-next/migration-tools/migration-ts";
|
|
|
16
16
|
/**
|
|
17
17
|
* `migration new` — scaffolds a migration package with a migration.ts file
|
|
18
18
|
* for manual authoring. The user writes operation descriptors and data
|
|
19
|
-
* transforms; `migration
|
|
19
|
+
* transforms; `migration emit` resolves them to ops.json.
|
|
20
20
|
*/
|
|
21
21
|
async function executeMigrationNewCommand(options) {
|
|
22
22
|
const config = await loadConfig(options.config);
|
|
@@ -116,7 +116,7 @@ async function executeMigrationNewCommand(options) {
|
|
|
116
116
|
}
|
|
117
117
|
function createMigrationNewCommand() {
|
|
118
118
|
const command = new Command("new");
|
|
119
|
-
setCommandDescriptions(command, "Scaffold a new migration for manual authoring", "Creates a migration package with a migration.ts file for manual authoring.\nWrite operation descriptors and data transforms in migration.ts, then run\n`migration
|
|
119
|
+
setCommandDescriptions(command, "Scaffold a new migration for manual authoring", "Creates a migration package with a migration.ts file for manual authoring.\nWrite operation descriptors and data transforms in migration.ts, then run\n`migration emit` to resolve and attest the package.");
|
|
120
120
|
setCommandExamples(command, ["prisma-next migration new --name split-name", "prisma-next migration new --name custom-fk --from sha256:abc..."]);
|
|
121
121
|
addGlobalOptions(command).option("--name <slug>", "Migration name (used in directory name)").option("--from <hash>", "Starting contract hash (default: latest migration target)").option("--config <path>", "Path to prisma-next.config.ts").action(async (options) => {
|
|
122
122
|
const flags = parseGlobalFlags(options);
|
|
@@ -139,7 +139,7 @@ function createMigrationNewCommand() {
|
|
|
139
139
|
ui.output(`\nScaffolded migration at ${value.dir}`);
|
|
140
140
|
ui.output(` from: ${value.from}`);
|
|
141
141
|
ui.output(` to: ${value.to}`);
|
|
142
|
-
ui.output(`\nEdit migration.ts, then run \`prisma-next migration
|
|
142
|
+
ui.output(`\nEdit migration.ts, then run \`prisma-next migration emit --dir "${value.dir}"\` to attest.`);
|
|
143
143
|
}
|
|
144
144
|
});
|
|
145
145
|
process.exit(exitCode);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration-new.mjs","names":["contractJsonContent: string","toContractJson: Contract","fromContract: Contract | null","fromHash: string","manifest: MigrationManifest"],"sources":["../../src/commands/migration-new.ts"],"sourcesContent":["/**\n * `migration new` — scaffolds a migration package with a migration.ts file\n * for manual authoring. The user writes operation descriptors and data\n * transforms; `migration verify` resolves them to ops.json.\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findLatestMigration, reconstructGraph } from '@prisma-next/migration-tools/dag';\nimport {\n formatMigrationDirName,\n readMigrationsDir,\n writeMigrationPackage,\n} from '@prisma-next/migration-tools/io';\nimport { scaffoldMigrationTs } from '@prisma-next/migration-tools/migration-ts';\nimport type { MigrationManifest } from '@prisma-next/migration-tools/types';\nimport { isAttested, MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { type CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationNewOptions extends CommonCommandOptions {\n readonly name?: string;\n readonly from?: string;\n readonly config?: string;\n}\n\ninterface MigrationNewResult {\n readonly ok: true;\n readonly dir: string;\n readonly from: string;\n readonly to: string;\n readonly summary: string;\n}\n\nasync function executeMigrationNewCommand(\n options: MigrationNewOptions,\n): Promise<Result<MigrationNewResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);\n\n // Read the emitted contract (destination)\n const contractPath = config.contract?.output ?? 'contract.json';\n const contractPathAbsolute = resolve(\n options.config ? resolve(options.config, '..') : process.cwd(),\n contractPath,\n );\n\n let contractJsonContent: string;\n try {\n contractJsonContent = readFileSync(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorRuntime(`Contract file not found at ${contractPathAbsolute}`, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: 'Run `prisma-next contract emit` first to generate the contract',\n }),\n );\n }\n throw error;\n }\n\n let toContractJson: Contract;\n try {\n toContractJson = JSON.parse(contractJsonContent) as Contract;\n } catch (error) {\n return notOk(\n errorRuntime('Contract JSON is invalid', {\n why: `Failed to parse ${contractPathAbsolute}: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n const toStorageHash = (\n (toContractJson as unknown as Record<string, unknown>)['storage'] as\n | Record<string, unknown>\n | undefined\n )?.['storageHash'] as string | undefined;\n if (!toStorageHash) {\n return notOk(\n errorRuntime('Contract is missing storageHash', {\n why: `Contract at ${contractPathAbsolute} has no storageHash`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n // Determine \"from\" hash\n let fromContract: Contract | null = null;\n let fromHash: string = EMPTY_CONTRACT_HASH;\n\n try {\n const packages = await readMigrationsDir(migrationsDir);\n const attested = packages.filter(isAttested);\n\n if (attested.length > 0) {\n const graph = reconstructGraph(attested);\n\n if (options.from) {\n // Explicit --from: find the migration with matching to hash\n const match = attested.find((p) => p.manifest.to.startsWith(options.from!));\n if (!match) {\n return notOk(\n errorRuntime('Starting contract not found', {\n why: `No migration with to hash matching \"${options.from}\" exists in ${migrationsRelative}`,\n fix: 'Check that the --from hash matches a known migration target hash.',\n }),\n );\n }\n fromHash = match.manifest.to;\n fromContract = match.manifest.toContract;\n } else {\n const latestMigration = findLatestMigration(graph);\n if (latestMigration) {\n fromHash = latestMigration.to;\n const leafPkg = attested.find(\n (p) => p.manifest.migrationId === latestMigration.migrationId,\n );\n if (leafPkg) {\n fromContract = leafPkg.manifest.toContract;\n }\n }\n }\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code },\n }),\n );\n }\n throw error;\n }\n\n // Check for no-op\n if (fromHash === toStorageHash) {\n return notOk(\n errorRuntime('No changes detected', {\n why: 'The from and to contract hashes are identical — there is nothing to migrate.',\n fix: 'Change the contract and run `prisma-next contract emit` before creating a new migration.',\n }),\n );\n }\n\n // Build manifest and write package\n const timestamp = new Date();\n const slug = options.name ?? 'migration';\n const dirName = formatMigrationDirName(timestamp, slug);\n const packageDir = join(migrationsDir, dirName);\n\n const manifest: MigrationManifest = {\n from: fromHash,\n to: toStorageHash,\n migrationId: null,\n kind: 'regular',\n fromContract,\n toContract: toContractJson,\n hints: {\n used: [],\n applied: [],\n plannerVersion: '1.0.0',\n planningStrategy: 'manual',\n },\n labels: [],\n createdAt: timestamp.toISOString(),\n };\n\n try {\n // Write package with empty ops (draft)\n await writeMigrationPackage(packageDir, manifest, []);\n\n // Scaffold migration.ts\n await scaffoldMigrationTs(packageDir);\n\n return ok({\n ok: true as const,\n dir: relative(process.cwd(), packageDir),\n from: fromHash,\n to: toStorageHash,\n summary: `Scaffolded migration at ${relative(process.cwd(), packageDir)}`,\n });\n } catch (error) {\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to scaffold migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nexport function createMigrationNewCommand(): Command {\n const command = new Command('new');\n setCommandDescriptions(\n command,\n 'Scaffold a new migration for manual authoring',\n 'Creates a migration package with a migration.ts file for manual authoring.\\n' +\n 'Write operation descriptors and data transforms in migration.ts, then run\\n' +\n '`migration verify` to resolve and attest the package.',\n );\n setCommandExamples(command, [\n 'prisma-next migration new --name split-name',\n 'prisma-next migration new --name custom-fk --from sha256:abc...',\n ]);\n addGlobalOptions(command)\n .option('--name <slug>', 'Migration name (used in directory name)')\n .option('--from <hash>', 'Starting contract hash (default: latest migration target)')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: MigrationNewOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n if (!flags.json && !flags.quiet) {\n const header = formatStyledHeader({\n command: 'migration new',\n description: 'Scaffold a new migration',\n details: [],\n flags,\n });\n ui.stderr(header);\n }\n\n const result = await executeMigrationNewCommand(options);\n\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n } else if (!flags.quiet) {\n ui.output(`\\nScaffolded migration at ${value.dir}`);\n ui.output(` from: ${value.from}`);\n ui.output(` to: ${value.to}`);\n ui.output(\n `\\nEdit migration.ts, then run \\`prisma-next migration verify --dir ${value.dir}\\` to attest.`,\n );\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAe,2BACb,SACyD;CACzD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,EAAE,eAAe,uBAAuB,sBAAsB,QAAQ,QAAQ,OAAO;CAG3F,MAAM,eAAe,OAAO,UAAU,UAAU;CAChD,MAAM,uBAAuB,QAC3B,QAAQ,SAAS,QAAQ,QAAQ,QAAQ,KAAK,GAAG,QAAQ,KAAK,EAC9D,aACD;CAED,IAAIA;AACJ,KAAI;AACF,wBAAsB,aAAa,sBAAsB,QAAQ;UAC1D,OAAO;AACd,MAAI,iBAAiB,SAAU,MAA4B,SAAS,SAClE,QAAO,MACL,aAAa,8BAA8B,wBAAwB;GACjE,KAAK,8BAA8B;GACnC,KAAK;GACN,CAAC,CACH;AAEH,QAAM;;CAGR,IAAIC;AACJ,KAAI;AACF,mBAAiB,KAAK,MAAM,oBAAoB;UACzC,OAAO;AACd,SAAO,MACL,aAAa,4BAA4B;GACvC,KAAK,mBAAmB,qBAAqB,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GACvG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E,CAAC;YAChC,CAAC,MAAM,OAAO;AACvB,OAAG,OAAO,6BAA6B,MAAM,MAAM;AACnD,OAAG,OAAO,WAAW,MAAM,OAAO;AAClC,OAAG,OAAO,WAAW,MAAM,KAAK;AAChC,OAAG,OACD,sEAAsE,MAAM,IAAI,eACjF;;IAEH;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
1
|
+
{"version":3,"file":"migration-new.mjs","names":["contractJsonContent: string","toContractJson: Contract","fromContract: Contract | null","fromHash: string","manifest: MigrationManifest"],"sources":["../../src/commands/migration-new.ts"],"sourcesContent":["/**\n * `migration new` — scaffolds a migration package with a migration.ts file\n * for manual authoring. The user writes operation descriptors and data\n * transforms; `migration emit` resolves them to ops.json.\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findLatestMigration, reconstructGraph } from '@prisma-next/migration-tools/dag';\nimport {\n formatMigrationDirName,\n readMigrationsDir,\n writeMigrationPackage,\n} from '@prisma-next/migration-tools/io';\nimport { scaffoldMigrationTs } from '@prisma-next/migration-tools/migration-ts';\nimport type { MigrationManifest } from '@prisma-next/migration-tools/types';\nimport { isAttested, MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { type CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationNewOptions extends CommonCommandOptions {\n readonly name?: string;\n readonly from?: string;\n readonly config?: string;\n}\n\ninterface MigrationNewResult {\n readonly ok: true;\n readonly dir: string;\n readonly from: string;\n readonly to: string;\n readonly summary: string;\n}\n\nasync function executeMigrationNewCommand(\n options: MigrationNewOptions,\n): Promise<Result<MigrationNewResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);\n\n // Read the emitted contract (destination)\n const contractPath = config.contract?.output ?? 'contract.json';\n const contractPathAbsolute = resolve(\n options.config ? resolve(options.config, '..') : process.cwd(),\n contractPath,\n );\n\n let contractJsonContent: string;\n try {\n contractJsonContent = readFileSync(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorRuntime(`Contract file not found at ${contractPathAbsolute}`, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: 'Run `prisma-next contract emit` first to generate the contract',\n }),\n );\n }\n throw error;\n }\n\n let toContractJson: Contract;\n try {\n toContractJson = JSON.parse(contractJsonContent) as Contract;\n } catch (error) {\n return notOk(\n errorRuntime('Contract JSON is invalid', {\n why: `Failed to parse ${contractPathAbsolute}: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n const toStorageHash = (\n (toContractJson as unknown as Record<string, unknown>)['storage'] as\n | Record<string, unknown>\n | undefined\n )?.['storageHash'] as string | undefined;\n if (!toStorageHash) {\n return notOk(\n errorRuntime('Contract is missing storageHash', {\n why: `Contract at ${contractPathAbsolute} has no storageHash`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n // Determine \"from\" hash\n let fromContract: Contract | null = null;\n let fromHash: string = EMPTY_CONTRACT_HASH;\n\n try {\n const packages = await readMigrationsDir(migrationsDir);\n const attested = packages.filter(isAttested);\n\n if (attested.length > 0) {\n const graph = reconstructGraph(attested);\n\n if (options.from) {\n // Explicit --from: find the migration with matching to hash\n const match = attested.find((p) => p.manifest.to.startsWith(options.from!));\n if (!match) {\n return notOk(\n errorRuntime('Starting contract not found', {\n why: `No migration with to hash matching \"${options.from}\" exists in ${migrationsRelative}`,\n fix: 'Check that the --from hash matches a known migration target hash.',\n }),\n );\n }\n fromHash = match.manifest.to;\n fromContract = match.manifest.toContract;\n } else {\n const latestMigration = findLatestMigration(graph);\n if (latestMigration) {\n fromHash = latestMigration.to;\n const leafPkg = attested.find(\n (p) => p.manifest.migrationId === latestMigration.migrationId,\n );\n if (leafPkg) {\n fromContract = leafPkg.manifest.toContract;\n }\n }\n }\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code },\n }),\n );\n }\n throw error;\n }\n\n // Check for no-op\n if (fromHash === toStorageHash) {\n return notOk(\n errorRuntime('No changes detected', {\n why: 'The from and to contract hashes are identical — there is nothing to migrate.',\n fix: 'Change the contract and run `prisma-next contract emit` before creating a new migration.',\n }),\n );\n }\n\n // Build manifest and write package\n const timestamp = new Date();\n const slug = options.name ?? 'migration';\n const dirName = formatMigrationDirName(timestamp, slug);\n const packageDir = join(migrationsDir, dirName);\n\n const manifest: MigrationManifest = {\n from: fromHash,\n to: toStorageHash,\n migrationId: null,\n kind: 'regular',\n fromContract,\n toContract: toContractJson,\n hints: {\n used: [],\n applied: [],\n plannerVersion: '1.0.0',\n planningStrategy: 'manual',\n },\n labels: [],\n createdAt: timestamp.toISOString(),\n };\n\n try {\n // Write package with empty ops (draft)\n await writeMigrationPackage(packageDir, manifest, []);\n\n // Scaffold migration.ts\n await scaffoldMigrationTs(packageDir);\n\n return ok({\n ok: true as const,\n dir: relative(process.cwd(), packageDir),\n from: fromHash,\n to: toStorageHash,\n summary: `Scaffolded migration at ${relative(process.cwd(), packageDir)}`,\n });\n } catch (error) {\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to scaffold migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nexport function createMigrationNewCommand(): Command {\n const command = new Command('new');\n setCommandDescriptions(\n command,\n 'Scaffold a new migration for manual authoring',\n 'Creates a migration package with a migration.ts file for manual authoring.\\n' +\n 'Write operation descriptors and data transforms in migration.ts, then run\\n' +\n '`migration emit` to resolve and attest the package.',\n );\n setCommandExamples(command, [\n 'prisma-next migration new --name split-name',\n 'prisma-next migration new --name custom-fk --from sha256:abc...',\n ]);\n addGlobalOptions(command)\n .option('--name <slug>', 'Migration name (used in directory name)')\n .option('--from <hash>', 'Starting contract hash (default: latest migration target)')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: MigrationNewOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n if (!flags.json && !flags.quiet) {\n const header = formatStyledHeader({\n command: 'migration new',\n description: 'Scaffold a new migration',\n details: [],\n flags,\n });\n ui.stderr(header);\n }\n\n const result = await executeMigrationNewCommand(options);\n\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n } else if (!flags.quiet) {\n ui.output(`\\nScaffolded migration at ${value.dir}`);\n ui.output(` from: ${value.from}`);\n ui.output(` to: ${value.to}`);\n ui.output(\n `\\nEdit migration.ts, then run \\`prisma-next migration emit --dir \"${value.dir}\"\\` to attest.`,\n );\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAe,2BACb,SACyD;CACzD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,EAAE,eAAe,uBAAuB,sBAAsB,QAAQ,QAAQ,OAAO;CAG3F,MAAM,eAAe,OAAO,UAAU,UAAU;CAChD,MAAM,uBAAuB,QAC3B,QAAQ,SAAS,QAAQ,QAAQ,QAAQ,KAAK,GAAG,QAAQ,KAAK,EAC9D,aACD;CA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Q,iBAAiB,QAAQ;EACvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;AAEjF,MAAI,CAAC,MAAM,QAAQ,CAAC,MAAM,OAAO;GAC/B,MAAM,SAAS,mBAAmB;IAChC,SAAS;IACT,aAAa;IACb,SAAS,EAAE;IACX;IACD,CAAC;AACF,MAAG,OAAO,OAAO;;EAKnB,MAAM,WAAW,aAFF,MAAM,2BAA2B,QAAQ,EAElB,OAAO,KAAK,UAAU;AAC1D,OAAI,MAAM,KACR,IAAG,OAAO,KAAK,UAAU,OAAO,MAAM,EAAE,CAAC;YAChC,CAAC,MAAM,OAAO;AACvB,OAAG,OAAO,6BAA6B,MAAM,MAAM;AACnD,OAAG,OAAO,WAAW,MAAM,OAAO;AAClC,OAAG,OAAO,WAAW,MAAM,KAAK;AAChC,OAAG,OACD,qEAAqE,MAAM,IAAI,gBAChF;;IAEH;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration-plan.d.mts","names":[],"sources":["../../src/commands/migration-plan.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"migration-plan.d.mts","names":[],"sources":["../../src/commands/migration-plan.ts"],"sourcesContent":[],"mappings":";;;;UA6CiB,mBAAA;;EAAA,SAAA,IAAA,EAAA,OAAmB;EAwSpB,SAAA,IAAA,EAAA,MAAA;EA4GJ,SAAA,EAAA,EAAA,MAAA;EAcI,SAAA,WAAA,CAAA,EAAA,MAAqB;EACjB,SAAA,GAAA,CAAA,EAAA,MAAA;EAEV,SAAA,UAAA,EAAA,SAAA;IAAG,SAAA,EAAA,EAAA,MAAA;IAAV,SAAA,KAAA,EAAA,MAAA;IAAM,SAAA,cAAA,EAAA,MAAA;;;;;;;;iBA7HO,0BAAA,CAAA,GAA8B;KA4GlC,uBAAA;;;;;;;;;;;;;;;;iBAcI;;;;qBACI,sBAEjB,OAAO,GAAG"}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-C4VXKl8f.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { t as assertFrameworkComponentsCompatible } from "../framework-components-
|
|
2
|
+
import { a as errorContractValidationFailed, g as errorTargetMigrationNotSupported, h as errorRuntime, l as errorFileNotFound, p as errorMigrationPlanningFailed, t as CliStructuredError, v as errorUnexpected } from "../cli-errors-BUuJr6py.mjs";
|
|
3
|
+
import { t as assertFrameworkComponentsCompatible } from "../framework-components-Bsr1GaIj.mjs";
|
|
4
4
|
import { t as extractSqlDdl } from "../extract-sql-ddl-DDMX-9mz.mjs";
|
|
5
|
-
import { _ as formatStyledHeader, c as resolveMigrationPaths, d as setCommandExamples, i as loadAllBundles, m as parseGlobalFlags, n as addGlobalOptions, r as getTargetMigrations, s as resolveContractPath, t as handleResult, u as setCommandDescriptions } from "../result-handler-
|
|
5
|
+
import { _ as formatStyledHeader, c as resolveMigrationPaths, d as setCommandExamples, i as loadAllBundles, m as parseGlobalFlags, n as addGlobalOptions, r as getTargetMigrations, s as resolveContractPath, t as handleResult, u as setCommandDescriptions } from "../result-handler-AFK4hxyX.mjs";
|
|
6
6
|
import { t as TerminalUI } from "../terminal-ui-C5k88MmW.mjs";
|
|
7
|
+
import { t as emitMigration } from "../migration-emit-dRXV6QSz.mjs";
|
|
7
8
|
import { Command } from "commander";
|
|
8
9
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
9
10
|
import { join, relative } from "pathe";
|
|
10
11
|
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
11
12
|
import { readFile } from "node:fs/promises";
|
|
12
13
|
import { findLatestMigration } from "@prisma-next/migration-tools/dag";
|
|
13
|
-
import { formatMigrationDirName,
|
|
14
|
+
import { formatMigrationDirName, writeMigrationPackage } from "@prisma-next/migration-tools/io";
|
|
14
15
|
import { MigrationToolsError } from "@prisma-next/migration-tools/types";
|
|
15
|
-
import {
|
|
16
|
-
import { attestMigration } from "@prisma-next/migration-tools/attestation";
|
|
16
|
+
import { scaffoldMigrationTs } from "@prisma-next/migration-tools/migration-ts";
|
|
17
17
|
|
|
18
18
|
//#region src/commands/migration-plan.ts
|
|
19
19
|
function mapMigrationToolsError(error) {
|
|
@@ -91,7 +91,7 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
91
91
|
const existingDraft = drafts.find((d) => d.manifest.to === toStorageHash);
|
|
92
92
|
if (existingDraft) return notOk(errorRuntime("A draft migration to this contract already exists", {
|
|
93
93
|
why: `Draft migration at "${existingDraft.dirName}" already targets ${toStorageHash}`,
|
|
94
|
-
fix: `Run 'prisma-next migration
|
|
94
|
+
fix: `Run 'prisma-next migration emit --dir ${migrationsRelative}/${existingDraft.dirName}' to attest it, or delete it and re-plan.`
|
|
95
95
|
}));
|
|
96
96
|
if (options.from) {
|
|
97
97
|
const resolved = resolveBundleByPrefix(bundles, options.from);
|
|
@@ -170,31 +170,12 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
170
170
|
descriptors: descriptorResult.descriptors,
|
|
171
171
|
contractJsonPath: contractPathAbsolute
|
|
172
172
|
});
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
from: fromHash,
|
|
177
|
-
to: toStorageHash,
|
|
178
|
-
dir: relative(process.cwd(), packageDir),
|
|
179
|
-
operations: descriptorResult.descriptors.map((d) => ({
|
|
180
|
-
id: d.kind,
|
|
181
|
-
label: d.kind,
|
|
182
|
-
operationClass: "data"
|
|
183
|
-
})),
|
|
184
|
-
sql: [],
|
|
185
|
-
summary: `Planned ${descriptorResult.descriptors.length} operation(s) — data migration required. Edit migration.ts and run \`migration verify --dir ${relative(process.cwd(), packageDir)}\` to attest.`,
|
|
186
|
-
timings: { total: Date.now() - startTime }
|
|
187
|
-
});
|
|
188
|
-
const evaluatedDescriptors = await evaluateMigrationTs(packageDir);
|
|
189
|
-
if (!migrations.resolveDescriptors) throw errorTargetMigrationNotSupported({ why: `Target "${config.target.targetId}" does not implement resolveDescriptors; cannot finalize migration plan with migration.ts` });
|
|
190
|
-
const resolvedOps = migrations.resolveDescriptors(evaluatedDescriptors, {
|
|
191
|
-
fromContract,
|
|
192
|
-
toContract: toContractJson,
|
|
173
|
+
const { operations, migrationId } = await emitMigration(packageDir, {
|
|
174
|
+
targetId: config.target.targetId,
|
|
175
|
+
migrations,
|
|
193
176
|
frameworkComponents
|
|
194
177
|
});
|
|
195
|
-
|
|
196
|
-
const migrationId = await attestMigration(packageDir);
|
|
197
|
-
const sql = extractSqlDdl(resolvedOps);
|
|
178
|
+
const sql = extractSqlDdl(operations);
|
|
198
179
|
return ok({
|
|
199
180
|
ok: true,
|
|
200
181
|
noOp: false,
|
|
@@ -202,13 +183,13 @@ async function executeMigrationPlanCommand(options, flags, ui, startTime) {
|
|
|
202
183
|
to: toStorageHash,
|
|
203
184
|
migrationId,
|
|
204
185
|
dir: relative(process.cwd(), packageDir),
|
|
205
|
-
operations:
|
|
186
|
+
operations: operations.map((op) => ({
|
|
206
187
|
id: op.id,
|
|
207
188
|
label: op.label,
|
|
208
189
|
operationClass: op.operationClass
|
|
209
190
|
})),
|
|
210
191
|
sql,
|
|
211
|
-
summary: `Planned ${
|
|
192
|
+
summary: `Planned ${operations.length} operation(s)`,
|
|
212
193
|
timings: { total: Date.now() - startTime }
|
|
213
194
|
});
|
|
214
195
|
} catch (error) {
|