prisma-next 0.11.0-dev.6 → 0.11.0-dev.8
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/dist/cli-errors-Bw2GlweY.mjs +175 -0
- package/dist/cli-errors-Bw2GlweY.mjs.map +1 -0
- package/dist/cli.mjs +7 -7
- package/dist/{client-oXO2WCPD.mjs → client-UnIveZxZ.mjs} +4 -4
- package/dist/{client-oXO2WCPD.mjs.map → client-UnIveZxZ.mjs.map} +1 -1
- package/dist/{command-helpers-DtavI0wJ.mjs → command-helpers-CRfjbZRz.mjs} +2 -2
- package/dist/{command-helpers-DtavI0wJ.mjs.map → command-helpers-CRfjbZRz.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.d.mts.map +1 -1
- package/dist/commands/db-init.mjs +33 -6
- package/dist/commands/db-init.mjs.map +1 -1
- package/dist/commands/db-schema.mjs +3 -3
- package/dist/commands/db-sign.mjs +5 -5
- package/dist/commands/db-update.d.mts.map +1 -1
- package/dist/commands/db-update.mjs +36 -7
- package/dist/commands/db-update.mjs.map +1 -1
- package/dist/commands/db-verify.mjs +1 -1
- package/dist/commands/migrate.d.mts +5 -1
- package/dist/commands/migrate.d.mts.map +1 -1
- package/dist/commands/migrate.mjs +44 -8
- package/dist/commands/migrate.mjs.map +1 -1
- package/dist/commands/migration-check.mjs +2 -2
- package/dist/commands/migration-graph.mjs +3 -3
- package/dist/commands/migration-list.mjs +2 -2
- package/dist/commands/migration-log.mjs +3 -3
- package/dist/commands/migration-new.mjs +3 -3
- package/dist/commands/migration-plan.d.mts +1 -0
- package/dist/commands/migration-plan.d.mts.map +1 -1
- package/dist/commands/migration-plan.mjs +1 -1
- package/dist/commands/migration-show.d.mts +1 -1
- package/dist/commands/migration-show.mjs +6 -6
- package/dist/commands/migration-status.mjs +7 -7
- package/dist/commands/ref.d.mts +1 -1
- package/dist/commands/ref.d.mts.map +1 -1
- package/dist/commands/ref.mjs +34 -8
- package/dist/commands/ref.mjs.map +1 -1
- package/dist/{contract-emit-o-8VmdQX.mjs → contract-emit-C6rlsljO.mjs} +3 -3
- package/dist/{contract-emit-o-8VmdQX.mjs.map → contract-emit-C6rlsljO.mjs.map} +1 -1
- package/dist/{contract-emit-CmsklifJ.mjs → contract-emit-mqXmapxB.mjs} +4 -4
- package/dist/{contract-emit-CmsklifJ.mjs.map → contract-emit-mqXmapxB.mjs.map} +1 -1
- package/dist/{contract-infer-pKkiCt7C.mjs → contract-infer-C4jxc1aZ.mjs} +3 -3
- package/dist/{contract-infer-pKkiCt7C.mjs.map → contract-infer-C4jxc1aZ.mjs.map} +1 -1
- package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs → contract-space-aggregate-loader-CGakRlKM.mjs} +2 -2
- package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs.map → contract-space-aggregate-loader-CGakRlKM.mjs.map} +1 -1
- package/dist/{db-verify-AoIUriL4.mjs → db-verify-1d8tDoFN.mjs} +5 -5
- package/dist/{db-verify-AoIUriL4.mjs.map → db-verify-1d8tDoFN.mjs.map} +1 -1
- package/dist/exports/control-api.d.mts +1 -1
- package/dist/exports/control-api.mjs +2 -2
- package/dist/exports/index.mjs +1 -1
- package/dist/exports/init-output.mjs +1 -1
- package/dist/{framework-components-65gOHkHB.mjs → framework-components-Bexd0f4E.mjs} +2 -2
- package/dist/{framework-components-65gOHkHB.mjs.map → framework-components-Bexd0f4E.mjs.map} +1 -1
- package/dist/{graph-render-DJVv0_uf.mjs → graph-render-BE8vmJ_7.mjs} +1 -1
- package/dist/{graph-render-DJVv0_uf.mjs.map → graph-render-BE8vmJ_7.mjs.map} +1 -1
- package/dist/{init-Db5Itt5r.mjs → init-ByoeQphC.mjs} +4 -4
- package/dist/{init-Db5Itt5r.mjs.map → init-ByoeQphC.mjs.map} +1 -1
- package/dist/{inspect-live-schema-LeWvkZVz.mjs → inspect-live-schema-B1Q49RF0.mjs} +4 -4
- package/dist/{inspect-live-schema-LeWvkZVz.mjs.map → inspect-live-schema-B1Q49RF0.mjs.map} +1 -1
- package/dist/{migration-command-scaffold-BtkunvFQ.mjs → migration-command-scaffold-oY4P1Qto.mjs} +4 -4
- package/dist/{migration-command-scaffold-BtkunvFQ.mjs.map → migration-command-scaffold-oY4P1Qto.mjs.map} +1 -1
- package/dist/{migration-plan-C2jeH1J5.mjs → migration-plan-jdAHg_gK.mjs} +346 -87
- package/dist/migration-plan-jdAHg_gK.mjs.map +1 -0
- package/dist/{migrations-CwZMa1Ck.mjs → migrations-B7n518mT.mjs} +10 -1
- package/dist/migrations-B7n518mT.mjs.map +1 -0
- package/dist/{output-BlsrGMEF.mjs → output-CUIdfYo5.mjs} +1 -1
- package/dist/{output-BlsrGMEF.mjs.map → output-CUIdfYo5.mjs.map} +1 -1
- package/dist/ref-advancement-DRh5Nquq.mjs +50 -0
- package/dist/ref-advancement-DRh5Nquq.mjs.map +1 -0
- package/dist/{types-C9FfXb1l.d.mts → types-UWB2-rrw.d.mts} +5 -4
- package/dist/types-UWB2-rrw.d.mts.map +1 -0
- package/dist/{verify-Bom75OYI.mjs → verify-C5UvbrF1.mjs} +1 -1
- package/dist/{verify-Bom75OYI.mjs.map → verify-C5UvbrF1.mjs.map} +1 -1
- package/package.json +11 -11
- package/dist/cli-errors-Czmx92Zy.d.mts +0 -3
- package/dist/cli-errors-Djtz98Vm.mjs +0 -71
- package/dist/cli-errors-Djtz98Vm.mjs.map +0 -1
- package/dist/migration-plan-C2jeH1J5.mjs.map +0 -1
- package/dist/migrations-CwZMa1Ck.mjs.map +0 -1
- package/dist/types-C9FfXb1l.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db-update.mjs","names":[],"sources":["../../src/commands/db-update.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join } from 'pathe';\nimport { ContractValidationError } from '../control-api/errors';\nimport type { DbUpdateFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n ERROR_CODE_DESTRUCTIVE_CHANGES,\n errorContractValidationFailed,\n errorDestructiveChanges,\n errorMigrationPlanningFailed,\n errorRunnerFailed,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport type { MigrationCommandOptions } from '../utils/command-helpers';\nimport {\n loadMigrationPackages,\n resolveMigrationPaths,\n sanitizeErrorMessage,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n formatMigrationApplyOutput,\n formatMigrationJson,\n formatMigrationPlanOutput,\n type MigrationCommandResult,\n} from '../utils/formatters/migrations';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport {\n addMigrationCommandOptions,\n prepareMigrationContext,\n} from '../utils/migration-command-scaffold';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface DbUpdateOptions extends MigrationCommandOptions {\n readonly to?: string;\n}\n\n/**\n * Maps a DbUpdateFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapDbUpdateFailure(failure: DbUpdateFailure): CliStructuredError {\n if (failure.code === 'PLANNING_FAILED') {\n return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });\n }\n\n if (failure.code === 'RUNNER_FAILED') {\n const runnerCode =\n typeof failure.meta?.['runnerErrorCode'] === 'string'\n ? failure.meta['runnerErrorCode']\n : undefined;\n const fix =\n runnerCode === 'LEGACY_MARKER_SHAPE'\n ? 'Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `prisma-next db init` to recreate it with the current per-space schema.'\n : 'Inspect the reported conflict, reconcile schema drift if needed, then re-run `prisma-next db update`';\n return errorRunnerFailed(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix,\n ...ifDefined('meta', failure.meta),\n });\n }\n\n if (failure.code === 'DESTRUCTIVE_CHANGES') {\n return errorDestructiveChanges(failure.summary, {\n ...ifDefined('why', failure.why),\n fix: 'Re-run with `-y` to apply destructive changes, or use `--dry-run` to preview first',\n ...ifDefined('meta', failure.meta),\n });\n }\n\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled DbUpdateFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the db update command and returns a structured Result.\n */\nasync function executeDbUpdateCommand(\n options: DbUpdateOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationCommandResult, CliStructuredError>> {\n // Prepare shared migration context (config, contract, connection, client)\n const ctxResult = await prepareMigrationContext(options, flags, ui, {\n commandName: 'db update',\n description: 'Update your database schema to match your contract',\n url: 'https://pris.ly/db-update',\n });\n if (!ctxResult.ok) {\n return ctxResult;\n }\n const { client, config, dbConnection, onProgress, contractPathAbsolute } = ctxResult.value;\n let { contractJson } = ctxResult.value;\n const { migrationsDir, appMigrationsDir, refsDir } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n if (options.to) {\n try {\n const { bundles, graph } = await loadMigrationPackages(appMigrationsDir);\n const refs = await readRefs(refsDir);\n const refResult = parseContractRef(options.to, { graph, refs });\n if (!refResult.ok) {\n return notOk(mapRefResolutionError(refResult.failure));\n }\n const targetHash = refResult.value.hash;\n const matchingBundle = bundles.find((p) => p.metadata.to === targetHash);\n if (!matchingBundle) {\n return notOk(\n errorUnexpected(\n `No migration bundle found for --to \"${options.to}\" (resolved hash: ${targetHash})`,\n {\n why: `The ref resolved successfully but no on-disk migration package has an end-contract hash matching ${targetHash}.`,\n fix: 'Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.',\n },\n ),\n );\n }\n const endContractPath = join(matchingBundle.dirPath, 'end-contract.json');\n const raw = await readFile(endContractPath, 'utf-8');\n contractJson = JSON.parse(raw) as Record<string, unknown>;\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n throw error;\n }\n }\n\n try {\n await client.connect(dbConnection);\n\n const result = await client.dbUpdate({\n contract: contractJson,\n mode: options.dryRun ? 'plan' : 'apply',\n migrationsDir,\n ...(flags.yes ? { acceptDataLoss: true } : {}),\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapDbUpdateFailure(result.failure));\n }\n\n // Convert success result to CLI output format\n const dbUpdateResult: MigrationCommandResult = {\n ok: true,\n mode: result.value.mode,\n plan: {\n targetId: ctxResult.value.config.target.targetId,\n destination: {\n storageHash: result.value.destination.storageHash,\n ...ifDefined('profileHash', result.value.destination.profileHash),\n },\n operations: result.value.plan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n ...ifDefined('preview', result.value.plan.preview),\n },\n ...ifDefined(\n 'execution',\n result.value.execution\n ? {\n operationsPlanned: result.value.execution.operationsPlanned,\n operationsExecuted: result.value.execution.operationsExecuted,\n }\n : undefined,\n ),\n ...ifDefined(\n 'marker',\n result.value.marker\n ? {\n storageHash: result.value.marker.storageHash,\n ...ifDefined('profileHash', result.value.marker.profileHash),\n }\n : undefined,\n ),\n ...ifDefined('perSpace', result.value.perSpace),\n summary: result.value.summary,\n timings: { total: Date.now() - startTime },\n };\n\n return ok(dbUpdateResult);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n\n const rawMessage = error instanceof Error ? error.message : String(error);\n const safeMessage = sanitizeErrorMessage(\n rawMessage,\n typeof dbConnection === 'string' ? dbConnection : undefined,\n );\n return notOk(\n errorUnexpected(safeMessage, {\n why: `Unexpected error during db update: ${safeMessage}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbUpdateCommand(): Command {\n const command = new Command('update');\n setCommandDescriptions(\n command,\n 'Update your database schema to match your contract',\n 'Compares your database schema to the emitted contract and applies the necessary\\n' +\n 'changes. Works on any database, whether or not it has been initialized with `db init`.\\n' +\n 'Destructive operations prompt for confirmation in interactive mode. Use -y to\\n' +\n 'auto-accept or --dry-run to preview first.',\n );\n setCommandExamples(command, [\n 'prisma-next db update --db $DATABASE_URL',\n 'prisma-next db update --db $DATABASE_URL --dry-run',\n ]);\n addMigrationCommandOptions(command);\n command.option(\n '--to <contract>',\n 'Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)',\n );\n command.action(async (options: DbUpdateOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const startTime = Date.now();\n\n const ui = createTerminalUI(flags);\n\n let result = await executeDbUpdateCommand(options, flags, ui, startTime);\n\n // Interactive confirmation for destructive operations:\n // When the control API rejects destructive changes, prompt the user instead of failing.\n // In non-interactive mode (CI, piped, --no-interactive, --json), the error is returned as-is.\n if (\n !result.ok &&\n result.failure.code === ERROR_CODE_DESTRUCTIVE_CHANGES &&\n flags.interactive &&\n !flags.json &&\n !flags.yes\n ) {\n const meta = result.failure.meta as\n | { destructiveOperations?: readonly { id: string; label: string }[] }\n | undefined;\n const destructiveOps = meta?.destructiveOperations ?? [];\n\n if (destructiveOps.length > 0) {\n ui.warn(\n `${destructiveOps.length} destructive operation(s) that may cause data loss:\\n${destructiveOps.map((op) => ` ${ui.yellow('▸')} ${op.label}`).join('\\n')}`,\n );\n }\n\n const confirmed = await ui.confirm('Apply destructive changes? This cannot be undone.');\n\n if (confirmed) {\n result = await executeDbUpdateCommand(options, { ...flags, yes: true }, ui, Date.now());\n }\n }\n\n const exitCode = handleResult(result, flags, ui, (dbUpdateResult) => {\n if (flags.json) {\n ui.output(formatMigrationJson(dbUpdateResult));\n } else {\n const output =\n dbUpdateResult.mode === 'plan'\n ? formatMigrationPlanOutput(dbUpdateResult, flags)\n : formatMigrationApplyOutput(dbUpdateResult, flags);\n if (output) {\n ui.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkDA,SAAS,mBAAmB,SAA8C;CACxE,IAAI,QAAQ,SAAS,mBACnB,OAAO,6BAA6B,EAAE,WAAW,QAAQ,aAAa,EAAE,EAAE,CAAC;CAG7E,IAAI,QAAQ,SAAS,iBAAiB;EAKpC,MAAM,OAHJ,OAAO,QAAQ,OAAO,uBAAuB,WACzC,QAAQ,KAAK,qBACb,KAAA,OAEW,wBACX,iMACA;EACN,OAAO,kBAAkB,QAAQ,SAAS;GACxC,KAAK,QAAQ,OAAO;GACpB;GACA,GAAG,UAAU,QAAQ,QAAQ,KAAK;GACnC,CAAC;;CAGJ,IAAI,QAAQ,SAAS,uBACnB,OAAO,wBAAwB,QAAQ,SAAS;EAC9C,GAAG,UAAU,OAAO,QAAQ,IAAI;EAChC,KAAK;EACL,GAAG,UAAU,QAAQ,QAAQ,KAAK;EACnC,CAAC;CAGJ,MAAM,aAAoB,QAAQ;CAClC,MAAM,IAAI,MAAM,mCAAmC,aAAa;;;;;AAMlE,eAAe,uBACb,SACA,OACA,IACA,WAC6D;CAE7D,MAAM,YAAY,MAAM,wBAAwB,SAAS,OAAO,IAAI;EAClE,aAAa;EACb,aAAa;EACb,KAAK;EACN,CAAC;CACF,IAAI,CAAC,UAAU,IACb,OAAO;CAET,MAAM,EAAE,QAAQ,QAAQ,cAAc,YAAY,yBAAyB,UAAU;CACrF,IAAI,EAAE,iBAAiB,UAAU;CACjC,MAAM,EAAE,eAAe,kBAAkB,YAAY,sBACnD,QAAQ,QACR,OACD;CAED,IAAI,QAAQ,IACV,IAAI;EACF,MAAM,EAAE,SAAS,UAAU,MAAM,sBAAsB,iBAAiB;EACxE,MAAM,O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OAAO,QAAQ,SAAS,kCACxB,MAAM,eACN,CAAC,MAAM,QACP,CAAC,MAAM,KACP;GAIA,MAAM,iBAHO,OAAO,QAAQ,MAGC,yBAAyB,EAAE;GAExD,IAAI,eAAe,SAAS,GAC1B,GAAG,KACD,GAAG,eAAe,OAAO,uDAAuD,eAAe,KAAK,OAAO,KAAK,GAAG,OAAO,IAAI,CAAC,GAAG,GAAG,QAAQ,CAAC,KAAK,KAAK,GACzJ;GAKH,IAAI,MAFoB,GAAG,QAAQ,oDAAoD,EAGrF,SAAS,MAAM,uBAAuB,SAAS;IAAE,GAAG;IAAO,KAAK;IAAM,EAAE,IAAI,KAAK,KAAK,CAAC;;EAI3F,MAAM,WAAW,aAAa,QAAQ,OAAO,KAAK,mBAAmB;GACnE,IAAI,MAAM,MACR,GAAG,OAAO,oBAAoB,eAAe,CAAC;QACzC;IACL,MAAM,SACJ,eAAe,SAAS,SACpB,0BAA0B,gBAAgB,MAAM,GAChD,2BAA2B,gBAAgB,MAAM;IACvD,IAAI,QACF,GAAG,IAAI,OAAO;;IAGlB;EACF,QAAQ,KAAK,SAAS;GACtB;CAEF,OAAO"}
|
|
1
|
+
{"version":3,"file":"db-update.mjs","names":[],"sources":["../../src/commands/db-update.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join } from 'pathe';\nimport { ContractValidationError } from '../control-api/errors';\nimport type { DbUpdateFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n ERROR_CODE_DESTRUCTIVE_CHANGES,\n errorContractValidationFailed,\n errorDestructiveChanges,\n errorMigrationPlanningFailed,\n errorRunnerFailed,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport type { MigrationCommandOptions } from '../utils/command-helpers';\nimport {\n loadMigrationPackages,\n resolveMigrationPaths,\n sanitizeErrorMessage,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n formatMigrationApplyOutput,\n formatMigrationJson,\n formatMigrationPlanOutput,\n type MigrationCommandResult,\n} from '../utils/formatters/migrations';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport {\n addMigrationCommandOptions,\n prepareMigrationContext,\n} from '../utils/migration-command-scaffold';\nimport {\n buildRefAdvancementFields,\n computeRefAdvancementName,\n type RefAdvancementFields,\n readContractIR,\n} from '../utils/ref-advancement';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface DbUpdateOptions extends MigrationCommandOptions {\n readonly to?: string;\n readonly advanceRef?: string;\n}\n\n/**\n * Maps a DbUpdateFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapDbUpdateFailure(failure: DbUpdateFailure): CliStructuredError {\n if (failure.code === 'PLANNING_FAILED') {\n return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });\n }\n\n if (failure.code === 'RUNNER_FAILED') {\n const runnerCode =\n typeof failure.meta?.['runnerErrorCode'] === 'string'\n ? failure.meta['runnerErrorCode']\n : undefined;\n const fix =\n runnerCode === 'LEGACY_MARKER_SHAPE'\n ? 'Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `prisma-next db init` to recreate it with the current per-space schema.'\n : 'Inspect the reported conflict, reconcile schema drift if needed, then re-run `prisma-next db update`';\n return errorRunnerFailed(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix,\n ...ifDefined('meta', failure.meta),\n });\n }\n\n if (failure.code === 'DESTRUCTIVE_CHANGES') {\n return errorDestructiveChanges(failure.summary, {\n ...ifDefined('why', failure.why),\n fix: 'Re-run with `-y` to apply destructive changes, or use `--dry-run` to preview first',\n ...ifDefined('meta', failure.meta),\n });\n }\n\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled DbUpdateFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the db update command and returns a structured Result.\n */\nasync function executeDbUpdateCommand(\n options: DbUpdateOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationCommandResult, CliStructuredError>> {\n // Prepare shared migration context (config, contract, connection, client)\n const ctxResult = await prepareMigrationContext(options, flags, ui, {\n commandName: 'db update',\n description: 'Update your database schema to match your contract',\n url: 'https://pris.ly/db-update',\n });\n if (!ctxResult.ok) {\n return ctxResult;\n }\n const { client, config, dbConnection, onProgress, contractPathAbsolute } = ctxResult.value;\n let { contractJson } = ctxResult.value;\n let contractJsonPathForSnapshot = contractPathAbsolute;\n const { migrationsDir, appMigrationsDir, refsDir } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n if (options.to) {\n try {\n const { bundles, graph } = await loadMigrationPackages(appMigrationsDir);\n const refs = await readRefs(refsDir);\n const refResult = parseContractRef(options.to, { graph, refs });\n if (!refResult.ok) {\n return notOk(mapRefResolutionError(refResult.failure));\n }\n const targetHash = refResult.value.hash;\n const matchingBundle = bundles.find((p) => p.metadata.to === targetHash);\n if (!matchingBundle) {\n return notOk(\n errorUnexpected(\n `No migration bundle found for --to \"${options.to}\" (resolved hash: ${targetHash})`,\n {\n why: `The ref resolved successfully but no on-disk migration package has an end-contract hash matching ${targetHash}.`,\n fix: 'Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.',\n },\n ),\n );\n }\n const endContractPath = join(matchingBundle.dirPath, 'end-contract.json');\n const raw = await readFile(endContractPath, 'utf-8');\n contractJson = JSON.parse(raw) as Record<string, unknown>;\n contractJsonPathForSnapshot = endContractPath;\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n throw error;\n }\n }\n\n try {\n await client.connect(dbConnection);\n\n const result = await client.dbUpdate({\n contract: contractJson,\n mode: options.dryRun ? 'plan' : 'apply',\n migrationsDir,\n ...(flags.yes ? { acceptDataLoss: true } : {}),\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapDbUpdateFailure(result.failure));\n }\n\n const advancementHash =\n result.value.mode === 'apply'\n ? (result.value.marker?.storageHash ?? result.value.destination.storageHash)\n : result.value.destination.storageHash;\n\n let refAdvancementFields: RefAdvancementFields = {\n advancedRef: null,\n plannedAdvanceRef: null,\n };\n if (\n computeRefAdvancementName({\n ...ifDefined('advanceRef', options.advanceRef),\n ...ifDefined('db', options.db),\n }) !== null\n ) {\n try {\n const contractIR = await readContractIR(contractJson, contractJsonPathForSnapshot);\n refAdvancementFields = await buildRefAdvancementFields({\n ...ifDefined('advanceRef', options.advanceRef),\n ...ifDefined('db', options.db),\n refsDir,\n contractIR,\n mode: result.value.mode,\n hash: advancementHash,\n });\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n }\n\n // Convert success result to CLI output format\n const dbUpdateResult: MigrationCommandResult = {\n ok: true,\n mode: result.value.mode,\n plan: {\n targetId: ctxResult.value.config.target.targetId,\n destination: {\n storageHash: result.value.destination.storageHash,\n ...ifDefined('profileHash', result.value.destination.profileHash),\n },\n operations: result.value.plan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n ...ifDefined('preview', result.value.plan.preview),\n },\n ...ifDefined(\n 'execution',\n result.value.execution\n ? {\n operationsPlanned: result.value.execution.operationsPlanned,\n operationsExecuted: result.value.execution.operationsExecuted,\n }\n : undefined,\n ),\n ...ifDefined(\n 'marker',\n result.value.marker\n ? {\n storageHash: result.value.marker.storageHash,\n ...ifDefined('profileHash', result.value.marker.profileHash),\n }\n : undefined,\n ),\n ...ifDefined('perSpace', result.value.perSpace),\n advancedRef: refAdvancementFields.advancedRef,\n plannedAdvanceRef: refAdvancementFields.plannedAdvanceRef,\n summary: result.value.summary,\n timings: { total: Date.now() - startTime },\n };\n\n return ok(dbUpdateResult);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n\n const rawMessage = error instanceof Error ? error.message : String(error);\n const safeMessage = sanitizeErrorMessage(\n rawMessage,\n typeof dbConnection === 'string' ? dbConnection : undefined,\n );\n return notOk(\n errorUnexpected(safeMessage, {\n why: `Unexpected error during db update: ${safeMessage}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbUpdateCommand(): Command {\n const command = new Command('update');\n setCommandDescriptions(\n command,\n 'Update your database schema to match your contract',\n 'Compares your database schema to the emitted contract and applies the necessary\\n' +\n 'changes. Works on any database, whether or not it has been initialized with `db init`.\\n' +\n 'Destructive operations prompt for confirmation in interactive mode. Use -y to\\n' +\n 'auto-accept or --dry-run to preview first.',\n );\n setCommandExamples(command, [\n 'prisma-next db update --db $DATABASE_URL',\n 'prisma-next db update --db $DATABASE_URL --dry-run',\n ]);\n addMigrationCommandOptions(command);\n command.option(\n '--to <contract>',\n 'Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)',\n );\n command.option('--advance-ref <name>', 'Ref to advance to the post-command contract hash');\n command.action(async (options: DbUpdateOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const startTime = Date.now();\n\n const ui = createTerminalUI(flags);\n\n let result = await executeDbUpdateCommand(options, flags, ui, startTime);\n\n // Interactive confirmation for destructive operations:\n // When the control API rejects destructive changes, prompt the user instead of failing.\n // In non-interactive mode (CI, piped, --no-interactive, --json), the error is returned as-is.\n if (\n !result.ok &&\n result.failure.code === ERROR_CODE_DESTRUCTIVE_CHANGES &&\n flags.interactive &&\n !flags.json &&\n !flags.yes\n ) {\n const meta = result.failure.meta as\n | { destructiveOperations?: readonly { id: string; label: string }[] }\n | undefined;\n const destructiveOps = meta?.destructiveOperations ?? [];\n\n if (destructiveOps.length > 0) {\n ui.warn(\n `${destructiveOps.length} destructive operation(s) that may cause data loss:\\n${destructiveOps.map((op) => ` ${ui.yellow('▸')} ${op.label}`).join('\\n')}`,\n );\n }\n\n const confirmed = await ui.confirm('Apply destructive changes? This cannot be undone.');\n\n if (confirmed) {\n result = await executeDbUpdateCommand(options, { ...flags, yes: true }, ui, Date.now());\n }\n }\n\n const exitCode = handleResult(result, flags, ui, (dbUpdateResult) => {\n if (flags.json) {\n ui.output(formatMigrationJson(dbUpdateResult));\n } else {\n const output =\n dbUpdateResult.mode === 'plan'\n ? formatMigrationPlanOutput(dbUpdateResult, flags)\n : formatMigrationApplyOutput(dbUpdateResult, flags);\n if (output) {\n ui.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyDA,SAAS,mBAAmB,SAA8C;CACxE,IAAI,QAAQ,SAAS,mBACnB,OAAO,6BAA6B,EAAE,WAAW,QAAQ,aAAa,EAAE,EAAE,CAAC;CAG7E,IAAI,QAAQ,SAAS,iBAAiB;EAKpC,MAAM,OAHJ,OAAO,QAAQ,OAAO,uBAAuB,WACzC,QAAQ,KAAK,qBACb,KAAA,OAEW,wBACX,iMACA;EACN,OAAO,kBAAkB,QAAQ,SAAS;GACxC,KAAK,QAAQ,OAAO;GACpB;GACA,GAAG,UAAU,QAAQ,QAAQ,KAAK;GACnC,CAAC;;CAGJ,IAAI,QAAQ,SAAS,uBACnB,OAAO,wBAAwB,QAAQ,SAAS;EAC9C,GAAG,UAAU,OAAO,QAAQ,IAAI;EAChC,KAAK;EACL,GAAG,UAAU,QAAQ,QAAQ,KAAK;EACnC,CAAC;CAGJ,MAAM,aAAoB,QAAQ;CAClC,MAAM,IAAI,MAAM,mCAAmC,aAAa;;;;;AAMlE,eAAe,uBACb,SACA,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,MAGC,yBAAyB,EAAE;GAExD,IAAI,eAAe,SAAS,GAC1B,GAAG,KACD,GAAG,eAAe,OAAO,uDAAuD,eAAe,KAAK,OAAO,KAAK,GAAG,OAAO,IAAI,CAAC,GAAG,GAAG,QAAQ,CAAC,KAAK,KAAK,GACzJ;GAKH,IAAI,MAFoB,GAAG,QAAQ,oDAAoD,EAGrF,SAAS,MAAM,uBAAuB,SAAS;IAAE,GAAG;IAAO,KAAK;IAAM,EAAE,IAAI,KAAK,KAAK,CAAC;;EAI3F,MAAM,WAAW,aAAa,QAAQ,OAAO,KAAK,mBAAmB;GACnE,IAAI,MAAM,MACR,GAAG,OAAO,oBAAoB,eAAe,CAAC;QACzC;IACL,MAAM,SACJ,eAAe,SAAS,SACpB,0BAA0B,gBAAgB,MAAM,GAChD,2BAA2B,gBAAgB,MAAM;IACvD,IAAI,QACF,GAAG,IAAI,OAAO;;IAGlB;EACF,QAAQ,KAAK,SAAS;GACtB;CAEF,OAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createDbVerifyCommand } from "../db-verify-
|
|
1
|
+
import { t as createDbVerifyCommand } from "../db-verify-1d8tDoFN.mjs";
|
|
2
2
|
export { createDbVerifyCommand };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { T as MigrationApplyPathDecision, t as AggregatePerSpaceExecutionEntry } from "../types-
|
|
1
|
+
import { T as MigrationApplyPathDecision, t as AggregatePerSpaceExecutionEntry } from "../types-UWB2-rrw.mjs";
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
|
|
4
4
|
//#region src/commands/migrate.d.ts
|
|
@@ -21,6 +21,10 @@ interface MigrateResult {
|
|
|
21
21
|
readonly timings: {
|
|
22
22
|
readonly total: number;
|
|
23
23
|
};
|
|
24
|
+
readonly advancedRef?: {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
readonly hash: string;
|
|
27
|
+
} | null;
|
|
24
28
|
}
|
|
25
29
|
declare function createMigrateCommand(): Command;
|
|
26
30
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate.d.mts","names":[],"sources":["../../src/commands/migrate.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"migrate.d.mts","names":[],"sources":["../../src/commands/migrate.ts"],"mappings":";;;;UA4DiB,aAAA;EAAA,SACN,EAAA;EAAA,SACA,iBAAA;EAAA,SACA,eAAA;EAAA,SACA,UAAA;EAAA,SACA,OAAA;IAAA,SACE,OAAA;IAAA,SACA,OAAA;IAAA,SACA,aAAA;IAAA,SACA,IAAA;IAAA,SACA,EAAA;IAAA,SACA,kBAAA;EAAA;EAAA,SAEF,OAAA;EAAA,SACA,QAAA,WAAmB,+BAAA;EAAA,SACnB,YAAA,GAAe,0BAAA;EAAA,SACf,OAAA;IAAA,SACE,KAAA;EAAA;EAAA,SAEF,WAAA;IAAA,SAAyB,IAAA;IAAA,SAAuB,IAAA;EAAA;AAAA;AAAA,iBAgS3C,oBAAA,CAAA,GAAwB,OAAA"}
|
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected, O as mapRefResolutionError, S as errorRuntime, a as errorContractValidationFailed, c as errorDriverRequired, f as errorMarkerMismatch, g as errorPathUnreachable, l as errorFileNotFound, o as errorDatabaseConnectionRequired, t as CliStructuredError, w as errorTargetMigrationNotSupported } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
3
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
-
import { S as formatStyledHeader, a as loadMigrationPackages, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, m as targetSupportsMigrations, n as collectDeclaredInvariants, o as maskConnectionUrl, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
5
|
-
import { t as createControlClient } from "../client-
|
|
6
|
-
import { t as formatMigrationApplyCommandOutput } from "../migrations-
|
|
4
|
+
import { S as formatStyledHeader, a as loadMigrationPackages, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, m as targetSupportsMigrations, n as collectDeclaredInvariants, o as maskConnectionUrl, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
5
|
+
import { t as createControlClient } from "../client-UnIveZxZ.mjs";
|
|
6
|
+
import { t as formatMigrationApplyCommandOutput } from "../migrations-B7n518mT.mjs";
|
|
7
|
+
import { i as readContractIR, r as executeRefAdvancement } from "../ref-advancement-DRh5Nquq.mjs";
|
|
7
8
|
import { Command } from "commander";
|
|
8
9
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
9
10
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
11
|
+
import { join } from "pathe";
|
|
10
12
|
import { readFile } from "node:fs/promises";
|
|
11
13
|
import { createControlStack } from "@prisma-next/framework-components/control";
|
|
14
|
+
import { findLatestMigration, isGraphNode } from "@prisma-next/migration-tools/migration-graph";
|
|
12
15
|
import { MigrationToolsError, errorUnknownInvariant } from "@prisma-next/migration-tools/errors";
|
|
13
|
-
import { parseContractRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
14
16
|
import { readRefs } from "@prisma-next/migration-tools/refs";
|
|
17
|
+
import { parseContractRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
15
18
|
//#region src/commands/migrate.ts
|
|
16
19
|
function mapApplyFailure(failure) {
|
|
20
|
+
if (failure.code === "MIGRATION_PATH_NOT_FOUND") return errorPathUnreachable(failure);
|
|
17
21
|
return errorRuntime(failure.summary, {
|
|
18
22
|
why: failure.why ?? "Migration runner failed",
|
|
19
23
|
fix: "Fix the issue and re-run `prisma-next migrate --to <contract>` — previously applied migrations are preserved.",
|
|
@@ -111,8 +115,10 @@ async function executeMigrateCommand(options, flags, ui, startTime) {
|
|
|
111
115
|
});
|
|
112
116
|
try {
|
|
113
117
|
await client.connect(dbConnection);
|
|
118
|
+
const appMarker = (await client.readAllMarkers()).get("app") ?? null;
|
|
119
|
+
const { graph } = appPackages;
|
|
120
|
+
if (appMarker !== null && !isGraphNode(appMarker.storageHash, graph)) return notOk(errorMarkerMismatch(appMarker.storageHash, [...graph.nodes].sort(), findLatestMigration(graph)?.to ?? null));
|
|
114
121
|
if (refEntry && refEntry.invariants.length > 0) {
|
|
115
|
-
const appMarker = (await client.readAllMarkers()).get("app") ?? null;
|
|
116
122
|
const declared = collectDeclaredInvariants(appPackages.graph);
|
|
117
123
|
const known = new Set(declared);
|
|
118
124
|
for (const id of appMarker?.invariants ?? []) known.add(id);
|
|
@@ -134,6 +140,35 @@ async function executeMigrateCommand(options, flags, ui, startTime) {
|
|
|
134
140
|
});
|
|
135
141
|
if (!applyResult.ok) return notOk(mapApplyFailure(applyResult.failure));
|
|
136
142
|
const { value } = applyResult;
|
|
143
|
+
let advancedRef = null;
|
|
144
|
+
if (options.advanceRef !== void 0) {
|
|
145
|
+
let contractJsonPathForSnapshot = contractPathAbsolute;
|
|
146
|
+
let contractJsonForSnapshot = JSON.parse(contractContent);
|
|
147
|
+
if (toArg && refEntry) {
|
|
148
|
+
const matchingBundle = appPackages.bundles.find((p) => p.metadata.to === refEntry.hash);
|
|
149
|
+
if (matchingBundle) {
|
|
150
|
+
const endContractPath = join(matchingBundle.dirPath, "end-contract.json");
|
|
151
|
+
contractJsonPathForSnapshot = endContractPath;
|
|
152
|
+
try {
|
|
153
|
+
const raw = await readFile(endContractPath, "utf-8");
|
|
154
|
+
contractJsonForSnapshot = JSON.parse(raw);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if (error instanceof Error && error.code === "ENOENT") return notOk(errorFileNotFound(endContractPath, {
|
|
157
|
+
why: `Bundle end-contract not found at ${endContractPath}`,
|
|
158
|
+
fix: "Re-emit the migration bundle or pick a different --to target."
|
|
159
|
+
}));
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
const contractIR = await readContractIR(contractJsonForSnapshot, contractJsonPathForSnapshot);
|
|
166
|
+
advancedRef = await executeRefAdvancement(refsDir, options.advanceRef, value.markerHash, contractIR);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
137
172
|
return ok({
|
|
138
173
|
ok: true,
|
|
139
174
|
migrationsApplied: value.migrationsApplied,
|
|
@@ -143,7 +178,8 @@ async function executeMigrateCommand(options, flags, ui, startTime) {
|
|
|
143
178
|
summary: value.summary,
|
|
144
179
|
perSpace: value.perSpace,
|
|
145
180
|
...ifDefined("pathDecision", value.pathDecision),
|
|
146
|
-
timings: { total: Date.now() - startTime }
|
|
181
|
+
timings: { total: Date.now() - startTime },
|
|
182
|
+
advancedRef
|
|
147
183
|
});
|
|
148
184
|
} catch (error) {
|
|
149
185
|
if (CliStructuredError.is(error)) return notOk(error);
|
|
@@ -161,7 +197,7 @@ function createMigrateCommand() {
|
|
|
161
197
|
"prisma-next migrate --to production --db $DATABASE_URL",
|
|
162
198
|
"prisma-next migrate --to sha256:abc123 --db $DATABASE_URL"
|
|
163
199
|
]);
|
|
164
|
-
addGlobalOptions(command).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--to <contract>", "Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)").action(async (options) => {
|
|
200
|
+
addGlobalOptions(command).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--to <contract>", "Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)").option("--advance-ref <name>", "Advance the named ref to the post-apply marker after success").action(async (options) => {
|
|
165
201
|
const flags = parseGlobalFlagsOrExit(options);
|
|
166
202
|
const startTime = Date.now();
|
|
167
203
|
const ui = createTerminalUI(flags);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate.mjs","names":[],"sources":["../../src/commands/migrate.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { errorUnknownInvariant, MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';\nimport type { RefEntry } from '@prisma-next/migration-tools/refs';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { ifDefined } from '@prisma-next/utils/defined';\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 {\n AggregatePerSpaceExecutionEntry,\n MigrationApplyFailure,\n MigrationApplyPathDecision,\n} from '../control-api/types';\nimport {\n CliStructuredError,\n type CliStructuredError as CliStructuredErrorType,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n collectDeclaredInvariants,\n loadMigrationPackages,\n maskConnectionUrl,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n targetSupportsMigrations,\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, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrateCommandOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly to?: string;\n}\n\nexport interface MigrateResult {\n readonly ok: boolean;\n readonly migrationsApplied: number;\n readonly migrationsTotal: number;\n readonly markerHash: string;\n readonly applied: readonly {\n readonly spaceId: string;\n readonly dirName: string;\n readonly migrationHash: string;\n readonly from: string;\n readonly to: string;\n readonly operationsExecuted: number;\n }[];\n readonly summary: string;\n readonly perSpace: readonly AggregatePerSpaceExecutionEntry[];\n readonly pathDecision?: MigrationApplyPathDecision;\n readonly timings: {\n readonly total: number;\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 migrate --to <contract>` — previously applied migrations are preserved.',\n meta: failure.meta ?? {},\n });\n}\n\nasync function executeMigrateCommand(\n options: MigrateCommandOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrateResult, CliStructuredErrorType>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative, refsDir } =\n resolveMigrationPaths(options.config, config);\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for migrate (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: 'migrate',\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: 'Config.driver is required for migrate',\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 refEntry: RefEntry | undefined;\n const toArg = options.to;\n\n if (toArg) {\n try {\n const refs = await readRefs(refsDir);\n const { graph } = await loadMigrationPackages(appMigrationsDir);\n const refResult = parseContractRef(toArg, { graph, refs });\n if (!refResult.ok) {\n return notOk(mapRefResolutionError(refResult.failure));\n }\n if (refResult.value.provenance.kind === 'ref') {\n const resolved = refs[refResult.value.provenance.refName];\n if (resolved) refEntry = resolved;\n } else {\n refEntry = { hash: refResult.value.hash, invariants: [] };\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n }\n\n // Construct the family instance up-front so the on-disk contract read\n // crosses the serializer seam (`familyInstance.deserializeContract`) at\n // the read site. The downstream `client.migrationApply({ contract })`\n // re-validates internally (no harm — validation is idempotent), but\n // closing the gap at the read site is what makes the cast-pattern\n // lint enforceable and matches the other CLI commands. See TML-2536.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n\n const contractPathAbsolute = resolveContractPath(config);\n let contractRaw: Contract;\n let contractContent: string;\n try {\n contractContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: 'Run `prisma-next contract emit` to generate a valid contract.json, then retry.',\n }),\n );\n }\n return notOk(\n errorContractValidationFailed(\n `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n try {\n contractRaw = familyInstance.deserializeContract(JSON.parse(contractContent) as unknown);\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract at ${contractPathAbsolute} failed to deserialize: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\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: appMigrationsRelative },\n ];\n if (typeof dbConnection === 'string') {\n details.push({\n label: 'database',\n value: maskConnectionUrl(dbConnection),\n });\n }\n if (toArg) {\n details.push({ label: 'to', value: toArg });\n }\n const header = formatStyledHeader({\n command: 'migrate',\n description: 'Apply planned migrations to advance the database',\n url: 'https://pris.ly/migrate',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n let appPackages: Awaited<ReturnType<typeof loadMigrationPackages>>;\n try {\n appPackages = await loadMigrationPackages(appMigrationsDir);\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\n if (refEntry && refEntry.invariants.length > 0) {\n const allMarkers = await client.readAllMarkers();\n const appMarker = allMarkers.get('app') ?? null;\n const declared = collectDeclaredInvariants(appPackages.graph);\n const known = new Set<string>(declared);\n for (const id of appMarker?.invariants ?? []) known.add(id);\n const unknown = refEntry.invariants.filter((id) => !known.has(id));\n if (unknown.length > 0) {\n return notOk(\n mapMigrationToolsError(\n errorUnknownInvariant({\n ...ifDefined('refName', toArg),\n unknown,\n declared: [...declared].sort(),\n }),\n ),\n );\n }\n }\n\n if (!flags.quiet && !flags.json) {\n ui.step('Loading contract spaces…');\n }\n\n const applyResult = await client.migrationApply({\n contract: contractRaw,\n migrationsDir,\n appMigrationPackages: appPackages.bundles,\n ...ifDefined('refHash', refEntry?.hash),\n ...(refEntry?.invariants ? { refInvariants: refEntry.invariants } : {}),\n ...(refEntry !== undefined ? ifDefined('refName', toArg) : {}),\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: value.perSpace.length,\n markerHash: value.markerHash,\n applied: value.applied,\n summary: value.summary,\n perSpace: value.perSpace,\n ...ifDefined('pathDecision', value.pathDecision),\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migrate: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createMigrateCommand(): Command {\n const command = new Command('migrate');\n setCommandDescriptions(\n command,\n 'Apply planned migrations to advance the database',\n 'Walks every contract space (app + extensions) and applies pending\\n' +\n 'on-disk migrations in canonical order (extensions alphabetically,\\n' +\n 'then app). Graph-walks the on-disk migration graph for every space.\\n' +\n 'Use --to to target a specific contract (hash, ref name, migration dir).',\n );\n setCommandExamples(command, [\n 'prisma-next migrate --db $DATABASE_URL',\n 'prisma-next migrate --to production --db $DATABASE_URL',\n 'prisma-next migrate --to sha256:abc123 --db $DATABASE_URL',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option(\n '--to <contract>',\n 'Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)',\n )\n .action(async (options: MigrateCommandOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const startTime = Date.now();\n\n const ui = createTerminalUI(flags);\n\n const result = await executeMigrateCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (migrateResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(migrateResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationApplyCommandOutput(migrateResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4EA,SAAS,gBAAgB,SAAwD;CAC/E,OAAO,aAAa,QAAQ,SAAS;EACnC,KAAK,QAAQ,OAAO;EACpB,KAAK;EACL,MAAM,QAAQ,QAAQ,EAAE;EACzB,CAAC;;AAGJ,eAAe,sBACb,SACA,OACA,IACA,WACwD;CACxD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,EAAE,YAAY,eAAe,kBAAkB,uBAAuB,YAC1E,sBAAsB,QAAQ,QAAQ,OAAO;CAE/C,MAAM,eAAe,QAAQ,MAAM,OAAO,IAAI;CAC9C,IAAI,CAAC,cACH,OAAO,MACL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SAAgB,uBAAgC;CAC9C,MAAM,UAAU,IAAI,QAAQ,UAAU;CACtC,uBACE,SACA,oDACA,qRAID;CACD,mBAAmB,SAAS;EAC1B;EACA;EACA;EACD,CAAC;CACF,iBAAiB,QAAQ,CACtB,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OACC,mBACA,4FACD,CACA,OAAO,OAAO,YAAmC;EAChD,MAAM,QAAQ,uBAAuB,QAAQ;EAC7C,MAAM,YAAY,KAAK,KAAK;EAE5B,MAAM,KAAK,iBAAiB,MAAM;EAIlC,MAAM,WAAW,aAAa,MAFT,sBAAsB,SAAS,OAAO,IAAI,UAAU,EAEnC,OAAO,KAAK,kBAAkB;GAClE,IAAI,MAAM,MACR,GAAG,OAAO,KAAK,UAAU,eAAe,MAAM,EAAE,CAAC;QAC5C,IAAI,CAAC,MAAM,OAChB,GAAG,IAAI,kCAAkC,eAAe,MAAM,CAAC;IAEjE;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEJ,OAAO"}
|
|
1
|
+
{"version":3,"file":"migrate.mjs","names":[],"sources":["../../src/commands/migrate.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { errorUnknownInvariant, MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { findLatestMigration, isGraphNode } from '@prisma-next/migration-tools/migration-graph';\nimport { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';\nimport type { RefEntry } from '@prisma-next/migration-tools/refs';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type {\n AggregatePerSpaceExecutionEntry,\n MigrationApplyFailure,\n MigrationApplyPathDecision,\n} from '../control-api/types';\nimport {\n CliStructuredError,\n type CliStructuredError as CliStructuredErrorType,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorMarkerMismatch,\n errorPathUnreachable,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n collectDeclaredInvariants,\n loadMigrationPackages,\n maskConnectionUrl,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n targetSupportsMigrations,\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, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { executeRefAdvancement, readContractIR } from '../utils/ref-advancement';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrateCommandOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly to?: string;\n readonly advanceRef?: string;\n}\n\nexport interface MigrateResult {\n readonly ok: boolean;\n readonly migrationsApplied: number;\n readonly migrationsTotal: number;\n readonly markerHash: string;\n readonly applied: readonly {\n readonly spaceId: string;\n readonly dirName: string;\n readonly migrationHash: string;\n readonly from: string;\n readonly to: string;\n readonly operationsExecuted: number;\n }[];\n readonly summary: string;\n readonly perSpace: readonly AggregatePerSpaceExecutionEntry[];\n readonly pathDecision?: MigrationApplyPathDecision;\n readonly timings: {\n readonly total: number;\n };\n readonly advancedRef?: { readonly name: string; readonly hash: string } | null;\n}\n\nfunction mapApplyFailure(failure: MigrationApplyFailure): CliStructuredErrorType {\n if (failure.code === 'MIGRATION_PATH_NOT_FOUND') {\n return errorPathUnreachable(failure);\n }\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the issue and re-run `prisma-next migrate --to <contract>` — previously applied migrations are preserved.',\n meta: failure.meta ?? {},\n });\n}\n\nasync function executeMigrateCommand(\n options: MigrateCommandOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrateResult, CliStructuredErrorType>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative, refsDir } =\n resolveMigrationPaths(options.config, config);\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for migrate (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: 'migrate',\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: 'Config.driver is required for migrate',\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 refEntry: RefEntry | undefined;\n const toArg = options.to;\n\n if (toArg) {\n try {\n const refs = await readRefs(refsDir);\n const { graph } = await loadMigrationPackages(appMigrationsDir);\n const refResult = parseContractRef(toArg, { graph, refs });\n if (!refResult.ok) {\n return notOk(mapRefResolutionError(refResult.failure));\n }\n if (refResult.value.provenance.kind === 'ref') {\n const resolved = refs[refResult.value.provenance.refName];\n if (resolved) refEntry = resolved;\n } else {\n refEntry = { hash: refResult.value.hash, invariants: [] };\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n }\n\n // Construct the family instance up-front so the on-disk contract read\n // crosses the serializer seam (`familyInstance.deserializeContract`) at\n // the read site. The downstream `client.migrationApply({ contract })`\n // re-validates internally (no harm — validation is idempotent), but\n // closing the gap at the read site is what makes the cast-pattern\n // lint enforceable and matches the other CLI commands. See TML-2536.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n\n const contractPathAbsolute = resolveContractPath(config);\n let contractRaw: Contract;\n let contractContent: string;\n try {\n contractContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: 'Run `prisma-next contract emit` to generate a valid contract.json, then retry.',\n }),\n );\n }\n return notOk(\n errorContractValidationFailed(\n `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n try {\n contractRaw = familyInstance.deserializeContract(JSON.parse(contractContent) as unknown);\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract at ${contractPathAbsolute} failed to deserialize: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\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: appMigrationsRelative },\n ];\n if (typeof dbConnection === 'string') {\n details.push({\n label: 'database',\n value: maskConnectionUrl(dbConnection),\n });\n }\n if (toArg) {\n details.push({ label: 'to', value: toArg });\n }\n const header = formatStyledHeader({\n command: 'migrate',\n description: 'Apply planned migrations to advance the database',\n url: 'https://pris.ly/migrate',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n let appPackages: Awaited<ReturnType<typeof loadMigrationPackages>>;\n try {\n appPackages = await loadMigrationPackages(appMigrationsDir);\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\n const allMarkers = await client.readAllMarkers();\n const appMarker = allMarkers.get('app') ?? null;\n const { graph } = appPackages;\n\n if (appMarker !== null && !isGraphNode(appMarker.storageHash, graph)) {\n return notOk(\n errorMarkerMismatch(\n appMarker.storageHash,\n [...graph.nodes].sort(),\n findLatestMigration(graph)?.to ?? null,\n ),\n );\n }\n\n if (refEntry && refEntry.invariants.length > 0) {\n const declared = collectDeclaredInvariants(appPackages.graph);\n const known = new Set<string>(declared);\n for (const id of appMarker?.invariants ?? []) known.add(id);\n const unknown = refEntry.invariants.filter((id) => !known.has(id));\n if (unknown.length > 0) {\n return notOk(\n mapMigrationToolsError(\n errorUnknownInvariant({\n ...ifDefined('refName', toArg),\n unknown,\n declared: [...declared].sort(),\n }),\n ),\n );\n }\n }\n\n if (!flags.quiet && !flags.json) {\n ui.step('Loading contract spaces…');\n }\n\n const applyResult = await client.migrationApply({\n contract: contractRaw,\n migrationsDir,\n appMigrationPackages: appPackages.bundles,\n ...ifDefined('refHash', refEntry?.hash),\n ...(refEntry?.invariants ? { refInvariants: refEntry.invariants } : {}),\n ...(refEntry !== undefined ? ifDefined('refName', toArg) : {}),\n });\n\n if (!applyResult.ok) {\n return notOk(mapApplyFailure(applyResult.failure));\n }\n\n const { value } = applyResult;\n\n let advancedRef: { name: string; hash: string } | null = null;\n if (options.advanceRef !== undefined) {\n let contractJsonPathForSnapshot = contractPathAbsolute;\n let contractJsonForSnapshot: Record<string, unknown> = JSON.parse(contractContent) as Record<\n string,\n unknown\n >;\n if (toArg && refEntry) {\n const matchingBundle = appPackages.bundles.find((p) => p.metadata.to === refEntry.hash);\n if (matchingBundle) {\n const endContractPath = join(matchingBundle.dirPath, 'end-contract.json');\n contractJsonPathForSnapshot = endContractPath;\n try {\n const raw = await readFile(endContractPath, 'utf-8');\n contractJsonForSnapshot = JSON.parse(raw) as Record<string, unknown>;\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(endContractPath, {\n why: `Bundle end-contract not found at ${endContractPath}`,\n fix: 'Re-emit the migration bundle or pick a different --to target.',\n }),\n );\n }\n throw error;\n }\n }\n }\n try {\n const contractIR = await readContractIR(\n contractJsonForSnapshot,\n contractJsonPathForSnapshot,\n );\n advancedRef = await executeRefAdvancement(\n refsDir,\n options.advanceRef,\n value.markerHash,\n contractIR,\n );\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n }\n\n return ok({\n ok: true,\n migrationsApplied: value.migrationsApplied,\n migrationsTotal: value.perSpace.length,\n markerHash: value.markerHash,\n applied: value.applied,\n summary: value.summary,\n perSpace: value.perSpace,\n ...ifDefined('pathDecision', value.pathDecision),\n timings: { total: Date.now() - startTime },\n advancedRef,\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during migrate: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createMigrateCommand(): Command {\n const command = new Command('migrate');\n setCommandDescriptions(\n command,\n 'Apply planned migrations to advance the database',\n 'Walks every contract space (app + extensions) and applies pending\\n' +\n 'on-disk migrations in canonical order (extensions alphabetically,\\n' +\n 'then app). Graph-walks the on-disk migration graph for every space.\\n' +\n 'Use --to to target a specific contract (hash, ref name, migration dir).',\n );\n setCommandExamples(command, [\n 'prisma-next migrate --db $DATABASE_URL',\n 'prisma-next migrate --to production --db $DATABASE_URL',\n 'prisma-next migrate --to sha256:abc123 --db $DATABASE_URL',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option(\n '--to <contract>',\n 'Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)',\n )\n .option('--advance-ref <name>', 'Advance the named ref to the post-apply marker after success')\n .action(async (options: MigrateCommandOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const startTime = Date.now();\n\n const ui = createTerminalUI(flags);\n\n const result = await executeMigrateCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (migrateResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(migrateResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationApplyCommandOutput(migrateResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkFA,SAAS,gBAAgB,SAAwD;CAC/E,IAAI,QAAQ,SAAS,4BACnB,OAAO,qBAAqB,QAAQ;CAEtC,OAAO,aAAa,QAAQ,SAAS;EACnC,KAAK,QAAQ,OAAO;EACpB,KAAK;EACL,MAAM,QAAQ,QAAQ,EAAE;EACzB,CAAC;;AAGJ,eAAe,sBACb,SACA,OACA,IACA,WACwD;CACxD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,EAAE,YAAY,eAAe,kBAAkB,uBAAuB,YAC1E,sBAAsB,QAAQ,QAAQ,OAAO;CAE/C,MAAM,eAAe,QAAQ,MAAM,OAAO,IAAI;CAC9C,IAAI,CAAC,cACH,OAAO,MACL,gCAAgC;EAC9B,KAAK,qEAAqE,WAAW;EACrF,aAAa;EACd,CAAC,CACH;CAGH,IAAI,CAAC,OAAO,QACV,OAAO,MACL,oBAAoB,EAClB,KAAK,yCACN,CAAC,CACH;CAGH,IAAI,CAAC,yBAAyB,OAAO,OAAO,EAC1C,OAAO,MACL,iCAAiC,EAC/B,KAAK,WAAW,OAAO,OAAO,GAAG,gCAClC,CAAC,CACH;CAGH,IAAI;CACJ,MAAM,QAAQ,QAAQ;CAEtB,IAAI,OACF,IAAI;EACF,MAAM,OAAO,MAAM,SAAS,QAAQ;EACpC,MAAM,EAAE,UAAU,MAAM,sBAAsB,iBAAiB;EAC/D,MAAM,YAAY,iBAAiB,OAAO;GAAE;GAAO;GAAM,CAAC;EAC1D,IAAI,CAAC,UAAU,IACb,OAAO,MAAM,sBAAsB,UAAU,QAAQ,CAAC;EAExD,IAAI,UAAU,MAAM,WAAW,SAAS,OAA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O,KAAK,KAAK,GAAG,WAAW;GAC1C;GACD,CAAC;UACK,OAAO;EACd,IAAI,mBAAmB,GAAG,MAAM,EAC9B,OAAO,MAAM,MAAM;EAErB,IAAI,oBAAoB,GAAG,MAAM,EAC/B,OAAO,MAAM,uBAAuB,MAAM,CAAC;EAE7C,OAAO,MACL,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAAE,EACtE,KAAK,oCAAoC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAChG,CAAC,CACH;WACO;EACR,MAAM,OAAO,OAAO;;;AAIxB,SAAgB,uBAAgC;CAC9C,MAAM,UAAU,IAAI,QAAQ,UAAU;CACtC,uBACE,SACA,oDACA,qRAID;CACD,mBAAmB,SAAS;EAC1B;EACA;EACA;EACD,CAAC;CACF,iBAAiB,QAAQ,CACtB,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OACC,mBACA,4FACD,CACA,OAAO,wBAAwB,+DAA+D,CAC9F,OAAO,OAAO,YAAmC;EAChD,MAAM,QAAQ,uBAAuB,QAAQ;EAC7C,MAAM,YAAY,KAAK,KAAK;EAE5B,MAAM,KAAK,iBAAiB,MAAM;EAIlC,MAAM,WAAW,aAAa,MAFT,sBAAsB,SAAS,OAAO,IAAI,UAAU,EAEnC,OAAO,KAAK,kBAAkB;GAClE,IAAI,MAAM,MACR,GAAG,OAAO,KAAK,UAAU,eAAe,MAAM,EAAE,CAAC;QAC5C,IAAI,CAAC,MAAM,OAChB,GAAG,IAAI,kCAAkC,eAAe,MAAM,CAAC;IAEjE;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEJ,OAAO"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
2
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
3
|
-
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit } from "../command-helpers-
|
|
3
|
+
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit } from "../command-helpers-CRfjbZRz.mjs";
|
|
4
4
|
import { Command } from "commander";
|
|
5
5
|
import { join, relative } from "pathe";
|
|
6
6
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
7
7
|
import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
|
|
8
|
-
import { parseMigrationRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
9
8
|
import { readRefs } from "@prisma-next/migration-tools/refs";
|
|
9
|
+
import { parseMigrationRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
10
10
|
import { verifyMigrationHash } from "@prisma-next/migration-tools/hash";
|
|
11
11
|
//#region src/commands/migration-check.ts
|
|
12
12
|
/**
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
3
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
-
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, s as readContractEnvelope, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
5
|
-
import { i as migrationGraphToRenderInput, n as graphRenderer } from "../graph-render-
|
|
4
|
+
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, s as readContractEnvelope, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
5
|
+
import { i as migrationGraphToRenderInput, n as graphRenderer } from "../graph-render-BE8vmJ_7.mjs";
|
|
6
6
|
import { Command } from "commander";
|
|
7
7
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
8
8
|
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
3
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
-
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
4
|
+
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
7
7
|
import { findPath } from "@prisma-next/migration-tools/migration-graph";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected, c as errorDriverRequired, o as errorDatabaseConnectionRequired, t as CliStructuredError } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
3
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
-
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, m as targetSupportsMigrations, o as maskConnectionUrl, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
5
|
-
import { t as createControlClient } from "../client-
|
|
4
|
+
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, m as targetSupportsMigrations, o as maskConnectionUrl, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
5
|
+
import { t as createControlClient } from "../client-UnIveZxZ.mjs";
|
|
6
6
|
import { Command } from "commander";
|
|
7
7
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
8
8
|
import { findPath } from "@prisma-next/migration-tools/migration-graph";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { t as assertFrameworkComponentsCompatible } from "../framework-components-
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected, S as errorRuntime, l as errorFileNotFound, t as CliStructuredError, w as errorTargetMigrationNotSupported } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
|
+
import { t as assertFrameworkComponentsCompatible } from "../framework-components-Bexd0f4E.mjs";
|
|
4
4
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
5
|
-
import { S as formatStyledHeader, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, i as getTargetMigrations, l as resolveMigrationPaths, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
5
|
+
import { S as formatStyledHeader, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, i as getTargetMigrations, l as resolveMigrationPaths, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
6
6
|
import { Command } from "commander";
|
|
7
7
|
import { getEmittedArtifactPaths } from "@prisma-next/emitter";
|
|
8
8
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -10,6 +10,7 @@ interface MigrationPlanResult {
|
|
|
10
10
|
readonly from: string | null;
|
|
11
11
|
readonly to: string;
|
|
12
12
|
readonly dir?: string;
|
|
13
|
+
readonly baselineDir?: string;
|
|
13
14
|
/**
|
|
14
15
|
* Extension-space migration packages materialised onto disk during this
|
|
15
16
|
* `plan` run. Each entry names a `migrations/<spaceId>/<dirName>/`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration-plan.d.mts","names":[],"sources":["../../src/commands/migration-plan.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"migration-plan.d.mts","names":[],"sources":["../../src/commands/migration-plan.ts"],"mappings":";;;;;;UAiOiB,mBAAA;EAAA,SACN,EAAA;EAAA,SACA,IAAA;EAAA,SACA,IAAA;EAAA,SACA,EAAA;EAAA,SACA,GAAA;EAAA,SACA,WAAA;EAJA;;;;;;;;;;;;EAAA,SAiBA,oBAAA;IAAA,SAA0C,OAAA;IAAA,SAA0B,OAAA;EAAA;EAAA,SACpE,UAAA;IAAA,SACE,EAAA;IAAA,SACA,KAAA;IAAA,SACA,cAAA;EAAA;EAuf6B;;;;AA0E1C;EA1E0C,SAhf/B,OAAA,GAAU,gBAAA;EAAA,SACV,OAAA;EAyjB8E;;;;;EAAA,SAnjB9E,mBAAA;EAAA,SACA,OAAA;IAAA,SACE,KAAA;EAAA;AAAA;AAAA,iBAueG,0BAAA,CAAA,GAA8B,OAAA;AAAA,iBA0E9B,yBAAA,CAA0B,MAAA,EAAQ,mBAAA,EAAqB,KAAA,EAAO,WAAA;AAAA,KAkIlE,uBAAA;EACN,MAAA;EAAqB,KAAA;AAAA;EACrB,MAAA;AAAA;;;;;;;;;;;;;;iBAeU,qBAAA;EAAkC,QAAA;IAAY,EAAA;EAAA;AAAA,EAAA,CAC5D,OAAA,WAAkB,CAAA,IAClB,MAAA,WACC,MAAA,CAAO,CAAA,EAAG,uBAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as formatMigrationPlanOutput, r as resolveBundleByPrefix, t as createMigrationPlanCommand } from "../migration-plan-
|
|
1
|
+
import { n as formatMigrationPlanOutput, r as resolveBundleByPrefix, t as createMigrationPlanCommand } from "../migration-plan-jdAHg_gK.mjs";
|
|
2
2
|
export { createMigrationPlanCommand, formatMigrationPlanOutput, resolveBundleByPrefix };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { N as CliStructuredError } from "../types-UWB2-rrw.mjs";
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { Result } from "@prisma-next/utils/result";
|
|
4
4
|
import { OperationPreview } from "@prisma-next/framework-components/control";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected, O as mapRefResolutionError, S as errorRuntime, a as errorContractValidationFailed, l as errorFileNotFound } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
3
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
-
import { S as formatStyledHeader, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
5
|
-
import { t as createControlClient } from "../client-
|
|
6
|
-
import { t as buildContractSpaceAggregate } from "../contract-space-aggregate-loader-
|
|
7
|
-
import { a as formatMigrationShowOutput } from "../migrations-
|
|
4
|
+
import { S as formatStyledHeader, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
5
|
+
import { t as createControlClient } from "../client-UnIveZxZ.mjs";
|
|
6
|
+
import { t as buildContractSpaceAggregate } from "../contract-space-aggregate-loader-CGakRlKM.mjs";
|
|
7
|
+
import { a as formatMigrationShowOutput } from "../migrations-B7n518mT.mjs";
|
|
8
8
|
import { Command } from "commander";
|
|
9
9
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
10
10
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -15,8 +15,8 @@ import { readMigrationPackage, readMigrationsDir } from "@prisma-next/migration-
|
|
|
15
15
|
import { findLatestMigration, reconstructGraph } from "@prisma-next/migration-tools/migration-graph";
|
|
16
16
|
import { spaceMigrationDirectory } from "@prisma-next/migration-tools/spaces";
|
|
17
17
|
import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
|
|
18
|
-
import { parseMigrationRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
19
18
|
import { readRefs } from "@prisma-next/migration-tools/refs";
|
|
19
|
+
import { parseMigrationRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
20
20
|
//#region src/commands/migration-show.ts
|
|
21
21
|
function looksLikePath(target) {
|
|
22
22
|
return target.includes("/") || target.includes("\\");
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected, O as mapRefResolutionError, S as errorRuntime, t as CliStructuredError } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
3
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
-
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, g as toStructuralEdge, h as toPathDecisionResult, l as resolveMigrationPaths, n as collectDeclaredInvariants, o as maskConnectionUrl, p as setCommandSeeAlso, s as readContractEnvelope, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
5
|
-
import { t as createControlClient } from "../client-
|
|
6
|
-
import { t as buildContractSpaceAggregate } from "../contract-space-aggregate-loader-
|
|
7
|
-
import { i as migrationGraphToRenderInput, n as graphRenderer, r as isLinearGraph, t as extractRelevantSubgraph } from "../graph-render-
|
|
4
|
+
import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, g as toStructuralEdge, h as toPathDecisionResult, l as resolveMigrationPaths, n as collectDeclaredInvariants, o as maskConnectionUrl, p as setCommandSeeAlso, s as readContractEnvelope, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
5
|
+
import { t as createControlClient } from "../client-UnIveZxZ.mjs";
|
|
6
|
+
import { t as buildContractSpaceAggregate } from "../contract-space-aggregate-loader-CGakRlKM.mjs";
|
|
7
|
+
import { i as migrationGraphToRenderInput, n as graphRenderer, r as isLinearGraph, t as extractRelevantSubgraph } from "../graph-render-BE8vmJ_7.mjs";
|
|
8
8
|
import { Command } from "commander";
|
|
9
9
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
10
10
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -14,8 +14,8 @@ import { cyan, dim, magenta, yellow } from "colorette";
|
|
|
14
14
|
import { graphWalkStrategy } from "@prisma-next/migration-tools/aggregate";
|
|
15
15
|
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
16
16
|
import { MigrationToolsError, errorNoInvariantPath, errorUnknownInvariant } from "@prisma-next/migration-tools/errors";
|
|
17
|
-
import { parseContractRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
18
17
|
import { readRefs } from "@prisma-next/migration-tools/refs";
|
|
18
|
+
import { parseContractRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
19
19
|
//#region src/commands/migration-status.ts
|
|
20
20
|
/**
|
|
21
21
|
* Sum per-space `pendingCount` into a cross-space total, but only when
|
|
@@ -253,7 +253,7 @@ async function loadAggregateStatusSpaces(args) {
|
|
|
253
253
|
*/
|
|
254
254
|
async function loadContractRawSafely(config) {
|
|
255
255
|
try {
|
|
256
|
-
const path = (await import("../command-helpers-
|
|
256
|
+
const path = (await import("../command-helpers-CRfjbZRz.mjs").then((n) => n.r)).resolveContractPath(config);
|
|
257
257
|
const raw = await (await import("node:fs/promises")).readFile(path, "utf-8");
|
|
258
258
|
return JSON.parse(raw);
|
|
259
259
|
} catch {
|
package/dist/commands/ref.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { N as CliStructuredError } from "../types-UWB2-rrw.mjs";
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { Result } from "@prisma-next/utils/result";
|
|
4
4
|
import { RefEntry } from "@prisma-next/migration-tools/refs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ref.d.mts","names":[],"sources":["../../src/commands/ref.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"ref.d.mts","names":[],"sources":["../../src/commands/ref.ts"],"mappings":";;;;;;UAwCU,YAAA;EAAA,SACC,EAAA;EAAA,SACA,GAAA;EAAA,SACA,IAAA;EAAA,SACA,UAAA;AAAA;AAAA,UAGD,eAAA;EAAA,SACC,EAAA;EAAA,SACA,GAAA;EAAA,SACA,OAAA;AAAA;AAAA,UAGD,aAAA;EAAA,SACC,EAAA;EAAA,SACA,IAAA,EAAM,MAAA,SAAe,QAAA;AAAA;AAAA,iBAiBV,oBAAA,CACpB,IAAA,UACA,aAAA,UACA,OAAA;EAAW,MAAA;AAAA,IACV,OAAA,CAAQ,MAAA,CAAO,YAAA,EAAc,kBAAA;AAAA,iBA8DV,uBAAA,CACpB,IAAA,UACA,OAAA;EAAW,MAAA;AAAA,IACV,OAAA,CAAQ,MAAA,CAAO,eAAA,EAAiB,kBAAA;AAAA,iBAYb,qBAAA,CAAsB,OAAA;EAC1C,MAAA;AAAA,IACE,OAAA,CAAQ,MAAA,CAAO,aAAA,EAAe,kBAAA;AAAA,iBAyGlB,gBAAA,CAAA,GAAoB,OAAA"}
|
package/dist/commands/ref.mjs
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as mapMigrationToolsError, E as errorUnexpected, O as mapRefResolutionError, S as errorRuntime, b as errorRefSetHashNotInGraph, l as errorFileNotFound, t as CliStructuredError, v as errorRefSetBundleNotFound, y as errorRefSetEmptySentinel } from "../cli-errors-Bw2GlweY.mjs";
|
|
3
3
|
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
-
import { _ as parseGlobalFlags, a as loadMigrationPackages, b as formatCommandHelp, d as setCommandDescriptions, l as resolveMigrationPaths, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-
|
|
4
|
+
import { _ as parseGlobalFlags, a as loadMigrationPackages, b as formatCommandHelp, d as setCommandDescriptions, l as resolveMigrationPaths, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-CRfjbZRz.mjs";
|
|
5
|
+
import { i as readContractIR } from "../ref-advancement-DRh5Nquq.mjs";
|
|
5
6
|
import { Command } from "commander";
|
|
6
7
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
8
|
+
import { join } from "pathe";
|
|
9
|
+
import { readFile } from "node:fs/promises";
|
|
10
|
+
import { findLatestMigration, isGraphNode } from "@prisma-next/migration-tools/migration-graph";
|
|
11
|
+
import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
|
|
7
12
|
import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
|
|
13
|
+
import { deleteRefPaired, readRefs, validateRefName, validateRefValue, writeRefPaired } from "@prisma-next/migration-tools/refs";
|
|
8
14
|
import { parseContractRef } from "@prisma-next/migration-tools/ref-resolution";
|
|
9
|
-
import { deleteRef, readRefs, validateRefName, validateRefValue, writeRef } from "@prisma-next/migration-tools/refs";
|
|
10
15
|
//#region src/commands/ref.ts
|
|
11
16
|
function mapError(error) {
|
|
12
17
|
if (MigrationToolsError.is(error)) return mapMigrationToolsError(error);
|
|
@@ -23,21 +28,42 @@ async function executeRefSetCommand(name, contractInput, options) {
|
|
|
23
28
|
try {
|
|
24
29
|
const config = await loadConfig(options.config);
|
|
25
30
|
const { appMigrationsDir, refsDir } = resolveMigrationPaths(options.config, config);
|
|
31
|
+
const { graph, bundles } = await loadMigrationPackages(appMigrationsDir);
|
|
32
|
+
const refs = await readRefs(refsDir);
|
|
26
33
|
let resolvedHash;
|
|
27
34
|
if (validateRefValue(contractInput)) resolvedHash = contractInput;
|
|
28
35
|
else {
|
|
29
|
-
const { graph } = await loadMigrationPackages(appMigrationsDir);
|
|
30
36
|
const refResult = parseContractRef(contractInput, {
|
|
31
37
|
graph,
|
|
32
|
-
refs
|
|
38
|
+
refs
|
|
33
39
|
});
|
|
34
40
|
if (!refResult.ok) return notOk(mapRefResolutionError(refResult.failure));
|
|
35
41
|
resolvedHash = refResult.value.hash;
|
|
36
42
|
}
|
|
37
|
-
|
|
43
|
+
if (resolvedHash === EMPTY_CONTRACT_HASH) return notOk(errorRefSetEmptySentinel(resolvedHash));
|
|
44
|
+
if (!isGraphNode(resolvedHash, graph)) {
|
|
45
|
+
const graphTip = findLatestMigration(graph)?.to ?? null;
|
|
46
|
+
return notOk(errorRefSetHashNotInGraph(resolvedHash, [...graph.nodes].sort(), graphTip));
|
|
47
|
+
}
|
|
48
|
+
const matchingBundle = bundles.find((bundle) => bundle.metadata.to === resolvedHash);
|
|
49
|
+
if (!matchingBundle) return notOk(errorRefSetBundleNotFound(resolvedHash));
|
|
50
|
+
const contractJsonPath = join(matchingBundle.dirPath, "end-contract.json");
|
|
51
|
+
let contractJson;
|
|
52
|
+
try {
|
|
53
|
+
const raw = await readFile(contractJsonPath, "utf-8");
|
|
54
|
+
contractJson = JSON.parse(raw);
|
|
55
|
+
} catch (readError) {
|
|
56
|
+
if (readError instanceof Error && readError.code === "ENOENT") return notOk(errorFileNotFound(contractJsonPath, {
|
|
57
|
+
why: `Migration bundle for hash ${resolvedHash} is missing its end-contract snapshot at ${contractJsonPath}`,
|
|
58
|
+
fix: "Run `pnpm fixtures:check`, or re-emit the migration so its end-contract.json is restored."
|
|
59
|
+
}));
|
|
60
|
+
throw readError;
|
|
61
|
+
}
|
|
62
|
+
const contractIR = await readContractIR(contractJson, contractJsonPath);
|
|
63
|
+
await writeRefPaired(refsDir, name, {
|
|
38
64
|
hash: resolvedHash,
|
|
39
65
|
invariants: []
|
|
40
|
-
});
|
|
66
|
+
}, contractIR);
|
|
41
67
|
return ok({
|
|
42
68
|
ok: true,
|
|
43
69
|
ref: name,
|
|
@@ -53,7 +79,7 @@ async function executeRefDeleteCommand(name, options) {
|
|
|
53
79
|
try {
|
|
54
80
|
const config = await loadConfig(options.config);
|
|
55
81
|
const { refsDir } = resolveMigrationPaths(options.config, config);
|
|
56
|
-
await
|
|
82
|
+
await deleteRefPaired(refsDir, name);
|
|
57
83
|
return ok({
|
|
58
84
|
ok: true,
|
|
59
85
|
ref: name,
|