@prisma-next/cli 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.
Files changed (89) hide show
  1. package/dist/cli-errors-Bw2GlweY.mjs +175 -0
  2. package/dist/cli-errors-Bw2GlweY.mjs.map +1 -0
  3. package/dist/cli.mjs +7 -7
  4. package/dist/{client-oXO2WCPD.mjs → client-UnIveZxZ.mjs} +4 -4
  5. package/dist/{client-oXO2WCPD.mjs.map → client-UnIveZxZ.mjs.map} +1 -1
  6. package/dist/{command-helpers-DtavI0wJ.mjs → command-helpers-CRfjbZRz.mjs} +2 -2
  7. package/dist/{command-helpers-DtavI0wJ.mjs.map → command-helpers-CRfjbZRz.mjs.map} +1 -1
  8. package/dist/commands/contract-emit.mjs +1 -1
  9. package/dist/commands/contract-infer.mjs +1 -1
  10. package/dist/commands/db-init.d.mts.map +1 -1
  11. package/dist/commands/db-init.mjs +33 -6
  12. package/dist/commands/db-init.mjs.map +1 -1
  13. package/dist/commands/db-schema.mjs +3 -3
  14. package/dist/commands/db-sign.mjs +5 -5
  15. package/dist/commands/db-update.d.mts.map +1 -1
  16. package/dist/commands/db-update.mjs +36 -7
  17. package/dist/commands/db-update.mjs.map +1 -1
  18. package/dist/commands/db-verify.mjs +1 -1
  19. package/dist/commands/migrate.d.mts +5 -1
  20. package/dist/commands/migrate.d.mts.map +1 -1
  21. package/dist/commands/migrate.mjs +44 -8
  22. package/dist/commands/migrate.mjs.map +1 -1
  23. package/dist/commands/migration-check.mjs +2 -2
  24. package/dist/commands/migration-graph.mjs +3 -3
  25. package/dist/commands/migration-list.mjs +2 -2
  26. package/dist/commands/migration-log.mjs +3 -3
  27. package/dist/commands/migration-new.mjs +3 -3
  28. package/dist/commands/migration-plan.d.mts +1 -0
  29. package/dist/commands/migration-plan.d.mts.map +1 -1
  30. package/dist/commands/migration-plan.mjs +1 -1
  31. package/dist/commands/migration-show.d.mts +1 -1
  32. package/dist/commands/migration-show.mjs +6 -6
  33. package/dist/commands/migration-status.mjs +7 -7
  34. package/dist/commands/ref.d.mts +1 -1
  35. package/dist/commands/ref.d.mts.map +1 -1
  36. package/dist/commands/ref.mjs +34 -8
  37. package/dist/commands/ref.mjs.map +1 -1
  38. package/dist/{contract-emit-o-8VmdQX.mjs → contract-emit-C6rlsljO.mjs} +3 -3
  39. package/dist/{contract-emit-o-8VmdQX.mjs.map → contract-emit-C6rlsljO.mjs.map} +1 -1
  40. package/dist/{contract-emit-CmsklifJ.mjs → contract-emit-mqXmapxB.mjs} +4 -4
  41. package/dist/{contract-emit-CmsklifJ.mjs.map → contract-emit-mqXmapxB.mjs.map} +1 -1
  42. package/dist/{contract-infer-pKkiCt7C.mjs → contract-infer-C4jxc1aZ.mjs} +3 -3
  43. package/dist/{contract-infer-pKkiCt7C.mjs.map → contract-infer-C4jxc1aZ.mjs.map} +1 -1
  44. package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs → contract-space-aggregate-loader-CGakRlKM.mjs} +2 -2
  45. package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs.map → contract-space-aggregate-loader-CGakRlKM.mjs.map} +1 -1
  46. package/dist/{db-verify-AoIUriL4.mjs → db-verify-1d8tDoFN.mjs} +5 -5
  47. package/dist/{db-verify-AoIUriL4.mjs.map → db-verify-1d8tDoFN.mjs.map} +1 -1
  48. package/dist/exports/control-api.d.mts +1 -1
  49. package/dist/exports/control-api.mjs +2 -2
  50. package/dist/exports/index.mjs +1 -1
  51. package/dist/exports/init-output.mjs +1 -1
  52. package/dist/{framework-components-65gOHkHB.mjs → framework-components-Bexd0f4E.mjs} +2 -2
  53. package/dist/{framework-components-65gOHkHB.mjs.map → framework-components-Bexd0f4E.mjs.map} +1 -1
  54. package/dist/{graph-render-DJVv0_uf.mjs → graph-render-BE8vmJ_7.mjs} +1 -1
  55. package/dist/{graph-render-DJVv0_uf.mjs.map → graph-render-BE8vmJ_7.mjs.map} +1 -1
  56. package/dist/{init-Db5Itt5r.mjs → init-ByoeQphC.mjs} +4 -4
  57. package/dist/{init-Db5Itt5r.mjs.map → init-ByoeQphC.mjs.map} +1 -1
  58. package/dist/{inspect-live-schema-LeWvkZVz.mjs → inspect-live-schema-B1Q49RF0.mjs} +4 -4
  59. package/dist/{inspect-live-schema-LeWvkZVz.mjs.map → inspect-live-schema-B1Q49RF0.mjs.map} +1 -1
  60. package/dist/{migration-command-scaffold-BtkunvFQ.mjs → migration-command-scaffold-oY4P1Qto.mjs} +4 -4
  61. package/dist/{migration-command-scaffold-BtkunvFQ.mjs.map → migration-command-scaffold-oY4P1Qto.mjs.map} +1 -1
  62. package/dist/{migration-plan-C2jeH1J5.mjs → migration-plan-jdAHg_gK.mjs} +346 -87
  63. package/dist/migration-plan-jdAHg_gK.mjs.map +1 -0
  64. package/dist/{migrations-CwZMa1Ck.mjs → migrations-B7n518mT.mjs} +10 -1
  65. package/dist/migrations-B7n518mT.mjs.map +1 -0
  66. package/dist/{output-BlsrGMEF.mjs → output-CUIdfYo5.mjs} +1 -1
  67. package/dist/{output-BlsrGMEF.mjs.map → output-CUIdfYo5.mjs.map} +1 -1
  68. package/dist/ref-advancement-DRh5Nquq.mjs +50 -0
  69. package/dist/ref-advancement-DRh5Nquq.mjs.map +1 -0
  70. package/dist/{types-C9FfXb1l.d.mts → types-UWB2-rrw.d.mts} +5 -4
  71. package/dist/types-UWB2-rrw.d.mts.map +1 -0
  72. package/dist/{verify-Bom75OYI.mjs → verify-C5UvbrF1.mjs} +1 -1
  73. package/dist/{verify-Bom75OYI.mjs.map → verify-C5UvbrF1.mjs.map} +1 -1
  74. package/package.json +18 -18
  75. package/src/commands/db-init.ts +48 -2
  76. package/src/commands/db-update.ts +45 -0
  77. package/src/commands/migrate.ts +73 -3
  78. package/src/commands/migration-plan.ts +365 -128
  79. package/src/commands/ref.ts +46 -6
  80. package/src/utils/cli-errors.ts +173 -0
  81. package/src/utils/formatters/migrations.ts +25 -0
  82. package/src/utils/plan-resolution.ts +257 -0
  83. package/src/utils/ref-advancement.ts +68 -0
  84. package/dist/cli-errors-Czmx92Zy.d.mts +0 -3
  85. package/dist/cli-errors-Djtz98Vm.mjs +0 -71
  86. package/dist/cli-errors-Djtz98Vm.mjs.map +0 -1
  87. package/dist/migration-plan-C2jeH1J5.mjs.map +0 -1
  88. package/dist/migrations-CwZMa1Ck.mjs.map +0 -1
  89. package/dist/types-C9FfXb1l.d.mts.map +0 -1
@@ -1,18 +1,26 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';
1
3
  import { MigrationToolsError } from '@prisma-next/migration-tools/errors';
4
+ import { findLatestMigration, isGraphNode } from '@prisma-next/migration-tools/migration-graph';
2
5
  import { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';
3
6
  import type { RefEntry } from '@prisma-next/migration-tools/refs';
4
7
  import {
5
- deleteRef,
8
+ deleteRefPaired,
6
9
  readRefs,
7
10
  validateRefName,
8
11
  validateRefValue,
9
- writeRef,
12
+ writeRefPaired,
10
13
  } from '@prisma-next/migration-tools/refs';
11
14
  import { notOk, ok, type Result } from '@prisma-next/utils/result';
12
15
  import { Command } from 'commander';
16
+ import { join } from 'pathe';
13
17
  import { loadConfig } from '../config-loader';
14
18
  import {
15
19
  CliStructuredError,
20
+ errorFileNotFound,
21
+ errorRefSetBundleNotFound,
22
+ errorRefSetEmptySentinel,
23
+ errorRefSetHashNotInGraph,
16
24
  errorRuntime,
17
25
  errorUnexpected,
18
26
  mapMigrationToolsError,
@@ -26,6 +34,7 @@ import {
26
34
  } from '../utils/command-helpers';
27
35
  import { formatCommandHelp } from '../utils/formatters/help';
28
36
  import { parseGlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';
37
+ import { readContractIR } from '../utils/ref-advancement';
29
38
  import { handleResult } from '../utils/result-handler';
30
39
  import { createTerminalUI } from '../utils/terminal-ui';
31
40
 
@@ -73,13 +82,13 @@ export async function executeRefSetCommand(
73
82
  try {
74
83
  const config = await loadConfig(options.config);
75
84
  const { appMigrationsDir, refsDir } = resolveMigrationPaths(options.config, config);
85
+ const { graph, bundles } = await loadMigrationPackages(appMigrationsDir);
86
+ const refs = await readRefs(refsDir);
76
87
 
77
88
  let resolvedHash: string;
78
89
  if (validateRefValue(contractInput)) {
79
90
  resolvedHash = contractInput;
80
91
  } else {
81
- const { graph } = await loadMigrationPackages(appMigrationsDir);
82
- const refs = await readRefs(refsDir);
83
92
  const refResult = parseContractRef(contractInput, { graph, refs });
84
93
  if (!refResult.ok) {
85
94
  return notOk(mapRefResolutionError(refResult.failure));
@@ -87,8 +96,39 @@ export async function executeRefSetCommand(
87
96
  resolvedHash = refResult.value.hash;
88
97
  }
89
98
 
99
+ if (resolvedHash === EMPTY_CONTRACT_HASH) {
100
+ return notOk(errorRefSetEmptySentinel(resolvedHash));
101
+ }
102
+ if (!isGraphNode(resolvedHash, graph)) {
103
+ const graphTip = findLatestMigration(graph)?.to ?? null;
104
+ return notOk(errorRefSetHashNotInGraph(resolvedHash, [...graph.nodes].sort(), graphTip));
105
+ }
106
+
107
+ const matchingBundle = bundles.find((bundle) => bundle.metadata.to === resolvedHash);
108
+ if (!matchingBundle) {
109
+ return notOk(errorRefSetBundleNotFound(resolvedHash));
110
+ }
111
+
112
+ const contractJsonPath = join(matchingBundle.dirPath, 'end-contract.json');
113
+ let contractJson: Record<string, unknown>;
114
+ try {
115
+ const raw = await readFile(contractJsonPath, 'utf-8');
116
+ contractJson = JSON.parse(raw) as Record<string, unknown>;
117
+ } catch (readError) {
118
+ if (readError instanceof Error && (readError as NodeJS.ErrnoException).code === 'ENOENT') {
119
+ return notOk(
120
+ errorFileNotFound(contractJsonPath, {
121
+ why: `Migration bundle for hash ${resolvedHash} is missing its end-contract snapshot at ${contractJsonPath}`,
122
+ fix: 'Run `pnpm fixtures:check`, or re-emit the migration so its end-contract.json is restored.',
123
+ }),
124
+ );
125
+ }
126
+ throw readError;
127
+ }
128
+
129
+ const contractIR = await readContractIR(contractJson, contractJsonPath);
90
130
  const entry: RefEntry = { hash: resolvedHash, invariants: [] };
91
- await writeRef(refsDir, name, entry);
131
+ await writeRefPaired(refsDir, name, entry, contractIR);
92
132
  return ok({ ok: true as const, ref: name, hash: resolvedHash, invariants: [] });
93
133
  } catch (error) {
94
134
  if (error instanceof CliStructuredError) return notOk(error);
@@ -103,7 +143,7 @@ export async function executeRefDeleteCommand(
103
143
  try {
104
144
  const config = await loadConfig(options.config);
105
145
  const { refsDir } = resolveMigrationPaths(options.config, config);
106
- await deleteRef(refsDir, name);
146
+ await deleteRefPaired(refsDir, name);
107
147
  return ok({ ok: true as const, ref: name, deleted: true as const });
108
148
  } catch (error) {
109
149
  if (error instanceof CliStructuredError) return notOk(error);
@@ -28,6 +28,7 @@ import {
28
28
  import { errorRuntime } from '@prisma-next/errors/execution';
29
29
  import type { MigrationToolsError } from '@prisma-next/migration-tools/errors';
30
30
  import type { RefResolutionError } from '@prisma-next/migration-tools/ref-resolution';
31
+ import type { MigrationApplyFailure } from '../control-api/types';
31
32
 
32
33
  export {
33
34
  ERROR_CODE_DESTRUCTIVE_CHANGES,
@@ -68,6 +69,178 @@ export {
68
69
  errorUnexpected,
69
70
  };
70
71
 
72
+ export function errorRefSetHashNotInGraph(
73
+ resolvedHash: string,
74
+ reachableHashes: readonly string[],
75
+ graphTipHash: string | null,
76
+ ): CliStructuredError {
77
+ const reachableList =
78
+ reachableHashes.length > 0 ? reachableHashes.join(', ') : '(none — migration graph is empty)';
79
+ const fix =
80
+ reachableHashes.length > 0
81
+ ? graphTipHash !== null
82
+ ? `Set the ref to a graph-node hash such as ${graphTipHash}, or run \`prisma-next migration plan\` to extend the graph.`
83
+ : 'Set the ref to a hash that appears in the migration graph.'
84
+ : 'Run `prisma-next migration plan` first.';
85
+ return errorRuntime(`Resolved contract hash is not in the migration graph: ${resolvedHash}`, {
86
+ why:
87
+ reachableHashes.length > 0
88
+ ? `The migration graph reaches ${reachableList}; resolved ${resolvedHash} isn't a graph node.`
89
+ : 'The migration graph is empty — no hashes reachable.',
90
+ fix,
91
+ meta: {
92
+ code: 'MIGRATION.HASH_NOT_IN_GRAPH',
93
+ resolvedHash,
94
+ reachableHashes: [...reachableHashes],
95
+ ...(graphTipHash !== null ? { graphTipHash } : {}),
96
+ },
97
+ });
98
+ }
99
+
100
+ export function errorRefSetEmptySentinel(hash: string): CliStructuredError {
101
+ return errorRuntime(`Cannot set ref to the empty-database sentinel: ${hash}`, {
102
+ why: 'The empty-database sentinel is a planner internal; it is not a valid ref target.',
103
+ fix: 'Set the ref to a contract hash from the migration graph, or use another ref name.',
104
+ meta: {
105
+ code: 'MIGRATION.REF_SET_EMPTY_SENTINEL',
106
+ hash,
107
+ },
108
+ });
109
+ }
110
+
111
+ export function errorRefSetBundleNotFound(hash: string): CliStructuredError {
112
+ return errorRuntime(`No migration bundle matches graph-node hash ${hash}`, {
113
+ why: `The hash is a graph node but no on-disk bundle has metadata.to = ${hash}.`,
114
+ fix: 'Run `pnpm fixtures:check`, or re-emit the migration that produces this hash so its bundle is restored.',
115
+ meta: {
116
+ code: 'MIGRATION.REF_SET_BUNDLE_NOT_FOUND',
117
+ hash,
118
+ },
119
+ });
120
+ }
121
+
122
+ export function errorPlanForgotTheFlag(
123
+ resolvedHash: string,
124
+ reachableRefs: ReadonlyArray<{ readonly name: string; readonly hash: string }>,
125
+ graphTipHash: string | null,
126
+ ): CliStructuredError {
127
+ const reachableList =
128
+ reachableRefs.length > 0
129
+ ? reachableRefs.map((r) => `${r.name} (${r.hash})`).join(', ')
130
+ : '(none)';
131
+ const refFix =
132
+ reachableRefs.length > 0
133
+ ? `Run migration plan with ${reachableRefs.map((r) => `--from ${r.name}`).join(' or ')}.`
134
+ : graphTipHash !== null
135
+ ? `Run migration plan --from ${graphTipHash}.`
136
+ : 'Commit pending migrations first, then run migration plan.';
137
+ return errorRuntime(`Resolved from-hash is not in the migration graph: ${resolvedHash}`, {
138
+ why: `The migration graph reaches ${reachableList}; resolved ${resolvedHash} isn't a graph node.`,
139
+ fix: refFix,
140
+ meta: {
141
+ code: 'MIGRATION.HASH_NOT_IN_GRAPH',
142
+ resolvedHash,
143
+ reachableRefs: reachableRefs.map((r) => r.name),
144
+ ...(graphTipHash !== null ? { graphTipHash } : {}),
145
+ },
146
+ });
147
+ }
148
+
149
+ export function errorSnapshotMissing(
150
+ identifier: string,
151
+ options?: { readonly viaRef?: boolean },
152
+ ): CliStructuredError {
153
+ const viaRef = options?.viaRef !== false;
154
+ const fix = viaRef
155
+ ? `Run "prisma-next db update --advance-ref ${identifier}" to repopulate the snapshot, or "prisma-next ref delete ${identifier}" to clear the orphan pointer.`
156
+ : `No contract source exists for hash "${identifier}" on an empty migration graph. Use --from with a ref name that has a paired snapshot, or run db update first.`;
157
+ return errorRuntime(
158
+ viaRef
159
+ ? `Ref "${identifier}" has no paired contract snapshot`
160
+ : `No contract source for from-hash "${identifier}"`,
161
+ {
162
+ why: viaRef
163
+ ? `Ref "${identifier}" exists but its paired snapshot files are missing.`
164
+ : `Hash "${identifier}" is not a graph node and no paired ref snapshot supplies a contract.`,
165
+ fix,
166
+ meta: {
167
+ code: 'MIGRATION.SNAPSHOT_MISSING',
168
+ identifier,
169
+ viaRef,
170
+ },
171
+ },
172
+ );
173
+ }
174
+
175
+ export function errorMarkerMismatch(
176
+ markerHash: string,
177
+ reachableHashes: readonly string[],
178
+ graphTip: string | null,
179
+ ): CliStructuredError {
180
+ const reachableList =
181
+ reachableHashes.length > 0 ? reachableHashes.join(', ') : '(none — migration graph is empty)';
182
+ const planFromFix =
183
+ graphTip !== null
184
+ ? `Run \`prisma-next migration plan --from ${graphTip}\` if the live marker is canonical and the on-disk graph needs catching up.`
185
+ : 'Run `prisma-next migration plan` if the live marker is canonical and the on-disk graph needs catching up.';
186
+ return errorRuntime('Database marker is not reachable in the on-disk migration graph', {
187
+ why: `DB marker is ${markerHash}, but the on-disk migration graph reaches: ${reachableList}.`,
188
+ fix: [
189
+ planFromFix,
190
+ `Run \`prisma-next ref set db ${markerHash}\` if the on-disk graph is canonical and the local \`db\` ref drifted.`,
191
+ 'Investigate whether the database was migrated by an out-of-band process.',
192
+ ].join('\n'),
193
+ meta: {
194
+ code: 'MIGRATION.MARKER_MISMATCH',
195
+ markerHash,
196
+ reachableHashes: [...reachableHashes],
197
+ ...(graphTip !== null ? { graphTip } : {}),
198
+ },
199
+ });
200
+ }
201
+
202
+ export function errorPathUnreachable(failure: MigrationApplyFailure): CliStructuredError {
203
+ const meta = failure.meta ?? {};
204
+ const fromHash = typeof meta['fromHash'] === 'string' ? meta['fromHash'] : null;
205
+ const targetHash =
206
+ typeof meta['targetHash'] === 'string'
207
+ ? meta['targetHash']
208
+ : typeof meta['target'] === 'string'
209
+ ? meta['target']
210
+ : null;
211
+ const deadEnds = meta['deadEnds'];
212
+ const deadEndsSuffix =
213
+ Array.isArray(deadEnds) && deadEnds.length > 0
214
+ ? ` Dead-ends: ${deadEnds.map(String).join(', ')}.`
215
+ : '';
216
+ const planFix = (() => {
217
+ if (fromHash !== null && targetHash !== null) {
218
+ return `Run \`prisma-next migration plan --from ${fromHash} --to ${targetHash}\` to introduce the missing path.`;
219
+ }
220
+ if (targetHash !== null) {
221
+ return `Run \`prisma-next migration plan --to ${targetHash}\` to introduce the missing path.`;
222
+ }
223
+ if (fromHash !== null) {
224
+ return `Run \`prisma-next migration plan --from ${fromHash}\` to introduce the missing path.`;
225
+ }
226
+ return 'Run `prisma-next migration plan` to introduce the missing path.';
227
+ })();
228
+ return errorRuntime(failure.summary, {
229
+ why:
230
+ failure.why ??
231
+ `Cannot reach target "${targetHash ?? '<unknown>'}" from current marker "${fromHash ?? '<unknown>'}".${deadEndsSuffix}`,
232
+ fix: [
233
+ 'Run `prisma-next migration list` to see the on-disk graph.',
234
+ planFix,
235
+ 'Run `prisma-next migration show <bundle>` for any bundle in the path you expected.',
236
+ ].join('\n'),
237
+ meta: {
238
+ ...meta,
239
+ code: 'MIGRATION.PATH_UNREACHABLE',
240
+ },
241
+ });
242
+ }
243
+
71
244
  /**
72
245
  * Maps a `MigrationToolsError` raised by the migration-tools loader/graph
73
246
  * surface (`readMigrationPackage`, `readMigrationsDir`, `readRefs`,
@@ -82,6 +82,8 @@ export interface MigrationCommandResult {
82
82
  * into a single ambiguous list. See {@link AggregatePerSpaceExecutionEntry}.
83
83
  */
84
84
  readonly perSpace?: ReadonlyArray<AggregatePerSpaceExecutionEntry>;
85
+ readonly advancedRef?: { readonly name: string; readonly hash: string } | null;
86
+ readonly plannedAdvanceRef?: { readonly name: string; readonly hash: string } | null;
85
87
  readonly summary: string;
86
88
  readonly timings: {
87
89
  readonly total: number;
@@ -208,6 +210,15 @@ export function formatMigrationPlanOutput(
208
210
  lines.push(`${formatDimText(`Destination hash: ${result.plan.destination.storageHash}`)}`);
209
211
  }
210
212
 
213
+ if (result.plannedAdvanceRef) {
214
+ lines.push('');
215
+ lines.push(
216
+ formatDimText(
217
+ `Would advance ref "${result.plannedAdvanceRef.name}" → ${result.plannedAdvanceRef.hash}`,
218
+ ),
219
+ );
220
+ }
221
+
211
222
  // Statement preview (any family that implements OperationPreviewCapable)
212
223
  const preview = result.plan?.preview;
213
224
  if (preview) {
@@ -260,6 +271,7 @@ export interface MigrationApplyCommandOutputResult {
260
271
  readonly timings?: {
261
272
  readonly total: number;
262
273
  };
274
+ readonly advancedRef?: { readonly name: string; readonly hash: string } | null;
263
275
  }
264
276
 
265
277
  export function formatMigrationApplyCommandOutput(
@@ -284,6 +296,13 @@ export function formatMigrationApplyCommandOutput(
284
296
  }
285
297
  }
286
298
 
299
+ if (result.advancedRef) {
300
+ lines.push('');
301
+ lines.push(
302
+ formatDimText(`Advanced ref "${result.advancedRef.name}" → ${result.advancedRef.hash}`),
303
+ );
304
+ }
305
+
287
306
  lines.push('');
288
307
  lines.push(formatDimText('Next: prisma-next migration status'));
289
308
 
@@ -470,6 +489,12 @@ export function formatMigrationApplyOutput(
470
489
  if (isVerbose(flags, 1)) {
471
490
  lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);
472
491
  }
492
+
493
+ if (result.advancedRef) {
494
+ lines.push(
495
+ formatDimText(`Advanced ref "${result.advancedRef.name}" → ${result.advancedRef.hash}`),
496
+ );
497
+ }
473
498
  }
474
499
 
475
500
  return lines.join('\n');
@@ -0,0 +1,257 @@
1
+ import type { Contract } from '@prisma-next/contract/types';
2
+ import type { ControlFamilyInstance } from '@prisma-next/framework-components/control';
3
+ import { MigrationToolsError } from '@prisma-next/migration-tools/errors';
4
+ import type { MigrationGraph } from '@prisma-next/migration-tools/graph';
5
+ import {
6
+ assertHashIsGraphNode,
7
+ findLatestMigration,
8
+ isGraphNode,
9
+ } from '@prisma-next/migration-tools/migration-graph';
10
+ import type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';
11
+ import { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';
12
+ import type { Refs } from '@prisma-next/migration-tools/refs';
13
+ import { readRefSnapshot, readRefs } from '@prisma-next/migration-tools/refs';
14
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
15
+ import {
16
+ CliStructuredError,
17
+ errorContractValidationFailed,
18
+ errorPlanForgotTheFlag,
19
+ errorSnapshotMissing,
20
+ errorUnexpected,
21
+ mapMigrationToolsError,
22
+ mapRefResolutionError,
23
+ } from './cli-errors';
24
+
25
+ const FULL_HASH_PATTERN = /^sha256:([0-9a-f]{64}|empty)$/;
26
+
27
+ export function looksLikeFullHash(input: string): boolean {
28
+ return FULL_HASH_PATTERN.test(input);
29
+ }
30
+
31
+ export type FromResolution =
32
+ | { kind: 'greenfield'; fromHash: null; fromContract: null }
33
+ | { kind: 'graph-node'; fromHash: string; fromContract: Contract; sourceDir: string }
34
+ | {
35
+ kind: 'snapshot';
36
+ fromHash: string;
37
+ fromContract: Contract;
38
+ contractDts: string;
39
+ contractJson: unknown;
40
+ }
41
+ | {
42
+ kind: 'auto-baseline';
43
+ fromHash: string;
44
+ fromContract: Contract;
45
+ contractDts: string;
46
+ contractJson: unknown;
47
+ };
48
+
49
+ export interface ResolveFromForPlanInput {
50
+ readonly optionsFrom?: string | undefined;
51
+ readonly refsDir: string;
52
+ readonly bundles: readonly OnDiskMigrationPackage[];
53
+ readonly graph: MigrationGraph;
54
+ readonly familyInstance: ControlFamilyInstance<string, unknown>;
55
+ readonly readBundleEndContract: (migrationDir: string) => Promise<Contract>;
56
+ }
57
+
58
+ function graphIsEmpty(bundles: readonly OnDiskMigrationPackage[]): boolean {
59
+ return bundles.length === 0;
60
+ }
61
+
62
+ function getReachableRefs(
63
+ refs: Refs,
64
+ graph: MigrationGraph,
65
+ ): ReadonlyArray<{ name: string; hash: string }> {
66
+ return Object.entries(refs)
67
+ .flatMap(([name, entry]) =>
68
+ entry && isGraphNode(entry.hash, graph) ? [{ name, hash: entry.hash }] : [],
69
+ )
70
+ .sort((a, b) => a.name.localeCompare(b.name));
71
+ }
72
+
73
+ export function assertFromIsGraphNode(
74
+ fromHash: string,
75
+ graph: MigrationGraph,
76
+ refs: Refs,
77
+ graphTipHash: string | null,
78
+ ): void {
79
+ try {
80
+ assertHashIsGraphNode(fromHash, graph);
81
+ } catch (error) {
82
+ if (MigrationToolsError.is(error) && error.code === 'MIGRATION.HASH_NOT_IN_GRAPH') {
83
+ throw errorPlanForgotTheFlag(fromHash, getReachableRefs(refs, graph), graphTipHash);
84
+ }
85
+ throw error;
86
+ }
87
+ }
88
+
89
+ async function deserializeSnapshotContract(
90
+ familyInstance: ControlFamilyInstance<string, unknown>,
91
+ contract: unknown,
92
+ ): Promise<Result<Contract, CliStructuredError>> {
93
+ try {
94
+ return ok(familyInstance.deserializeContract(contract));
95
+ } catch (error) {
96
+ if (CliStructuredError.is(error)) {
97
+ return notOk(error);
98
+ }
99
+ return notOk(
100
+ errorContractValidationFailed(
101
+ `Ref snapshot contract failed to deserialize: ${error instanceof Error ? error.message : String(error)}`,
102
+ { where: { path: 'ref-snapshot' } },
103
+ ),
104
+ );
105
+ }
106
+ }
107
+
108
+ async function resolveGraphNodeFromBundle(
109
+ fromHash: string,
110
+ bundles: readonly OnDiskMigrationPackage[],
111
+ readBundleEndContract: (migrationDir: string) => Promise<Contract>,
112
+ explicitFromLabel?: string,
113
+ ): Promise<Result<Extract<FromResolution, { kind: 'graph-node' }>, CliStructuredError>> {
114
+ const matchingBundle = bundles.find((pkg) => pkg.metadata.to === fromHash);
115
+ if (!matchingBundle) {
116
+ return notOk(
117
+ errorUnexpected(
118
+ explicitFromLabel
119
+ ? `No migration bundle found for --from "${explicitFromLabel}" (resolved hash: ${fromHash})`
120
+ : `No migration bundle found for graph node ${fromHash}`,
121
+ {
122
+ why: `The hash ${fromHash} is a graph node but no on-disk migration package has an end-contract hash matching it.`,
123
+ fix: 'Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.',
124
+ },
125
+ ),
126
+ );
127
+ }
128
+ try {
129
+ const fromContract = await readBundleEndContract(matchingBundle.dirPath);
130
+ return ok({
131
+ kind: 'graph-node',
132
+ fromHash,
133
+ fromContract,
134
+ sourceDir: matchingBundle.dirPath,
135
+ });
136
+ } catch (error) {
137
+ if (CliStructuredError.is(error)) {
138
+ return notOk(error);
139
+ }
140
+ throw error;
141
+ }
142
+ }
143
+
144
+ async function resolveFromRefName(
145
+ refName: string,
146
+ fromHash: string,
147
+ input: ResolveFromForPlanInput,
148
+ refs: Refs,
149
+ ): Promise<Result<FromResolution, CliStructuredError>> {
150
+ const { refsDir, bundles, graph, familyInstance, readBundleEndContract } = input;
151
+ const empty = graphIsEmpty(bundles);
152
+ const graphTip = findLatestMigration(graph)?.to ?? null;
153
+
154
+ let snapshot: Awaited<ReturnType<typeof readRefSnapshot>>;
155
+ try {
156
+ snapshot = await readRefSnapshot(refsDir, refName);
157
+ } catch (error) {
158
+ if (MigrationToolsError.is(error)) {
159
+ return notOk(mapMigrationToolsError(error));
160
+ }
161
+ throw error;
162
+ }
163
+
164
+ if (snapshot) {
165
+ const contractResult = await deserializeSnapshotContract(familyInstance, snapshot.contract);
166
+ if (!contractResult.ok) {
167
+ return contractResult;
168
+ }
169
+ const fromContract = contractResult.value;
170
+ const { contractDts, contract: contractJson } = snapshot;
171
+ if (empty) {
172
+ return ok({ kind: 'auto-baseline', fromHash, fromContract, contractDts, contractJson });
173
+ }
174
+ try {
175
+ assertFromIsGraphNode(fromHash, graph, refs, graphTip);
176
+ } catch (error) {
177
+ if (CliStructuredError.is(error)) {
178
+ return notOk(error);
179
+ }
180
+ throw error;
181
+ }
182
+ return ok({ kind: 'snapshot', fromHash, fromContract, contractDts, contractJson });
183
+ }
184
+
185
+ if (isGraphNode(fromHash, graph)) {
186
+ return resolveGraphNodeFromBundle(fromHash, bundles, readBundleEndContract);
187
+ }
188
+
189
+ return notOk(errorSnapshotMissing(refName));
190
+ }
191
+
192
+ async function resolveFromHashProvenance(
193
+ fromHash: string,
194
+ input: ResolveFromForPlanInput,
195
+ _refs: Refs,
196
+ explicitFromLabel?: string,
197
+ ): Promise<Result<FromResolution, CliStructuredError>> {
198
+ const { bundles, graph } = input;
199
+
200
+ if (isGraphNode(fromHash, graph)) {
201
+ return resolveGraphNodeFromBundle(
202
+ fromHash,
203
+ bundles,
204
+ input.readBundleEndContract,
205
+ explicitFromLabel,
206
+ );
207
+ }
208
+
209
+ throw new Error(
210
+ `resolveFromHashProvenance: non-graph-node hash ${fromHash} should be refused via looksLikeFullHash before this helper is called`,
211
+ );
212
+ }
213
+
214
+ export async function resolveFromForPlan(
215
+ input: ResolveFromForPlanInput,
216
+ ): Promise<Result<FromResolution, CliStructuredError>> {
217
+ const { optionsFrom, refsDir, graph } = input;
218
+
219
+ let refs: Refs;
220
+ try {
221
+ refs = await readRefs(refsDir);
222
+ } catch (error) {
223
+ if (MigrationToolsError.is(error)) {
224
+ return notOk(mapMigrationToolsError(error));
225
+ }
226
+ throw error;
227
+ }
228
+
229
+ if (optionsFrom === undefined) {
230
+ const dbRef = refs['db'];
231
+ if (!dbRef) {
232
+ return ok({ kind: 'greenfield', fromHash: null, fromContract: null });
233
+ }
234
+ return resolveFromRefName('db', dbRef.hash, input, refs);
235
+ }
236
+
237
+ const refResult = parseContractRef(optionsFrom, { graph, refs });
238
+ if (!refResult.ok) {
239
+ if (looksLikeFullHash(optionsFrom)) {
240
+ const empty = graphIsEmpty(input.bundles);
241
+ const graphTip = findLatestMigration(graph)?.to ?? null;
242
+ if (empty) {
243
+ return notOk(errorSnapshotMissing(optionsFrom, { viaRef: false }));
244
+ }
245
+ return notOk(errorPlanForgotTheFlag(optionsFrom, getReachableRefs(refs, graph), graphTip));
246
+ }
247
+ return notOk(mapRefResolutionError(refResult.failure));
248
+ }
249
+
250
+ const { hash: fromHash, provenance } = refResult.value;
251
+
252
+ if (provenance.kind === 'ref') {
253
+ return resolveFromRefName(provenance.refName, fromHash, input, refs);
254
+ }
255
+
256
+ return resolveFromHashProvenance(fromHash, input, refs, optionsFrom);
257
+ }
@@ -0,0 +1,68 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import type { ContractIR } from '@prisma-next/migration-tools/refs';
3
+ import { writeRefPaired } from '@prisma-next/migration-tools/refs';
4
+ import { ifDefined } from '@prisma-next/utils/defined';
5
+
6
+ export interface RefAdvancementFields {
7
+ readonly advancedRef: { readonly name: string; readonly hash: string } | null;
8
+ readonly plannedAdvanceRef: { readonly name: string; readonly hash: string } | null;
9
+ }
10
+
11
+ export function computeRefAdvancementName(options: {
12
+ readonly advanceRef?: string;
13
+ readonly db?: string;
14
+ }): string | null {
15
+ if (options.advanceRef !== undefined) {
16
+ return options.advanceRef;
17
+ }
18
+ if (options.db === undefined) {
19
+ return 'db';
20
+ }
21
+ return null;
22
+ }
23
+
24
+ export async function readContractIR(
25
+ contractJson: Record<string, unknown>,
26
+ contractJsonPath: string,
27
+ ): Promise<ContractIR> {
28
+ const contractDtsPath = contractJsonPath.replace(/\.json$/i, '.d.ts');
29
+ const contractDts = await readFile(contractDtsPath, 'utf-8');
30
+ return { contract: contractJson, contractDts };
31
+ }
32
+
33
+ export async function executeRefAdvancement(
34
+ refsDir: string,
35
+ name: string,
36
+ hash: string,
37
+ contractIR: ContractIR,
38
+ ): Promise<{ name: string; hash: string }> {
39
+ await writeRefPaired(refsDir, name, { hash, invariants: [] }, contractIR);
40
+ return { name, hash };
41
+ }
42
+
43
+ export async function buildRefAdvancementFields(options: {
44
+ readonly advanceRef?: string;
45
+ readonly db?: string;
46
+ readonly refsDir: string;
47
+ readonly contractIR: ContractIR;
48
+ readonly mode: 'plan' | 'apply';
49
+ readonly hash: string;
50
+ }): Promise<RefAdvancementFields> {
51
+ const name = computeRefAdvancementName({
52
+ ...ifDefined('advanceRef', options.advanceRef),
53
+ ...ifDefined('db', options.db),
54
+ });
55
+ if (name === null) {
56
+ return { advancedRef: null, plannedAdvanceRef: null };
57
+ }
58
+ if (options.mode === 'plan') {
59
+ return { advancedRef: null, plannedAdvanceRef: { name, hash: options.hash } };
60
+ }
61
+ const advancedRef = await executeRefAdvancement(
62
+ options.refsDir,
63
+ name,
64
+ options.hash,
65
+ options.contractIR,
66
+ );
67
+ return { advancedRef, plannedAdvanceRef: null };
68
+ }
@@ -1,3 +0,0 @@
1
- import { CliStructuredError as CliStructuredError$1 } from "@prisma-next/errors/control";
2
- import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
3
- export { CliStructuredError$1 as t };