@prisma-next/cli 0.3.0-dev.11 → 0.3.0-dev.113

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 (215) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +470 -134
  3. package/dist/cli-errors-ByGuoqNj.mjs +3 -0
  4. package/dist/cli-errors-D6HxRn3A.d.mts +2 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.js +1 -2350
  7. package/dist/cli.mjs +235 -0
  8. package/dist/cli.mjs.map +1 -0
  9. package/dist/client-612RJJD_.mjs +1069 -0
  10. package/dist/client-612RJJD_.mjs.map +1 -0
  11. package/dist/commands/contract-emit.d.mts +7 -0
  12. package/dist/commands/contract-emit.d.mts.map +1 -0
  13. package/dist/commands/contract-emit.mjs +4 -0
  14. package/dist/commands/contract-infer.d.mts +7 -0
  15. package/dist/commands/contract-infer.d.mts.map +1 -0
  16. package/dist/commands/contract-infer.mjs +4 -0
  17. package/dist/commands/db-init.d.mts +7 -0
  18. package/dist/commands/db-init.d.mts.map +1 -0
  19. package/dist/commands/db-init.mjs +124 -0
  20. package/dist/commands/db-init.mjs.map +1 -0
  21. package/dist/commands/db-schema.d.mts +7 -0
  22. package/dist/commands/db-schema.d.mts.map +1 -0
  23. package/dist/commands/db-schema.mjs +52 -0
  24. package/dist/commands/db-schema.mjs.map +1 -0
  25. package/dist/commands/db-sign.d.mts +7 -0
  26. package/dist/commands/db-sign.d.mts.map +1 -0
  27. package/dist/commands/db-sign.mjs +135 -0
  28. package/dist/commands/db-sign.mjs.map +1 -0
  29. package/dist/commands/db-update.d.mts +7 -0
  30. package/dist/commands/db-update.d.mts.map +1 -0
  31. package/dist/commands/db-update.mjs +121 -0
  32. package/dist/commands/db-update.mjs.map +1 -0
  33. package/dist/commands/db-verify.d.mts +7 -0
  34. package/dist/commands/db-verify.d.mts.map +1 -0
  35. package/dist/commands/db-verify.mjs +310 -0
  36. package/dist/commands/db-verify.mjs.map +1 -0
  37. package/dist/commands/migration-apply.d.mts +36 -0
  38. package/dist/commands/migration-apply.d.mts.map +1 -0
  39. package/dist/commands/migration-apply.mjs +240 -0
  40. package/dist/commands/migration-apply.mjs.map +1 -0
  41. package/dist/commands/migration-plan.d.mts +47 -0
  42. package/dist/commands/migration-plan.d.mts.map +1 -0
  43. package/dist/commands/migration-plan.mjs +288 -0
  44. package/dist/commands/migration-plan.mjs.map +1 -0
  45. package/dist/commands/migration-ref.d.mts +43 -0
  46. package/dist/commands/migration-ref.d.mts.map +1 -0
  47. package/dist/commands/migration-ref.mjs +194 -0
  48. package/dist/commands/migration-ref.mjs.map +1 -0
  49. package/dist/commands/migration-show.d.mts +28 -0
  50. package/dist/commands/migration-show.d.mts.map +1 -0
  51. package/dist/commands/migration-show.mjs +139 -0
  52. package/dist/commands/migration-show.mjs.map +1 -0
  53. package/dist/commands/migration-status.d.mts +85 -0
  54. package/dist/commands/migration-status.d.mts.map +1 -0
  55. package/dist/commands/migration-status.mjs +4 -0
  56. package/dist/commands/migration-verify.d.mts +16 -0
  57. package/dist/commands/migration-verify.d.mts.map +1 -0
  58. package/dist/commands/migration-verify.mjs +87 -0
  59. package/dist/commands/migration-verify.mjs.map +1 -0
  60. package/dist/config-loader-d_KF19Tw.mjs +43 -0
  61. package/dist/config-loader-d_KF19Tw.mjs.map +1 -0
  62. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  63. package/dist/config-loader.d.mts.map +1 -0
  64. package/dist/config-loader.mjs +3 -0
  65. package/dist/contract-emit-CVv7dbQ9.mjs +187 -0
  66. package/dist/contract-emit-CVv7dbQ9.mjs.map +1 -0
  67. package/dist/contract-infer-Bvw8u8Eu.mjs +83 -0
  68. package/dist/contract-infer-Bvw8u8Eu.mjs.map +1 -0
  69. package/dist/exports/config-types.d.mts +2 -0
  70. package/dist/exports/config-types.mjs +3 -0
  71. package/dist/exports/control-api.d.mts +626 -0
  72. package/dist/exports/control-api.d.mts.map +1 -0
  73. package/dist/exports/control-api.mjs +107 -0
  74. package/dist/exports/control-api.mjs.map +1 -0
  75. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  76. package/dist/exports/index.d.mts.map +1 -0
  77. package/dist/exports/index.mjs +130 -0
  78. package/dist/exports/index.mjs.map +1 -0
  79. package/dist/extract-sql-ddl-Jf5blEO0.mjs +26 -0
  80. package/dist/extract-sql-ddl-Jf5blEO0.mjs.map +1 -0
  81. package/dist/framework-components-M2j-qPfr.mjs +59 -0
  82. package/dist/framework-components-M2j-qPfr.mjs.map +1 -0
  83. package/dist/inspect-live-schema-BQe5i4YE.mjs +90 -0
  84. package/dist/inspect-live-schema-BQe5i4YE.mjs.map +1 -0
  85. package/dist/migration-command-scaffold-SLrjcKXS.mjs +104 -0
  86. package/dist/migration-command-scaffold-SLrjcKXS.mjs.map +1 -0
  87. package/dist/migration-status-DAQKsmWW.mjs +1576 -0
  88. package/dist/migration-status-DAQKsmWW.mjs.map +1 -0
  89. package/dist/migrations-Db_ea9eE.mjs +173 -0
  90. package/dist/migrations-Db_ea9eE.mjs.map +1 -0
  91. package/dist/progress-adapter-DRNe2idZ.mjs +43 -0
  92. package/dist/progress-adapter-DRNe2idZ.mjs.map +1 -0
  93. package/dist/terminal-ui-DAcMBRKf.mjs +980 -0
  94. package/dist/terminal-ui-DAcMBRKf.mjs.map +1 -0
  95. package/dist/verify-DXKxBFvU.mjs +385 -0
  96. package/dist/verify-DXKxBFvU.mjs.map +1 -0
  97. package/package.json +88 -43
  98. package/src/cli.ts +109 -58
  99. package/src/commands/contract-emit.ts +236 -143
  100. package/src/commands/contract-infer-paths.ts +32 -0
  101. package/src/commands/contract-infer.ts +131 -0
  102. package/src/commands/db-init.ts +211 -425
  103. package/src/commands/db-schema.ts +77 -0
  104. package/src/commands/db-sign.ts +207 -228
  105. package/src/commands/db-update.ts +236 -0
  106. package/src/commands/db-verify.ts +484 -186
  107. package/src/commands/inspect-live-schema.ts +171 -0
  108. package/src/commands/migration-apply.ts +416 -0
  109. package/src/commands/migration-plan.ts +451 -0
  110. package/src/commands/migration-ref.ts +305 -0
  111. package/src/commands/migration-show.ts +246 -0
  112. package/src/commands/migration-status.ts +838 -0
  113. package/src/commands/migration-verify.ts +134 -0
  114. package/src/config-loader.ts +13 -3
  115. package/src/control-api/client.ts +614 -0
  116. package/src/control-api/contract-enrichment.ts +135 -0
  117. package/src/control-api/errors.ts +9 -0
  118. package/src/control-api/operations/contract-emit.ts +173 -0
  119. package/src/control-api/operations/db-init.ts +286 -0
  120. package/src/control-api/operations/db-update.ts +221 -0
  121. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  122. package/src/control-api/operations/migration-apply.ts +194 -0
  123. package/src/control-api/operations/migration-helpers.ts +49 -0
  124. package/src/control-api/types.ts +683 -0
  125. package/src/exports/config-types.ts +4 -3
  126. package/src/exports/control-api.ts +56 -0
  127. package/src/load-ts-contract.ts +16 -11
  128. package/src/utils/cli-errors.ts +5 -2
  129. package/src/utils/command-helpers.ts +293 -3
  130. package/src/utils/formatters/emit.ts +67 -0
  131. package/src/utils/formatters/errors.ts +82 -0
  132. package/src/utils/formatters/graph-migration-mapper.ts +220 -0
  133. package/src/utils/formatters/graph-render.ts +1317 -0
  134. package/src/utils/formatters/graph-types.ts +114 -0
  135. package/src/utils/formatters/help.ts +380 -0
  136. package/src/utils/formatters/helpers.ts +28 -0
  137. package/src/utils/formatters/migrations.ts +346 -0
  138. package/src/utils/formatters/styled.ts +212 -0
  139. package/src/utils/formatters/verify.ts +620 -0
  140. package/src/utils/global-flags.ts +41 -23
  141. package/src/utils/migration-command-scaffold.ts +187 -0
  142. package/src/utils/migration-types.ts +12 -0
  143. package/src/utils/progress-adapter.ts +75 -0
  144. package/src/utils/result-handler.ts +12 -13
  145. package/src/utils/shutdown.ts +92 -0
  146. package/src/utils/suggest-command.ts +31 -0
  147. package/src/utils/terminal-ui.ts +276 -0
  148. package/dist/chunk-BZMBKEEQ.js +0 -997
  149. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  150. package/dist/chunk-CVNWLFXO.js +0 -91
  151. package/dist/chunk-CVNWLFXO.js.map +0 -1
  152. package/dist/chunk-HWYQOCAJ.js +0 -47
  153. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  154. package/dist/chunk-QUPBU4KV.js +0 -131
  155. package/dist/chunk-QUPBU4KV.js.map +0 -1
  156. package/dist/cli.d.ts +0 -2
  157. package/dist/cli.d.ts.map +0 -1
  158. package/dist/cli.js.map +0 -1
  159. package/dist/commands/contract-emit.d.ts +0 -3
  160. package/dist/commands/contract-emit.d.ts.map +0 -1
  161. package/dist/commands/contract-emit.js +0 -9
  162. package/dist/commands/contract-emit.js.map +0 -1
  163. package/dist/commands/db-init.d.ts +0 -3
  164. package/dist/commands/db-init.d.ts.map +0 -1
  165. package/dist/commands/db-init.js +0 -337
  166. package/dist/commands/db-init.js.map +0 -1
  167. package/dist/commands/db-introspect.d.ts +0 -3
  168. package/dist/commands/db-introspect.d.ts.map +0 -1
  169. package/dist/commands/db-introspect.js +0 -186
  170. package/dist/commands/db-introspect.js.map +0 -1
  171. package/dist/commands/db-schema-verify.d.ts +0 -3
  172. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  173. package/dist/commands/db-schema-verify.js +0 -160
  174. package/dist/commands/db-schema-verify.js.map +0 -1
  175. package/dist/commands/db-sign.d.ts +0 -3
  176. package/dist/commands/db-sign.d.ts.map +0 -1
  177. package/dist/commands/db-sign.js +0 -195
  178. package/dist/commands/db-sign.js.map +0 -1
  179. package/dist/commands/db-verify.d.ts +0 -3
  180. package/dist/commands/db-verify.d.ts.map +0 -1
  181. package/dist/commands/db-verify.js +0 -169
  182. package/dist/commands/db-verify.js.map +0 -1
  183. package/dist/config-loader.d.ts.map +0 -1
  184. package/dist/config-loader.js +0 -7
  185. package/dist/config-loader.js.map +0 -1
  186. package/dist/exports/config-types.d.ts +0 -3
  187. package/dist/exports/config-types.d.ts.map +0 -1
  188. package/dist/exports/config-types.js +0 -6
  189. package/dist/exports/config-types.js.map +0 -1
  190. package/dist/exports/index.d.ts +0 -4
  191. package/dist/exports/index.d.ts.map +0 -1
  192. package/dist/exports/index.js +0 -175
  193. package/dist/exports/index.js.map +0 -1
  194. package/dist/load-ts-contract.d.ts.map +0 -1
  195. package/dist/utils/action.d.ts +0 -16
  196. package/dist/utils/action.d.ts.map +0 -1
  197. package/dist/utils/cli-errors.d.ts +0 -7
  198. package/dist/utils/cli-errors.d.ts.map +0 -1
  199. package/dist/utils/command-helpers.d.ts +0 -12
  200. package/dist/utils/command-helpers.d.ts.map +0 -1
  201. package/dist/utils/framework-components.d.ts +0 -70
  202. package/dist/utils/framework-components.d.ts.map +0 -1
  203. package/dist/utils/global-flags.d.ts +0 -25
  204. package/dist/utils/global-flags.d.ts.map +0 -1
  205. package/dist/utils/output.d.ts +0 -142
  206. package/dist/utils/output.d.ts.map +0 -1
  207. package/dist/utils/result-handler.d.ts +0 -15
  208. package/dist/utils/result-handler.d.ts.map +0 -1
  209. package/dist/utils/spinner.d.ts +0 -29
  210. package/dist/utils/spinner.d.ts.map +0 -1
  211. package/src/commands/db-introspect.ts +0 -256
  212. package/src/commands/db-schema-verify.ts +0 -232
  213. package/src/utils/action.ts +0 -43
  214. package/src/utils/output.ts +0 -1471
  215. package/src/utils/spinner.ts +0 -67
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Programmatic Control API for Prisma Next.
3
+ *
4
+ * This module exports the control client factory and types for programmatic
5
+ * access to control-plane operations without using the CLI.
6
+ *
7
+ * @see README.md "Programmatic Control API" section for usage examples
8
+ * @module
9
+ */
10
+
11
+ // Re-export core control plane types for consumer convenience
12
+ export type {
13
+ ControlPlaneStack,
14
+ SignDatabaseResult,
15
+ VerifyDatabaseResult,
16
+ VerifyDatabaseSchemaResult,
17
+ } from '@prisma-next/core-control-plane/types';
18
+ // Client factory
19
+ export { createControlClient } from '../control-api/client';
20
+
21
+ // Contract enrichment (merges framework-derived capabilities and extension pack metadata into IR)
22
+ export { enrichContractIR } from '../control-api/contract-enrichment';
23
+
24
+ // Standalone operations (for tooling that doesn't need full client)
25
+ export { executeContractEmit } from '../control-api/operations/contract-emit';
26
+
27
+ // CLI-specific types
28
+ export type {
29
+ ContractEmitOptions,
30
+ ContractEmitResult,
31
+ ControlActionName,
32
+ ControlClient,
33
+ ControlClientOptions,
34
+ ControlProgressEvent,
35
+ DbInitFailure,
36
+ DbInitFailureCode,
37
+ DbInitOptions,
38
+ DbInitResult,
39
+ DbInitSuccess,
40
+ DbUpdateFailure,
41
+ DbUpdateFailureCode,
42
+ DbUpdateOptions,
43
+ DbUpdateResult,
44
+ DbUpdateSuccess,
45
+ EmitContractConfig,
46
+ EmitFailure,
47
+ EmitFailureCode,
48
+ EmitOptions,
49
+ EmitResult,
50
+ EmitSuccess,
51
+ IntrospectOptions,
52
+ OnControlProgress,
53
+ SchemaVerifyOptions,
54
+ SignOptions,
55
+ VerifyOptions,
56
+ } from '../control-api/types';
@@ -30,26 +30,31 @@ function validatePurity(value: unknown): void {
30
30
  return;
31
31
  }
32
32
 
33
- const seen = new WeakSet();
33
+ const path = new WeakSet();
34
+
34
35
  function check(value: unknown): void {
35
36
  if (value === null || typeof value !== 'object') {
36
37
  return;
37
38
  }
38
39
 
39
- if (seen.has(value)) {
40
+ if (path.has(value)) {
40
41
  throw new Error('Contract export contains circular references');
41
42
  }
42
- seen.add(value);
43
+ path.add(value);
43
44
 
44
- for (const key in value) {
45
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
46
- if (descriptor && (descriptor.get || descriptor.set)) {
47
- throw new Error(`Contract export contains getter/setter at key "${key}"`);
48
- }
49
- if (descriptor && typeof descriptor.value === 'function') {
50
- throw new Error(`Contract export contains function at key "${key}"`);
45
+ try {
46
+ for (const key in value) {
47
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
48
+ if (descriptor && (descriptor.get || descriptor.set)) {
49
+ throw new Error(`Contract export contains getter/setter at key "${key}"`);
50
+ }
51
+ if (descriptor && typeof descriptor.value === 'function') {
52
+ throw new Error(`Contract export contains function at key "${key}"`);
53
+ }
54
+ check((value as Record<string, unknown>)[key]);
51
55
  }
52
- check((value as Record<string, unknown>)[key]);
56
+ } finally {
57
+ path.delete(value);
53
58
  }
54
59
  }
55
60
 
@@ -5,21 +5,24 @@
5
5
  export type { CliErrorConflict, CliErrorEnvelope } from '@prisma-next/core-control-plane/errors';
6
6
  export {
7
7
  CliStructuredError,
8
+ ERROR_CODE_DESTRUCTIVE_CHANGES,
8
9
  errorConfigFileNotFound,
9
10
  errorConfigValidation,
10
11
  errorContractConfigMissing,
11
12
  errorContractMissingExtensionPacks,
12
13
  errorContractValidationFailed,
13
- errorDatabaseUrlRequired,
14
+ errorDatabaseConnectionRequired,
15
+ errorDestructiveChanges,
14
16
  errorDriverRequired,
15
17
  errorFamilyReadMarkerSqlRequired,
16
18
  errorFileNotFound,
17
19
  errorHashMismatch,
18
- errorJsonFormatNotSupported,
19
20
  errorMarkerMissing,
20
21
  errorMigrationPlanningFailed,
21
22
  errorQueryRunnerFactoryRequired,
23
+ errorRunnerFailed,
22
24
  errorRuntime,
25
+ errorSchemaVerificationFailed,
23
26
  errorTargetMigrationNotSupported,
24
27
  errorTargetMismatch,
25
28
  errorUnexpected,
@@ -1,4 +1,19 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import type { ControlTargetDescriptor } from '@prisma-next/core-control-plane/types';
3
+ import type { PathDecision } from '@prisma-next/migration-tools/dag';
4
+ import { reconstructGraph } from '@prisma-next/migration-tools/dag';
5
+ import { readMigrationsDir } from '@prisma-next/migration-tools/io';
6
+ import type { AttestedMigrationBundle, MigrationGraph } from '@prisma-next/migration-tools/types';
7
+ import { isAttested } from '@prisma-next/migration-tools/types';
8
+ import { ifDefined } from '@prisma-next/utils/defined';
1
9
  import type { Command } from 'commander';
10
+ import { relative, resolve } from 'pathe';
11
+ import { formatCommandHelp } from './formatters/help';
12
+ import type { CommonCommandOptions } from './global-flags';
13
+ import { parseGlobalFlags } from './global-flags';
14
+
15
+ const longDescriptions = new WeakMap<Command, string>();
16
+ const commandExamples = new WeakMap<Command, readonly string[]>();
2
17
 
3
18
  /**
4
19
  * Sets both short and long descriptions for a command.
@@ -12,15 +27,290 @@ export function setCommandDescriptions(
12
27
  ): Command {
13
28
  command.description(shortDescription);
14
29
  if (longDescription) {
15
- // Store long description in a custom property for our formatters to access
16
- (command as Command & { _longDescription?: string })._longDescription = longDescription;
30
+ longDescriptions.set(command, longDescription);
17
31
  }
18
32
  return command;
19
33
  }
20
34
 
35
+ /**
36
+ * Sets copy-pastable examples for a command, shown in help text.
37
+ */
38
+ export function setCommandExamples(command: Command, examples: readonly string[]): Command {
39
+ commandExamples.set(command, examples);
40
+ return command;
41
+ }
42
+
21
43
  /**
22
44
  * Gets the long description from a command if it was set via setCommandDescriptions.
23
45
  */
24
46
  export function getLongDescription(command: Command): string | undefined {
25
- return (command as Command & { _longDescription?: string })._longDescription;
47
+ return longDescriptions.get(command);
48
+ }
49
+
50
+ /**
51
+ * Gets examples from a command if set via setCommandExamples.
52
+ */
53
+ export function getCommandExamples(command: Command): readonly string[] | undefined {
54
+ return commandExamples.get(command);
55
+ }
56
+
57
+ /**
58
+ * Shared CLI options interface for migration commands (db init, db update).
59
+ * These are the Commander.js parsed options common to both commands.
60
+ */
61
+ export interface MigrationCommandOptions extends CommonCommandOptions {
62
+ readonly db?: string;
63
+ readonly config?: string;
64
+ readonly dryRun?: boolean;
65
+ }
66
+
67
+ /**
68
+ * Resolves the absolute path to contract.json from the config.
69
+ * Centralises the fallback logic shared by every command that reads the contract.
70
+ */
71
+ export function resolveContractPath(config: { contract?: { output?: string } }): string {
72
+ return config.contract?.output
73
+ ? resolve(config.contract.output)
74
+ : resolve('src/prisma/contract.json');
75
+ }
76
+
77
+ /**
78
+ * Resolves the migrations directory and config path from CLI options.
79
+ * Shared by migration-apply, migration-plan, and migration-status.
80
+ */
81
+ export function resolveMigrationPaths(
82
+ configOption: string | undefined,
83
+ config: { migrations?: { dir?: string } },
84
+ ): {
85
+ configPath: string;
86
+ migrationsDir: string;
87
+ migrationsRelative: string;
88
+ refsPath: string;
89
+ } {
90
+ const configPath = configOption
91
+ ? relative(process.cwd(), resolve(configOption))
92
+ : 'prisma-next.config.ts';
93
+ const migrationsDir = resolve(
94
+ configOption ? resolve(configOption, '..') : process.cwd(),
95
+ config.migrations?.dir ?? 'migrations',
96
+ );
97
+ const migrationsRelative = relative(process.cwd(), migrationsDir);
98
+ const refsPath = resolve(migrationsDir, 'refs.json');
99
+ return { configPath, migrationsDir, migrationsRelative, refsPath };
100
+ }
101
+
102
+ /**
103
+ * Slim representation of a PathDecision for CLI JSON output.
104
+ * Strips internal fields (createdAt, labels) from chain entries.
105
+ */
106
+ export interface PathDecisionResult {
107
+ readonly fromHash: string;
108
+ readonly toHash: string;
109
+ readonly alternativeCount: number;
110
+ readonly tieBreakReasons: readonly string[];
111
+ readonly refName?: string;
112
+ readonly selectedPath: readonly {
113
+ readonly dirName: string;
114
+ readonly migrationId: string;
115
+ readonly from: string;
116
+ readonly to: string;
117
+ }[];
118
+ }
119
+
120
+ /**
121
+ * Maps a PathDecision to the slim CLI output representation.
122
+ */
123
+ export function toPathDecisionResult(decision: PathDecision): PathDecisionResult {
124
+ return {
125
+ fromHash: decision.fromHash,
126
+ toHash: decision.toHash,
127
+ alternativeCount: decision.alternativeCount,
128
+ tieBreakReasons: decision.tieBreakReasons,
129
+ ...ifDefined('refName', decision.refName),
130
+ selectedPath: decision.selectedPath.map((entry) => ({
131
+ dirName: entry.dirName,
132
+ migrationId: entry.migrationId,
133
+ from: entry.from,
134
+ to: entry.to,
135
+ })),
136
+ };
137
+ }
138
+
139
+ /**
140
+ * Checks whether a target descriptor supports migrations.
141
+ *
142
+ * The config-level `ControlTargetDescriptor` (from `@prisma-next/config`) does not include
143
+ * `migrations` — that property lives on the migration-control-plane's version of the same
144
+ * interface. At runtime the postgres target descriptor *does* carry `migrations`, so we
145
+ * widen to the migration-aware descriptor and check the optional property directly.
146
+ */
147
+ export function targetSupportsMigrations(target: ControlTargetDescriptor<string, string>): boolean {
148
+ return !!target.migrations;
149
+ }
150
+
151
+ /**
152
+ * Extracts the typed migrations capability from a target descriptor.
153
+ * Returns `undefined` when the target does not support migrations.
154
+ */
155
+ export function getTargetMigrations(target: ControlTargetDescriptor<string, string>) {
156
+ return target.migrations;
157
+ }
158
+
159
+ /**
160
+ * Reads the migrations directory, filters to attested bundles, and builds
161
+ * the migration graph. Throws on I/O or graph errors — callers handle
162
+ * error mapping.
163
+ */
164
+ export async function loadMigrationBundles(migrationsDir: string): Promise<{
165
+ bundles: readonly AttestedMigrationBundle[];
166
+ graph: MigrationGraph;
167
+ }> {
168
+ const allBundles = await readMigrationsDir(migrationsDir);
169
+ const bundles = allBundles.filter(isAttested);
170
+ const graph = reconstructGraph(bundles);
171
+ return { bundles, graph };
172
+ }
173
+
174
+ /**
175
+ * The subset of the emitted contract.json that the framework layer can
176
+ * safely type. The emitter adds these fields on top of the family-specific
177
+ * storage/models/relations. Other fields exist in the JSON but are opaque
178
+ * at this layer — the index signature preserves them for downstream
179
+ * consumers that operate at the family level (e.g., the control client).
180
+ */
181
+ export interface ContractEnvelope {
182
+ readonly storageHash: string;
183
+ readonly schemaVersion: string;
184
+ readonly target: string;
185
+ readonly targetFamily: string;
186
+ readonly profileHash?: string;
187
+ readonly [key: string]: unknown;
188
+ }
189
+
190
+ /**
191
+ * Reads and parses contract.json, validating the framework-level envelope
192
+ * fields (storageHash, schemaVersion, target, targetFamily).
193
+ *
194
+ * Family-specific validation (storage structure, codec mappings, etc.)
195
+ * happens downstream in the control client via the family instance.
196
+ */
197
+ export async function readContractEnvelope(config: {
198
+ contract?: { output?: string };
199
+ }): Promise<ContractEnvelope> {
200
+ const contractPath = resolveContractPath(config);
201
+ const content = await readFile(contractPath, 'utf-8');
202
+ const json = JSON.parse(content) as Record<string, unknown>;
203
+
204
+ const { storageHash, schemaVersion, target, targetFamily, profileHash } = json;
205
+
206
+ if (typeof storageHash !== 'string') {
207
+ throw new Error(
208
+ `Contract at ${relative(process.cwd(), contractPath)} is missing a valid storageHash. Run \`prisma-next contract emit\` to regenerate.`,
209
+ );
210
+ }
211
+ if (typeof schemaVersion !== 'string') {
212
+ throw new Error(
213
+ `Contract at ${relative(process.cwd(), contractPath)} is missing schemaVersion.`,
214
+ );
215
+ }
216
+ if (typeof target !== 'string') {
217
+ throw new Error(`Contract at ${relative(process.cwd(), contractPath)} is missing target.`);
218
+ }
219
+ if (typeof targetFamily !== 'string') {
220
+ throw new Error(
221
+ `Contract at ${relative(process.cwd(), contractPath)} is missing targetFamily.`,
222
+ );
223
+ }
224
+
225
+ return {
226
+ ...json,
227
+ storageHash,
228
+ schemaVersion,
229
+ target,
230
+ targetFamily,
231
+ ...(typeof profileHash === 'string' ? { profileHash } : {}),
232
+ };
233
+ }
234
+
235
+ /**
236
+ * Masks credentials in a database connection URL.
237
+ * Handles standard URLs (username + password + query params) and libpq-style key=value strings.
238
+ */
239
+ export function maskConnectionUrl(url: string): string {
240
+ try {
241
+ const parsed = new URL(url);
242
+ if (parsed.username) {
243
+ parsed.username = '****';
244
+ }
245
+ if (parsed.password) {
246
+ parsed.password = '****';
247
+ }
248
+ // Also mask password in query parameters (e.g., ?password=secret, ?sslpassword=secret)
249
+ for (const key of [...parsed.searchParams.keys()]) {
250
+ if (/password/i.test(key)) {
251
+ parsed.searchParams.set(key, '****');
252
+ }
253
+ }
254
+ return parsed.toString();
255
+ } catch {
256
+ // Fallback for libpq-style key=value connection strings (e.g., "host=localhost password=secret user=admin")
257
+ return url
258
+ .replace(/password\s*=\s*\S+/gi, 'password=****')
259
+ .replace(/user\s*=\s*\S+/gi, 'user=****');
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Strips raw connection URL fragments from an error message to prevent credential leakage.
265
+ * Call this before surfacing driver errors to the user.
266
+ */
267
+ export function sanitizeErrorMessage(message: string, connectionUrl?: string): string {
268
+ if (!connectionUrl) {
269
+ return message;
270
+ }
271
+ try {
272
+ const parsed = new URL(connectionUrl);
273
+ // Replace the full URL (with and without trailing slash)
274
+ let sanitized = message;
275
+ sanitized = sanitized.replaceAll(connectionUrl, maskConnectionUrl(connectionUrl));
276
+ // Also replace the password and username individually if they appear
277
+ if (parsed.password) {
278
+ sanitized = sanitized.replaceAll(parsed.password, '****');
279
+ }
280
+ if (parsed.username) {
281
+ sanitized = sanitized.replaceAll(parsed.username, '****');
282
+ }
283
+ return sanitized;
284
+ } catch {
285
+ // For libpq-style strings, mask password and user values in the message
286
+ return message
287
+ .replace(/password\s*=\s*\S+/gi, 'password=****')
288
+ .replace(/user\s*=\s*\S+/gi, 'user=****');
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Registers the global CLI options shared by every command:
294
+ * --json, -q/--quiet, -v/--verbose, --trace, --color, --no-color,
295
+ * --interactive, --no-interactive, -y/--yes.
296
+ *
297
+ * Also sets up the styled help formatter.
298
+ */
299
+ export function addGlobalOptions(command: Command): Command {
300
+ return command
301
+ .configureHelp({
302
+ formatHelp: (cmd) => {
303
+ const flags = parseGlobalFlags({});
304
+ return formatCommandHelp({ command: cmd, flags });
305
+ },
306
+ })
307
+ .option('--json', 'Output as JSON')
308
+ .option('-q, --quiet', 'Quiet mode: errors only')
309
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
310
+ .option('--trace', 'Trace output: deep internals, stack traces')
311
+ .option('--color', 'Force color output')
312
+ .option('--no-color', 'Disable color output')
313
+ .option('--interactive', 'Force interactive mode')
314
+ .option('--no-interactive', 'Disable interactive prompts')
315
+ .option('-y, --yes', 'Auto-accept prompts');
26
316
  }
@@ -0,0 +1,67 @@
1
+ import { ifDefined } from '@prisma-next/utils/defined';
2
+ import { relative } from 'pathe';
3
+
4
+ import type { GlobalFlags } from '../global-flags';
5
+ import { isVerbose } from './helpers';
6
+
7
+ // EmitContractResult type for CLI output formatting (includes file paths)
8
+ export interface EmitContractResult {
9
+ readonly storageHash: string;
10
+ readonly executionHash?: string;
11
+ readonly profileHash: string;
12
+ readonly outDir: string;
13
+ readonly files: {
14
+ readonly json: string;
15
+ readonly dts: string;
16
+ };
17
+ readonly timings: {
18
+ readonly total: number;
19
+ };
20
+ }
21
+
22
+ /**
23
+ * Formats human-readable output for contract emit.
24
+ */
25
+ export function formatEmitOutput(result: EmitContractResult, flags: GlobalFlags): string {
26
+ if (flags.quiet) {
27
+ return '';
28
+ }
29
+
30
+ const lines: string[] = [];
31
+
32
+ // Convert absolute paths to relative paths from cwd
33
+ const jsonPath = relative(process.cwd(), result.files.json);
34
+ const dtsPath = relative(process.cwd(), result.files.dts);
35
+
36
+ lines.push(`✔ Emitted contract.json → ${jsonPath}`);
37
+ lines.push(`✔ Emitted contract.d.ts → ${dtsPath}`);
38
+ lines.push(` storageHash: ${result.storageHash}`);
39
+ if (result.executionHash) {
40
+ lines.push(` executionHash: ${result.executionHash}`);
41
+ }
42
+ if (result.profileHash) {
43
+ lines.push(` profileHash: ${result.profileHash}`);
44
+ }
45
+ if (isVerbose(flags, 1)) {
46
+ lines.push(` Total time: ${result.timings.total}ms`);
47
+ }
48
+
49
+ return lines.join('\n');
50
+ }
51
+
52
+ /**
53
+ * Formats JSON output for contract emit.
54
+ */
55
+ export function formatEmitJson(result: EmitContractResult): string {
56
+ const output = {
57
+ ok: true,
58
+ storageHash: result.storageHash,
59
+ ...ifDefined('executionHash', result.executionHash),
60
+ ...(result.profileHash ? { profileHash: result.profileHash } : {}),
61
+ outDir: result.outDir,
62
+ files: result.files,
63
+ timings: result.timings,
64
+ };
65
+
66
+ return JSON.stringify(output, null, 2);
67
+ }
@@ -0,0 +1,82 @@
1
+ import { red } from 'colorette';
2
+
3
+ import type { CliErrorConflict, CliErrorEnvelope } from '../cli-errors';
4
+ import type { GlobalFlags } from '../global-flags';
5
+ import { createColorFormatter, formatDim, isVerbose } from './helpers';
6
+
7
+ /**
8
+ * Formats error output for human-readable display.
9
+ */
10
+ export function formatErrorOutput(error: CliErrorEnvelope, flags: GlobalFlags): string {
11
+ const lines: string[] = [];
12
+
13
+ const useColor = flags.color !== false;
14
+ const formatRed = createColorFormatter(useColor, red);
15
+ const formatDimText = (text: string) => formatDim(useColor, text);
16
+
17
+ lines.push(`${formatRed('✖')} ${error.summary} (${error.code})`);
18
+
19
+ if (error.why) {
20
+ lines.push(`${formatDimText(` Why: ${error.why}`)}`);
21
+ }
22
+ if (error.fix) {
23
+ lines.push(`${formatDimText(` Fix: ${error.fix}`)}`);
24
+ }
25
+ if (error.where?.path) {
26
+ const whereLine = error.where.line
27
+ ? `${error.where.path}:${error.where.line}`
28
+ : error.where.path;
29
+ lines.push(`${formatDimText(` Where: ${whereLine}`)}`);
30
+ }
31
+ // Show conflicts list if present (always show a short list; show full list when verbose)
32
+ if (error.meta?.['conflicts']) {
33
+ const conflicts = error.meta['conflicts'] as readonly CliErrorConflict[];
34
+ if (conflicts.length > 0) {
35
+ const maxToShow = isVerbose(flags, 1) ? conflicts.length : Math.min(3, conflicts.length);
36
+ const header = isVerbose(flags, 1)
37
+ ? ' Conflicts:'
38
+ : ` Conflicts (showing ${maxToShow} of ${conflicts.length}):`;
39
+ lines.push(`${formatDimText(header)}`);
40
+ for (const conflict of conflicts.slice(0, maxToShow)) {
41
+ lines.push(`${formatDimText(` - [${conflict.kind}] ${conflict.summary}`)}`);
42
+ }
43
+ if (!isVerbose(flags, 1) && conflicts.length > maxToShow) {
44
+ lines.push(`${formatDimText(' Re-run with -v/--verbose to see all conflicts')}`);
45
+ }
46
+ }
47
+ }
48
+ // Show issues list if present (always show a short list; show full list when verbose)
49
+ if (error.meta?.['issues']) {
50
+ const issues = error.meta['issues'] as readonly { kind?: string; message?: string }[];
51
+ if (issues.length > 0) {
52
+ const maxToShow = isVerbose(flags, 1) ? issues.length : Math.min(3, issues.length);
53
+ const header = isVerbose(flags, 1)
54
+ ? ' Issues:'
55
+ : ` Issues (showing ${maxToShow} of ${issues.length}):`;
56
+ lines.push(`${formatDimText(header)}`);
57
+ for (const issue of issues.slice(0, maxToShow)) {
58
+ const kind = issue.kind ?? 'issue';
59
+ const message = issue.message ?? '';
60
+ lines.push(`${formatDimText(` - [${kind}] ${message}`)}`);
61
+ }
62
+ if (!isVerbose(flags, 1) && issues.length > maxToShow) {
63
+ lines.push(`${formatDimText(' Re-run with -v/--verbose to see all issues')}`);
64
+ }
65
+ }
66
+ }
67
+ if (error.docsUrl && isVerbose(flags, 1)) {
68
+ lines.push(formatDimText(error.docsUrl));
69
+ }
70
+ if (isVerbose(flags, 2) && error.meta) {
71
+ lines.push(`${formatDimText(` Meta: ${JSON.stringify(error.meta, null, 2)}`)}`);
72
+ }
73
+
74
+ return lines.join('\n');
75
+ }
76
+
77
+ /**
78
+ * Formats error output as JSON.
79
+ */
80
+ export function formatErrorJson(error: CliErrorEnvelope): string {
81
+ return JSON.stringify(error, null, 2);
82
+ }