@prisma-next/cli 0.3.0-dev.7 → 0.3.0-dev.70

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 (180) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +314 -80
  3. package/dist/cli-errors-JlPTsazx.mjs +3 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/cli.js +1 -2376
  6. package/dist/cli.mjs +203 -0
  7. package/dist/cli.mjs.map +1 -0
  8. package/dist/client-PimzSD1f.mjs +981 -0
  9. package/dist/client-PimzSD1f.mjs.map +1 -0
  10. package/dist/commands/contract-emit.d.mts +7 -0
  11. package/dist/commands/contract-emit.d.mts.map +1 -0
  12. package/dist/commands/contract-emit.mjs +151 -0
  13. package/dist/commands/contract-emit.mjs.map +1 -0
  14. package/dist/commands/db-init.d.mts +7 -0
  15. package/dist/commands/db-init.d.mts.map +1 -0
  16. package/dist/commands/db-init.mjs +134 -0
  17. package/dist/commands/db-init.mjs.map +1 -0
  18. package/dist/commands/db-introspect.d.mts +7 -0
  19. package/dist/commands/db-introspect.d.mts.map +1 -0
  20. package/dist/commands/db-introspect.mjs +118 -0
  21. package/dist/commands/db-introspect.mjs.map +1 -0
  22. package/dist/commands/db-schema-verify.d.mts +7 -0
  23. package/dist/commands/db-schema-verify.d.mts.map +1 -0
  24. package/dist/commands/db-schema-verify.mjs +120 -0
  25. package/dist/commands/db-schema-verify.mjs.map +1 -0
  26. package/dist/commands/db-sign.d.mts +7 -0
  27. package/dist/commands/db-sign.d.mts.map +1 -0
  28. package/dist/commands/db-sign.mjs +142 -0
  29. package/dist/commands/db-sign.mjs.map +1 -0
  30. package/dist/commands/db-update.d.mts +7 -0
  31. package/dist/commands/db-update.d.mts.map +1 -0
  32. package/dist/commands/db-update.mjs +123 -0
  33. package/dist/commands/db-update.mjs.map +1 -0
  34. package/dist/commands/db-verify.d.mts +7 -0
  35. package/dist/commands/db-verify.d.mts.map +1 -0
  36. package/dist/commands/db-verify.mjs +133 -0
  37. package/dist/commands/db-verify.mjs.map +1 -0
  38. package/dist/commands/migration-apply.d.mts +23 -0
  39. package/dist/commands/migration-apply.d.mts.map +1 -0
  40. package/dist/commands/migration-apply.mjs +250 -0
  41. package/dist/commands/migration-apply.mjs.map +1 -0
  42. package/dist/commands/migration-plan.d.mts +25 -0
  43. package/dist/commands/migration-plan.d.mts.map +1 -0
  44. package/dist/commands/migration-plan.mjs +266 -0
  45. package/dist/commands/migration-plan.mjs.map +1 -0
  46. package/dist/commands/migration-show.d.mts +28 -0
  47. package/dist/commands/migration-show.d.mts.map +1 -0
  48. package/dist/commands/migration-show.mjs +138 -0
  49. package/dist/commands/migration-show.mjs.map +1 -0
  50. package/dist/commands/migration-status.d.mts +35 -0
  51. package/dist/commands/migration-status.d.mts.map +1 -0
  52. package/dist/commands/migration-status.mjs +260 -0
  53. package/dist/commands/migration-status.mjs.map +1 -0
  54. package/dist/commands/migration-verify.d.mts +16 -0
  55. package/dist/commands/migration-verify.d.mts.map +1 -0
  56. package/dist/commands/migration-verify.mjs +86 -0
  57. package/dist/commands/migration-verify.mjs.map +1 -0
  58. package/dist/config-loader-PPf4CtDj.mjs +43 -0
  59. package/dist/config-loader-PPf4CtDj.mjs.map +1 -0
  60. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  61. package/dist/config-loader.d.mts.map +1 -0
  62. package/dist/config-loader.mjs +3 -0
  63. package/dist/exports/config-types.d.mts +2 -0
  64. package/dist/exports/config-types.mjs +3 -0
  65. package/dist/exports/control-api.d.mts +621 -0
  66. package/dist/exports/control-api.d.mts.map +1 -0
  67. package/dist/exports/control-api.mjs +98 -0
  68. package/dist/exports/control-api.mjs.map +1 -0
  69. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  70. package/dist/exports/index.d.mts.map +1 -0
  71. package/dist/exports/index.mjs +135 -0
  72. package/dist/exports/index.mjs.map +1 -0
  73. package/dist/extract-sql-ddl-BmlKvk4o.mjs +26 -0
  74. package/dist/extract-sql-ddl-BmlKvk4o.mjs.map +1 -0
  75. package/dist/framework-components-CjV_jD8f.mjs +59 -0
  76. package/dist/framework-components-CjV_jD8f.mjs.map +1 -0
  77. package/dist/migration-command-scaffold-DfY_F3ev.mjs +97 -0
  78. package/dist/migration-command-scaffold-DfY_F3ev.mjs.map +1 -0
  79. package/dist/progress-adapter-DENrzF6I.mjs +49 -0
  80. package/dist/progress-adapter-DENrzF6I.mjs.map +1 -0
  81. package/dist/result-handler-iA9JtUC7.mjs +1186 -0
  82. package/dist/result-handler-iA9JtUC7.mjs.map +1 -0
  83. package/package.json +74 -37
  84. package/src/cli.ts +43 -0
  85. package/src/commands/contract-emit.ts +221 -111
  86. package/src/commands/db-init.ts +217 -426
  87. package/src/commands/db-introspect.ts +148 -185
  88. package/src/commands/db-schema-verify.ts +162 -149
  89. package/src/commands/db-sign.ts +215 -202
  90. package/src/commands/db-update.ts +220 -0
  91. package/src/commands/db-verify.ts +193 -156
  92. package/src/commands/migration-apply.ts +431 -0
  93. package/src/commands/migration-plan.ts +446 -0
  94. package/src/commands/migration-show.ts +255 -0
  95. package/src/commands/migration-status.ts +436 -0
  96. package/src/commands/migration-verify.ts +151 -0
  97. package/src/config-loader.ts +13 -3
  98. package/src/control-api/client.ts +605 -0
  99. package/src/control-api/errors.ts +9 -0
  100. package/src/control-api/operations/contract-emit.ts +161 -0
  101. package/src/control-api/operations/db-init.ts +286 -0
  102. package/src/control-api/operations/db-update.ts +221 -0
  103. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  104. package/src/control-api/operations/migration-apply.ts +195 -0
  105. package/src/control-api/operations/migration-helpers.ts +49 -0
  106. package/src/control-api/types.ts +687 -0
  107. package/src/exports/config-types.ts +3 -3
  108. package/src/exports/control-api.ts +53 -0
  109. package/src/load-ts-contract.ts +16 -11
  110. package/src/utils/cli-errors.ts +3 -1
  111. package/src/utils/command-helpers.ts +92 -3
  112. package/src/utils/framework-components.ts +11 -30
  113. package/src/utils/migration-command-scaffold.ts +190 -0
  114. package/src/utils/output.ts +363 -25
  115. package/src/utils/progress-adapter.ts +86 -0
  116. package/dist/chunk-464LNZCE.js +0 -134
  117. package/dist/chunk-464LNZCE.js.map +0 -1
  118. package/dist/chunk-BZMBKEEQ.js +0 -997
  119. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  120. package/dist/chunk-HWYQOCAJ.js +0 -47
  121. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  122. package/dist/chunk-ZKYEJROM.js +0 -94
  123. package/dist/chunk-ZKYEJROM.js.map +0 -1
  124. package/dist/cli.d.ts +0 -2
  125. package/dist/cli.d.ts.map +0 -1
  126. package/dist/cli.js.map +0 -1
  127. package/dist/commands/contract-emit.d.ts +0 -3
  128. package/dist/commands/contract-emit.d.ts.map +0 -1
  129. package/dist/commands/contract-emit.js +0 -9
  130. package/dist/commands/contract-emit.js.map +0 -1
  131. package/dist/commands/db-init.d.ts +0 -3
  132. package/dist/commands/db-init.d.ts.map +0 -1
  133. package/dist/commands/db-init.js +0 -341
  134. package/dist/commands/db-init.js.map +0 -1
  135. package/dist/commands/db-introspect.d.ts +0 -3
  136. package/dist/commands/db-introspect.d.ts.map +0 -1
  137. package/dist/commands/db-introspect.js +0 -190
  138. package/dist/commands/db-introspect.js.map +0 -1
  139. package/dist/commands/db-schema-verify.d.ts +0 -3
  140. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  141. package/dist/commands/db-schema-verify.js +0 -164
  142. package/dist/commands/db-schema-verify.js.map +0 -1
  143. package/dist/commands/db-sign.d.ts +0 -3
  144. package/dist/commands/db-sign.d.ts.map +0 -1
  145. package/dist/commands/db-sign.js +0 -199
  146. package/dist/commands/db-sign.js.map +0 -1
  147. package/dist/commands/db-verify.d.ts +0 -3
  148. package/dist/commands/db-verify.d.ts.map +0 -1
  149. package/dist/commands/db-verify.js +0 -173
  150. package/dist/commands/db-verify.js.map +0 -1
  151. package/dist/config-loader.d.ts.map +0 -1
  152. package/dist/config-loader.js +0 -7
  153. package/dist/config-loader.js.map +0 -1
  154. package/dist/exports/config-types.d.ts +0 -3
  155. package/dist/exports/config-types.d.ts.map +0 -1
  156. package/dist/exports/config-types.js +0 -6
  157. package/dist/exports/config-types.js.map +0 -1
  158. package/dist/exports/index.d.ts +0 -4
  159. package/dist/exports/index.d.ts.map +0 -1
  160. package/dist/exports/index.js +0 -175
  161. package/dist/exports/index.js.map +0 -1
  162. package/dist/load-ts-contract.d.ts.map +0 -1
  163. package/dist/utils/action.d.ts +0 -16
  164. package/dist/utils/action.d.ts.map +0 -1
  165. package/dist/utils/cli-errors.d.ts +0 -7
  166. package/dist/utils/cli-errors.d.ts.map +0 -1
  167. package/dist/utils/command-helpers.d.ts +0 -12
  168. package/dist/utils/command-helpers.d.ts.map +0 -1
  169. package/dist/utils/framework-components.d.ts +0 -81
  170. package/dist/utils/framework-components.d.ts.map +0 -1
  171. package/dist/utils/global-flags.d.ts +0 -25
  172. package/dist/utils/global-flags.d.ts.map +0 -1
  173. package/dist/utils/output.d.ts +0 -142
  174. package/dist/utils/output.d.ts.map +0 -1
  175. package/dist/utils/result-handler.d.ts +0 -15
  176. package/dist/utils/result-handler.d.ts.map +0 -1
  177. package/dist/utils/spinner.d.ts +0 -29
  178. package/dist/utils/spinner.d.ts.map +0 -1
  179. package/src/utils/action.ts +0 -43
  180. package/src/utils/spinner.ts +0 -67
@@ -0,0 +1,1186 @@
1
+ import { relative, resolve } from "pathe";
2
+ import { ifDefined } from "@prisma-next/utils/defined";
3
+ import { bgGreen, blue, bold, cyan, dim, green, magenta, red, yellow } from "colorette";
4
+ import stringWidth from "string-width";
5
+ import stripAnsi from "strip-ansi";
6
+ import wrapAnsi from "wrap-ansi";
7
+
8
+ //#region src/utils/command-helpers.ts
9
+ const longDescriptions = /* @__PURE__ */ new WeakMap();
10
+ /**
11
+ * Sets both short and long descriptions for a command.
12
+ * The short description is used in command trees and headers.
13
+ * The long description is shown at the bottom of help output.
14
+ */
15
+ function setCommandDescriptions(command, shortDescription, longDescription) {
16
+ command.description(shortDescription);
17
+ if (longDescription) longDescriptions.set(command, longDescription);
18
+ return command;
19
+ }
20
+ /**
21
+ * Gets the long description from a command if it was set via setCommandDescriptions.
22
+ */
23
+ function getLongDescription(command) {
24
+ return longDescriptions.get(command);
25
+ }
26
+ /**
27
+ * Resolves the absolute path to contract.json from the config.
28
+ * Centralises the fallback logic shared by every command that reads the contract.
29
+ */
30
+ function resolveContractPath(config) {
31
+ return config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
32
+ }
33
+ /**
34
+ * Masks credentials in a database connection URL.
35
+ * Handles standard URLs (username + password + query params) and libpq-style key=value strings.
36
+ */
37
+ function maskConnectionUrl(url) {
38
+ try {
39
+ const parsed = new URL(url);
40
+ if (parsed.username) parsed.username = "****";
41
+ if (parsed.password) parsed.password = "****";
42
+ for (const key of [...parsed.searchParams.keys()]) if (/password/i.test(key)) parsed.searchParams.set(key, "****");
43
+ return parsed.toString();
44
+ } catch {
45
+ return url.replace(/password\s*=\s*\S+/gi, "password=****").replace(/user\s*=\s*\S+/gi, "user=****");
46
+ }
47
+ }
48
+ /**
49
+ * Strips raw connection URL fragments from an error message to prevent credential leakage.
50
+ * Call this before surfacing driver errors to the user.
51
+ */
52
+ function sanitizeErrorMessage(message, connectionUrl) {
53
+ if (!connectionUrl) return message;
54
+ try {
55
+ const parsed = new URL(connectionUrl);
56
+ let sanitized = message;
57
+ sanitized = sanitized.replaceAll(connectionUrl, maskConnectionUrl(connectionUrl));
58
+ if (parsed.password) sanitized = sanitized.replaceAll(parsed.password, "****");
59
+ if (parsed.username) sanitized = sanitized.replaceAll(parsed.username, "****");
60
+ return sanitized;
61
+ } catch {
62
+ return message.replace(/password\s*=\s*\S+/gi, "password=****").replace(/user\s*=\s*\S+/gi, "user=****");
63
+ }
64
+ }
65
+
66
+ //#endregion
67
+ //#region src/utils/global-flags.ts
68
+ /**
69
+ * Parses global flags from CLI options.
70
+ * Handles verbosity flags (-v, -vv, --trace), JSON output, quiet mode, timestamps, and color.
71
+ */
72
+ function parseGlobalFlags(options) {
73
+ const flags = {};
74
+ if (options.json === true || options.json === "object") flags.json = "object";
75
+ else if (options.json === "ndjson") flags.json = "ndjson";
76
+ if (options.quiet || options.q) flags.quiet = true;
77
+ if (options.vv || options.trace) flags.verbose = 2;
78
+ else if (options.verbose || options.v) flags.verbose = 1;
79
+ else flags.verbose = 0;
80
+ if (options.timestamps) flags.timestamps = true;
81
+ if (process.env["NO_COLOR"] || flags.json) flags.color = false;
82
+ else if (options["no-color"]) flags.color = false;
83
+ else if (options.color !== void 0) flags.color = options.color;
84
+ else flags.color = process.stdout.isTTY && !process.env["CI"];
85
+ return flags;
86
+ }
87
+
88
+ //#endregion
89
+ //#region src/utils/output.ts
90
+ /**
91
+ * Formats a timestamp for output.
92
+ */
93
+ function formatTimestamp() {
94
+ return (/* @__PURE__ */ new Date()).toISOString();
95
+ }
96
+ /**
97
+ * Creates a prefix string if timestamps are enabled.
98
+ */
99
+ function createPrefix(flags) {
100
+ return flags.timestamps ? `[${formatTimestamp()}] ` : "";
101
+ }
102
+ /**
103
+ * Checks if verbose output is enabled at the specified level.
104
+ */
105
+ function isVerbose(flags, level) {
106
+ return (flags.verbose ?? 0) >= level;
107
+ }
108
+ /**
109
+ * Creates a color-aware formatter function.
110
+ * Returns a function that applies the color only if colors are enabled.
111
+ */
112
+ function createColorFormatter(useColor, colorFn) {
113
+ return useColor ? colorFn : (text) => text;
114
+ }
115
+ /**
116
+ * Formats text with dim styling if colors are enabled.
117
+ */
118
+ function formatDim(useColor, text) {
119
+ return useColor ? dim(text) : text;
120
+ }
121
+ /**
122
+ * Formats human-readable output for contract emit.
123
+ */
124
+ function formatEmitOutput(result, flags) {
125
+ if (flags.quiet) return "";
126
+ const lines = [];
127
+ const prefix = createPrefix(flags);
128
+ const jsonPath = relative(process.cwd(), result.files.json);
129
+ const dtsPath = relative(process.cwd(), result.files.dts);
130
+ lines.push(`${prefix}✔ Emitted contract.json → ${jsonPath}`);
131
+ lines.push(`${prefix}✔ Emitted contract.d.ts → ${dtsPath}`);
132
+ lines.push(`${prefix} storageHash: ${result.storageHash}`);
133
+ if (result.executionHash) lines.push(`${prefix} executionHash: ${result.executionHash}`);
134
+ if (result.profileHash) lines.push(`${prefix} profileHash: ${result.profileHash}`);
135
+ if (isVerbose(flags, 1)) lines.push(`${prefix} Total time: ${result.timings.total}ms`);
136
+ return lines.join("\n");
137
+ }
138
+ /**
139
+ * Formats JSON output for contract emit.
140
+ */
141
+ function formatEmitJson(result) {
142
+ const output = {
143
+ ok: true,
144
+ storageHash: result.storageHash,
145
+ ...ifDefined("executionHash", result.executionHash),
146
+ ...result.profileHash ? { profileHash: result.profileHash } : {},
147
+ outDir: result.outDir,
148
+ files: result.files,
149
+ timings: result.timings
150
+ };
151
+ return JSON.stringify(output, null, 2);
152
+ }
153
+ /**
154
+ * Formats error output for human-readable display.
155
+ */
156
+ function formatErrorOutput(error, flags) {
157
+ const lines = [];
158
+ const prefix = createPrefix(flags);
159
+ const useColor = flags.color !== false;
160
+ const formatRed = createColorFormatter(useColor, red);
161
+ const formatDimText = (text) => formatDim(useColor, text);
162
+ lines.push(`${prefix}${formatRed("✖")} ${error.summary} (${error.code})`);
163
+ if (error.why) lines.push(`${prefix}${formatDimText(` Why: ${error.why}`)}`);
164
+ if (error.fix) lines.push(`${prefix}${formatDimText(` Fix: ${error.fix}`)}`);
165
+ if (error.where?.path) {
166
+ const whereLine = error.where.line ? `${error.where.path}:${error.where.line}` : error.where.path;
167
+ lines.push(`${prefix}${formatDimText(` Where: ${whereLine}`)}`);
168
+ }
169
+ if (error.meta?.["conflicts"]) {
170
+ const conflicts = error.meta["conflicts"];
171
+ if (conflicts.length > 0) {
172
+ const maxToShow = isVerbose(flags, 1) ? conflicts.length : Math.min(3, conflicts.length);
173
+ const header = isVerbose(flags, 1) ? " Conflicts:" : ` Conflicts (showing ${maxToShow} of ${conflicts.length}):`;
174
+ lines.push(`${prefix}${formatDimText(header)}`);
175
+ for (const conflict of conflicts.slice(0, maxToShow)) lines.push(`${prefix}${formatDimText(` - [${conflict.kind}] ${conflict.summary}`)}`);
176
+ if (!isVerbose(flags, 1) && conflicts.length > maxToShow) lines.push(`${prefix}${formatDimText(" Re-run with -v/--verbose to see all conflicts")}`);
177
+ }
178
+ }
179
+ if (error.meta?.["issues"]) {
180
+ const issues = error.meta["issues"];
181
+ if (issues.length > 0) {
182
+ const maxToShow = isVerbose(flags, 1) ? issues.length : Math.min(3, issues.length);
183
+ const header = isVerbose(flags, 1) ? " Issues:" : ` Issues (showing ${maxToShow} of ${issues.length}):`;
184
+ lines.push(`${prefix}${formatDimText(header)}`);
185
+ for (const issue of issues.slice(0, maxToShow)) {
186
+ const kind = issue.kind ?? "issue";
187
+ const message = issue.message ?? "";
188
+ lines.push(`${prefix}${formatDimText(` - [${kind}] ${message}`)}`);
189
+ }
190
+ if (!isVerbose(flags, 1) && issues.length > maxToShow) lines.push(`${prefix}${formatDimText(" Re-run with -v/--verbose to see all issues")}`);
191
+ }
192
+ }
193
+ if (error.docsUrl && isVerbose(flags, 1)) lines.push(formatDimText(error.docsUrl));
194
+ if (isVerbose(flags, 2) && error.meta) lines.push(`${prefix}${formatDimText(` Meta: ${JSON.stringify(error.meta, null, 2)}`)}`);
195
+ return lines.join("\n");
196
+ }
197
+ /**
198
+ * Formats error output as JSON.
199
+ */
200
+ function formatErrorJson(error) {
201
+ return JSON.stringify(error, null, 2);
202
+ }
203
+ /**
204
+ * Formats human-readable output for database verify.
205
+ */
206
+ function formatVerifyOutput(result, flags) {
207
+ if (flags.quiet) return "";
208
+ const lines = [];
209
+ const prefix = createPrefix(flags);
210
+ const useColor = flags.color !== false;
211
+ const formatGreen = createColorFormatter(useColor, green);
212
+ const formatRed = createColorFormatter(useColor, red);
213
+ const formatDimText = (text) => formatDim(useColor, text);
214
+ if (result.ok) {
215
+ lines.push(`${prefix}${formatGreen("✔")} ${result.summary}`);
216
+ lines.push(`${prefix}${formatDimText(` storageHash: ${result.contract.storageHash}`)}`);
217
+ if (result.contract.profileHash) lines.push(`${prefix}${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);
218
+ } else lines.push(`${prefix}${formatRed("✖")} ${result.summary} (${result.code})`);
219
+ if (isVerbose(flags, 1)) {
220
+ if (result.codecCoverageSkipped) lines.push(`${prefix}${formatDimText(" Codec coverage check skipped (helper returned no supported types)")}`);
221
+ lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
222
+ }
223
+ return lines.join("\n");
224
+ }
225
+ /**
226
+ * Formats JSON output for database verify.
227
+ */
228
+ function formatVerifyJson(result) {
229
+ const output = {
230
+ ok: result.ok,
231
+ ...result.code ? { code: result.code } : {},
232
+ summary: result.summary,
233
+ contract: result.contract,
234
+ ...result.marker ? { marker: result.marker } : {},
235
+ target: result.target,
236
+ ...result.missingCodecs ? { missingCodecs: result.missingCodecs } : {},
237
+ ...result.meta ? { meta: result.meta } : {},
238
+ timings: result.timings
239
+ };
240
+ return JSON.stringify(output, null, 2);
241
+ }
242
+ /**
243
+ * Formats JSON output for database introspection.
244
+ */
245
+ function formatIntrospectJson(result) {
246
+ return JSON.stringify(result, null, 2);
247
+ }
248
+ /**
249
+ * Renders a schema tree structure from CoreSchemaView.
250
+ * Matches the style of renderSchemaVerificationTree for consistency.
251
+ */
252
+ function renderSchemaTree(node, flags, options) {
253
+ const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;
254
+ const lines = [];
255
+ let formattedLabel = node.label;
256
+ if (useColor) switch (node.kind) {
257
+ case "root":
258
+ formattedLabel = bold(node.label);
259
+ break;
260
+ case "entity": {
261
+ const tableMatch = node.label.match(/^table\s+(.+)$/);
262
+ if (tableMatch?.[1]) {
263
+ const tableName = tableMatch[1];
264
+ formattedLabel = `${dim("table")} ${cyan(tableName)}`;
265
+ } else formattedLabel = cyan(node.label);
266
+ break;
267
+ }
268
+ case "collection":
269
+ formattedLabel = dim(node.label);
270
+ break;
271
+ case "field": {
272
+ const columnMatch = node.label.match(/^([^:]+):\s*(.+)$/);
273
+ if (columnMatch?.[1] && columnMatch[2]) {
274
+ const columnName = columnMatch[1];
275
+ const rest = columnMatch[2];
276
+ const typeMatch = rest.match(/^([^\s(]+)\s*(\([^)]+\))$/);
277
+ if (typeMatch?.[1] && typeMatch[2]) {
278
+ const typeDisplay = typeMatch[1];
279
+ const nullability = typeMatch[2];
280
+ formattedLabel = `${cyan(columnName)}: ${typeDisplay} ${dim(nullability)}`;
281
+ } else formattedLabel = `${cyan(columnName)}: ${rest}`;
282
+ } else formattedLabel = node.label;
283
+ break;
284
+ }
285
+ case "index": {
286
+ const pkMatch = node.label.match(/^primary key:\s*(.+)$/);
287
+ if (pkMatch?.[1]) {
288
+ const columnNames = pkMatch[1];
289
+ formattedLabel = `${dim("primary key")}: ${cyan(columnNames)}`;
290
+ } else {
291
+ const uniqueMatch = node.label.match(/^unique\s+(.+)$/);
292
+ if (uniqueMatch?.[1]) {
293
+ const name = uniqueMatch[1];
294
+ formattedLabel = `${dim("unique")} ${cyan(name)}`;
295
+ } else {
296
+ const indexMatch = node.label.match(/^(unique\s+)?index\s+(.+)$/);
297
+ if (indexMatch?.[2]) {
298
+ const prefix$1 = indexMatch[1] ? `${dim("unique")} ` : "";
299
+ const name = indexMatch[2];
300
+ formattedLabel = `${prefix$1}${dim("index")} ${cyan(name)}`;
301
+ } else formattedLabel = dim(node.label);
302
+ }
303
+ }
304
+ break;
305
+ }
306
+ case "extension": {
307
+ const extMatch = node.label.match(/^([^\s]+)\s+(extension is enabled)$/);
308
+ if (extMatch?.[1] && extMatch[2]) {
309
+ const extName = extMatch[1];
310
+ const rest = extMatch[2];
311
+ formattedLabel = `${cyan(extName)} ${dim(rest)}`;
312
+ } else formattedLabel = magenta(node.label);
313
+ break;
314
+ }
315
+ default:
316
+ formattedLabel = node.label;
317
+ break;
318
+ }
319
+ if (isRoot) lines.push(formattedLabel);
320
+ else {
321
+ const treePrefix = `${prefix}${formatDimText(isLast ? "└" : "├")}─ `;
322
+ const isRootChild = prefix === "";
323
+ const prefixHasVerticalBar = stripAnsi(prefix).includes("│");
324
+ if (isRootChild) lines.push(`${treePrefix}${formattedLabel}`);
325
+ else if (prefixHasVerticalBar) lines.push(`${treePrefix}${formattedLabel}`);
326
+ else lines.push(`${formatDimText("│")} ${treePrefix}${formattedLabel}`);
327
+ }
328
+ if (node.children && node.children.length > 0) {
329
+ const childPrefix = isRoot ? "" : isLast ? `${prefix} ` : `${prefix}${formatDimText("│")} `;
330
+ for (let i = 0; i < node.children.length; i++) {
331
+ const child = node.children[i];
332
+ if (!child) continue;
333
+ const childLines = renderSchemaTree(child, flags, {
334
+ isLast: i === node.children.length - 1,
335
+ prefix: childPrefix,
336
+ useColor,
337
+ formatDimText,
338
+ isRoot: false
339
+ });
340
+ lines.push(...childLines);
341
+ }
342
+ }
343
+ return lines;
344
+ }
345
+ /**
346
+ * Formats human-readable output for database introspection.
347
+ */
348
+ function formatIntrospectOutput(result, schemaView, flags) {
349
+ if (flags.quiet) return "";
350
+ const lines = [];
351
+ const prefix = createPrefix(flags);
352
+ const useColor = flags.color !== false;
353
+ const formatDimText = (text) => formatDim(useColor, text);
354
+ if (schemaView) {
355
+ const prefixedTreeLines = renderSchemaTree(schemaView.root, flags, {
356
+ isLast: true,
357
+ prefix: "",
358
+ useColor,
359
+ formatDimText,
360
+ isRoot: true
361
+ }).map((line) => `${prefix}${line}`);
362
+ lines.push(...prefixedTreeLines);
363
+ } else {
364
+ lines.push(`${prefix}✔ ${result.summary}`);
365
+ if (isVerbose(flags, 1)) {
366
+ lines.push(`${prefix} Target: ${result.target.familyId}/${result.target.id}`);
367
+ if (result.meta?.dbUrl) lines.push(`${prefix} Database: ${result.meta.dbUrl}`);
368
+ }
369
+ }
370
+ if (isVerbose(flags, 1)) lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
371
+ return lines.join("\n");
372
+ }
373
+ /**
374
+ * Renders a schema verification tree structure from SchemaVerificationNode.
375
+ * Similar to renderSchemaTree but for verification nodes with status-based colors and glyphs.
376
+ */
377
+ function renderSchemaVerificationTree(node, flags, options) {
378
+ const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;
379
+ const lines = [];
380
+ let statusGlyph = "";
381
+ let statusColor = (text) => text;
382
+ if (useColor) switch (node.status) {
383
+ case "pass":
384
+ statusGlyph = "✔";
385
+ statusColor = green;
386
+ break;
387
+ case "warn":
388
+ statusGlyph = "⚠";
389
+ statusColor = (text) => useColor ? yellow(text) : text;
390
+ break;
391
+ case "fail":
392
+ statusGlyph = "✖";
393
+ statusColor = red;
394
+ break;
395
+ }
396
+ else switch (node.status) {
397
+ case "pass":
398
+ statusGlyph = "✔";
399
+ break;
400
+ case "warn":
401
+ statusGlyph = "⚠";
402
+ break;
403
+ case "fail":
404
+ statusGlyph = "✖";
405
+ break;
406
+ }
407
+ let labelColor = (text) => text;
408
+ let formattedLabel = node.name;
409
+ if (useColor) switch (node.kind) {
410
+ case "contract":
411
+ case "schema":
412
+ labelColor = bold;
413
+ formattedLabel = labelColor(node.name);
414
+ break;
415
+ case "table": {
416
+ const tableMatch = node.name.match(/^table\s+(.+)$/);
417
+ if (tableMatch?.[1]) {
418
+ const tableName = tableMatch[1];
419
+ formattedLabel = `${dim("table")} ${cyan(tableName)}`;
420
+ } else formattedLabel = dim(node.name);
421
+ break;
422
+ }
423
+ case "columns":
424
+ labelColor = dim;
425
+ formattedLabel = labelColor(node.name);
426
+ break;
427
+ case "column": {
428
+ const columnMatch = node.name.match(/^([^:]+):\s*(.+)$/);
429
+ if (columnMatch?.[1] && columnMatch[2]) {
430
+ const columnName = columnMatch[1];
431
+ const rest = columnMatch[2];
432
+ const typeMatch = rest.match(/^([^\s→]+)\s*→\s*([^\s(]+)\s*(\([^)]+\))$/);
433
+ if (typeMatch?.[1] && typeMatch[2] && typeMatch[3]) {
434
+ const contractType = typeMatch[1];
435
+ const nativeType = typeMatch[2];
436
+ const nullability = typeMatch[3];
437
+ formattedLabel = `${cyan(columnName)}: ${contractType} → ${dim(nativeType)} ${dim(nullability)}`;
438
+ } else formattedLabel = `${cyan(columnName)}: ${rest}`;
439
+ } else formattedLabel = node.name;
440
+ break;
441
+ }
442
+ case "type":
443
+ case "nullability":
444
+ labelColor = (text) => text;
445
+ formattedLabel = labelColor(node.name);
446
+ break;
447
+ case "primaryKey": {
448
+ const pkMatch = node.name.match(/^primary key:\s*(.+)$/);
449
+ if (pkMatch?.[1]) {
450
+ const columnNames = pkMatch[1];
451
+ formattedLabel = `${dim("primary key")}: ${cyan(columnNames)}`;
452
+ } else formattedLabel = dim(node.name);
453
+ break;
454
+ }
455
+ case "foreignKey":
456
+ case "unique":
457
+ case "index":
458
+ labelColor = dim;
459
+ formattedLabel = labelColor(node.name);
460
+ break;
461
+ case "extension": {
462
+ const dbMatch = node.name.match(/^database is\s+(.+)$/);
463
+ if (dbMatch?.[1]) {
464
+ const dbName = dbMatch[1];
465
+ formattedLabel = `${dim("database is")} ${cyan(dbName)}`;
466
+ } else {
467
+ const extMatch = node.name.match(/^([^\s]+)\s+(extension is enabled)$/);
468
+ if (extMatch?.[1] && extMatch[2]) {
469
+ const extName = extMatch[1];
470
+ const rest = extMatch[2];
471
+ formattedLabel = `${cyan(extName)} ${dim(rest)}`;
472
+ } else {
473
+ labelColor = magenta;
474
+ formattedLabel = labelColor(node.name);
475
+ }
476
+ }
477
+ break;
478
+ }
479
+ default:
480
+ formattedLabel = node.name;
481
+ break;
482
+ }
483
+ else formattedLabel = node.name;
484
+ const statusGlyphColored = statusColor(statusGlyph);
485
+ let nodeLabel = formattedLabel;
486
+ if ((node.status === "fail" || node.status === "warn") && node.message && node.message.length > 0) {
487
+ const messageText = formatDimText(`(${node.message})`);
488
+ nodeLabel = `${formattedLabel} ${messageText}`;
489
+ }
490
+ if (isRoot) lines.push(`${statusGlyphColored} ${nodeLabel}`);
491
+ else {
492
+ const treePrefix = `${prefix}${formatDimText(isLast ? "└" : "├")}─ `;
493
+ const isRootChild = prefix === "";
494
+ const prefixHasVerticalBar = stripAnsi(prefix).includes("│");
495
+ if (isRootChild) lines.push(`${treePrefix}${statusGlyphColored} ${nodeLabel}`);
496
+ else if (prefixHasVerticalBar) lines.push(`${treePrefix}${statusGlyphColored} ${nodeLabel}`);
497
+ else lines.push(`${formatDimText("│")} ${treePrefix}${statusGlyphColored} ${nodeLabel}`);
498
+ }
499
+ if (node.children && node.children.length > 0) {
500
+ const childPrefix = isRoot ? "" : isLast ? `${prefix} ` : `${prefix}${formatDimText("│")} `;
501
+ for (let i = 0; i < node.children.length; i++) {
502
+ const child = node.children[i];
503
+ if (!child) continue;
504
+ const childLines = renderSchemaVerificationTree(child, flags, {
505
+ isLast: i === node.children.length - 1,
506
+ prefix: childPrefix,
507
+ useColor,
508
+ formatDimText,
509
+ isRoot: false
510
+ });
511
+ lines.push(...childLines);
512
+ }
513
+ }
514
+ return lines;
515
+ }
516
+ /**
517
+ * Formats human-readable output for database schema verification.
518
+ */
519
+ function formatSchemaVerifyOutput(result, flags) {
520
+ if (flags.quiet) return "";
521
+ const lines = [];
522
+ const prefix = createPrefix(flags);
523
+ const useColor = flags.color !== false;
524
+ const formatGreen = createColorFormatter(useColor, green);
525
+ const formatRed = createColorFormatter(useColor, red);
526
+ const formatDimText = (text) => formatDim(useColor, text);
527
+ const prefixedTreeLines = renderSchemaVerificationTree(result.schema.root, flags, {
528
+ isLast: true,
529
+ prefix: "",
530
+ useColor,
531
+ formatDimText,
532
+ isRoot: true
533
+ }).map((line) => `${prefix}${line}`);
534
+ lines.push(...prefixedTreeLines);
535
+ if (isVerbose(flags, 1)) {
536
+ lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
537
+ lines.push(`${prefix}${formatDimText(` pass=${result.schema.counts.pass} warn=${result.schema.counts.warn} fail=${result.schema.counts.fail}`)}`);
538
+ }
539
+ lines.push("");
540
+ if (result.ok) lines.push(`${prefix}${formatGreen("✔")} ${result.summary}`);
541
+ else {
542
+ const codeText = result.code ? ` (${result.code})` : "";
543
+ lines.push(`${prefix}${formatRed("✖")} ${result.summary}${codeText}`);
544
+ }
545
+ return lines.join("\n");
546
+ }
547
+ /**
548
+ * Formats JSON output for database schema verification.
549
+ */
550
+ function formatSchemaVerifyJson(result) {
551
+ return JSON.stringify(result, null, 2);
552
+ }
553
+ /**
554
+ * Formats human-readable output for database sign.
555
+ */
556
+ function formatSignOutput(result, flags) {
557
+ if (flags.quiet) return "";
558
+ const lines = [];
559
+ const prefix = createPrefix(flags);
560
+ const useColor = flags.color !== false;
561
+ const formatGreen = createColorFormatter(useColor, green);
562
+ const formatDimText = (text) => formatDim(useColor, text);
563
+ if (result.ok) {
564
+ lines.push(`${prefix}${formatGreen("✔")} Database signed`);
565
+ const previousHash = result.marker.previous?.storageHash ?? "none";
566
+ const currentHash = result.contract.storageHash;
567
+ lines.push(`${prefix}${formatDimText(` from: ${previousHash}`)}`);
568
+ lines.push(`${prefix}${formatDimText(` to: ${currentHash}`)}`);
569
+ if (isVerbose(flags, 1)) {
570
+ if (result.contract.profileHash) lines.push(`${prefix}${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);
571
+ if (result.marker.previous?.profileHash) lines.push(`${prefix}${formatDimText(` previous profileHash: ${result.marker.previous.profileHash}`)}`);
572
+ lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
573
+ }
574
+ }
575
+ return lines.join("\n");
576
+ }
577
+ /**
578
+ * Formats JSON output for database sign.
579
+ */
580
+ function formatSignJson(result) {
581
+ return JSON.stringify(result, null, 2);
582
+ }
583
+ /**
584
+ * Formats human-readable output for migration commands (db init, db update) in plan mode.
585
+ */
586
+ function formatMigrationPlanOutput(result, flags) {
587
+ if (flags.quiet) return "";
588
+ const lines = [];
589
+ const prefix = createPrefix(flags);
590
+ const useColor = flags.color !== false;
591
+ const formatGreen = createColorFormatter(useColor, green);
592
+ const formatDimText = (text) => formatDim(useColor, text);
593
+ const operationCount = result.plan?.operations.length ?? 0;
594
+ lines.push(`${prefix}${formatGreen("✔")} Planned ${operationCount} operation(s)`);
595
+ if (result.plan?.operations && result.plan.operations.length > 0) {
596
+ const formatYellow = createColorFormatter(useColor, yellow);
597
+ lines.push(`${prefix}${formatDimText("│")}`);
598
+ for (let i = 0; i < result.plan.operations.length; i++) {
599
+ const op = result.plan.operations[i];
600
+ if (!op) continue;
601
+ const treeChar = i === result.plan.operations.length - 1 ? "└" : "├";
602
+ const opClassLabel = op.operationClass === "destructive" ? formatYellow(`[${op.operationClass}]`) : formatDimText(`[${op.operationClass}]`);
603
+ lines.push(`${prefix}${formatDimText(treeChar)}─ ${op.label} ${opClassLabel}`);
604
+ }
605
+ if (result.plan.operations.some((op) => op.operationClass === "destructive")) {
606
+ lines.push(`${prefix}`);
607
+ lines.push(`${prefix}${formatYellow("⚠")} This migration contains destructive operations that may cause data loss.`);
608
+ }
609
+ }
610
+ if (result.plan?.destination) {
611
+ lines.push(`${prefix}`);
612
+ lines.push(`${prefix}${formatDimText(`Destination hash: ${result.plan.destination.storageHash}`)}`);
613
+ }
614
+ const planSql = result.plan?.sql;
615
+ if (planSql) {
616
+ lines.push(`${prefix}`);
617
+ lines.push(`${prefix}${formatDimText("DDL preview")}`);
618
+ if (planSql.length === 0) lines.push(`${prefix}${formatDimText("No DDL operations.")}`);
619
+ else {
620
+ lines.push(`${prefix}`);
621
+ for (const statement of planSql) {
622
+ const trimmed = statement.trim();
623
+ if (!trimmed) continue;
624
+ const line = trimmed.endsWith(";") ? trimmed : `${trimmed};`;
625
+ lines.push(`${prefix}${line}`);
626
+ }
627
+ }
628
+ }
629
+ if (isVerbose(flags, 1)) lines.push(`${prefix}${formatDimText(`Total time: ${result.timings.total}ms`)}`);
630
+ lines.push(`${prefix}`);
631
+ lines.push(`${prefix}${formatDimText("This is a dry run. No changes were applied.")}`);
632
+ lines.push(`${prefix}${formatDimText("Run without --plan to apply changes.")}`);
633
+ return lines.join("\n");
634
+ }
635
+ function formatMigrationApplyCommandOutput(result, flags) {
636
+ if (flags.quiet) return "";
637
+ const lines = [];
638
+ const useColor = flags.color !== false;
639
+ const formatGreen = createColorFormatter(useColor, green);
640
+ const formatDimText = (text) => formatDim(useColor, text);
641
+ if (result.migrationsApplied === 0) {
642
+ lines.push(`${formatGreen("✔")} ${result.summary}`);
643
+ lines.push(formatDimText(` marker: ${result.markerHash}`));
644
+ return lines.join("\n");
645
+ }
646
+ lines.push(`${formatGreen("✔")} ${result.summary}`);
647
+ lines.push("");
648
+ for (let i = 0; i < result.applied.length; i++) {
649
+ const migration = result.applied[i];
650
+ const treeChar = i === result.applied.length - 1 ? "└" : "├";
651
+ lines.push(`${formatDimText(treeChar)}─ ${migration.dirName} ${formatDimText(`[${migration.operationsExecuted} op(s)]`)}`);
652
+ }
653
+ lines.push("");
654
+ lines.push(formatDimText(`marker: ${result.markerHash}`));
655
+ if (isVerbose(flags, 1) && result.timings) {
656
+ lines.push("");
657
+ lines.push(formatDimText(`Total time: ${result.timings.total}ms`));
658
+ }
659
+ return lines.join("\n");
660
+ }
661
+ function formatMigrationVerifyCommandOutput(result, flags) {
662
+ if (flags.quiet) return "";
663
+ const lines = [];
664
+ const useColor = flags.color !== false;
665
+ const formatGreen = createColorFormatter(useColor, green);
666
+ const formatYellow = createColorFormatter(useColor, yellow);
667
+ const formatDimText = (text) => formatDim(useColor, text);
668
+ switch (result.status) {
669
+ case "verified":
670
+ lines.push(`${formatGreen("✔")} Migration verified`);
671
+ lines.push(formatDimText(` migrationId: ${result.migrationId}`));
672
+ break;
673
+ case "attested":
674
+ lines.push(`${formatYellow("◉")} Draft migration attested`);
675
+ lines.push(formatDimText(` migrationId: ${result.migrationId}`));
676
+ break;
677
+ }
678
+ return lines.join("\n");
679
+ }
680
+ function formatMigrationShowOutput(result, flags) {
681
+ if (flags.quiet) return "";
682
+ const lines = [];
683
+ const prefix = createPrefix(flags);
684
+ const useColor = flags.color !== false;
685
+ const formatGreen = createColorFormatter(useColor, green);
686
+ const formatYellow = createColorFormatter(useColor, yellow);
687
+ const formatDimText = (text) => formatDim(useColor, text);
688
+ lines.push(`${prefix}${formatGreen("✔")} ${result.dirName}`);
689
+ lines.push(`${prefix}${formatDimText(` kind: ${result.kind}`)}`);
690
+ lines.push(`${prefix}${formatDimText(` from: ${result.from}`)}`);
691
+ lines.push(`${prefix}${formatDimText(` to: ${result.to}`)}`);
692
+ if (result.migrationId) lines.push(`${prefix}${formatDimText(` migrationId: ${result.migrationId}`)}`);
693
+ else lines.push(`${prefix}${formatYellow(" migrationId: (draft — not yet attested)")}`);
694
+ lines.push(`${prefix}${formatDimText(` created: ${result.createdAt}`)}`);
695
+ lines.push(`${prefix}`);
696
+ lines.push(`${prefix}${result.operations.length} operation(s)`);
697
+ if (result.operations.length > 0) {
698
+ lines.push(`${prefix}${formatDimText("│")}`);
699
+ for (let i = 0; i < result.operations.length; i++) {
700
+ const op = result.operations[i];
701
+ const treeChar = i === result.operations.length - 1 ? "└" : "├";
702
+ const opClassLabel = op.operationClass === "destructive" ? formatYellow(`[${op.operationClass}]`) : formatDimText(`[${op.operationClass}]`);
703
+ lines.push(`${prefix}${formatDimText(treeChar)}─ ${op.label} ${opClassLabel}`);
704
+ }
705
+ if (result.operations.some((op) => op.operationClass === "destructive")) {
706
+ lines.push(`${prefix}`);
707
+ lines.push(`${prefix}${formatYellow("⚠")} This migration contains destructive operations that may cause data loss.`);
708
+ }
709
+ }
710
+ if (result.sql.length > 0) {
711
+ lines.push(`${prefix}`);
712
+ lines.push(`${prefix}${formatDimText("DDL preview")}`);
713
+ lines.push(`${prefix}`);
714
+ for (const statement of result.sql) {
715
+ const trimmed = statement.trim();
716
+ if (!trimmed) continue;
717
+ const line = trimmed.endsWith(";") ? trimmed : `${trimmed};`;
718
+ lines.push(`${prefix}${line}`);
719
+ }
720
+ }
721
+ return lines.join("\n");
722
+ }
723
+ function formatMigrationStatusOutput(result, flags) {
724
+ if (flags.quiet) return "";
725
+ const lines = [];
726
+ const prefix = createPrefix(flags);
727
+ const useColor = flags.color !== false;
728
+ const formatGreen = createColorFormatter(useColor, green);
729
+ const formatYellow = createColorFormatter(useColor, yellow);
730
+ const formatDimText = (text) => formatDim(useColor, text);
731
+ const formatCyan = createColorFormatter(useColor, cyan);
732
+ if (result.migrations.length === 0) lines.push(`${prefix}${formatDimText("No migrations found")}`);
733
+ else {
734
+ lines.push(`${prefix}${formatDimText("∅ (empty)")}`);
735
+ lines.push(`${prefix}${formatDimText("│")}`);
736
+ for (let i = 0; i < result.migrations.length; i++) {
737
+ const entry = result.migrations[i];
738
+ const isLast = i === result.migrations.length - 1;
739
+ const treeChar = isLast ? "└" : "├";
740
+ const continueLine = isLast ? " " : "│";
741
+ let statusBadge = "";
742
+ if (entry.status === "applied") statusBadge = formatGreen(" ✓ Applied");
743
+ else if (entry.status === "pending") statusBadge = formatYellow(" ⧗ Pending");
744
+ let marker = "";
745
+ if (result.mode === "online") {
746
+ if (entry.status === "applied" && (i === result.migrations.length - 1 || result.migrations[i + 1]?.status !== "applied")) marker = formatCyan(" ◄ DB");
747
+ }
748
+ if (isLast && entry.to === result.contractHash) marker += ` ${formatCyan("◄ Contract")}`;
749
+ else if (isLast && result.contractHash !== entry.to) marker += ` ${formatYellow("◄ Contract is ahead — run migration plan")}`;
750
+ lines.push(`${prefix}${formatDimText(treeChar)}─ ${entry.dirName}${statusBadge}${marker}`);
751
+ const opsSummary = entry.hasDestructive ? formatYellow(entry.operationSummary) : formatDimText(entry.operationSummary);
752
+ lines.push(`${prefix}${formatDimText(continueLine)} ${opsSummary}`);
753
+ const hashDisplay = entry.to.length > 20 ? `${entry.to.slice(0, 20)}...` : entry.to;
754
+ lines.push(`${prefix}${formatDimText(continueLine)} ${formatDimText(`→ ${hashDisplay}`)}`);
755
+ if (!isLast) lines.push(`${prefix}${formatDimText("│")}`);
756
+ }
757
+ lines.push(`${prefix}`);
758
+ if (result.mode === "online") {
759
+ const hasUnknown = result.migrations.some((e) => e.status === "unknown");
760
+ const pendingCount = result.migrations.filter((e) => e.status === "pending").length;
761
+ if (hasUnknown) lines.push(`${prefix}${formatYellow("⚠")} ${result.summary}`);
762
+ else if (pendingCount === 0) lines.push(`${prefix}${formatGreen("✔")} ${result.summary}`);
763
+ else lines.push(`${prefix}${formatYellow("⧗")} ${result.summary}`);
764
+ } else lines.push(`${prefix}${result.summary}`);
765
+ }
766
+ const warnings = result.diagnostics?.filter((d) => d.severity === "warn") ?? [];
767
+ if (warnings.length > 0) {
768
+ lines.push("");
769
+ for (const diag of warnings) {
770
+ lines.push(`${prefix}${formatYellow("⚠")} ${diag.message}`);
771
+ for (const hint of diag.hints) lines.push(`${prefix} ${formatDimText(hint)}`);
772
+ }
773
+ }
774
+ return lines.join("\n");
775
+ }
776
+ /**
777
+ * Formats human-readable output for migration commands (db init, db update) in apply mode.
778
+ */
779
+ function formatMigrationApplyOutput(result, flags) {
780
+ if (flags.quiet) return "";
781
+ const lines = [];
782
+ const prefix = createPrefix(flags);
783
+ const useColor = flags.color !== false;
784
+ const formatGreen = createColorFormatter(useColor, green);
785
+ const formatDimText = (text) => formatDim(useColor, text);
786
+ if (result.ok) {
787
+ const executed = result.execution?.operationsExecuted ?? 0;
788
+ if (executed === 0) lines.push(`${prefix}${formatGreen("✔")} Database already matches contract`);
789
+ else lines.push(`${prefix}${formatGreen("✔")} Applied ${executed} operation(s)`);
790
+ if (result.marker) {
791
+ lines.push(`${prefix}${formatDimText(` Signature: ${result.marker.storageHash}`)}`);
792
+ if (result.marker.profileHash) lines.push(`${prefix}${formatDimText(` Profile hash: ${result.marker.profileHash}`)}`);
793
+ }
794
+ if (isVerbose(flags, 1)) lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
795
+ }
796
+ return lines.join("\n");
797
+ }
798
+ /**
799
+ * Formats JSON output for migration commands (db init, db update).
800
+ */
801
+ function formatMigrationJson(result) {
802
+ return JSON.stringify(result, null, 2);
803
+ }
804
+ /**
805
+ * Fixed width for left column in help output.
806
+ */
807
+ const LEFT_COLUMN_WIDTH = 20;
808
+ /**
809
+ * Minimum width for right column wrapping in help output.
810
+ */
811
+ const RIGHT_COLUMN_MIN_WIDTH = 40;
812
+ /**
813
+ * Maximum width for right column wrapping in help output (when terminal is wide enough).
814
+ */
815
+ const RIGHT_COLUMN_MAX_WIDTH = 90;
816
+ /**
817
+ * Gets the terminal width, or returns a default if not available.
818
+ */
819
+ function getTerminalWidth() {
820
+ const terminalWidth = process.stdout.columns;
821
+ const defaultWidth = Number.parseInt(process.env["CLI_WIDTH"] || "80", 10);
822
+ return terminalWidth || defaultWidth;
823
+ }
824
+ /**
825
+ * Calculates the available width for the right column based on terminal width.
826
+ * Format: "│ " (2) + left column (20) + " " (2) + right column = total
827
+ * So: right column = terminal width - 2 - 20 - 2 = terminal width - 24
828
+ */
829
+ function calculateRightColumnWidth() {
830
+ const availableWidth = getTerminalWidth() - 2 - LEFT_COLUMN_WIDTH - 2;
831
+ return Math.max(RIGHT_COLUMN_MIN_WIDTH, Math.min(availableWidth, RIGHT_COLUMN_MAX_WIDTH));
832
+ }
833
+ /**
834
+ * Creates an arrow segment badge with green background and white text.
835
+ * Body: green background with white "prisma-next" text
836
+ * Tip: dark grey arrow pointing right (Powerline separator)
837
+ */
838
+ function createPrismaNextBadge(useColor) {
839
+ if (!useColor) return "prisma-next";
840
+ return `${bgGreen(bold(" prisma-next "))}${green("")}`;
841
+ }
842
+ /**
843
+ * Creates a padding function.
844
+ */
845
+ function createPadFunction() {
846
+ return (s, w) => s + " ".repeat(Math.max(0, w - s.length));
847
+ }
848
+ /**
849
+ * Formats a header line: brand + operation + intent
850
+ */
851
+ function formatHeaderLine(options) {
852
+ if (options.operation) return `${options.brand} ${options.operation} → ${options.intent}`;
853
+ return `${options.brand} ${options.intent}`;
854
+ }
855
+ /**
856
+ * Formats a "Read more" URL line.
857
+ * The "Read more" label is in default color (not cyan), and the URL is blue.
858
+ */
859
+ function formatReadMoreLine(options) {
860
+ const labelPadded = createPadFunction()("Read more", options.maxLabelWidth);
861
+ const valueColored = options.useColor ? blue(options.url) : options.url;
862
+ return `${options.formatDimText("│")} ${labelPadded} ${valueColored}`;
863
+ }
864
+ /**
865
+ * Pads text to a fixed width, accounting for ANSI escape codes.
866
+ * Uses string-width to measure the actual display width.
867
+ */
868
+ function padToFixedWidth(text, width) {
869
+ const actualWidth = stringWidth(text);
870
+ const padding = Math.max(0, width - actualWidth);
871
+ return text + " ".repeat(padding);
872
+ }
873
+ /**
874
+ * Wraps text to fit within a specified width using wrap-ansi.
875
+ * Preserves ANSI escape codes and breaks at word boundaries.
876
+ */
877
+ function wrapTextAnsi(text, width) {
878
+ return wrapAnsi(text, width, {
879
+ hard: false,
880
+ trim: true
881
+ }).split("\n");
882
+ }
883
+ /**
884
+ * Formats a default value as "default: <value>" with dimming.
885
+ */
886
+ function formatDefaultValue(value, useColor) {
887
+ const defaultText = `default: ${String(value)}`;
888
+ return useColor ? dim(defaultText) : defaultText;
889
+ }
890
+ /**
891
+ * Renders a command tree structure.
892
+ * Handles both single-level (subcommands of a command) and multi-level (top-level commands with subcommands) trees.
893
+ */
894
+ function renderCommandTree(options) {
895
+ const { commands, useColor, formatDimText, hasItemsAfter, continuationPrefix } = options;
896
+ const lines = [];
897
+ if (commands.length === 0) return lines;
898
+ for (let i = 0; i < commands.length; i++) {
899
+ const cmd = commands[i];
900
+ if (!cmd) continue;
901
+ const subcommands = cmd.commands.filter((subcmd) => !subcmd.name().startsWith("_"));
902
+ const isLastCommand = i === commands.length - 1;
903
+ if (subcommands.length > 0) {
904
+ const treePrefix = `${isLastCommand && !hasItemsAfter ? formatDimText("└") : formatDimText("├")}─ `;
905
+ const remainingWidth = LEFT_COLUMN_WIDTH - stringWidth(stripAnsi(treePrefix));
906
+ const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);
907
+ const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;
908
+ lines.push(`${formatDimText("│")} ${treePrefix}${commandNameColored}`);
909
+ for (let j = 0; j < subcommands.length; j++) {
910
+ const subcmd = subcommands[j];
911
+ if (!subcmd) continue;
912
+ const isLastSubcommand = j === subcommands.length - 1;
913
+ const shortDescription = subcmd.description() || "";
914
+ const treeChar = isLastSubcommand ? "└" : "├";
915
+ const continuation = continuationPrefix ?? (isLastCommand && isLastSubcommand && !hasItemsAfter ? " " : formatDimText("│"));
916
+ const subTreePrefix = `${continuation === " " ? " " : continuation} ${formatDimText(treeChar)}─ `;
917
+ const subRemainingWidth = LEFT_COLUMN_WIDTH - stringWidth(stripAnsi(subTreePrefix));
918
+ const subcommandNamePadded = padToFixedWidth(subcmd.name(), subRemainingWidth);
919
+ const subcommandNameColored = useColor ? cyan(subcommandNamePadded) : subcommandNamePadded;
920
+ lines.push(`${formatDimText("│")} ${subTreePrefix}${subcommandNameColored} ${shortDescription}`);
921
+ }
922
+ } else {
923
+ const treePrefix = `${isLastCommand && !hasItemsAfter ? formatDimText("└") : formatDimText("├")}─ `;
924
+ const remainingWidth = LEFT_COLUMN_WIDTH - stringWidth(stripAnsi(treePrefix));
925
+ const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);
926
+ const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;
927
+ const shortDescription = cmd.description() || "";
928
+ lines.push(`${formatDimText("│")} ${treePrefix}${commandNameColored} ${shortDescription}`);
929
+ }
930
+ }
931
+ return lines;
932
+ }
933
+ /**
934
+ * Formats multiline description with "Prisma Next" in green.
935
+ * Wraps at the same right-hand boundary as the right column.
936
+ * The right edge is defined by: left column (20) + gap (2) + right column (90) = 112 characters total.
937
+ * Since the description line starts with "│ " (2 chars), the text wraps at 112 - 2 = 110 characters.
938
+ */
939
+ function formatMultilineDescription(options) {
940
+ const lines = [];
941
+ const formatGreen = (text) => options.useColor ? green(text) : text;
942
+ const rightColumnWidth = calculateRightColumnWidth();
943
+ const wrapWidth = 2 + LEFT_COLUMN_WIDTH + 2 + rightColumnWidth - 2;
944
+ for (const descLine of options.descriptionLines) {
945
+ const wrappedLines = wrapTextAnsi(descLine.replace(/Prisma Next/g, (match) => formatGreen(match)), wrapWidth);
946
+ for (const wrappedLine of wrappedLines) lines.push(`${options.formatDimText("│")} ${wrappedLine}`);
947
+ }
948
+ return lines;
949
+ }
950
+ /**
951
+ * Formats the header in the new experimental visual style.
952
+ * This header appears at the start of command output, showing the operation,
953
+ * intent, documentation link, and parameters.
954
+ */
955
+ function formatStyledHeader(options) {
956
+ const lines = [];
957
+ const useColor = options.flags.color !== false;
958
+ const formatDimText = (text) => formatDim(useColor, text);
959
+ const brand = createPrismaNextBadge(useColor);
960
+ const operation = useColor ? bold(options.command) : options.command;
961
+ const intent = formatDimText(options.description);
962
+ lines.push(formatHeaderLine({
963
+ brand,
964
+ operation,
965
+ intent
966
+ }));
967
+ lines.push(formatDimText("│"));
968
+ for (const detail of options.details) {
969
+ const labelPadded = padToFixedWidth(`${detail.label}:`, LEFT_COLUMN_WIDTH);
970
+ const labelColored = useColor ? cyan(labelPadded) : labelPadded;
971
+ lines.push(`${formatDimText("│")} ${labelColored} ${detail.value}`);
972
+ }
973
+ if (options.url) {
974
+ lines.push(formatDimText("│"));
975
+ lines.push(formatReadMoreLine({
976
+ url: options.url,
977
+ maxLabelWidth: LEFT_COLUMN_WIDTH,
978
+ useColor,
979
+ formatDimText
980
+ }));
981
+ }
982
+ lines.push(formatDimText("└"));
983
+ return `${lines.join("\n")}\n`;
984
+ }
985
+ /**
986
+ * Formats a success message in the styled output format.
987
+ */
988
+ function formatSuccessMessage(flags) {
989
+ return `${createColorFormatter(flags.color !== false, green)("✔")} Success`;
990
+ }
991
+ /**
992
+ * Maps command paths to their documentation URLs.
993
+ */
994
+ function getCommandDocsUrl(commandPath) {
995
+ return {
996
+ "contract emit": "https://pris.ly/contract-emit",
997
+ "db verify": "https://pris.ly/db-verify",
998
+ "db update": "https://pris.ly/db-update"
999
+ }[commandPath];
1000
+ }
1001
+ /**
1002
+ * Builds the full command path from a command and its parents.
1003
+ */
1004
+ function buildCommandPath(command) {
1005
+ const parts = [];
1006
+ let current = command;
1007
+ while (current && current.name() !== "prisma-next") {
1008
+ parts.unshift(current.name());
1009
+ current = current.parent ?? void 0;
1010
+ }
1011
+ return parts.join(" ");
1012
+ }
1013
+ /**
1014
+ * Formats help output for a command using the styled format.
1015
+ */
1016
+ function formatCommandHelp(options) {
1017
+ const { command, flags } = options;
1018
+ const lines = [];
1019
+ const useColor = flags.color !== false;
1020
+ const formatDimText = (text) => formatDim(useColor, text);
1021
+ const commandPath = buildCommandPath(command);
1022
+ const shortDescription = command.description() || "";
1023
+ const longDescription = getLongDescription(command);
1024
+ const brand = createPrismaNextBadge(useColor);
1025
+ const operation = useColor ? bold(commandPath) : commandPath;
1026
+ const intent = formatDimText(shortDescription);
1027
+ lines.push(formatHeaderLine({
1028
+ brand,
1029
+ operation,
1030
+ intent
1031
+ }));
1032
+ lines.push(formatDimText("│"));
1033
+ const optionsList = command.options.map((opt) => {
1034
+ return {
1035
+ flags: opt.flags,
1036
+ description: opt.description || "",
1037
+ defaultValue: opt.defaultValue
1038
+ };
1039
+ });
1040
+ const subcommands = command.commands.filter((cmd) => !cmd.name().startsWith("_"));
1041
+ if (subcommands.length > 0) {
1042
+ const treeLines = renderCommandTree({
1043
+ commands: subcommands,
1044
+ useColor,
1045
+ formatDimText,
1046
+ hasItemsAfter: optionsList.length > 0
1047
+ });
1048
+ lines.push(...treeLines);
1049
+ }
1050
+ if (subcommands.length > 0 && optionsList.length > 0) lines.push(formatDimText("│"));
1051
+ if (optionsList.length > 0) for (const opt of optionsList) {
1052
+ const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);
1053
+ let flagsColored = flagsPadded;
1054
+ if (useColor) {
1055
+ flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match) => magenta(match));
1056
+ flagsColored = cyan(flagsColored);
1057
+ }
1058
+ const rightColumnWidth = calculateRightColumnWidth();
1059
+ const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);
1060
+ lines.push(`${formatDimText("│")} ${flagsColored} ${wrappedDescription[0] || ""}`);
1061
+ for (let i = 1; i < wrappedDescription.length; i++) {
1062
+ const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1063
+ lines.push(`${formatDimText("│")} ${emptyLabel} ${wrappedDescription[i] || ""}`);
1064
+ }
1065
+ if (opt.defaultValue !== void 0) {
1066
+ const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1067
+ const defaultText = formatDefaultValue(opt.defaultValue, useColor);
1068
+ lines.push(`${formatDimText("│")} ${emptyLabel} ${defaultText}`);
1069
+ }
1070
+ }
1071
+ const docsUrl = getCommandDocsUrl(commandPath);
1072
+ if (docsUrl) {
1073
+ lines.push(formatDimText("│"));
1074
+ lines.push(formatReadMoreLine({
1075
+ url: docsUrl,
1076
+ maxLabelWidth: LEFT_COLUMN_WIDTH,
1077
+ useColor,
1078
+ formatDimText
1079
+ }));
1080
+ }
1081
+ if (longDescription) {
1082
+ lines.push(formatDimText("│"));
1083
+ const descriptionLines = longDescription.split("\n").filter((line) => line.trim().length > 0);
1084
+ lines.push(...formatMultilineDescription({
1085
+ descriptionLines,
1086
+ useColor,
1087
+ formatDimText
1088
+ }));
1089
+ }
1090
+ lines.push(formatDimText("└"));
1091
+ return `${lines.join("\n")}\n`;
1092
+ }
1093
+ /**
1094
+ * Formats help output for the root program using the styled format.
1095
+ */
1096
+ function formatRootHelp(options) {
1097
+ const { program, flags } = options;
1098
+ const lines = [];
1099
+ const useColor = flags.color !== false;
1100
+ const formatDimText = (text) => formatDim(useColor, text);
1101
+ const brand = createPrismaNextBadge(useColor);
1102
+ const intent = formatDimText("Manage your data layer");
1103
+ lines.push(formatHeaderLine({
1104
+ brand,
1105
+ operation: "",
1106
+ intent
1107
+ }));
1108
+ lines.push(formatDimText("│"));
1109
+ const topLevelCommands = program.commands.filter((cmd) => !cmd.name().startsWith("_") && cmd.name() !== "help");
1110
+ const globalOptions = program.options.map((opt) => {
1111
+ return {
1112
+ flags: opt.flags,
1113
+ description: opt.description || "",
1114
+ defaultValue: opt.defaultValue
1115
+ };
1116
+ });
1117
+ if (topLevelCommands.length > 0) {
1118
+ const treeLines = renderCommandTree({
1119
+ commands: topLevelCommands,
1120
+ useColor,
1121
+ formatDimText,
1122
+ hasItemsAfter: globalOptions.length > 0
1123
+ });
1124
+ lines.push(...treeLines);
1125
+ }
1126
+ if (topLevelCommands.length > 0 && globalOptions.length > 0) lines.push(formatDimText("│"));
1127
+ if (globalOptions.length > 0) for (const opt of globalOptions) {
1128
+ const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);
1129
+ let flagsColored = flagsPadded;
1130
+ if (useColor) {
1131
+ flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match) => magenta(match));
1132
+ flagsColored = cyan(flagsColored);
1133
+ }
1134
+ const rightColumnWidth = calculateRightColumnWidth();
1135
+ const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);
1136
+ lines.push(`${formatDimText("│")} ${flagsColored} ${wrappedDescription[0] || ""}`);
1137
+ for (let i = 1; i < wrappedDescription.length; i++) {
1138
+ const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1139
+ lines.push(`${formatDimText("│")} ${emptyLabel} ${wrappedDescription[i] || ""}`);
1140
+ }
1141
+ if (opt.defaultValue !== void 0) {
1142
+ const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1143
+ const defaultText = formatDefaultValue(opt.defaultValue, useColor);
1144
+ lines.push(`${formatDimText("│")} ${emptyLabel} ${defaultText}`);
1145
+ }
1146
+ }
1147
+ const formatGreen = (text) => useColor ? green(text) : text;
1148
+ const descriptionLines = [`Use ${formatGreen("Prisma Next")} to define your data layer as a contract. Sign your database and application with the same contract to guarantee compatibility. Plan and apply migrations to safely evolve your schema.`];
1149
+ if (descriptionLines.length > 0) {
1150
+ lines.push(formatDimText("│"));
1151
+ lines.push(...formatMultilineDescription({
1152
+ descriptionLines,
1153
+ useColor,
1154
+ formatDimText
1155
+ }));
1156
+ }
1157
+ lines.push(formatDimText("└"));
1158
+ return `${lines.join("\n")}\n`;
1159
+ }
1160
+
1161
+ //#endregion
1162
+ //#region src/utils/result-handler.ts
1163
+ /**
1164
+ * Processes a CLI command result, handling both success and error cases.
1165
+ * Formats output appropriately and returns the exit code.
1166
+ * Never throws - returns exit code for commands to use with process.exit().
1167
+ *
1168
+ * @param result - The result from a CLI command
1169
+ * @param flags - Global flags for output formatting
1170
+ * @param onSuccess - Optional callback for successful results (for custom success output)
1171
+ * @returns The exit code that should be used (0 for success, non-zero for errors)
1172
+ */
1173
+ function handleResult(result, flags, onSuccess) {
1174
+ if (result.ok) {
1175
+ if (onSuccess) onSuccess(result.value);
1176
+ return 0;
1177
+ }
1178
+ const envelope = result.failure.toEnvelope();
1179
+ if (flags.json) console.error(formatErrorJson(envelope));
1180
+ else console.error(formatErrorOutput(envelope, flags));
1181
+ return result.failure.domain === "CLI" ? 2 : 1;
1182
+ }
1183
+
1184
+ //#endregion
1185
+ export { parseGlobalFlags as C, setCommandDescriptions as D, sanitizeErrorMessage as E, formatVerifyOutput as S, resolveContractPath as T, formatSignJson as _, formatIntrospectJson as a, formatSuccessMessage as b, formatMigrationApplyOutput as c, formatMigrationShowOutput as d, formatMigrationStatusOutput as f, formatSchemaVerifyOutput as g, formatSchemaVerifyJson as h, formatEmitOutput as i, formatMigrationJson as l, formatRootHelp as m, formatCommandHelp as n, formatIntrospectOutput as o, formatMigrationVerifyCommandOutput as p, formatEmitJson as r, formatMigrationApplyCommandOutput as s, handleResult as t, formatMigrationPlanOutput as u, formatSignOutput as v, maskConnectionUrl as w, formatVerifyJson as x, formatStyledHeader as y };
1186
+ //# sourceMappingURL=result-handler-iA9JtUC7.mjs.map