@prisma-next/cli 0.10.0 → 0.11.0-dev.10

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 (166) hide show
  1. package/README.md +1 -1
  2. package/dist/cli-errors-Bw2GlweY.mjs +175 -0
  3. package/dist/cli-errors-Bw2GlweY.mjs.map +1 -0
  4. package/dist/cli.mjs +400 -13
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/{client-Brv4qlfB.mjs → client-UnIveZxZ.mjs} +6 -5
  7. package/dist/client-UnIveZxZ.mjs.map +1 -0
  8. package/dist/{command-helpers-D3vL5yi8.mjs → command-helpers-CRfjbZRz.mjs} +109 -12
  9. package/dist/command-helpers-CRfjbZRz.mjs.map +1 -0
  10. package/dist/commands/contract-emit.d.mts.map +1 -1
  11. package/dist/commands/contract-emit.mjs +1 -1
  12. package/dist/commands/contract-infer.mjs +1 -1
  13. package/dist/commands/db-init.d.mts.map +1 -1
  14. package/dist/commands/db-init.mjs +47 -21
  15. package/dist/commands/db-init.mjs.map +1 -1
  16. package/dist/commands/db-schema.mjs +6 -10
  17. package/dist/commands/db-schema.mjs.map +1 -1
  18. package/dist/commands/db-sign.mjs +8 -12
  19. package/dist/commands/db-sign.mjs.map +1 -1
  20. package/dist/commands/db-update.d.mts.map +1 -1
  21. package/dist/commands/db-update.mjs +47 -19
  22. package/dist/commands/db-update.mjs.map +1 -1
  23. package/dist/commands/db-verify.mjs +1 -1
  24. package/dist/commands/migrate.d.mts +5 -1
  25. package/dist/commands/migrate.d.mts.map +1 -1
  26. package/dist/commands/migrate.mjs +47 -15
  27. package/dist/commands/migrate.mjs.map +1 -1
  28. package/dist/commands/migration-check.mjs +5 -8
  29. package/dist/commands/migration-check.mjs.map +1 -1
  30. package/dist/commands/migration-graph.d.mts +1 -1
  31. package/dist/commands/migration-graph.mjs +6 -10
  32. package/dist/commands/migration-graph.mjs.map +1 -1
  33. package/dist/commands/migration-list.mjs +5 -9
  34. package/dist/commands/migration-list.mjs.map +1 -1
  35. package/dist/commands/migration-log.d.mts.map +1 -1
  36. package/dist/commands/migration-log.mjs +7 -10
  37. package/dist/commands/migration-log.mjs.map +1 -1
  38. package/dist/commands/migration-new.mjs +6 -10
  39. package/dist/commands/migration-new.mjs.map +1 -1
  40. package/dist/commands/migration-plan.d.mts +2 -1
  41. package/dist/commands/migration-plan.d.mts.map +1 -1
  42. package/dist/commands/migration-plan.mjs +1 -1
  43. package/dist/commands/migration-show.d.mts +1 -1
  44. package/dist/commands/migration-show.mjs +9 -13
  45. package/dist/commands/migration-show.mjs.map +1 -1
  46. package/dist/commands/migration-status.d.mts +1 -1
  47. package/dist/commands/migration-status.d.mts.map +1 -1
  48. package/dist/commands/migration-status.mjs +37 -15
  49. package/dist/commands/migration-status.mjs.map +1 -1
  50. package/dist/commands/ref.d.mts +1 -1
  51. package/dist/commands/ref.d.mts.map +1 -1
  52. package/dist/commands/ref.mjs +41 -25
  53. package/dist/commands/ref.mjs.map +1 -1
  54. package/dist/{contract-emit-iynA3BCA.mjs → contract-emit-C6rlsljO.mjs} +7 -6
  55. package/dist/contract-emit-C6rlsljO.mjs.map +1 -0
  56. package/dist/{contract-emit-C3STUIBg.mjs → contract-emit-mqXmapxB.mjs} +22 -20
  57. package/dist/contract-emit-mqXmapxB.mjs.map +1 -0
  58. package/dist/{contract-infer-Cnj8G1E2.mjs → contract-infer-C4jxc1aZ.mjs} +9 -14
  59. package/dist/contract-infer-C4jxc1aZ.mjs.map +1 -0
  60. package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs → contract-space-aggregate-loader-CGakRlKM.mjs} +2 -2
  61. package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs.map → contract-space-aggregate-loader-CGakRlKM.mjs.map} +1 -1
  62. package/dist/{db-verify-D7cyH_zz.mjs → db-verify-1d8tDoFN.mjs} +9 -13
  63. package/dist/db-verify-1d8tDoFN.mjs.map +1 -0
  64. package/dist/exports/control-api.d.mts +1 -1
  65. package/dist/exports/control-api.mjs +2 -2
  66. package/dist/exports/index.mjs +2 -2
  67. package/dist/exports/init-output.mjs +1 -1
  68. package/dist/{framework-components-xFLFpZUO.mjs → framework-components-Bexd0f4E.mjs} +2 -2
  69. package/dist/{framework-components-xFLFpZUO.mjs.map → framework-components-Bexd0f4E.mjs.map} +1 -1
  70. package/dist/{global-flags-DGmw6Kqg.d.mts → global-flags-CdE7M0d9.d.mts} +4 -1
  71. package/dist/global-flags-CdE7M0d9.d.mts.map +1 -0
  72. package/dist/{graph-render-eJDcLWny.mjs → graph-render-BE8vmJ_7.mjs} +1 -1
  73. package/dist/{graph-render-eJDcLWny.mjs.map → graph-render-BE8vmJ_7.mjs.map} +1 -1
  74. package/dist/{init-eh2z5Tl6.mjs → init-ByoeQphC.mjs} +528 -627
  75. package/dist/init-ByoeQphC.mjs.map +1 -0
  76. package/dist/{inspect-live-schema-CWLK_lgs.mjs → inspect-live-schema-B1Q49RF0.mjs} +4 -4
  77. package/dist/{inspect-live-schema-CWLK_lgs.mjs.map → inspect-live-schema-B1Q49RF0.mjs.map} +1 -1
  78. package/dist/{migration-command-scaffold-CmXXC1UZ.mjs → migration-command-scaffold-oY4P1Qto.mjs} +4 -4
  79. package/dist/{migration-command-scaffold-CmXXC1UZ.mjs.map → migration-command-scaffold-oY4P1Qto.mjs.map} +1 -1
  80. package/dist/{migration-plan-CHyUlBV0.mjs → migration-plan-jdAHg_gK.mjs} +349 -94
  81. package/dist/migration-plan-jdAHg_gK.mjs.map +1 -0
  82. package/dist/{migration-types-D2FW63pr.d.mts → migration-types-BXWvz12q.d.mts} +1 -1
  83. package/dist/{migration-types-D2FW63pr.d.mts.map → migration-types-BXWvz12q.d.mts.map} +1 -1
  84. package/dist/{migrations-DyUf5lTt.mjs → migrations-B7n518mT.mjs} +11 -2
  85. package/dist/migrations-B7n518mT.mjs.map +1 -0
  86. package/dist/{output-B60Gw5fu.mjs → output-CUIdfYo5.mjs} +1 -1
  87. package/dist/{output-B60Gw5fu.mjs.map → output-CUIdfYo5.mjs.map} +1 -1
  88. package/dist/quick-reference-mongo.md +1 -1
  89. package/dist/quick-reference-postgres.md +1 -1
  90. package/dist/readme-mongo.md +35 -0
  91. package/dist/readme-postgres.md +34 -0
  92. package/dist/ref-advancement-DRh5Nquq.mjs +50 -0
  93. package/dist/ref-advancement-DRh5Nquq.mjs.map +1 -0
  94. package/dist/{terminal-ui-XtOQsqe9.mjs → terminal-ui-BiB_8KNo.mjs} +131 -24
  95. package/dist/terminal-ui-BiB_8KNo.mjs.map +1 -0
  96. package/dist/{types-0aS865QN.d.mts → types-UWB2-rrw.d.mts} +12 -4
  97. package/dist/types-UWB2-rrw.d.mts.map +1 -0
  98. package/dist/{verify-D7ypCCe6.mjs → verify-C5UvbrF1.mjs} +2 -2
  99. package/dist/{verify-D7ypCCe6.mjs.map → verify-C5UvbrF1.mjs.map} +1 -1
  100. package/package.json +20 -18
  101. package/src/cli.ts +42 -0
  102. package/src/commands/contract-emit.ts +23 -11
  103. package/src/commands/contract-infer.ts +7 -7
  104. package/src/commands/db-init.ts +61 -7
  105. package/src/commands/db-schema.ts +4 -4
  106. package/src/commands/db-sign.ts +4 -4
  107. package/src/commands/db-update.ts +58 -5
  108. package/src/commands/db-verify.ts +5 -5
  109. package/src/commands/init/detect-package-manager.ts +15 -0
  110. package/src/commands/init/errors.ts +33 -2
  111. package/src/commands/init/hygiene-gitattributes.ts +2 -2
  112. package/src/commands/init/index.ts +15 -6
  113. package/src/commands/init/init.ts +61 -32
  114. package/src/commands/init/inputs.ts +82 -5
  115. package/src/commands/init/output.ts +1 -1
  116. package/src/commands/init/{agent-skill-install.ts → skill-install.ts} +42 -31
  117. package/src/commands/init/templates/code-templates.ts +26 -24
  118. package/src/commands/init/templates/env.ts +8 -1
  119. package/src/commands/init/templates/quick-reference-mongo.md +1 -1
  120. package/src/commands/init/templates/quick-reference-postgres.md +1 -1
  121. package/src/commands/init/templates/readme-mongo.md +35 -0
  122. package/src/commands/init/templates/readme-postgres.md +34 -0
  123. package/src/commands/init/templates/readme.ts +62 -0
  124. package/src/commands/migrate.ts +77 -10
  125. package/src/commands/migration-check.ts +4 -4
  126. package/src/commands/migration-graph.ts +4 -4
  127. package/src/commands/migration-list.ts +4 -4
  128. package/src/commands/migration-log.ts +6 -5
  129. package/src/commands/migration-new.ts +4 -4
  130. package/src/commands/migration-plan.ts +369 -132
  131. package/src/commands/migration-show.ts +4 -4
  132. package/src/commands/migration-status.ts +49 -6
  133. package/src/commands/ref.ts +54 -14
  134. package/src/control-api/operations/apply-aggregate.ts +1 -0
  135. package/src/control-api/operations/contract-emit.ts +7 -4
  136. package/src/control-api/types.ts +7 -0
  137. package/src/utils/cli-errors.ts +177 -0
  138. package/src/utils/command-helpers.ts +14 -6
  139. package/src/utils/formatters/migrations.ts +25 -0
  140. package/src/utils/global-flags.ts +105 -16
  141. package/src/utils/is-ci.ts +18 -0
  142. package/src/utils/plan-resolution.ts +257 -0
  143. package/src/utils/ref-advancement.ts +68 -0
  144. package/src/utils/telemetry.ts +141 -0
  145. package/src/utils/terminal-ui.ts +44 -23
  146. package/dist/cli-errors-CF60g2cG.mjs +0 -71
  147. package/dist/cli-errors-CF60g2cG.mjs.map +0 -1
  148. package/dist/cli-errors-DdcjVLJV.d.mts +0 -3
  149. package/dist/client-Brv4qlfB.mjs.map +0 -1
  150. package/dist/command-helpers-D3vL5yi8.mjs.map +0 -1
  151. package/dist/contract-emit-C3STUIBg.mjs.map +0 -1
  152. package/dist/contract-emit-iynA3BCA.mjs.map +0 -1
  153. package/dist/contract-infer-Cnj8G1E2.mjs.map +0 -1
  154. package/dist/db-verify-D7cyH_zz.mjs.map +0 -1
  155. package/dist/errors-Cw6kyTyV.mjs +0 -56
  156. package/dist/errors-Cw6kyTyV.mjs.map +0 -1
  157. package/dist/global-flags-DGmw6Kqg.d.mts.map +0 -1
  158. package/dist/helpers-eqdN8tH6.mjs +0 -25
  159. package/dist/helpers-eqdN8tH6.mjs.map +0 -1
  160. package/dist/init-eh2z5Tl6.mjs.map +0 -1
  161. package/dist/migration-plan-CHyUlBV0.mjs.map +0 -1
  162. package/dist/migrations-DyUf5lTt.mjs.map +0 -1
  163. package/dist/result-handler-Bm_6dDYg.mjs +0 -25
  164. package/dist/result-handler-Bm_6dDYg.mjs.map +0 -1
  165. package/dist/terminal-ui-XtOQsqe9.mjs.map +0 -1
  166. package/dist/types-0aS865QN.d.mts.map +0 -1
@@ -30,7 +30,7 @@ import { Command } from 'commander';
30
30
  import { loadConfig } from '../config-loader';
31
31
  import { createControlClient } from '../control-api/client';
32
32
  import {
33
- type CliStructuredError,
33
+ CliStructuredError,
34
34
  errorRuntime,
35
35
  errorUnexpected,
36
36
  mapMigrationToolsError,
@@ -65,10 +65,10 @@ import {
65
65
  } from '../utils/formatters/graph-render';
66
66
  import { formatStyledHeader } from '../utils/formatters/styled';
67
67
  import type { CommonCommandOptions } from '../utils/global-flags';
68
- import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
68
+ import { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';
69
69
  import type { StatusDiagnostic, StatusRef } from '../utils/migration-types';
70
70
  import { handleResult } from '../utils/result-handler';
71
- import { TerminalUI } from '../utils/terminal-ui';
71
+ import { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';
72
72
 
73
73
  interface MigrationStatusOptions extends CommonCommandOptions {
74
74
  readonly db?: string;
@@ -540,6 +540,40 @@ async function loadContractRawSafely(config: {
540
540
  }
541
541
  }
542
542
 
543
+ async function validateOnlineMarkerRead(
544
+ config: Awaited<ReturnType<typeof loadConfig>>,
545
+ dbConnection: unknown,
546
+ ): Promise<Result<void, CliStructuredError>> {
547
+ const driver = config.driver;
548
+ if (!driver) {
549
+ return ok(undefined);
550
+ }
551
+
552
+ const client = createControlClient({
553
+ family: config.family,
554
+ target: config.target,
555
+ adapter: config.adapter,
556
+ driver,
557
+ extensionPacks: config.extensionPacks ?? [],
558
+ });
559
+ try {
560
+ await client.connect(dbConnection);
561
+ await client.readMarker();
562
+ return ok(undefined);
563
+ } catch (error) {
564
+ if (CliStructuredError.is(error)) {
565
+ return notOk(error);
566
+ }
567
+ return notOk(
568
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
569
+ why: `Failed to read database marker: ${error instanceof Error ? error.message : String(error)}`,
570
+ }),
571
+ );
572
+ } finally {
573
+ await client.close();
574
+ }
575
+ }
576
+
543
577
  async function executeMigrationStatusCommand(
544
578
  options: MigrationStatusOptions,
545
579
  flags: GlobalFlags,
@@ -666,6 +700,12 @@ async function executeMigrationStatusCommand(
666
700
  }
667
701
 
668
702
  if (bundles.length === 0) {
703
+ if (dbConnection && hasDriver) {
704
+ const markerProbe = await validateOnlineMarkerRead(config, dbConnection);
705
+ if (!markerProbe.ok) {
706
+ return markerProbe;
707
+ }
708
+ }
669
709
  if (contractHash !== EMPTY_CONTRACT_HASH) {
670
710
  diagnostics.push({
671
711
  code: 'CONTRACT.AHEAD',
@@ -750,7 +790,10 @@ async function executeMigrationStatusCommand(
750
790
  // space has no marker", which is a different condition).
751
791
  allMarkers = null;
752
792
  }
753
- } catch {
793
+ } catch (error) {
794
+ if (CliStructuredError.is(error)) {
795
+ return notOk(error);
796
+ }
754
797
  if (!flags.json && !flags.quiet) {
755
798
  ui.warn('Could not connect to database — showing offline status');
756
799
  }
@@ -1097,8 +1140,8 @@ export function createMigrationStatusCommand(): Command {
1097
1140
  'Origin contract reference; same grammar as --to. Supplying --from switches to offline path computation.',
1098
1141
  )
1099
1142
  .action(async (options: MigrationStatusOptions) => {
1100
- const flags = parseGlobalFlags(options);
1101
- const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
1143
+ const flags = parseGlobalFlagsOrExit(options);
1144
+ const ui = createTerminalUI(flags);
1102
1145
 
1103
1146
  const result = await executeMigrationStatusCommand(options, flags, ui);
1104
1147
 
@@ -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,
@@ -25,9 +33,10 @@ import {
25
33
  setCommandDescriptions,
26
34
  } from '../utils/command-helpers';
27
35
  import { formatCommandHelp } from '../utils/formatters/help';
28
- import { parseGlobalFlags } from '../utils/global-flags';
36
+ import { parseGlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';
37
+ import { readContractIR } from '../utils/ref-advancement';
29
38
  import { handleResult } from '../utils/result-handler';
30
- import { TerminalUI } from '../utils/terminal-ui';
39
+ import { createTerminalUI } from '../utils/terminal-ui';
31
40
 
32
41
  interface RefSetResult {
33
42
  readonly ok: true;
@@ -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);
@@ -145,8 +185,8 @@ function createRefSetCommand(): Command {
145
185
  hash: string,
146
186
  options: { config?: string; json?: string | boolean; quiet?: boolean },
147
187
  ) => {
148
- const flags = parseGlobalFlags(options);
149
- const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
188
+ const flags = parseGlobalFlagsOrExit(options);
189
+ const ui = createTerminalUI(flags);
150
190
  const result = await executeRefSetCommand(name, hash, options);
151
191
  const exitCode = handleResult(result, flags, ui, (value) => {
152
192
  if (flags.json) {
@@ -172,8 +212,8 @@ function createRefDeleteCommand(): Command {
172
212
  name: string,
173
213
  options: { config?: string; json?: string | boolean; quiet?: boolean },
174
214
  ) => {
175
- const flags = parseGlobalFlags(options);
176
- const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
215
+ const flags = parseGlobalFlagsOrExit(options);
216
+ const ui = createTerminalUI(flags);
177
217
  const result = await executeRefDeleteCommand(name, options);
178
218
  const exitCode = handleResult(result, flags, ui, (value) => {
179
219
  if (flags.json) {
@@ -194,8 +234,8 @@ function createRefListCommand(): Command {
194
234
  addGlobalOptions(command)
195
235
  .option('--config <path>', 'Path to prisma-next.config.ts')
196
236
  .action(async (options: { config?: string; json?: string | boolean; quiet?: boolean }) => {
197
- const flags = parseGlobalFlags(options);
198
- const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
237
+ const flags = parseGlobalFlagsOrExit(options);
238
+ const ui = createTerminalUI(flags);
199
239
  const result = await executeRefListCommand(options);
200
240
  const exitCode = handleResult(result, flags, ui, (value) => {
201
241
  if (flags.json) {
@@ -178,6 +178,7 @@ export async function applyAggregate<TFamilyId extends string, TTargetId extends
178
178
  meta: {
179
179
  ...(runnerResult.failure.meta ?? {}),
180
180
  failingSpace: runnerResult.failure.failingSpace,
181
+ runnerErrorCode: runnerResult.failure.code,
181
182
  },
182
183
  });
183
184
  }
@@ -5,7 +5,7 @@ import { createControlStack } from '@prisma-next/framework-components/control';
5
5
  import { abortable } from '@prisma-next/utils/abortable';
6
6
  import { ifDefined } from '@prisma-next/utils/defined';
7
7
  import type { JsonObject } from '@prisma-next/utils/json';
8
- import { dirname } from 'pathe';
8
+ import { dirname, join } from 'pathe';
9
9
  import { loadConfig } from '../../config-loader';
10
10
  import { errorContractConfigMissing, errorRuntime } from '../../utils/cli-errors';
11
11
  import { queueEmitByOutput } from '../../utils/emit-queue';
@@ -153,7 +153,7 @@ function validateProviderResult(providerResult: unknown): ValidatedProviderResul
153
153
  export async function executeContractEmit(
154
154
  options: ContractEmitOptions,
155
155
  ): Promise<ContractEmitResult> {
156
- const { configPath, signal = new AbortController().signal, onProgress } = options;
156
+ const { configPath, outputPath, signal = new AbortController().signal, onProgress } = options;
157
157
  const unlessAborted = abortable(signal);
158
158
 
159
159
  const config = await unlessAborted(loadConfig(configPath));
@@ -166,7 +166,10 @@ export async function executeContractEmit(
166
166
 
167
167
  const contractConfig = config.contract;
168
168
 
169
- if (!contractConfig.output) {
169
+ const effectiveOutput =
170
+ outputPath !== undefined ? join(outputPath, 'contract.json') : contractConfig.output;
171
+
172
+ if (!effectiveOutput) {
170
173
  throw errorContractConfigMissing({
171
174
  why: 'Contract config must have output path. This should not happen if defineConfig() was used.',
172
175
  });
@@ -180,7 +183,7 @@ export async function executeContractEmit(
180
183
 
181
184
  let outputPaths: ReturnType<typeof getEmittedArtifactPaths>;
182
185
  try {
183
- outputPaths = getEmittedArtifactPaths(contractConfig.output);
186
+ outputPaths = getEmittedArtifactPaths(effectiveOutput);
184
187
  } catch (error) {
185
188
  throw errorContractConfigMissing({
186
189
  why: error instanceof Error ? error.message : String(error),
@@ -719,6 +719,13 @@ export type MigrationApplyResult = Result<MigrationApplySuccess, MigrationApplyF
719
719
  export interface ContractEmitOptions {
720
720
  /** Path to the prisma-next.config.ts file */
721
721
  readonly configPath: string;
722
+ /**
723
+ * Directory to write contract artifacts into. When set, `contract.json` and
724
+ * `contract.d.ts` are written inside this directory, taking precedence over
725
+ * any output path from the loaded config. The value must be an absolute path;
726
+ * resolution against cwd is the caller's responsibility.
727
+ */
728
+ readonly outputPath?: string;
722
729
  /** Optional AbortSignal for cancelling the in-flight emit */
723
730
  readonly signal?: AbortSignal;
724
731
  /** Optional progress callback for observing source-resolution and emit spans */
@@ -16,9 +16,11 @@ import {
16
16
  errorDriverRequired,
17
17
  errorFamilyReadMarkerSqlRequired,
18
18
  errorFileNotFound,
19
+ errorInvalidOutputFormat,
19
20
  errorMigrationCliInvalidConfigArg,
20
21
  errorMigrationCliUnknownFlag,
21
22
  errorMigrationPlanningFailed,
23
+ errorOutputFormatMutex,
22
24
  errorQueryRunnerFactoryRequired,
23
25
  errorTargetMigrationNotSupported,
24
26
  errorUnexpected,
@@ -26,6 +28,7 @@ import {
26
28
  import { errorRuntime } from '@prisma-next/errors/execution';
27
29
  import type { MigrationToolsError } from '@prisma-next/migration-tools/errors';
28
30
  import type { RefResolutionError } from '@prisma-next/migration-tools/ref-resolution';
31
+ import type { MigrationApplyFailure } from '../control-api/types';
29
32
 
30
33
  export {
31
34
  ERROR_CODE_DESTRUCTIVE_CHANGES,
@@ -56,14 +59,188 @@ export {
56
59
  errorDriverRequired,
57
60
  errorFamilyReadMarkerSqlRequired,
58
61
  errorFileNotFound,
62
+ errorInvalidOutputFormat,
59
63
  errorMigrationCliInvalidConfigArg,
60
64
  errorMigrationCliUnknownFlag,
61
65
  errorMigrationPlanningFailed,
66
+ errorOutputFormatMutex,
62
67
  errorQueryRunnerFactoryRequired,
63
68
  errorTargetMigrationNotSupported,
64
69
  errorUnexpected,
65
70
  };
66
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
+
67
244
  /**
68
245
  * Maps a `MigrationToolsError` raised by the migration-tools loader/graph
69
246
  * surface (`readMigrationPackage`, `readMigrationsDir`, `readRefs`,
@@ -11,6 +11,7 @@ import { APP_SPACE_ID, spaceMigrationDirectory } from '@prisma-next/migration-to
11
11
  import { ifDefined } from '@prisma-next/utils/defined';
12
12
  import type { Command } from 'commander';
13
13
  import { relative, resolve } from 'pathe';
14
+ import { errorRuntime } from './cli-errors';
14
15
  import { formatCommandHelp } from './formatters/help';
15
16
  import type { CommonCommandOptions } from './global-flags';
16
17
  import { parseGlobalFlags } from './global-flags';
@@ -94,12 +95,15 @@ export interface MigrationCommandOptions extends CommonCommandOptions {
94
95
 
95
96
  /**
96
97
  * Resolves the absolute path to contract.json from the config.
97
- * Centralises the fallback logic shared by every command that reads the contract.
98
98
  */
99
99
  export function resolveContractPath(config: { contract?: { output?: string } }): string {
100
- return config.contract?.output
101
- ? resolve(config.contract.output)
102
- : resolve('src/prisma/contract.json');
100
+ if (config.contract?.output === undefined) {
101
+ throw errorRuntime('config.contract.output is required to resolve the contract path', {
102
+ why: 'CLI commands read the emitted contract from config.contract.output; the config has no value to read.',
103
+ fix: 'Ensure your prisma-next.config.ts goes through `defineConfig()`, which normalises a default output when the provider supplies an input path, or set `contract.output` explicitly.',
104
+ });
105
+ }
106
+ return resolve(config.contract.output);
103
107
  }
104
108
 
105
109
  /**
@@ -365,7 +369,7 @@ export function sanitizeErrorMessage(message: string, connectionUrl?: string): s
365
369
 
366
370
  /**
367
371
  * Registers the global CLI options shared by every command:
368
- * --json, -q/--quiet, -v/--verbose, --trace, --color, --no-color,
372
+ * --format, --json, -q/--quiet, -v/--verbose, --trace, --color, --no-color,
369
373
  * --interactive, --no-interactive, -y/--yes.
370
374
  *
371
375
  * Also sets up the styled help formatter.
@@ -378,7 +382,11 @@ export function addGlobalOptions(command: Command): Command {
378
382
  return formatCommandHelp({ command: cmd, flags });
379
383
  },
380
384
  })
381
- .option('--json', 'Output as JSON')
385
+ .option(
386
+ '--format <pretty|json>',
387
+ 'Output format (default: pretty, or json when stdout is not a TTY)',
388
+ )
389
+ .option('--json', 'Output as JSON (alias for --format json)')
382
390
  .option('-q, --quiet', 'Quiet mode: errors only')
383
391
  .option('-v, --verbose', 'Verbose output: debug info, timings')
384
392
  .option('--trace', 'Trace output: deep internals, stack traces')
@@ -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');