@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
package/dist/cli.js CHANGED
@@ -1,2351 +1,2 @@
1
1
  #!/usr/bin/env node
2
-
3
- // src/cli.ts
4
- import { Command as Command7 } from "commander";
5
-
6
- // src/commands/contract-emit.ts
7
- import { mkdirSync, writeFileSync } from "fs";
8
- import { dirname as dirname2, relative as relative2, resolve as resolve2 } from "path";
9
- import { errorContractConfigMissing as errorContractConfigMissing2 } from "@prisma-next/core-control-plane/errors";
10
- import { createControlPlaneStack } from "@prisma-next/core-control-plane/types";
11
- import { Command } from "commander";
12
-
13
- // src/config-loader.ts
14
- import { dirname, resolve } from "path";
15
- import { validateConfig } from "@prisma-next/core-control-plane/config-validation";
16
- import { errorConfigFileNotFound, errorUnexpected } from "@prisma-next/core-control-plane/errors";
17
- import { loadConfig as loadConfigC12 } from "c12";
18
- async function loadConfig(configPath) {
19
- try {
20
- const cwd = process.cwd();
21
- const resolvedConfigPath = configPath ? resolve(cwd, configPath) : void 0;
22
- const configCwd = resolvedConfigPath ? dirname(resolvedConfigPath) : cwd;
23
- const result = await loadConfigC12({
24
- name: "prisma-next",
25
- ...resolvedConfigPath ? { configFile: resolvedConfigPath } : {},
26
- cwd: configCwd
27
- });
28
- if (resolvedConfigPath && result.configFile !== resolvedConfigPath) {
29
- throw errorConfigFileNotFound(resolvedConfigPath);
30
- }
31
- if (!result.config || Object.keys(result.config).length === 0) {
32
- const displayPath = result.configFile || resolvedConfigPath || configPath;
33
- throw errorConfigFileNotFound(displayPath);
34
- }
35
- validateConfig(result.config);
36
- return result.config;
37
- } catch (error) {
38
- if (error instanceof Error && "code" in error && typeof error.code === "string") {
39
- throw error;
40
- }
41
- if (error instanceof Error) {
42
- if (error.message.includes("not found") || error.message.includes("Cannot find") || error.message.includes("ENOENT")) {
43
- const displayPath = configPath ? resolve(process.cwd(), configPath) : void 0;
44
- throw errorConfigFileNotFound(displayPath, {
45
- why: error.message
46
- });
47
- }
48
- throw errorUnexpected(error.message, {
49
- why: `Failed to load config: ${error.message}`
50
- });
51
- }
52
- throw errorUnexpected(String(error));
53
- }
54
- }
55
-
56
- // src/utils/action.ts
57
- import { notOk, ok } from "@prisma-next/utils/result";
58
-
59
- // src/utils/cli-errors.ts
60
- import {
61
- CliStructuredError,
62
- errorConfigFileNotFound as errorConfigFileNotFound2,
63
- errorConfigValidation,
64
- errorContractConfigMissing,
65
- errorContractMissingExtensionPacks,
66
- errorContractValidationFailed,
67
- errorDatabaseUrlRequired,
68
- errorDriverRequired,
69
- errorFamilyReadMarkerSqlRequired,
70
- errorFileNotFound,
71
- errorHashMismatch,
72
- errorJsonFormatNotSupported,
73
- errorMarkerMissing,
74
- errorMigrationPlanningFailed,
75
- errorQueryRunnerFactoryRequired,
76
- errorRuntime,
77
- errorTargetMigrationNotSupported,
78
- errorTargetMismatch,
79
- errorUnexpected as errorUnexpected2
80
- } from "@prisma-next/core-control-plane/errors";
81
-
82
- // src/utils/action.ts
83
- async function performAction(fn) {
84
- try {
85
- const value = await fn();
86
- return ok(value);
87
- } catch (error) {
88
- if (error instanceof CliStructuredError) {
89
- return notOk(error);
90
- }
91
- throw error;
92
- }
93
- }
94
-
95
- // src/utils/command-helpers.ts
96
- function setCommandDescriptions(command, shortDescription, longDescription) {
97
- command.description(shortDescription);
98
- if (longDescription) {
99
- command._longDescription = longDescription;
100
- }
101
- return command;
102
- }
103
- function getLongDescription(command) {
104
- return command._longDescription;
105
- }
106
-
107
- // src/utils/global-flags.ts
108
- function parseGlobalFlags(options) {
109
- const flags = {};
110
- if (options.json === true || options.json === "object") {
111
- flags.json = "object";
112
- } else if (options.json === "ndjson") {
113
- flags.json = "ndjson";
114
- }
115
- if (options.quiet || options.q) {
116
- flags.quiet = true;
117
- }
118
- if (options.vv || options.trace) {
119
- flags.verbose = 2;
120
- } else if (options.verbose || options.v) {
121
- flags.verbose = 1;
122
- } else {
123
- flags.verbose = 0;
124
- }
125
- if (options.timestamps) {
126
- flags.timestamps = true;
127
- }
128
- if (process.env["NO_COLOR"] || flags.json) {
129
- flags.color = false;
130
- } else if (options["no-color"]) {
131
- flags.color = false;
132
- } else if (options.color !== void 0) {
133
- flags.color = options.color;
134
- } else {
135
- flags.color = process.stdout.isTTY && !process.env["CI"];
136
- }
137
- return flags;
138
- }
139
-
140
- // src/utils/output.ts
141
- import { relative } from "path";
142
- import { bgGreen, blue, bold, cyan, dim, green, magenta, red, yellow } from "colorette";
143
- import stringWidth from "string-width";
144
- import stripAnsi from "strip-ansi";
145
- import wrapAnsi from "wrap-ansi";
146
- function formatTimestamp() {
147
- return (/* @__PURE__ */ new Date()).toISOString();
148
- }
149
- function createPrefix(flags) {
150
- return flags.timestamps ? `[${formatTimestamp()}] ` : "";
151
- }
152
- function isVerbose(flags, level) {
153
- return (flags.verbose ?? 0) >= level;
154
- }
155
- function createColorFormatter(useColor, colorFn) {
156
- return useColor ? colorFn : (text) => text;
157
- }
158
- function formatDim(useColor, text) {
159
- return useColor ? dim(text) : text;
160
- }
161
- function formatEmitOutput(result, flags) {
162
- if (flags.quiet) {
163
- return "";
164
- }
165
- const lines = [];
166
- const prefix = createPrefix(flags);
167
- const jsonPath = relative(process.cwd(), result.files.json);
168
- const dtsPath = relative(process.cwd(), result.files.dts);
169
- lines.push(`${prefix}\u2714 Emitted contract.json \u2192 ${jsonPath}`);
170
- lines.push(`${prefix}\u2714 Emitted contract.d.ts \u2192 ${dtsPath}`);
171
- lines.push(`${prefix} coreHash: ${result.coreHash}`);
172
- if (result.profileHash) {
173
- lines.push(`${prefix} profileHash: ${result.profileHash}`);
174
- }
175
- if (isVerbose(flags, 1)) {
176
- lines.push(`${prefix} Total time: ${result.timings.total}ms`);
177
- }
178
- return lines.join("\n");
179
- }
180
- function formatEmitJson(result) {
181
- const output = {
182
- ok: true,
183
- coreHash: result.coreHash,
184
- ...result.profileHash ? { profileHash: result.profileHash } : {},
185
- outDir: result.outDir,
186
- files: result.files,
187
- timings: result.timings
188
- };
189
- return JSON.stringify(output, null, 2);
190
- }
191
- function formatErrorOutput(error, flags) {
192
- const lines = [];
193
- const prefix = createPrefix(flags);
194
- const useColor = flags.color !== false;
195
- const formatRed = createColorFormatter(useColor, red);
196
- const formatDimText = (text) => formatDim(useColor, text);
197
- lines.push(`${prefix}${formatRed("\u2716")} ${error.summary} (${error.code})`);
198
- if (error.why) {
199
- lines.push(`${prefix}${formatDimText(` Why: ${error.why}`)}`);
200
- }
201
- if (error.fix) {
202
- lines.push(`${prefix}${formatDimText(` Fix: ${error.fix}`)}`);
203
- }
204
- if (error.where?.path) {
205
- const whereLine = error.where.line ? `${error.where.path}:${error.where.line}` : error.where.path;
206
- lines.push(`${prefix}${formatDimText(` Where: ${whereLine}`)}`);
207
- }
208
- if (error.meta?.["conflicts"]) {
209
- const conflicts = error.meta["conflicts"];
210
- if (conflicts.length > 0) {
211
- const maxToShow = isVerbose(flags, 1) ? conflicts.length : Math.min(3, conflicts.length);
212
- const header = isVerbose(flags, 1) ? " Conflicts:" : ` Conflicts (showing ${maxToShow} of ${conflicts.length}):`;
213
- lines.push(`${prefix}${formatDimText(header)}`);
214
- for (const conflict of conflicts.slice(0, maxToShow)) {
215
- lines.push(`${prefix}${formatDimText(` - [${conflict.kind}] ${conflict.summary}`)}`);
216
- }
217
- if (!isVerbose(flags, 1) && conflicts.length > maxToShow) {
218
- lines.push(`${prefix}${formatDimText(" Re-run with -v/--verbose to see all conflicts")}`);
219
- }
220
- }
221
- }
222
- if (error.meta?.["issues"]) {
223
- const issues = error.meta["issues"];
224
- if (issues.length > 0) {
225
- const maxToShow = isVerbose(flags, 1) ? issues.length : Math.min(3, issues.length);
226
- const header = isVerbose(flags, 1) ? " Issues:" : ` Issues (showing ${maxToShow} of ${issues.length}):`;
227
- lines.push(`${prefix}${formatDimText(header)}`);
228
- for (const issue of issues.slice(0, maxToShow)) {
229
- const kind = issue.kind ?? "issue";
230
- const message = issue.message ?? "";
231
- lines.push(`${prefix}${formatDimText(` - [${kind}] ${message}`)}`);
232
- }
233
- if (!isVerbose(flags, 1) && issues.length > maxToShow) {
234
- lines.push(`${prefix}${formatDimText(" Re-run with -v/--verbose to see all issues")}`);
235
- }
236
- }
237
- }
238
- if (error.docsUrl && isVerbose(flags, 1)) {
239
- lines.push(formatDimText(error.docsUrl));
240
- }
241
- if (isVerbose(flags, 2) && error.meta) {
242
- lines.push(`${prefix}${formatDimText(` Meta: ${JSON.stringify(error.meta, null, 2)}`)}`);
243
- }
244
- return lines.join("\n");
245
- }
246
- function formatErrorJson(error) {
247
- return JSON.stringify(error, null, 2);
248
- }
249
- function formatVerifyOutput(result, flags) {
250
- if (flags.quiet) {
251
- return "";
252
- }
253
- const lines = [];
254
- const prefix = createPrefix(flags);
255
- const useColor = flags.color !== false;
256
- const formatGreen = createColorFormatter(useColor, green);
257
- const formatRed = createColorFormatter(useColor, red);
258
- const formatDimText = (text) => formatDim(useColor, text);
259
- if (result.ok) {
260
- lines.push(`${prefix}${formatGreen("\u2714")} ${result.summary}`);
261
- lines.push(`${prefix}${formatDimText(` coreHash: ${result.contract.coreHash}`)}`);
262
- if (result.contract.profileHash) {
263
- lines.push(`${prefix}${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);
264
- }
265
- } else {
266
- lines.push(`${prefix}${formatRed("\u2716")} ${result.summary} (${result.code})`);
267
- }
268
- if (isVerbose(flags, 1)) {
269
- if (result.codecCoverageSkipped) {
270
- lines.push(
271
- `${prefix}${formatDimText(" Codec coverage check skipped (helper returned no supported types)")}`
272
- );
273
- }
274
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
275
- }
276
- return lines.join("\n");
277
- }
278
- function formatVerifyJson(result) {
279
- const output = {
280
- ok: result.ok,
281
- ...result.code ? { code: result.code } : {},
282
- summary: result.summary,
283
- contract: result.contract,
284
- ...result.marker ? { marker: result.marker } : {},
285
- target: result.target,
286
- ...result.missingCodecs ? { missingCodecs: result.missingCodecs } : {},
287
- ...result.meta ? { meta: result.meta } : {},
288
- timings: result.timings
289
- };
290
- return JSON.stringify(output, null, 2);
291
- }
292
- function formatIntrospectJson(result) {
293
- return JSON.stringify(result, null, 2);
294
- }
295
- function renderSchemaTree(node, flags, options) {
296
- const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;
297
- const lines = [];
298
- let formattedLabel = node.label;
299
- if (useColor) {
300
- switch (node.kind) {
301
- case "root":
302
- formattedLabel = bold(node.label);
303
- break;
304
- case "entity": {
305
- const tableMatch = node.label.match(/^table\s+(.+)$/);
306
- if (tableMatch?.[1]) {
307
- const tableName = tableMatch[1];
308
- formattedLabel = `${dim("table")} ${cyan(tableName)}`;
309
- } else {
310
- formattedLabel = cyan(node.label);
311
- }
312
- break;
313
- }
314
- case "collection": {
315
- formattedLabel = dim(node.label);
316
- break;
317
- }
318
- case "field": {
319
- const columnMatch = node.label.match(/^([^:]+):\s*(.+)$/);
320
- if (columnMatch?.[1] && columnMatch[2]) {
321
- const columnName = columnMatch[1];
322
- const rest = columnMatch[2];
323
- const typeMatch = rest.match(/^([^\s(]+)\s*(\([^)]+\))$/);
324
- if (typeMatch?.[1] && typeMatch[2]) {
325
- const typeDisplay = typeMatch[1];
326
- const nullability = typeMatch[2];
327
- formattedLabel = `${cyan(columnName)}: ${typeDisplay} ${dim(nullability)}`;
328
- } else {
329
- formattedLabel = `${cyan(columnName)}: ${rest}`;
330
- }
331
- } else {
332
- formattedLabel = node.label;
333
- }
334
- break;
335
- }
336
- case "index": {
337
- const pkMatch = node.label.match(/^primary key:\s*(.+)$/);
338
- if (pkMatch?.[1]) {
339
- const columnNames = pkMatch[1];
340
- formattedLabel = `${dim("primary key")}: ${cyan(columnNames)}`;
341
- } else {
342
- const uniqueMatch = node.label.match(/^unique\s+(.+)$/);
343
- if (uniqueMatch?.[1]) {
344
- const name = uniqueMatch[1];
345
- formattedLabel = `${dim("unique")} ${cyan(name)}`;
346
- } else {
347
- const indexMatch = node.label.match(/^(unique\s+)?index\s+(.+)$/);
348
- if (indexMatch?.[2]) {
349
- const prefix2 = indexMatch[1] ? `${dim("unique")} ` : "";
350
- const name = indexMatch[2];
351
- formattedLabel = `${prefix2}${dim("index")} ${cyan(name)}`;
352
- } else {
353
- formattedLabel = dim(node.label);
354
- }
355
- }
356
- }
357
- break;
358
- }
359
- case "extension": {
360
- const extMatch = node.label.match(/^([^\s]+)\s+(extension is enabled)$/);
361
- if (extMatch?.[1] && extMatch[2]) {
362
- const extName = extMatch[1];
363
- const rest = extMatch[2];
364
- formattedLabel = `${cyan(extName)} ${dim(rest)}`;
365
- } else {
366
- formattedLabel = magenta(node.label);
367
- }
368
- break;
369
- }
370
- default:
371
- formattedLabel = node.label;
372
- break;
373
- }
374
- }
375
- if (isRoot) {
376
- lines.push(formattedLabel);
377
- } else {
378
- const treeChar = isLast ? "\u2514" : "\u251C";
379
- const treePrefix = `${prefix}${formatDimText(treeChar)}\u2500 `;
380
- const isRootChild = prefix === "";
381
- const prefixWithoutAnsi = stripAnsi(prefix);
382
- const prefixHasVerticalBar = prefixWithoutAnsi.includes("\u2502");
383
- if (isRootChild) {
384
- lines.push(`${treePrefix}${formattedLabel}`);
385
- } else if (prefixHasVerticalBar) {
386
- lines.push(`${treePrefix}${formattedLabel}`);
387
- } else {
388
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${formattedLabel}`);
389
- }
390
- }
391
- if (node.children && node.children.length > 0) {
392
- const childPrefix = isRoot ? "" : isLast ? `${prefix} ` : `${prefix}${formatDimText("\u2502")} `;
393
- for (let i = 0; i < node.children.length; i++) {
394
- const child = node.children[i];
395
- if (!child) continue;
396
- const isLastChild = i === node.children.length - 1;
397
- const childLines = renderSchemaTree(child, flags, {
398
- isLast: isLastChild,
399
- prefix: childPrefix,
400
- useColor,
401
- formatDimText,
402
- isRoot: false
403
- });
404
- lines.push(...childLines);
405
- }
406
- }
407
- return lines;
408
- }
409
- function formatIntrospectOutput(result, schemaView, flags) {
410
- if (flags.quiet) {
411
- return "";
412
- }
413
- const lines = [];
414
- const prefix = createPrefix(flags);
415
- const useColor = flags.color !== false;
416
- const formatDimText = (text) => formatDim(useColor, text);
417
- if (schemaView) {
418
- const treeLines = renderSchemaTree(schemaView.root, flags, {
419
- isLast: true,
420
- prefix: "",
421
- useColor,
422
- formatDimText,
423
- isRoot: true
424
- });
425
- const prefixedTreeLines = treeLines.map((line) => `${prefix}${line}`);
426
- lines.push(...prefixedTreeLines);
427
- } else {
428
- lines.push(`${prefix}\u2714 ${result.summary}`);
429
- if (isVerbose(flags, 1)) {
430
- lines.push(`${prefix} Target: ${result.target.familyId}/${result.target.id}`);
431
- if (result.meta?.dbUrl) {
432
- lines.push(`${prefix} Database: ${result.meta.dbUrl}`);
433
- }
434
- }
435
- }
436
- if (isVerbose(flags, 1)) {
437
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
438
- }
439
- return lines.join("\n");
440
- }
441
- function renderSchemaVerificationTree(node, flags, options) {
442
- const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;
443
- const lines = [];
444
- let statusGlyph = "";
445
- let statusColor = (text) => text;
446
- if (useColor) {
447
- switch (node.status) {
448
- case "pass":
449
- statusGlyph = "\u2714";
450
- statusColor = green;
451
- break;
452
- case "warn":
453
- statusGlyph = "\u26A0";
454
- statusColor = (text) => useColor ? yellow(text) : text;
455
- break;
456
- case "fail":
457
- statusGlyph = "\u2716";
458
- statusColor = red;
459
- break;
460
- }
461
- } else {
462
- switch (node.status) {
463
- case "pass":
464
- statusGlyph = "\u2714";
465
- break;
466
- case "warn":
467
- statusGlyph = "\u26A0";
468
- break;
469
- case "fail":
470
- statusGlyph = "\u2716";
471
- break;
472
- }
473
- }
474
- let labelColor = (text) => text;
475
- let formattedLabel = node.name;
476
- if (useColor) {
477
- switch (node.kind) {
478
- case "contract":
479
- case "schema":
480
- labelColor = bold;
481
- formattedLabel = labelColor(node.name);
482
- break;
483
- case "table": {
484
- const tableMatch = node.name.match(/^table\s+(.+)$/);
485
- if (tableMatch?.[1]) {
486
- const tableName = tableMatch[1];
487
- formattedLabel = `${dim("table")} ${cyan(tableName)}`;
488
- } else {
489
- formattedLabel = dim(node.name);
490
- }
491
- break;
492
- }
493
- case "columns":
494
- labelColor = dim;
495
- formattedLabel = labelColor(node.name);
496
- break;
497
- case "column": {
498
- const columnMatch = node.name.match(/^([^:]+):\s*(.+)$/);
499
- if (columnMatch?.[1] && columnMatch[2]) {
500
- const columnName = columnMatch[1];
501
- const rest = columnMatch[2];
502
- const typeMatch = rest.match(/^([^\s→]+)\s*→\s*([^\s(]+)\s*(\([^)]+\))$/);
503
- if (typeMatch?.[1] && typeMatch[2] && typeMatch[3]) {
504
- const contractType = typeMatch[1];
505
- const nativeType = typeMatch[2];
506
- const nullability = typeMatch[3];
507
- formattedLabel = `${cyan(columnName)}: ${contractType} \u2192 ${dim(nativeType)} ${dim(nullability)}`;
508
- } else {
509
- formattedLabel = `${cyan(columnName)}: ${rest}`;
510
- }
511
- } else {
512
- formattedLabel = node.name;
513
- }
514
- break;
515
- }
516
- case "type":
517
- case "nullability":
518
- labelColor = (text) => text;
519
- formattedLabel = labelColor(node.name);
520
- break;
521
- case "primaryKey": {
522
- const pkMatch = node.name.match(/^primary key:\s*(.+)$/);
523
- if (pkMatch?.[1]) {
524
- const columnNames = pkMatch[1];
525
- formattedLabel = `${dim("primary key")}: ${cyan(columnNames)}`;
526
- } else {
527
- formattedLabel = dim(node.name);
528
- }
529
- break;
530
- }
531
- case "foreignKey":
532
- case "unique":
533
- case "index":
534
- labelColor = dim;
535
- formattedLabel = labelColor(node.name);
536
- break;
537
- case "extension": {
538
- const dbMatch = node.name.match(/^database is\s+(.+)$/);
539
- if (dbMatch?.[1]) {
540
- const dbName = dbMatch[1];
541
- formattedLabel = `${dim("database is")} ${cyan(dbName)}`;
542
- } else {
543
- const extMatch = node.name.match(/^([^\s]+)\s+(extension is enabled)$/);
544
- if (extMatch?.[1] && extMatch[2]) {
545
- const extName = extMatch[1];
546
- const rest = extMatch[2];
547
- formattedLabel = `${cyan(extName)} ${dim(rest)}`;
548
- } else {
549
- labelColor = magenta;
550
- formattedLabel = labelColor(node.name);
551
- }
552
- }
553
- break;
554
- }
555
- default:
556
- formattedLabel = node.name;
557
- break;
558
- }
559
- } else {
560
- formattedLabel = node.name;
561
- }
562
- const statusGlyphColored = statusColor(statusGlyph);
563
- let nodeLabel = formattedLabel;
564
- if ((node.status === "fail" || node.status === "warn") && node.message && node.message.length > 0) {
565
- const messageText = formatDimText(`(${node.message})`);
566
- nodeLabel = `${formattedLabel} ${messageText}`;
567
- }
568
- if (isRoot) {
569
- lines.push(`${statusGlyphColored} ${nodeLabel}`);
570
- } else {
571
- const treeChar = isLast ? "\u2514" : "\u251C";
572
- const treePrefix = `${prefix}${formatDimText(treeChar)}\u2500 `;
573
- const isRootChild = prefix === "";
574
- const prefixWithoutAnsi = stripAnsi(prefix);
575
- const prefixHasVerticalBar = prefixWithoutAnsi.includes("\u2502");
576
- if (isRootChild) {
577
- lines.push(`${treePrefix}${statusGlyphColored} ${nodeLabel}`);
578
- } else if (prefixHasVerticalBar) {
579
- lines.push(`${treePrefix}${statusGlyphColored} ${nodeLabel}`);
580
- } else {
581
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${statusGlyphColored} ${nodeLabel}`);
582
- }
583
- }
584
- if (node.children && node.children.length > 0) {
585
- const childPrefix = isRoot ? "" : isLast ? `${prefix} ` : `${prefix}${formatDimText("\u2502")} `;
586
- for (let i = 0; i < node.children.length; i++) {
587
- const child = node.children[i];
588
- if (!child) continue;
589
- const isLastChild = i === node.children.length - 1;
590
- const childLines = renderSchemaVerificationTree(child, flags, {
591
- isLast: isLastChild,
592
- prefix: childPrefix,
593
- useColor,
594
- formatDimText,
595
- isRoot: false
596
- });
597
- lines.push(...childLines);
598
- }
599
- }
600
- return lines;
601
- }
602
- function formatSchemaVerifyOutput(result, flags) {
603
- if (flags.quiet) {
604
- return "";
605
- }
606
- const lines = [];
607
- const prefix = createPrefix(flags);
608
- const useColor = flags.color !== false;
609
- const formatGreen = createColorFormatter(useColor, green);
610
- const formatRed = createColorFormatter(useColor, red);
611
- const formatDimText = (text) => formatDim(useColor, text);
612
- const treeLines = renderSchemaVerificationTree(result.schema.root, flags, {
613
- isLast: true,
614
- prefix: "",
615
- useColor,
616
- formatDimText,
617
- isRoot: true
618
- });
619
- const prefixedTreeLines = treeLines.map((line) => `${prefix}${line}`);
620
- lines.push(...prefixedTreeLines);
621
- if (isVerbose(flags, 1)) {
622
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
623
- lines.push(
624
- `${prefix}${formatDimText(` pass=${result.schema.counts.pass} warn=${result.schema.counts.warn} fail=${result.schema.counts.fail}`)}`
625
- );
626
- }
627
- lines.push("");
628
- if (result.ok) {
629
- lines.push(`${prefix}${formatGreen("\u2714")} ${result.summary}`);
630
- } else {
631
- const codeText = result.code ? ` (${result.code})` : "";
632
- lines.push(`${prefix}${formatRed("\u2716")} ${result.summary}${codeText}`);
633
- }
634
- return lines.join("\n");
635
- }
636
- function formatSchemaVerifyJson(result) {
637
- return JSON.stringify(result, null, 2);
638
- }
639
- function formatSignOutput(result, flags) {
640
- if (flags.quiet) {
641
- return "";
642
- }
643
- const lines = [];
644
- const prefix = createPrefix(flags);
645
- const useColor = flags.color !== false;
646
- const formatGreen = createColorFormatter(useColor, green);
647
- const formatDimText = (text) => formatDim(useColor, text);
648
- if (result.ok) {
649
- lines.push(`${prefix}${formatGreen("\u2714")} Database signed`);
650
- const previousHash = result.marker.previous?.coreHash ?? "none";
651
- const currentHash = result.contract.coreHash;
652
- lines.push(`${prefix}${formatDimText(` from: ${previousHash}`)}`);
653
- lines.push(`${prefix}${formatDimText(` to: ${currentHash}`)}`);
654
- if (isVerbose(flags, 1)) {
655
- if (result.contract.profileHash) {
656
- lines.push(`${prefix}${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);
657
- }
658
- if (result.marker.previous?.profileHash) {
659
- lines.push(
660
- `${prefix}${formatDimText(` previous profileHash: ${result.marker.previous.profileHash}`)}`
661
- );
662
- }
663
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
664
- }
665
- }
666
- return lines.join("\n");
667
- }
668
- function formatSignJson(result) {
669
- return JSON.stringify(result, null, 2);
670
- }
671
- function formatDbInitPlanOutput(result, flags) {
672
- if (flags.quiet) {
673
- return "";
674
- }
675
- const lines = [];
676
- const prefix = createPrefix(flags);
677
- const useColor = flags.color !== false;
678
- const formatGreen = createColorFormatter(useColor, green);
679
- const formatDimText = (text) => formatDim(useColor, text);
680
- const operationCount = result.plan?.operations.length ?? 0;
681
- lines.push(`${prefix}${formatGreen("\u2714")} Planned ${operationCount} operation(s)`);
682
- if (result.plan?.operations && result.plan.operations.length > 0) {
683
- lines.push(`${prefix}${formatDimText("\u2502")}`);
684
- for (let i = 0; i < result.plan.operations.length; i++) {
685
- const op = result.plan.operations[i];
686
- if (!op) continue;
687
- const isLast = i === result.plan.operations.length - 1;
688
- const treeChar = isLast ? "\u2514" : "\u251C";
689
- const opClass = formatDimText(`[${op.operationClass}]`);
690
- lines.push(`${prefix}${formatDimText(treeChar)}\u2500 ${op.label} ${opClass}`);
691
- }
692
- }
693
- if (result.plan?.destination) {
694
- lines.push(`${prefix}`);
695
- lines.push(
696
- `${prefix}${formatDimText(`Destination hash: ${result.plan.destination.coreHash}`)}`
697
- );
698
- }
699
- if (isVerbose(flags, 1)) {
700
- lines.push(`${prefix}${formatDimText(`Total time: ${result.timings.total}ms`)}`);
701
- }
702
- lines.push(`${prefix}`);
703
- lines.push(`${prefix}${formatDimText("This is a dry run. No changes were applied.")}`);
704
- lines.push(`${prefix}${formatDimText("Run without --plan to apply changes.")}`);
705
- return lines.join("\n");
706
- }
707
- function formatDbInitApplyOutput(result, flags) {
708
- if (flags.quiet) {
709
- return "";
710
- }
711
- const lines = [];
712
- const prefix = createPrefix(flags);
713
- const useColor = flags.color !== false;
714
- const formatGreen = createColorFormatter(useColor, green);
715
- const formatDimText = (text) => formatDim(useColor, text);
716
- if (result.ok) {
717
- const executed = result.execution?.operationsExecuted ?? 0;
718
- lines.push(`${prefix}${formatGreen("\u2714")} Applied ${executed} operation(s)`);
719
- if (result.marker) {
720
- lines.push(`${prefix}${formatDimText(` Marker written: ${result.marker.coreHash}`)}`);
721
- if (result.marker.profileHash) {
722
- lines.push(`${prefix}${formatDimText(` Profile hash: ${result.marker.profileHash}`)}`);
723
- }
724
- }
725
- if (isVerbose(flags, 1)) {
726
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
727
- }
728
- }
729
- return lines.join("\n");
730
- }
731
- function formatDbInitJson(result) {
732
- return JSON.stringify(result, null, 2);
733
- }
734
- var LEFT_COLUMN_WIDTH = 20;
735
- var RIGHT_COLUMN_MIN_WIDTH = 40;
736
- var RIGHT_COLUMN_MAX_WIDTH = 90;
737
- function getTerminalWidth() {
738
- const terminalWidth = process.stdout.columns;
739
- const defaultWidth = Number.parseInt(process.env["CLI_WIDTH"] || "80", 10);
740
- return terminalWidth || defaultWidth;
741
- }
742
- function calculateRightColumnWidth() {
743
- const terminalWidth = getTerminalWidth();
744
- const availableWidth = terminalWidth - 2 - LEFT_COLUMN_WIDTH - 2;
745
- return Math.max(RIGHT_COLUMN_MIN_WIDTH, Math.min(availableWidth, RIGHT_COLUMN_MAX_WIDTH));
746
- }
747
- function createPrismaNextBadge(useColor) {
748
- if (!useColor) {
749
- return "prisma-next";
750
- }
751
- const text = " prisma-next ";
752
- const body = bgGreen(bold(text));
753
- const separator = "\uE0B0";
754
- const tip = green(separator);
755
- return `${body}${tip}`;
756
- }
757
- function createPadFunction() {
758
- return (s, w) => s + " ".repeat(Math.max(0, w - s.length));
759
- }
760
- function formatHeaderLine(options) {
761
- if (options.operation) {
762
- return `${options.brand} ${options.operation} \u2192 ${options.intent}`;
763
- }
764
- return `${options.brand} ${options.intent}`;
765
- }
766
- function formatReadMoreLine(options) {
767
- const pad = createPadFunction();
768
- const labelPadded = pad("Read more", options.maxLabelWidth);
769
- const valueColored = options.useColor ? blue(options.url) : options.url;
770
- return `${options.formatDimText("\u2502")} ${labelPadded} ${valueColored}`;
771
- }
772
- function padToFixedWidth(text, width) {
773
- const actualWidth = stringWidth(text);
774
- const padding = Math.max(0, width - actualWidth);
775
- return text + " ".repeat(padding);
776
- }
777
- function wrapTextAnsi(text, width) {
778
- const wrapped = wrapAnsi(text, width, { hard: false, trim: true });
779
- return wrapped.split("\n");
780
- }
781
- function formatDefaultValue(value, useColor) {
782
- const valueStr = String(value);
783
- const defaultText = `default: ${valueStr}`;
784
- return useColor ? dim(defaultText) : defaultText;
785
- }
786
- function renderCommandTree(options) {
787
- const { commands, useColor, formatDimText, hasItemsAfter, continuationPrefix } = options;
788
- const lines = [];
789
- if (commands.length === 0) {
790
- return lines;
791
- }
792
- for (let i = 0; i < commands.length; i++) {
793
- const cmd = commands[i];
794
- if (!cmd) continue;
795
- const subcommands = cmd.commands.filter((subcmd) => !subcmd.name().startsWith("_"));
796
- const isLastCommand = i === commands.length - 1;
797
- if (subcommands.length > 0) {
798
- const prefix = isLastCommand && !hasItemsAfter ? formatDimText("\u2514") : formatDimText("\u251C");
799
- const treePrefix = `${prefix}\u2500 `;
800
- const treePrefixWidth = stringWidth(stripAnsi(treePrefix));
801
- const remainingWidth = LEFT_COLUMN_WIDTH - treePrefixWidth;
802
- const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);
803
- const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;
804
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${commandNameColored}`);
805
- for (let j = 0; j < subcommands.length; j++) {
806
- const subcmd = subcommands[j];
807
- if (!subcmd) continue;
808
- const isLastSubcommand = j === subcommands.length - 1;
809
- const shortDescription = subcmd.description() || "";
810
- const treeChar = isLastSubcommand ? "\u2514" : "\u251C";
811
- const continuation = continuationPrefix ?? (isLastCommand && isLastSubcommand && !hasItemsAfter ? " " : formatDimText("\u2502"));
812
- const continuationStr = continuation === " " ? " " : continuation;
813
- const subTreePrefix = `${continuationStr} ${formatDimText(treeChar)}\u2500 `;
814
- const subTreePrefixWidth = stringWidth(stripAnsi(subTreePrefix));
815
- const subRemainingWidth = LEFT_COLUMN_WIDTH - subTreePrefixWidth;
816
- const subcommandNamePadded = padToFixedWidth(subcmd.name(), subRemainingWidth);
817
- const subcommandNameColored = useColor ? cyan(subcommandNamePadded) : subcommandNamePadded;
818
- lines.push(
819
- `${formatDimText("\u2502")} ${subTreePrefix}${subcommandNameColored} ${shortDescription}`
820
- );
821
- }
822
- } else {
823
- const prefix = isLastCommand && !hasItemsAfter ? formatDimText("\u2514") : formatDimText("\u251C");
824
- const treePrefix = `${prefix}\u2500 `;
825
- const treePrefixWidth = stringWidth(stripAnsi(treePrefix));
826
- const remainingWidth = LEFT_COLUMN_WIDTH - treePrefixWidth;
827
- const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);
828
- const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;
829
- const shortDescription = cmd.description() || "";
830
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${commandNameColored} ${shortDescription}`);
831
- }
832
- }
833
- return lines;
834
- }
835
- function formatMultilineDescription(options) {
836
- const lines = [];
837
- const formatGreen = (text) => options.useColor ? green(text) : text;
838
- const rightColumnWidth = calculateRightColumnWidth();
839
- const totalWidth = 2 + LEFT_COLUMN_WIDTH + 2 + rightColumnWidth;
840
- const wrapWidth = totalWidth - 2;
841
- for (const descLine of options.descriptionLines) {
842
- const formattedLine = descLine.replace(/Prisma Next/g, (match) => formatGreen(match));
843
- const wrappedLines = wrapTextAnsi(formattedLine, wrapWidth);
844
- for (const wrappedLine of wrappedLines) {
845
- lines.push(`${options.formatDimText("\u2502")} ${wrappedLine}`);
846
- }
847
- }
848
- return lines;
849
- }
850
- function formatStyledHeader(options) {
851
- const lines = [];
852
- const useColor = options.flags.color !== false;
853
- const formatDimText = (text) => formatDim(useColor, text);
854
- const brand = createPrismaNextBadge(useColor);
855
- const operation = useColor ? bold(options.command) : options.command;
856
- const intent = formatDimText(options.description);
857
- lines.push(formatHeaderLine({ brand, operation, intent }));
858
- lines.push(formatDimText("\u2502"));
859
- for (const detail of options.details) {
860
- const labelWithColon = `${detail.label}:`;
861
- const labelPadded = padToFixedWidth(labelWithColon, LEFT_COLUMN_WIDTH);
862
- const labelColored = useColor ? cyan(labelPadded) : labelPadded;
863
- lines.push(`${formatDimText("\u2502")} ${labelColored} ${detail.value}`);
864
- }
865
- if (options.url) {
866
- lines.push(formatDimText("\u2502"));
867
- lines.push(
868
- formatReadMoreLine({
869
- url: options.url,
870
- maxLabelWidth: LEFT_COLUMN_WIDTH,
871
- useColor,
872
- formatDimText
873
- })
874
- );
875
- }
876
- lines.push(formatDimText("\u2514"));
877
- return `${lines.join("\n")}
878
- `;
879
- }
880
- function formatSuccessMessage(flags) {
881
- const useColor = flags.color !== false;
882
- const formatGreen = createColorFormatter(useColor, green);
883
- return `${formatGreen("\u2714")} Success`;
884
- }
885
- function getCommandDocsUrl(commandPath) {
886
- const docsMap = {
887
- "contract emit": "https://pris.ly/contract-emit",
888
- "db verify": "https://pris.ly/db-verify"
889
- };
890
- return docsMap[commandPath];
891
- }
892
- function buildCommandPath(command) {
893
- const parts = [];
894
- let current = command;
895
- while (current && current.name() !== "prisma-next") {
896
- parts.unshift(current.name());
897
- current = current.parent ?? void 0;
898
- }
899
- return parts.join(" ");
900
- }
901
- function formatCommandHelp(options) {
902
- const { command, flags } = options;
903
- const lines = [];
904
- const useColor = flags.color !== false;
905
- const formatDimText = (text) => formatDim(useColor, text);
906
- const commandPath = buildCommandPath(command);
907
- const shortDescription = command.description() || "";
908
- const longDescription = getLongDescription(command);
909
- const brand = createPrismaNextBadge(useColor);
910
- const operation = useColor ? bold(commandPath) : commandPath;
911
- const intent = formatDimText(shortDescription);
912
- lines.push(formatHeaderLine({ brand, operation, intent }));
913
- lines.push(formatDimText("\u2502"));
914
- const optionsList = command.options.map((opt) => {
915
- const flags2 = opt.flags;
916
- const description = opt.description || "";
917
- const defaultValue = opt.defaultValue;
918
- return { flags: flags2, description, defaultValue };
919
- });
920
- const subcommands = command.commands.filter((cmd) => !cmd.name().startsWith("_"));
921
- if (subcommands.length > 0) {
922
- const hasItemsAfter = optionsList.length > 0;
923
- const treeLines = renderCommandTree({
924
- commands: subcommands,
925
- useColor,
926
- formatDimText,
927
- hasItemsAfter
928
- });
929
- lines.push(...treeLines);
930
- }
931
- if (subcommands.length > 0 && optionsList.length > 0) {
932
- lines.push(formatDimText("\u2502"));
933
- }
934
- if (optionsList.length > 0) {
935
- for (const opt of optionsList) {
936
- const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);
937
- let flagsColored = flagsPadded;
938
- if (useColor) {
939
- flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match) => magenta(match));
940
- flagsColored = cyan(flagsColored);
941
- }
942
- const rightColumnWidth = calculateRightColumnWidth();
943
- const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);
944
- lines.push(`${formatDimText("\u2502")} ${flagsColored} ${wrappedDescription[0] || ""}`);
945
- for (let i = 1; i < wrappedDescription.length; i++) {
946
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
947
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${wrappedDescription[i] || ""}`);
948
- }
949
- if (opt.defaultValue !== void 0) {
950
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
951
- const defaultText = formatDefaultValue(opt.defaultValue, useColor);
952
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${defaultText}`);
953
- }
954
- }
955
- }
956
- const docsUrl = getCommandDocsUrl(commandPath);
957
- if (docsUrl) {
958
- lines.push(formatDimText("\u2502"));
959
- lines.push(
960
- formatReadMoreLine({
961
- url: docsUrl,
962
- maxLabelWidth: LEFT_COLUMN_WIDTH,
963
- useColor,
964
- formatDimText
965
- })
966
- );
967
- }
968
- if (longDescription) {
969
- lines.push(formatDimText("\u2502"));
970
- const descriptionLines = longDescription.split("\n").filter((line) => line.trim().length > 0);
971
- lines.push(...formatMultilineDescription({ descriptionLines, useColor, formatDimText }));
972
- }
973
- lines.push(formatDimText("\u2514"));
974
- return `${lines.join("\n")}
975
- `;
976
- }
977
- function formatRootHelp(options) {
978
- const { program: program2, flags } = options;
979
- const lines = [];
980
- const useColor = flags.color !== false;
981
- const formatDimText = (text) => formatDim(useColor, text);
982
- const brand = createPrismaNextBadge(useColor);
983
- const shortDescription = "Manage your data layer";
984
- const intent = formatDimText(shortDescription);
985
- lines.push(formatHeaderLine({ brand, operation: "", intent }));
986
- lines.push(formatDimText("\u2502"));
987
- const topLevelCommands = program2.commands.filter(
988
- (cmd) => !cmd.name().startsWith("_") && cmd.name() !== "help"
989
- );
990
- const globalOptions = program2.options.map((opt) => {
991
- const flags2 = opt.flags;
992
- const description = opt.description || "";
993
- const defaultValue = opt.defaultValue;
994
- return { flags: flags2, description, defaultValue };
995
- });
996
- if (topLevelCommands.length > 0) {
997
- const hasItemsAfter = globalOptions.length > 0;
998
- const treeLines = renderCommandTree({
999
- commands: topLevelCommands,
1000
- useColor,
1001
- formatDimText,
1002
- hasItemsAfter
1003
- });
1004
- lines.push(...treeLines);
1005
- }
1006
- if (topLevelCommands.length > 0 && globalOptions.length > 0) {
1007
- lines.push(formatDimText("\u2502"));
1008
- }
1009
- if (globalOptions.length > 0) {
1010
- for (const opt of globalOptions) {
1011
- const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);
1012
- let flagsColored = flagsPadded;
1013
- if (useColor) {
1014
- flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match) => magenta(match));
1015
- flagsColored = cyan(flagsColored);
1016
- }
1017
- const rightColumnWidth = calculateRightColumnWidth();
1018
- const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);
1019
- lines.push(`${formatDimText("\u2502")} ${flagsColored} ${wrappedDescription[0] || ""}`);
1020
- for (let i = 1; i < wrappedDescription.length; i++) {
1021
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1022
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${wrappedDescription[i] || ""}`);
1023
- }
1024
- if (opt.defaultValue !== void 0) {
1025
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1026
- const defaultText = formatDefaultValue(opt.defaultValue, useColor);
1027
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${defaultText}`);
1028
- }
1029
- }
1030
- }
1031
- const formatGreen = (text) => useColor ? green(text) : text;
1032
- const descriptionLines = [
1033
- `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.`
1034
- ];
1035
- if (descriptionLines.length > 0) {
1036
- lines.push(formatDimText("\u2502"));
1037
- lines.push(...formatMultilineDescription({ descriptionLines, useColor, formatDimText }));
1038
- }
1039
- lines.push(formatDimText("\u2514"));
1040
- return `${lines.join("\n")}
1041
- `;
1042
- }
1043
-
1044
- // src/utils/result-handler.ts
1045
- function handleResult(result, flags, onSuccess) {
1046
- if (result.ok) {
1047
- if (onSuccess) {
1048
- onSuccess(result.value);
1049
- }
1050
- return 0;
1051
- }
1052
- const envelope = result.failure.toEnvelope();
1053
- if (flags.json) {
1054
- console.error(formatErrorJson(envelope));
1055
- } else {
1056
- console.error(formatErrorOutput(envelope, flags));
1057
- }
1058
- const exitCode = result.failure.domain === "CLI" ? 2 : 1;
1059
- return exitCode;
1060
- }
1061
-
1062
- // src/utils/spinner.ts
1063
- import ora from "ora";
1064
- async function withSpinner(operation, options) {
1065
- const { message, flags } = options;
1066
- const shouldShowSpinner = !flags.quiet && flags.json !== "object" && process.stdout.isTTY;
1067
- if (!shouldShowSpinner) {
1068
- return operation();
1069
- }
1070
- const startTime = Date.now();
1071
- const spinner = ora({
1072
- text: message,
1073
- color: flags.color !== false ? "cyan" : false
1074
- }).start();
1075
- try {
1076
- const result = await operation();
1077
- const elapsed = Date.now() - startTime;
1078
- spinner.succeed(`${message} (${elapsed}ms)`);
1079
- return result;
1080
- } catch (error) {
1081
- spinner.fail(`${message} failed: ${error instanceof Error ? error.message : String(error)}`);
1082
- throw error;
1083
- }
1084
- }
1085
-
1086
- // src/commands/contract-emit.ts
1087
- function createContractEmitCommand() {
1088
- const command = new Command("emit");
1089
- setCommandDescriptions(
1090
- command,
1091
- "Write your contract to JSON and sign it",
1092
- "Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\ncontract.d.ts. The contract.json contains the canonical contract structure, and\ncontract.d.ts provides TypeScript types for type-safe query building."
1093
- );
1094
- command.configureHelp({
1095
- formatHelp: (cmd) => {
1096
- const flags = parseGlobalFlags({});
1097
- return formatCommandHelp({ command: cmd, flags });
1098
- }
1099
- }).option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1100
- const flags = parseGlobalFlags(options);
1101
- const result = await performAction(async () => {
1102
- const config = await loadConfig(options.config);
1103
- if (!config.contract) {
1104
- throw errorContractConfigMissing2({
1105
- why: "Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ..., types: ... }"
1106
- });
1107
- }
1108
- const contractConfig = config.contract;
1109
- if (!contractConfig.output || !contractConfig.types) {
1110
- throw errorContractConfigMissing2({
1111
- why: "Contract config must have output and types paths. This should not happen if defineConfig() was used."
1112
- });
1113
- }
1114
- const outputJsonPath = resolve2(contractConfig.output);
1115
- const outputDtsPath = resolve2(contractConfig.types);
1116
- if (flags.json !== "object" && !flags.quiet) {
1117
- const configPath = options.config ? relative2(process.cwd(), resolve2(options.config)) : "prisma-next.config.ts";
1118
- const contractPath = relative2(process.cwd(), outputJsonPath);
1119
- const typesPath = relative2(process.cwd(), outputDtsPath);
1120
- const header = formatStyledHeader({
1121
- command: "contract emit",
1122
- description: "Write your contract to JSON and sign it",
1123
- url: "https://pris.ly/contract-emit",
1124
- details: [
1125
- { label: "config", value: configPath },
1126
- { label: "contract", value: contractPath },
1127
- { label: "types", value: typesPath }
1128
- ],
1129
- flags
1130
- });
1131
- console.log(header);
1132
- }
1133
- const stack = createControlPlaneStack({
1134
- target: config.target,
1135
- adapter: config.adapter,
1136
- driver: config.driver,
1137
- extensionPacks: config.extensionPacks
1138
- });
1139
- const familyInstance = config.family.create(stack);
1140
- let contractRaw;
1141
- if (typeof contractConfig.source === "function") {
1142
- contractRaw = await contractConfig.source();
1143
- } else {
1144
- contractRaw = contractConfig.source;
1145
- }
1146
- const emitResult = await withSpinner(
1147
- () => familyInstance.emitContract({ contractIR: contractRaw }),
1148
- {
1149
- message: "Emitting contract...",
1150
- flags
1151
- }
1152
- );
1153
- mkdirSync(dirname2(outputJsonPath), { recursive: true });
1154
- mkdirSync(dirname2(outputDtsPath), { recursive: true });
1155
- writeFileSync(outputJsonPath, emitResult.contractJson, "utf-8");
1156
- writeFileSync(outputDtsPath, emitResult.contractDts, "utf-8");
1157
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
1158
- console.log("");
1159
- }
1160
- return {
1161
- coreHash: emitResult.coreHash,
1162
- profileHash: emitResult.profileHash,
1163
- outDir: dirname2(outputJsonPath),
1164
- files: {
1165
- json: outputJsonPath,
1166
- dts: outputDtsPath
1167
- },
1168
- timings: {
1169
- total: 0
1170
- // Timing is handled by emitContract internally if needed
1171
- }
1172
- };
1173
- });
1174
- const exitCode = handleResult(result, flags, (emitResult) => {
1175
- if (flags.json === "object") {
1176
- console.log(formatEmitJson(emitResult));
1177
- } else {
1178
- const output = formatEmitOutput(emitResult, flags);
1179
- if (output) {
1180
- console.log(output);
1181
- }
1182
- if (!flags.quiet) {
1183
- console.log(formatSuccessMessage(flags));
1184
- }
1185
- }
1186
- });
1187
- process.exit(exitCode);
1188
- });
1189
- return command;
1190
- }
1191
-
1192
- // src/commands/db-init.ts
1193
- import { readFile } from "fs/promises";
1194
- import { relative as relative3, resolve as resolve3 } from "path";
1195
- import { createControlPlaneStack as createControlPlaneStack2 } from "@prisma-next/core-control-plane/types";
1196
- import { redactDatabaseUrl } from "@prisma-next/utils/redact-db-url";
1197
- import { Command as Command2 } from "commander";
1198
-
1199
- // src/utils/framework-components.ts
1200
- import {
1201
- checkContractComponentRequirements
1202
- } from "@prisma-next/contract/framework-components";
1203
- function assertFrameworkComponentsCompatible(expectedFamilyId, expectedTargetId, frameworkComponents) {
1204
- for (let i = 0; i < frameworkComponents.length; i++) {
1205
- const component = frameworkComponents[i];
1206
- if (typeof component !== "object" || component === null) {
1207
- throw errorConfigValidation("frameworkComponents[]", {
1208
- why: `Framework component at index ${i} must be an object`
1209
- });
1210
- }
1211
- const record = component;
1212
- if (!Object.hasOwn(record, "kind")) {
1213
- throw errorConfigValidation("frameworkComponents[].kind", {
1214
- why: `Framework component at index ${i} must have 'kind' property`
1215
- });
1216
- }
1217
- const kind = record["kind"];
1218
- if (kind !== "target" && kind !== "adapter" && kind !== "extension" && kind !== "driver") {
1219
- throw errorConfigValidation("frameworkComponents[].kind", {
1220
- why: `Framework component at index ${i} has invalid kind '${String(kind)}' (must be 'target', 'adapter', 'extension', or 'driver')`
1221
- });
1222
- }
1223
- if (!Object.hasOwn(record, "familyId")) {
1224
- throw errorConfigValidation("frameworkComponents[].familyId", {
1225
- why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'familyId' property`
1226
- });
1227
- }
1228
- const familyId = record["familyId"];
1229
- if (familyId !== expectedFamilyId) {
1230
- throw errorConfigValidation("frameworkComponents[].familyId", {
1231
- why: `Framework component at index ${i} (kind: ${String(kind)}) has familyId '${String(familyId)}' but expected '${expectedFamilyId}'`
1232
- });
1233
- }
1234
- if (!Object.hasOwn(record, "targetId")) {
1235
- throw errorConfigValidation("frameworkComponents[].targetId", {
1236
- why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'targetId' property`
1237
- });
1238
- }
1239
- const targetId = record["targetId"];
1240
- if (targetId !== expectedTargetId) {
1241
- throw errorConfigValidation("frameworkComponents[].targetId", {
1242
- why: `Framework component at index ${i} (kind: ${String(kind)}) has targetId '${String(targetId)}' but expected '${expectedTargetId}'`
1243
- });
1244
- }
1245
- }
1246
- return frameworkComponents;
1247
- }
1248
- function assertContractRequirementsSatisfied({
1249
- contract,
1250
- stack
1251
- }) {
1252
- const providedComponentIds = /* @__PURE__ */ new Set([stack.target.id, stack.adapter.id]);
1253
- for (const extension of stack.extensionPacks) {
1254
- providedComponentIds.add(extension.id);
1255
- }
1256
- const result = checkContractComponentRequirements({
1257
- contract,
1258
- expectedTargetFamily: stack.target.familyId,
1259
- expectedTargetId: stack.target.targetId,
1260
- providedComponentIds
1261
- });
1262
- if (result.familyMismatch) {
1263
- throw errorConfigValidation("contract.targetFamily", {
1264
- why: `Contract was emitted for family '${result.familyMismatch.actual}' but CLI config is wired to '${result.familyMismatch.expected}'.`
1265
- });
1266
- }
1267
- if (result.targetMismatch) {
1268
- throw errorConfigValidation("contract.target", {
1269
- why: `Contract target '${result.targetMismatch.actual}' does not match CLI target '${result.targetMismatch.expected}'.`
1270
- });
1271
- }
1272
- if (result.missingExtensionPackIds.length > 0) {
1273
- throw errorContractMissingExtensionPacks({
1274
- missingExtensionPacks: result.missingExtensionPackIds,
1275
- providedComponentIds: [...providedComponentIds]
1276
- });
1277
- }
1278
- }
1279
-
1280
- // src/commands/db-init.ts
1281
- function createDbInitCommand() {
1282
- const command = new Command2("init");
1283
- setCommandDescriptions(
1284
- command,
1285
- "Bootstrap a database to match the current contract and write the contract marker",
1286
- "Initializes a database to match your emitted contract using additive-only operations.\nCreates any missing tables, columns, indexes, and constraints defined in your contract.\nLeaves existing compatible structures in place, surfaces conflicts when destructive changes\nwould be required, and writes a contract marker to track the database state. Use --plan to\npreview changes without applying."
1287
- );
1288
- command.configureHelp({
1289
- formatHelp: (cmd) => {
1290
- const flags = parseGlobalFlags({});
1291
- return formatCommandHelp({ command: cmd, flags });
1292
- }
1293
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--plan", "Preview planned operations without applying", false).option("--json [format]", "Output as JSON (object)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1294
- const flags = parseGlobalFlags(options);
1295
- const startTime = Date.now();
1296
- const result = await performAction(async () => {
1297
- if (flags.json === "ndjson") {
1298
- throw errorJsonFormatNotSupported({
1299
- command: "db init",
1300
- format: "ndjson",
1301
- supportedFormats: ["object"]
1302
- });
1303
- }
1304
- const config = await loadConfig(options.config);
1305
- const configPath = options.config ? relative3(process.cwd(), resolve3(options.config)) : "prisma-next.config.ts";
1306
- const contractPathAbsolute = config.contract?.output ? resolve3(config.contract.output) : resolve3("src/prisma/contract.json");
1307
- const contractPath = relative3(process.cwd(), contractPathAbsolute);
1308
- if (flags.json !== "object" && !flags.quiet) {
1309
- const details = [
1310
- { label: "config", value: configPath },
1311
- { label: "contract", value: contractPath }
1312
- ];
1313
- if (options.db) {
1314
- details.push({ label: "database", value: options.db });
1315
- }
1316
- if (options.plan) {
1317
- details.push({ label: "mode", value: "plan (dry run)" });
1318
- }
1319
- const header = formatStyledHeader({
1320
- command: "db init",
1321
- description: "Bootstrap a database to match the current contract",
1322
- url: "https://pris.ly/db-init",
1323
- details,
1324
- flags
1325
- });
1326
- console.log(header);
1327
- }
1328
- let contractJsonContent;
1329
- try {
1330
- contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
1331
- } catch (error) {
1332
- if (error instanceof Error && error.code === "ENOENT") {
1333
- throw errorFileNotFound(contractPathAbsolute, {
1334
- why: `Contract file not found at ${contractPathAbsolute}`,
1335
- fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
1336
- });
1337
- }
1338
- throw errorUnexpected2(error instanceof Error ? error.message : String(error), {
1339
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
1340
- });
1341
- }
1342
- let contractJson;
1343
- try {
1344
- contractJson = JSON.parse(contractJsonContent);
1345
- } catch (error) {
1346
- throw errorContractValidationFailed(
1347
- `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
1348
- { where: { path: contractPathAbsolute } }
1349
- );
1350
- }
1351
- const dbUrl = options.db ?? config.db?.url;
1352
- if (!dbUrl) {
1353
- throw errorDatabaseUrlRequired({
1354
- why: `Database URL is required for db init (set db.url in ${configPath}, or pass --db <url>)`
1355
- });
1356
- }
1357
- if (!config.driver) {
1358
- throw errorDriverRequired({ why: "Config.driver is required for db init" });
1359
- }
1360
- const driverDescriptor = config.driver;
1361
- if (!config.target.migrations) {
1362
- throw errorTargetMigrationNotSupported({
1363
- why: `Target "${config.target.id}" does not support migrations`
1364
- });
1365
- }
1366
- const migrations = config.target.migrations;
1367
- let driver;
1368
- try {
1369
- driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
1370
- message: "Connecting to database...",
1371
- flags
1372
- });
1373
- } catch (error) {
1374
- const message = error instanceof Error ? error.message : String(error);
1375
- const code = error.code;
1376
- const redacted = redactDatabaseUrl(dbUrl);
1377
- throw errorRuntime("Database connection failed", {
1378
- why: message,
1379
- fix: "Verify the database URL, ensure the database is reachable, and confirm credentials/permissions",
1380
- meta: {
1381
- ...typeof code !== "undefined" ? { code } : {},
1382
- ...redacted
1383
- }
1384
- });
1385
- }
1386
- try {
1387
- const stack = createControlPlaneStack2({
1388
- target: config.target,
1389
- adapter: config.adapter,
1390
- driver: driverDescriptor,
1391
- extensionPacks: config.extensionPacks
1392
- });
1393
- const familyInstance = config.family.create(stack);
1394
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
1395
- const frameworkComponents = assertFrameworkComponentsCompatible(
1396
- config.family.familyId,
1397
- config.target.targetId,
1398
- rawComponents
1399
- );
1400
- const contractIR = familyInstance.validateContractIR(contractJson);
1401
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
1402
- const planner = migrations.createPlanner(familyInstance);
1403
- const runner = migrations.createRunner(familyInstance);
1404
- const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {
1405
- message: "Introspecting database schema...",
1406
- flags
1407
- });
1408
- const policy = { allowedOperationClasses: ["additive"] };
1409
- const plannerResult = await withSpinner(
1410
- async () => planner.plan({
1411
- contract: contractIR,
1412
- schema: schemaIR,
1413
- policy,
1414
- frameworkComponents
1415
- }),
1416
- {
1417
- message: "Planning migration...",
1418
- flags
1419
- }
1420
- );
1421
- if (plannerResult.kind === "failure") {
1422
- throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });
1423
- }
1424
- const migrationPlan = plannerResult.plan;
1425
- const existingMarker = await familyInstance.readMarker({ driver });
1426
- if (existingMarker) {
1427
- const markerMatchesDestination = existingMarker.coreHash === migrationPlan.destination.coreHash && (!migrationPlan.destination.profileHash || existingMarker.profileHash === migrationPlan.destination.profileHash);
1428
- if (markerMatchesDestination) {
1429
- const dbInitResult2 = {
1430
- ok: true,
1431
- mode: options.plan ? "plan" : "apply",
1432
- plan: {
1433
- targetId: migrationPlan.targetId,
1434
- destination: migrationPlan.destination,
1435
- operations: []
1436
- },
1437
- ...options.plan ? {} : {
1438
- execution: { operationsPlanned: 0, operationsExecuted: 0 },
1439
- marker: {
1440
- coreHash: existingMarker.coreHash,
1441
- profileHash: existingMarker.profileHash
1442
- }
1443
- },
1444
- summary: "Database already at target contract state",
1445
- timings: { total: Date.now() - startTime }
1446
- };
1447
- return dbInitResult2;
1448
- }
1449
- const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;
1450
- const profileHashMismatch = migrationPlan.destination.profileHash && existingMarker.profileHash !== migrationPlan.destination.profileHash;
1451
- const mismatchParts = [];
1452
- if (coreHashMismatch) {
1453
- mismatchParts.push(
1454
- `coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`
1455
- );
1456
- }
1457
- if (profileHashMismatch) {
1458
- mismatchParts.push(
1459
- `profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`
1460
- );
1461
- }
1462
- throw errorRuntime(
1463
- `Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(" and ")}.`,
1464
- {
1465
- why: "Database has an existing contract marker that does not match the target contract",
1466
- fix: "If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow",
1467
- meta: {
1468
- code: "MARKER_ORIGIN_MISMATCH",
1469
- markerCoreHash: existingMarker.coreHash,
1470
- destinationCoreHash: migrationPlan.destination.coreHash,
1471
- ...existingMarker.profileHash ? { markerProfileHash: existingMarker.profileHash } : {},
1472
- ...migrationPlan.destination.profileHash ? { destinationProfileHash: migrationPlan.destination.profileHash } : {}
1473
- }
1474
- }
1475
- );
1476
- }
1477
- if (options.plan) {
1478
- const dbInitResult2 = {
1479
- ok: true,
1480
- mode: "plan",
1481
- plan: {
1482
- targetId: migrationPlan.targetId,
1483
- destination: migrationPlan.destination,
1484
- operations: migrationPlan.operations.map((op) => ({
1485
- id: op.id,
1486
- label: op.label,
1487
- operationClass: op.operationClass
1488
- }))
1489
- },
1490
- summary: `Planned ${migrationPlan.operations.length} operation(s)`,
1491
- timings: { total: Date.now() - startTime }
1492
- };
1493
- return dbInitResult2;
1494
- }
1495
- if (!flags.quiet && flags.json !== "object") {
1496
- console.log("Applying migration plan and verifying schema...");
1497
- }
1498
- const callbacks = {
1499
- onOperationStart: (op) => {
1500
- if (!flags.quiet && flags.json !== "object") {
1501
- console.log(` \u2192 ${op.label}...`);
1502
- }
1503
- },
1504
- onOperationComplete: (_op) => {
1505
- }
1506
- };
1507
- const runnerResult = await runner.execute({
1508
- plan: migrationPlan,
1509
- driver,
1510
- destinationContract: contractIR,
1511
- policy,
1512
- callbacks,
1513
- // db init plans and applies back-to-back from a fresh introspection, so per-operation
1514
- // pre/postchecks and the idempotency probe are usually redundant overhead. We still
1515
- // enforce marker/origin compatibility and a full schema verification after apply.
1516
- executionChecks: {
1517
- prechecks: false,
1518
- postchecks: false,
1519
- idempotencyChecks: false
1520
- },
1521
- frameworkComponents
1522
- });
1523
- if (!runnerResult.ok) {
1524
- const meta = {
1525
- code: runnerResult.failure.code,
1526
- ...runnerResult.failure.meta ?? {}
1527
- };
1528
- const sqlState = typeof meta["sqlState"] === "string" ? meta["sqlState"] : void 0;
1529
- const fix = sqlState === "42501" ? "Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role" : runnerResult.failure.code === "SCHEMA_VERIFY_FAILED" ? "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`" : void 0;
1530
- throw errorRuntime(runnerResult.failure.summary, {
1531
- why: runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,
1532
- ...fix ? { fix } : {},
1533
- meta
1534
- });
1535
- }
1536
- const execution = runnerResult.value;
1537
- const dbInitResult = {
1538
- ok: true,
1539
- mode: "apply",
1540
- plan: {
1541
- targetId: migrationPlan.targetId,
1542
- destination: migrationPlan.destination,
1543
- operations: migrationPlan.operations.map((op) => ({
1544
- id: op.id,
1545
- label: op.label,
1546
- operationClass: op.operationClass
1547
- }))
1548
- },
1549
- execution: {
1550
- operationsPlanned: execution.operationsPlanned,
1551
- operationsExecuted: execution.operationsExecuted
1552
- },
1553
- marker: migrationPlan.destination.profileHash ? {
1554
- coreHash: migrationPlan.destination.coreHash,
1555
- profileHash: migrationPlan.destination.profileHash
1556
- } : { coreHash: migrationPlan.destination.coreHash },
1557
- summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,
1558
- timings: { total: Date.now() - startTime }
1559
- };
1560
- return dbInitResult;
1561
- } finally {
1562
- await driver.close();
1563
- }
1564
- });
1565
- const exitCode = handleResult(result, flags, (dbInitResult) => {
1566
- if (flags.json === "object") {
1567
- console.log(formatDbInitJson(dbInitResult));
1568
- } else {
1569
- const output = dbInitResult.mode === "plan" ? formatDbInitPlanOutput(dbInitResult, flags) : formatDbInitApplyOutput(dbInitResult, flags);
1570
- if (output) {
1571
- console.log(output);
1572
- }
1573
- }
1574
- });
1575
- process.exit(exitCode);
1576
- });
1577
- return command;
1578
- }
1579
-
1580
- // src/commands/db-introspect.ts
1581
- import { readFile as readFile2 } from "fs/promises";
1582
- import { relative as relative4, resolve as resolve4 } from "path";
1583
- import {
1584
- errorDatabaseUrlRequired as errorDatabaseUrlRequired2,
1585
- errorDriverRequired as errorDriverRequired2,
1586
- errorRuntime as errorRuntime2,
1587
- errorUnexpected as errorUnexpected3
1588
- } from "@prisma-next/core-control-plane/errors";
1589
- import { createControlPlaneStack as createControlPlaneStack3 } from "@prisma-next/core-control-plane/types";
1590
- import { Command as Command3 } from "commander";
1591
- function createDbIntrospectCommand() {
1592
- const command = new Command3("introspect");
1593
- setCommandDescriptions(
1594
- command,
1595
- "Inspect the database schema",
1596
- "Reads the live database schema and displays it as a tree structure. This command\ndoes not check the schema against your contract - it only shows what exists in\nthe database. Use `db verify` or `db schema-verify` to compare against your contract."
1597
- );
1598
- command.configureHelp({
1599
- formatHelp: (cmd) => {
1600
- const flags = parseGlobalFlags({});
1601
- return formatCommandHelp({ command: cmd, flags });
1602
- }
1603
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1604
- const flags = parseGlobalFlags(options);
1605
- const result = await performAction(async () => {
1606
- const startTime = Date.now();
1607
- const config = await loadConfig(options.config);
1608
- const configPath = options.config ? relative4(process.cwd(), resolve4(options.config)) : "prisma-next.config.ts";
1609
- let contractIR;
1610
- if (config.contract?.output) {
1611
- const contractPath = resolve4(config.contract.output);
1612
- try {
1613
- const contractJsonContent = await readFile2(contractPath, "utf-8");
1614
- contractIR = JSON.parse(contractJsonContent);
1615
- } catch (error) {
1616
- if (error instanceof Error && error.code !== "ENOENT") {
1617
- throw errorUnexpected3(error.message, {
1618
- why: `Failed to read contract file: ${error.message}`
1619
- });
1620
- }
1621
- }
1622
- }
1623
- if (flags.json !== "object" && !flags.quiet) {
1624
- const details = [
1625
- { label: "config", value: configPath }
1626
- ];
1627
- if (options.db) {
1628
- const maskedUrl = options.db.replace(/:([^:@]+)@/, ":****@");
1629
- details.push({ label: "database", value: maskedUrl });
1630
- } else if (config.db?.url) {
1631
- const maskedUrl = config.db.url.replace(/:([^:@]+)@/, ":****@");
1632
- details.push({ label: "database", value: maskedUrl });
1633
- }
1634
- const header = formatStyledHeader({
1635
- command: "db introspect",
1636
- description: "Inspect the database schema",
1637
- url: "https://pris.ly/db-introspect",
1638
- details,
1639
- flags
1640
- });
1641
- console.log(header);
1642
- }
1643
- const dbUrl = options.db ?? config.db?.url;
1644
- if (!dbUrl) {
1645
- throw errorDatabaseUrlRequired2();
1646
- }
1647
- if (!config.driver) {
1648
- throw errorDriverRequired2();
1649
- }
1650
- const driverDescriptor = config.driver;
1651
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
1652
- message: "Connecting to database...",
1653
- flags
1654
- });
1655
- try {
1656
- const stack = createControlPlaneStack3({
1657
- target: config.target,
1658
- adapter: config.adapter,
1659
- driver: driverDescriptor,
1660
- extensionPacks: config.extensionPacks
1661
- });
1662
- const familyInstance = config.family.create(stack);
1663
- if (contractIR) {
1664
- const validatedContract = familyInstance.validateContractIR(contractIR);
1665
- assertContractRequirementsSatisfied({ contract: validatedContract, stack });
1666
- contractIR = validatedContract;
1667
- }
1668
- let schemaIR;
1669
- try {
1670
- schemaIR = await withSpinner(
1671
- () => familyInstance.introspect({
1672
- driver,
1673
- contractIR
1674
- }),
1675
- {
1676
- message: "Introspecting database schema...",
1677
- flags
1678
- }
1679
- );
1680
- } catch (error) {
1681
- throw errorRuntime2(error instanceof Error ? error.message : String(error), {
1682
- why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`
1683
- });
1684
- }
1685
- let schemaView;
1686
- if (familyInstance.toSchemaView) {
1687
- try {
1688
- schemaView = familyInstance.toSchemaView(schemaIR);
1689
- } catch (error) {
1690
- if (flags.verbose) {
1691
- console.error(
1692
- `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`
1693
- );
1694
- }
1695
- }
1696
- }
1697
- const totalTime = Date.now() - startTime;
1698
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
1699
- console.log("");
1700
- }
1701
- const introspectResult = {
1702
- ok: true,
1703
- summary: "Schema introspected successfully",
1704
- target: {
1705
- familyId: config.family.familyId,
1706
- id: config.target.targetId
1707
- },
1708
- schema: schemaIR,
1709
- ...configPath || options.db || config.db?.url ? {
1710
- meta: {
1711
- ...configPath ? { configPath } : {},
1712
- ...options.db || config.db?.url ? {
1713
- dbUrl: (options.db ?? config.db?.url ?? "").replace(
1714
- /:([^:@]+)@/,
1715
- ":****@"
1716
- )
1717
- } : {}
1718
- }
1719
- } : {},
1720
- timings: {
1721
- total: totalTime
1722
- }
1723
- };
1724
- return { introspectResult, schemaView };
1725
- } finally {
1726
- await driver.close();
1727
- }
1728
- });
1729
- const exitCode = handleResult(result, flags, (value) => {
1730
- const { introspectResult, schemaView } = value;
1731
- if (flags.json === "object") {
1732
- console.log(formatIntrospectJson(introspectResult));
1733
- } else {
1734
- const output = formatIntrospectOutput(introspectResult, schemaView, flags);
1735
- if (output) {
1736
- console.log(output);
1737
- }
1738
- }
1739
- });
1740
- process.exit(exitCode);
1741
- });
1742
- return command;
1743
- }
1744
-
1745
- // src/commands/db-schema-verify.ts
1746
- import { readFile as readFile3 } from "fs/promises";
1747
- import { relative as relative5, resolve as resolve5 } from "path";
1748
- import {
1749
- errorDatabaseUrlRequired as errorDatabaseUrlRequired3,
1750
- errorDriverRequired as errorDriverRequired3,
1751
- errorFileNotFound as errorFileNotFound2,
1752
- errorRuntime as errorRuntime3,
1753
- errorUnexpected as errorUnexpected4
1754
- } from "@prisma-next/core-control-plane/errors";
1755
- import { createControlPlaneStack as createControlPlaneStack4 } from "@prisma-next/core-control-plane/types";
1756
- import { Command as Command4 } from "commander";
1757
- function createDbSchemaVerifyCommand() {
1758
- const command = new Command4("schema-verify");
1759
- setCommandDescriptions(
1760
- command,
1761
- "Check whether the database schema satisfies your contract",
1762
- "Verifies that your database schema satisfies the emitted contract. Compares table structures,\ncolumn types, constraints, and extensions. Reports any mismatches via a contract-shaped\nverification tree. This is a read-only operation that does not modify the database."
1763
- );
1764
- command.configureHelp({
1765
- formatHelp: (cmd) => {
1766
- const flags = parseGlobalFlags({});
1767
- return formatCommandHelp({ command: cmd, flags });
1768
- }
1769
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("--strict", "Strict mode: extra schema elements cause failures", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1770
- const flags = parseGlobalFlags(options);
1771
- const result = await performAction(async () => {
1772
- const config = await loadConfig(options.config);
1773
- const configPath = options.config ? relative5(process.cwd(), resolve5(options.config)) : "prisma-next.config.ts";
1774
- const contractPathAbsolute = config.contract?.output ? resolve5(config.contract.output) : resolve5("src/prisma/contract.json");
1775
- const contractPath = relative5(process.cwd(), contractPathAbsolute);
1776
- if (flags.json !== "object" && !flags.quiet) {
1777
- const details = [
1778
- { label: "config", value: configPath },
1779
- { label: "contract", value: contractPath }
1780
- ];
1781
- if (options.db) {
1782
- details.push({ label: "database", value: options.db });
1783
- }
1784
- const header = formatStyledHeader({
1785
- command: "db schema-verify",
1786
- description: "Check whether the database schema satisfies your contract",
1787
- url: "https://pris.ly/db-schema-verify",
1788
- details,
1789
- flags
1790
- });
1791
- console.log(header);
1792
- }
1793
- let contractJsonContent;
1794
- try {
1795
- contractJsonContent = await readFile3(contractPathAbsolute, "utf-8");
1796
- } catch (error) {
1797
- if (error instanceof Error && error.code === "ENOENT") {
1798
- throw errorFileNotFound2(contractPathAbsolute, {
1799
- why: `Contract file not found at ${contractPathAbsolute}`
1800
- });
1801
- }
1802
- throw errorUnexpected4(error instanceof Error ? error.message : String(error), {
1803
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
1804
- });
1805
- }
1806
- const contractJson = JSON.parse(contractJsonContent);
1807
- if (!config.driver) {
1808
- throw errorDriverRequired3();
1809
- }
1810
- const driverDescriptor = config.driver;
1811
- const stack = createControlPlaneStack4({
1812
- target: config.target,
1813
- adapter: config.adapter,
1814
- driver: driverDescriptor,
1815
- extensionPacks: config.extensionPacks
1816
- });
1817
- const familyInstance = config.family.create(stack);
1818
- const contractIR = familyInstance.validateContractIR(contractJson);
1819
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
1820
- const dbUrl = options.db ?? config.db?.url;
1821
- if (!dbUrl) {
1822
- throw errorDatabaseUrlRequired3();
1823
- }
1824
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
1825
- message: "Connecting to database...",
1826
- flags
1827
- });
1828
- try {
1829
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
1830
- const frameworkComponents = assertFrameworkComponentsCompatible(
1831
- config.family.familyId,
1832
- config.target.targetId,
1833
- rawComponents
1834
- );
1835
- let schemaVerifyResult;
1836
- try {
1837
- schemaVerifyResult = await withSpinner(
1838
- () => familyInstance.schemaVerify({
1839
- driver,
1840
- contractIR,
1841
- strict: options.strict ?? false,
1842
- contractPath: contractPathAbsolute,
1843
- configPath,
1844
- frameworkComponents
1845
- }),
1846
- {
1847
- message: "Verifying database schema...",
1848
- flags
1849
- }
1850
- );
1851
- } catch (error) {
1852
- throw errorRuntime3(error instanceof Error ? error.message : String(error), {
1853
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
1854
- });
1855
- }
1856
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
1857
- console.log("");
1858
- }
1859
- return schemaVerifyResult;
1860
- } finally {
1861
- await driver.close();
1862
- }
1863
- });
1864
- const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
1865
- if (flags.json === "object") {
1866
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
1867
- } else {
1868
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
1869
- if (output) {
1870
- console.log(output);
1871
- }
1872
- }
1873
- });
1874
- if (result.ok && !result.value.ok) {
1875
- process.exit(1);
1876
- } else {
1877
- process.exit(exitCode);
1878
- }
1879
- });
1880
- return command;
1881
- }
1882
-
1883
- // src/commands/db-sign.ts
1884
- import { readFile as readFile4 } from "fs/promises";
1885
- import { relative as relative6, resolve as resolve6 } from "path";
1886
- import {
1887
- errorDatabaseUrlRequired as errorDatabaseUrlRequired4,
1888
- errorDriverRequired as errorDriverRequired4,
1889
- errorFileNotFound as errorFileNotFound3,
1890
- errorRuntime as errorRuntime4,
1891
- errorUnexpected as errorUnexpected5
1892
- } from "@prisma-next/core-control-plane/errors";
1893
- import { createControlPlaneStack as createControlPlaneStack5 } from "@prisma-next/core-control-plane/types";
1894
- import { Command as Command5 } from "commander";
1895
- function createDbSignCommand() {
1896
- const command = new Command5("sign");
1897
- setCommandDescriptions(
1898
- command,
1899
- "Sign the database with your contract so you can safely run queries",
1900
- "Verifies that your database schema satisfies the emitted contract, and if so, writes or\nupdates the contract marker in the database. This command is idempotent and safe to run\nin CI/deployment pipelines. The marker records that this database instance is aligned\nwith a specific contract version."
1901
- );
1902
- command.configureHelp({
1903
- formatHelp: (cmd) => {
1904
- const flags = parseGlobalFlags({});
1905
- return formatCommandHelp({ command: cmd, flags });
1906
- }
1907
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1908
- const flags = parseGlobalFlags(options);
1909
- const result = await performAction(async () => {
1910
- const config = await loadConfig(options.config);
1911
- const configPath = options.config ? relative6(process.cwd(), resolve6(options.config)) : "prisma-next.config.ts";
1912
- const contractPathAbsolute = config.contract?.output ? resolve6(config.contract.output) : resolve6("src/prisma/contract.json");
1913
- const contractPath = relative6(process.cwd(), contractPathAbsolute);
1914
- if (flags.json !== "object" && !flags.quiet) {
1915
- const details = [
1916
- { label: "config", value: configPath },
1917
- { label: "contract", value: contractPath }
1918
- ];
1919
- if (options.db) {
1920
- details.push({ label: "database", value: options.db });
1921
- }
1922
- const header = formatStyledHeader({
1923
- command: "db sign",
1924
- description: "Sign the database with your contract so you can safely run queries",
1925
- url: "https://pris.ly/db-sign",
1926
- details,
1927
- flags
1928
- });
1929
- console.log(header);
1930
- }
1931
- let contractJsonContent;
1932
- try {
1933
- contractJsonContent = await readFile4(contractPathAbsolute, "utf-8");
1934
- } catch (error) {
1935
- if (error instanceof Error && error.code === "ENOENT") {
1936
- throw errorFileNotFound3(contractPathAbsolute, {
1937
- why: `Contract file not found at ${contractPathAbsolute}`
1938
- });
1939
- }
1940
- throw errorUnexpected5(error instanceof Error ? error.message : String(error), {
1941
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
1942
- });
1943
- }
1944
- const contractJson = JSON.parse(contractJsonContent);
1945
- const dbUrl = options.db ?? config.db?.url;
1946
- if (!dbUrl) {
1947
- throw errorDatabaseUrlRequired4();
1948
- }
1949
- if (!config.driver) {
1950
- throw errorDriverRequired4();
1951
- }
1952
- const driverDescriptor = config.driver;
1953
- const stack = createControlPlaneStack5({
1954
- target: config.target,
1955
- adapter: config.adapter,
1956
- driver: driverDescriptor,
1957
- extensionPacks: config.extensionPacks
1958
- });
1959
- const familyInstance = config.family.create(stack);
1960
- const contractIR = familyInstance.validateContractIR(contractJson);
1961
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
1962
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
1963
- const frameworkComponents = assertFrameworkComponentsCompatible(
1964
- config.family.familyId,
1965
- config.target.targetId,
1966
- rawComponents
1967
- );
1968
- const driver = await driverDescriptor.create(dbUrl);
1969
- try {
1970
- let schemaVerifyResult;
1971
- try {
1972
- schemaVerifyResult = await withSpinner(
1973
- () => familyInstance.schemaVerify({
1974
- driver,
1975
- contractIR,
1976
- strict: false,
1977
- contractPath: contractPathAbsolute,
1978
- configPath,
1979
- frameworkComponents
1980
- }),
1981
- {
1982
- message: "Verifying database satisfies contract",
1983
- flags
1984
- }
1985
- );
1986
- } catch (error) {
1987
- throw errorRuntime4(error instanceof Error ? error.message : String(error), {
1988
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
1989
- });
1990
- }
1991
- if (!schemaVerifyResult.ok) {
1992
- return { schemaVerifyResult, signResult: void 0 };
1993
- }
1994
- let signResult;
1995
- try {
1996
- signResult = await withSpinner(
1997
- () => familyInstance.sign({
1998
- driver,
1999
- contractIR,
2000
- contractPath: contractPathAbsolute,
2001
- configPath
2002
- }),
2003
- {
2004
- message: "Signing database...",
2005
- flags
2006
- }
2007
- );
2008
- } catch (error) {
2009
- throw errorRuntime4(error instanceof Error ? error.message : String(error), {
2010
- why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`
2011
- });
2012
- }
2013
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2014
- console.log("");
2015
- }
2016
- return { schemaVerifyResult: void 0, signResult };
2017
- } finally {
2018
- await driver.close();
2019
- }
2020
- });
2021
- const exitCode = handleResult(result, flags, (value) => {
2022
- const { schemaVerifyResult, signResult } = value;
2023
- if (schemaVerifyResult && !schemaVerifyResult.ok) {
2024
- if (flags.json === "object") {
2025
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
2026
- } else {
2027
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
2028
- if (output) {
2029
- console.log(output);
2030
- }
2031
- }
2032
- return;
2033
- }
2034
- if (signResult) {
2035
- if (flags.json === "object") {
2036
- console.log(formatSignJson(signResult));
2037
- } else {
2038
- const output = formatSignOutput(signResult, flags);
2039
- if (output) {
2040
- console.log(output);
2041
- }
2042
- }
2043
- }
2044
- });
2045
- if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {
2046
- process.exit(1);
2047
- } else {
2048
- process.exit(exitCode);
2049
- }
2050
- });
2051
- return command;
2052
- }
2053
-
2054
- // src/commands/db-verify.ts
2055
- import { readFile as readFile5 } from "fs/promises";
2056
- import { relative as relative7, resolve as resolve7 } from "path";
2057
- import {
2058
- errorDatabaseUrlRequired as errorDatabaseUrlRequired5,
2059
- errorDriverRequired as errorDriverRequired5,
2060
- errorFileNotFound as errorFileNotFound4,
2061
- errorHashMismatch as errorHashMismatch2,
2062
- errorMarkerMissing as errorMarkerMissing2,
2063
- errorRuntime as errorRuntime5,
2064
- errorTargetMismatch as errorTargetMismatch2,
2065
- errorUnexpected as errorUnexpected6
2066
- } from "@prisma-next/core-control-plane/errors";
2067
- import { createControlPlaneStack as createControlPlaneStack6 } from "@prisma-next/core-control-plane/types";
2068
- import { Command as Command6 } from "commander";
2069
- function createDbVerifyCommand() {
2070
- const command = new Command6("verify");
2071
- setCommandDescriptions(
2072
- command,
2073
- "Check whether the database has been signed with your contract",
2074
- "Verifies that your database schema matches the emitted contract. Checks table structures,\ncolumn types, constraints, and codec coverage. Reports any mismatches or missing codecs."
2075
- );
2076
- command.configureHelp({
2077
- formatHelp: (cmd) => {
2078
- const flags = parseGlobalFlags({});
2079
- return formatCommandHelp({ command: cmd, flags });
2080
- }
2081
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
2082
- const flags = parseGlobalFlags(options);
2083
- const result = await performAction(async () => {
2084
- const config = await loadConfig(options.config);
2085
- const configPath = options.config ? relative7(process.cwd(), resolve7(options.config)) : "prisma-next.config.ts";
2086
- const contractPathAbsolute = config.contract?.output ? resolve7(config.contract.output) : resolve7("src/prisma/contract.json");
2087
- const contractPath = relative7(process.cwd(), contractPathAbsolute);
2088
- if (flags.json !== "object" && !flags.quiet) {
2089
- const details = [
2090
- { label: "config", value: configPath },
2091
- { label: "contract", value: contractPath }
2092
- ];
2093
- if (options.db) {
2094
- details.push({ label: "database", value: options.db });
2095
- }
2096
- const header = formatStyledHeader({
2097
- command: "db verify",
2098
- description: "Check whether the database has been signed with your contract",
2099
- url: "https://pris.ly/db-verify",
2100
- details,
2101
- flags
2102
- });
2103
- console.log(header);
2104
- }
2105
- let contractJsonContent;
2106
- try {
2107
- contractJsonContent = await readFile5(contractPathAbsolute, "utf-8");
2108
- } catch (error) {
2109
- if (error instanceof Error && error.code === "ENOENT") {
2110
- throw errorFileNotFound4(contractPathAbsolute, {
2111
- why: `Contract file not found at ${contractPathAbsolute}`
2112
- });
2113
- }
2114
- throw errorUnexpected6(error instanceof Error ? error.message : String(error), {
2115
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
2116
- });
2117
- }
2118
- const contractJson = JSON.parse(contractJsonContent);
2119
- const dbUrl = options.db ?? config.db?.url;
2120
- if (!dbUrl) {
2121
- throw errorDatabaseUrlRequired5();
2122
- }
2123
- if (!config.driver) {
2124
- throw errorDriverRequired5();
2125
- }
2126
- const driverDescriptor = config.driver;
2127
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
2128
- message: "Connecting to database...",
2129
- flags
2130
- });
2131
- try {
2132
- const stack = createControlPlaneStack6({
2133
- target: config.target,
2134
- adapter: config.adapter,
2135
- driver: driverDescriptor,
2136
- extensionPacks: config.extensionPacks
2137
- });
2138
- const familyInstance = config.family.create(stack);
2139
- const contractIR = familyInstance.validateContractIR(contractJson);
2140
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
2141
- let verifyResult;
2142
- try {
2143
- verifyResult = await withSpinner(
2144
- () => familyInstance.verify({
2145
- driver,
2146
- contractIR,
2147
- expectedTargetId: config.target.targetId,
2148
- contractPath: contractPathAbsolute,
2149
- configPath
2150
- }),
2151
- {
2152
- message: "Verifying database schema...",
2153
- flags
2154
- }
2155
- );
2156
- } catch (error) {
2157
- throw errorUnexpected6(error instanceof Error ? error.message : String(error), {
2158
- why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`
2159
- });
2160
- }
2161
- if (!verifyResult.ok && verifyResult.code) {
2162
- if (verifyResult.code === "PN-RTM-3001") {
2163
- throw errorMarkerMissing2();
2164
- }
2165
- if (verifyResult.code === "PN-RTM-3002") {
2166
- throw errorHashMismatch2({
2167
- expected: verifyResult.contract.coreHash,
2168
- ...verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}
2169
- });
2170
- }
2171
- if (verifyResult.code === "PN-RTM-3003") {
2172
- throw errorTargetMismatch2(
2173
- verifyResult.target.expected,
2174
- verifyResult.target.actual ?? "unknown"
2175
- );
2176
- }
2177
- throw errorRuntime5(verifyResult.summary);
2178
- }
2179
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2180
- console.log("");
2181
- }
2182
- return verifyResult;
2183
- } finally {
2184
- await driver.close();
2185
- }
2186
- });
2187
- const exitCode = handleResult(result, flags, (verifyResult) => {
2188
- if (flags.json === "object") {
2189
- console.log(formatVerifyJson(verifyResult));
2190
- } else {
2191
- const output = formatVerifyOutput(verifyResult, flags);
2192
- if (output) {
2193
- console.log(output);
2194
- }
2195
- }
2196
- });
2197
- process.exit(exitCode);
2198
- });
2199
- return command;
2200
- }
2201
-
2202
- // src/cli.ts
2203
- var program = new Command7();
2204
- program.name("prisma-next").description("Prisma Next CLI").version("0.0.1");
2205
- var versionOption = program.options.find((opt) => opt.flags.includes("--version"));
2206
- if (versionOption) {
2207
- versionOption.description = "Output the version number";
2208
- }
2209
- program.configureOutput({
2210
- writeErr: () => {
2211
- },
2212
- writeOut: () => {
2213
- }
2214
- });
2215
- var rootHelpFormatter = (cmd) => {
2216
- const flags = parseGlobalFlags({});
2217
- return formatRootHelp({ program: cmd, flags });
2218
- };
2219
- program.configureHelp({
2220
- formatHelp: rootHelpFormatter,
2221
- subcommandDescription: () => ""
2222
- });
2223
- program.exitOverride((err) => {
2224
- if (err) {
2225
- const errorCode = err.code;
2226
- const errorMessage = String(err.message ?? "");
2227
- const errorName = err.name ?? "";
2228
- const isUnknownCommandError = errorCode === "commander.unknownCommand" || errorCode === "commander.unknownArgument" || errorName === "CommanderError" && (errorMessage.includes("unknown command") || errorMessage.includes("unknown argument"));
2229
- if (isUnknownCommandError) {
2230
- const flags = parseGlobalFlags({});
2231
- const match = errorMessage.match(/unknown command ['"]([^'"]+)['"]/);
2232
- const commandName = match ? match[1] : process.argv[3] || process.argv[2] || "unknown";
2233
- const firstArg = process.argv[2];
2234
- const parentCommand = firstArg ? program.commands.find((cmd) => cmd.name() === firstArg) : void 0;
2235
- if (parentCommand && commandName !== firstArg) {
2236
- console.error(`Unknown command: ${commandName}`);
2237
- console.error("");
2238
- const helpText = formatCommandHelp({ command: parentCommand, flags });
2239
- console.log(helpText);
2240
- } else {
2241
- console.error(`Unknown command: ${commandName}`);
2242
- console.error("");
2243
- const helpText = formatRootHelp({ program, flags });
2244
- console.log(helpText);
2245
- }
2246
- process.exit(1);
2247
- return;
2248
- }
2249
- const isHelpError = errorCode === "commander.help" || errorCode === "commander.helpDisplayed" || errorCode === "outputHelp" || errorMessage === "(outputHelp)" || errorMessage.includes("outputHelp") || errorName === "CommanderError" && errorMessage.includes("outputHelp");
2250
- if (isHelpError) {
2251
- process.exit(0);
2252
- return;
2253
- }
2254
- const isMissingArgumentError = errorCode === "commander.missingArgument" || errorCode === "commander.missingMandatoryOptionValue" || errorName === "CommanderError" && (errorMessage.includes("missing") || errorMessage.includes("required"));
2255
- if (isMissingArgumentError) {
2256
- process.exit(0);
2257
- return;
2258
- }
2259
- console.error(`Unhandled error: ${err.message}`);
2260
- if (err.stack) {
2261
- console.error(err.stack);
2262
- }
2263
- process.exit(1);
2264
- }
2265
- process.exit(0);
2266
- });
2267
- var contractCommand = new Command7("contract");
2268
- setCommandDescriptions(
2269
- contractCommand,
2270
- "Contract management commands",
2271
- "Define and emit your application data contract. The contract describes your schema as a\ndeclarative data structure that can be signed and verified against your database."
2272
- );
2273
- contractCommand.configureHelp({
2274
- formatHelp: (cmd) => {
2275
- const flags = parseGlobalFlags({});
2276
- return formatCommandHelp({ command: cmd, flags });
2277
- },
2278
- subcommandDescription: () => ""
2279
- });
2280
- var contractEmitCommand = createContractEmitCommand();
2281
- contractCommand.addCommand(contractEmitCommand);
2282
- program.addCommand(contractCommand);
2283
- var dbCommand = new Command7("db");
2284
- setCommandDescriptions(
2285
- dbCommand,
2286
- "Database management commands",
2287
- "Verify and sign your database with your contract. Ensure your database schema matches\nyour contract, and sign it to record the contract hash for future verification."
2288
- );
2289
- dbCommand.configureHelp({
2290
- formatHelp: (cmd) => {
2291
- const flags = parseGlobalFlags({});
2292
- return formatCommandHelp({ command: cmd, flags });
2293
- },
2294
- subcommandDescription: () => ""
2295
- });
2296
- var dbVerifyCommand = createDbVerifyCommand();
2297
- dbCommand.addCommand(dbVerifyCommand);
2298
- var dbInitCommand = createDbInitCommand();
2299
- dbCommand.addCommand(dbInitCommand);
2300
- var dbIntrospectCommand = createDbIntrospectCommand();
2301
- dbCommand.addCommand(dbIntrospectCommand);
2302
- var dbSchemaVerifyCommand = createDbSchemaVerifyCommand();
2303
- dbCommand.addCommand(dbSchemaVerifyCommand);
2304
- var dbSignCommand = createDbSignCommand();
2305
- dbCommand.addCommand(dbSignCommand);
2306
- program.addCommand(dbCommand);
2307
- var helpCommand = new Command7("help").description("Show usage instructions").configureHelp({
2308
- formatHelp: (cmd) => {
2309
- const flags = parseGlobalFlags({});
2310
- return formatCommandHelp({ command: cmd, flags });
2311
- }
2312
- }).action(() => {
2313
- const flags = parseGlobalFlags({});
2314
- const helpText = formatRootHelp({ program, flags });
2315
- console.log(helpText);
2316
- process.exit(0);
2317
- });
2318
- program.addCommand(helpCommand);
2319
- program.action(() => {
2320
- const flags = parseGlobalFlags({});
2321
- const helpText = formatRootHelp({ program, flags });
2322
- console.log(helpText);
2323
- process.exit(0);
2324
- });
2325
- var args = process.argv.slice(2);
2326
- if (args.length > 0) {
2327
- const commandName = args[0];
2328
- if (commandName === "--version" || commandName === "-V") {
2329
- console.log(program.version());
2330
- process.exit(0);
2331
- }
2332
- const isGlobalOption = commandName === "--help" || commandName === "-h";
2333
- if (!isGlobalOption) {
2334
- const command = program.commands.find((cmd) => cmd.name() === commandName);
2335
- if (!command) {
2336
- const flags = parseGlobalFlags({});
2337
- console.error(`Unknown command: ${commandName}`);
2338
- console.error("");
2339
- const helpText = formatRootHelp({ program, flags });
2340
- console.log(helpText);
2341
- process.exit(1);
2342
- } else if (command.commands.length > 0 && args.length === 1) {
2343
- const flags = parseGlobalFlags({});
2344
- const helpText = formatCommandHelp({ command, flags });
2345
- console.log(helpText);
2346
- process.exit(0);
2347
- }
2348
- }
2349
- }
2350
- program.parse();
2351
- //# sourceMappingURL=cli.js.map
2
+ import './cli.mjs';