@prisma-next/cli 0.3.0-dev.16 → 0.3.0-dev.162

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 (242) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +381 -128
  3. package/dist/cli-errors-BDCYR5ap.mjs +4 -0
  4. package/dist/cli-errors-Dzs7Oxz7.d.mts +3 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.js +1 -2671
  7. package/dist/cli.mjs +245 -0
  8. package/dist/cli.mjs.map +1 -0
  9. package/dist/client-yYtotiSX.mjs +1063 -0
  10. package/dist/client-yYtotiSX.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 +8 -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 +9 -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 +125 -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 +55 -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 +136 -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 +122 -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 +322 -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 +244 -0
  40. package/dist/commands/migration-apply.mjs.map +1 -0
  41. package/dist/commands/migration-new.d.mts +8 -0
  42. package/dist/commands/migration-new.d.mts.map +1 -0
  43. package/dist/commands/migration-new.mjs +151 -0
  44. package/dist/commands/migration-new.mjs.map +1 -0
  45. package/dist/commands/migration-plan.d.mts +47 -0
  46. package/dist/commands/migration-plan.d.mts.map +1 -0
  47. package/dist/commands/migration-plan.mjs +312 -0
  48. package/dist/commands/migration-plan.mjs.map +1 -0
  49. package/dist/commands/migration-ref.d.mts +43 -0
  50. package/dist/commands/migration-ref.d.mts.map +1 -0
  51. package/dist/commands/migration-ref.mjs +194 -0
  52. package/dist/commands/migration-ref.mjs.map +1 -0
  53. package/dist/commands/migration-show.d.mts +28 -0
  54. package/dist/commands/migration-show.d.mts.map +1 -0
  55. package/dist/commands/migration-show.mjs +139 -0
  56. package/dist/commands/migration-show.mjs.map +1 -0
  57. package/dist/commands/migration-status.d.mts +86 -0
  58. package/dist/commands/migration-status.d.mts.map +1 -0
  59. package/dist/commands/migration-status.mjs +8 -0
  60. package/dist/commands/migration-verify.d.mts +16 -0
  61. package/dist/commands/migration-verify.d.mts.map +1 -0
  62. package/dist/commands/migration-verify.mjs +109 -0
  63. package/dist/commands/migration-verify.mjs.map +1 -0
  64. package/dist/config-loader-C4VXKl8f.mjs +43 -0
  65. package/dist/config-loader-C4VXKl8f.mjs.map +1 -0
  66. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  67. package/dist/config-loader.d.mts.map +1 -0
  68. package/dist/config-loader.mjs +3 -0
  69. package/dist/contract-emit-Bk_eEDKu.mjs +187 -0
  70. package/dist/contract-emit-Bk_eEDKu.mjs.map +1 -0
  71. package/dist/contract-infer-suMDmFSG.mjs +89 -0
  72. package/dist/contract-infer-suMDmFSG.mjs.map +1 -0
  73. package/dist/exports/config-types.d.mts +2 -0
  74. package/dist/exports/config-types.mjs +3 -0
  75. package/dist/exports/control-api.d.mts +624 -0
  76. package/dist/exports/control-api.d.mts.map +1 -0
  77. package/dist/exports/control-api.mjs +109 -0
  78. package/dist/exports/control-api.mjs.map +1 -0
  79. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +12 -7
  80. package/dist/exports/index.d.mts.map +1 -0
  81. package/dist/exports/index.mjs +141 -0
  82. package/dist/exports/index.mjs.map +1 -0
  83. package/dist/extract-operation-statements-BVlb3jxp.mjs +13 -0
  84. package/dist/extract-operation-statements-BVlb3jxp.mjs.map +1 -0
  85. package/dist/extract-sql-ddl-6EVSOThm.mjs +26 -0
  86. package/dist/extract-sql-ddl-6EVSOThm.mjs.map +1 -0
  87. package/dist/framework-components-BAsliT4V.mjs +59 -0
  88. package/dist/framework-components-BAsliT4V.mjs.map +1 -0
  89. package/dist/inspect-live-schema-HMutsJYh.mjs +91 -0
  90. package/dist/inspect-live-schema-HMutsJYh.mjs.map +1 -0
  91. package/dist/migration-command-scaffold-Dg7CKKCg.mjs +105 -0
  92. package/dist/migration-command-scaffold-Dg7CKKCg.mjs.map +1 -0
  93. package/dist/migration-status-BqfVmC0w.mjs +1582 -0
  94. package/dist/migration-status-BqfVmC0w.mjs.map +1 -0
  95. package/dist/migrations-Bv8oeiY_.mjs +173 -0
  96. package/dist/migrations-Bv8oeiY_.mjs.map +1 -0
  97. package/dist/progress-adapter-D4x8SbJa.mjs +43 -0
  98. package/dist/progress-adapter-D4x8SbJa.mjs.map +1 -0
  99. package/dist/terminal-ui-N5tR-ob5.mjs +967 -0
  100. package/dist/terminal-ui-N5tR-ob5.mjs.map +1 -0
  101. package/dist/verify-WARh5TjK.mjs +385 -0
  102. package/dist/verify-WARh5TjK.mjs.map +1 -0
  103. package/package.json +88 -42
  104. package/src/cli.ts +113 -58
  105. package/src/commands/contract-emit.ts +237 -144
  106. package/src/commands/contract-infer-paths.ts +32 -0
  107. package/src/commands/contract-infer.ts +143 -0
  108. package/src/commands/db-init.ts +97 -219
  109. package/src/commands/db-schema.ts +77 -0
  110. package/src/commands/db-sign.ts +208 -229
  111. package/src/commands/db-update.ts +236 -0
  112. package/src/commands/db-verify.ts +504 -184
  113. package/src/commands/inspect-live-schema.ts +170 -0
  114. package/src/commands/migration-apply.ts +427 -0
  115. package/src/commands/migration-new.ts +260 -0
  116. package/src/commands/migration-plan.ts +519 -0
  117. package/src/commands/migration-ref.ts +305 -0
  118. package/src/commands/migration-show.ts +246 -0
  119. package/src/commands/migration-status.ts +864 -0
  120. package/src/commands/migration-verify.ts +180 -0
  121. package/src/config-loader.ts +13 -3
  122. package/src/control-api/client.ts +424 -72
  123. package/src/control-api/contract-enrichment.ts +119 -0
  124. package/src/control-api/errors.ts +9 -0
  125. package/src/control-api/operations/contract-emit.ts +174 -0
  126. package/src/control-api/operations/db-init.ts +53 -49
  127. package/src/control-api/operations/db-update.ts +220 -0
  128. package/src/control-api/operations/extract-operation-statements.ts +14 -0
  129. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  130. package/src/control-api/operations/migration-apply.ts +191 -0
  131. package/src/control-api/operations/migration-helpers.ts +49 -0
  132. package/src/control-api/types.ts +388 -18
  133. package/src/exports/config-types.ts +4 -3
  134. package/src/exports/control-api.ts +21 -2
  135. package/src/load-ts-contract.ts +30 -19
  136. package/src/utils/cli-errors.ts +14 -8
  137. package/src/utils/command-helpers.ts +302 -3
  138. package/src/utils/formatters/emit.ts +67 -0
  139. package/src/utils/formatters/errors.ts +82 -0
  140. package/src/utils/formatters/graph-migration-mapper.ts +240 -0
  141. package/src/utils/formatters/graph-render.ts +1323 -0
  142. package/src/utils/formatters/graph-types.ts +120 -0
  143. package/src/utils/formatters/help.ts +380 -0
  144. package/src/utils/formatters/helpers.ts +28 -0
  145. package/src/utils/formatters/migrations.ts +346 -0
  146. package/src/utils/formatters/styled.ts +212 -0
  147. package/src/utils/formatters/verify.ts +621 -0
  148. package/src/utils/framework-components.ts +13 -10
  149. package/src/utils/global-flags.ts +41 -23
  150. package/src/utils/migration-command-scaffold.ts +184 -0
  151. package/src/utils/migration-types.ts +12 -0
  152. package/src/utils/progress-adapter.ts +18 -29
  153. package/src/utils/result-handler.ts +12 -13
  154. package/src/utils/shutdown.ts +92 -0
  155. package/src/utils/suggest-command.ts +31 -0
  156. package/src/utils/terminal-ui.ts +276 -0
  157. package/dist/chunk-5MPKZYVI.js +0 -47
  158. package/dist/chunk-5MPKZYVI.js.map +0 -1
  159. package/dist/chunk-6EPKRATC.js +0 -91
  160. package/dist/chunk-6EPKRATC.js.map +0 -1
  161. package/dist/chunk-74IELXRA.js +0 -371
  162. package/dist/chunk-74IELXRA.js.map +0 -1
  163. package/dist/chunk-HWYQOCAJ.js +0 -47
  164. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  165. package/dist/chunk-U6QI3AZ3.js +0 -133
  166. package/dist/chunk-U6QI3AZ3.js.map +0 -1
  167. package/dist/chunk-VI2YETW7.js +0 -38
  168. package/dist/chunk-VI2YETW7.js.map +0 -1
  169. package/dist/chunk-ZG5T6OB5.js +0 -923
  170. package/dist/chunk-ZG5T6OB5.js.map +0 -1
  171. package/dist/cli.d.ts +0 -2
  172. package/dist/cli.d.ts.map +0 -1
  173. package/dist/cli.js.map +0 -1
  174. package/dist/commands/contract-emit.d.ts +0 -3
  175. package/dist/commands/contract-emit.d.ts.map +0 -1
  176. package/dist/commands/contract-emit.js +0 -11
  177. package/dist/commands/contract-emit.js.map +0 -1
  178. package/dist/commands/db-init.d.ts +0 -3
  179. package/dist/commands/db-init.d.ts.map +0 -1
  180. package/dist/commands/db-init.js +0 -302
  181. package/dist/commands/db-init.js.map +0 -1
  182. package/dist/commands/db-introspect.d.ts +0 -3
  183. package/dist/commands/db-introspect.d.ts.map +0 -1
  184. package/dist/commands/db-introspect.js +0 -185
  185. package/dist/commands/db-introspect.js.map +0 -1
  186. package/dist/commands/db-schema-verify.d.ts +0 -3
  187. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  188. package/dist/commands/db-schema-verify.js +0 -163
  189. package/dist/commands/db-schema-verify.js.map +0 -1
  190. package/dist/commands/db-sign.d.ts +0 -3
  191. package/dist/commands/db-sign.d.ts.map +0 -1
  192. package/dist/commands/db-sign.js +0 -198
  193. package/dist/commands/db-sign.js.map +0 -1
  194. package/dist/commands/db-verify.d.ts +0 -3
  195. package/dist/commands/db-verify.d.ts.map +0 -1
  196. package/dist/commands/db-verify.js +0 -172
  197. package/dist/commands/db-verify.js.map +0 -1
  198. package/dist/config-loader.d.ts.map +0 -1
  199. package/dist/config-loader.js +0 -7
  200. package/dist/config-loader.js.map +0 -1
  201. package/dist/control-api/client.d.ts +0 -13
  202. package/dist/control-api/client.d.ts.map +0 -1
  203. package/dist/control-api/operations/db-init.d.ts +0 -29
  204. package/dist/control-api/operations/db-init.d.ts.map +0 -1
  205. package/dist/control-api/types.d.ts +0 -256
  206. package/dist/control-api/types.d.ts.map +0 -1
  207. package/dist/exports/config-types.d.ts +0 -3
  208. package/dist/exports/config-types.d.ts.map +0 -1
  209. package/dist/exports/config-types.js +0 -6
  210. package/dist/exports/config-types.js.map +0 -1
  211. package/dist/exports/control-api.d.ts +0 -13
  212. package/dist/exports/control-api.d.ts.map +0 -1
  213. package/dist/exports/control-api.js +0 -9
  214. package/dist/exports/control-api.js.map +0 -1
  215. package/dist/exports/index.d.ts +0 -4
  216. package/dist/exports/index.d.ts.map +0 -1
  217. package/dist/exports/index.js +0 -177
  218. package/dist/exports/index.js.map +0 -1
  219. package/dist/load-ts-contract.d.ts.map +0 -1
  220. package/dist/utils/action.d.ts +0 -16
  221. package/dist/utils/action.d.ts.map +0 -1
  222. package/dist/utils/cli-errors.d.ts +0 -7
  223. package/dist/utils/cli-errors.d.ts.map +0 -1
  224. package/dist/utils/command-helpers.d.ts +0 -12
  225. package/dist/utils/command-helpers.d.ts.map +0 -1
  226. package/dist/utils/framework-components.d.ts +0 -70
  227. package/dist/utils/framework-components.d.ts.map +0 -1
  228. package/dist/utils/global-flags.d.ts +0 -25
  229. package/dist/utils/global-flags.d.ts.map +0 -1
  230. package/dist/utils/output.d.ts +0 -142
  231. package/dist/utils/output.d.ts.map +0 -1
  232. package/dist/utils/progress-adapter.d.ts +0 -26
  233. package/dist/utils/progress-adapter.d.ts.map +0 -1
  234. package/dist/utils/result-handler.d.ts +0 -15
  235. package/dist/utils/result-handler.d.ts.map +0 -1
  236. package/dist/utils/spinner.d.ts +0 -29
  237. package/dist/utils/spinner.d.ts.map +0 -1
  238. package/src/commands/db-introspect.ts +0 -254
  239. package/src/commands/db-schema-verify.ts +0 -231
  240. package/src/utils/action.ts +0 -43
  241. package/src/utils/output.ts +0 -1471
  242. package/src/utils/spinner.ts +0 -67
package/dist/cli.js CHANGED
@@ -1,2672 +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
- errorDatabaseConnectionRequired,
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 { notOk as notOk3, ok as ok3 } from "@prisma-next/utils/result";
1196
- import { Command as Command2 } from "commander";
1197
-
1198
- // src/control-api/client.ts
1199
- import { createControlPlaneStack as createControlPlaneStack2 } from "@prisma-next/core-control-plane/stack";
1200
-
1201
- // src/utils/framework-components.ts
1202
- import {
1203
- checkContractComponentRequirements
1204
- } from "@prisma-next/contract/framework-components";
1205
- function assertFrameworkComponentsCompatible(expectedFamilyId, expectedTargetId, frameworkComponents) {
1206
- for (let i = 0; i < frameworkComponents.length; i++) {
1207
- const component = frameworkComponents[i];
1208
- if (typeof component !== "object" || component === null) {
1209
- throw errorConfigValidation("frameworkComponents[]", {
1210
- why: `Framework component at index ${i} must be an object`
1211
- });
1212
- }
1213
- const record = component;
1214
- if (!Object.hasOwn(record, "kind")) {
1215
- throw errorConfigValidation("frameworkComponents[].kind", {
1216
- why: `Framework component at index ${i} must have 'kind' property`
1217
- });
1218
- }
1219
- const kind = record["kind"];
1220
- if (kind !== "target" && kind !== "adapter" && kind !== "extension" && kind !== "driver") {
1221
- throw errorConfigValidation("frameworkComponents[].kind", {
1222
- why: `Framework component at index ${i} has invalid kind '${String(kind)}' (must be 'target', 'adapter', 'extension', or 'driver')`
1223
- });
1224
- }
1225
- if (!Object.hasOwn(record, "familyId")) {
1226
- throw errorConfigValidation("frameworkComponents[].familyId", {
1227
- why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'familyId' property`
1228
- });
1229
- }
1230
- const familyId = record["familyId"];
1231
- if (familyId !== expectedFamilyId) {
1232
- throw errorConfigValidation("frameworkComponents[].familyId", {
1233
- why: `Framework component at index ${i} (kind: ${String(kind)}) has familyId '${String(familyId)}' but expected '${expectedFamilyId}'`
1234
- });
1235
- }
1236
- if (!Object.hasOwn(record, "targetId")) {
1237
- throw errorConfigValidation("frameworkComponents[].targetId", {
1238
- why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'targetId' property`
1239
- });
1240
- }
1241
- const targetId = record["targetId"];
1242
- if (targetId !== expectedTargetId) {
1243
- throw errorConfigValidation("frameworkComponents[].targetId", {
1244
- why: `Framework component at index ${i} (kind: ${String(kind)}) has targetId '${String(targetId)}' but expected '${expectedTargetId}'`
1245
- });
1246
- }
1247
- }
1248
- return frameworkComponents;
1249
- }
1250
- function assertContractRequirementsSatisfied({
1251
- contract,
1252
- stack
1253
- }) {
1254
- const providedComponentIds = /* @__PURE__ */ new Set([stack.target.id, stack.adapter.id]);
1255
- for (const extension of stack.extensionPacks) {
1256
- providedComponentIds.add(extension.id);
1257
- }
1258
- const result = checkContractComponentRequirements({
1259
- contract,
1260
- expectedTargetFamily: stack.target.familyId,
1261
- expectedTargetId: stack.target.targetId,
1262
- providedComponentIds
1263
- });
1264
- if (result.familyMismatch) {
1265
- throw errorConfigValidation("contract.targetFamily", {
1266
- why: `Contract was emitted for family '${result.familyMismatch.actual}' but CLI config is wired to '${result.familyMismatch.expected}'.`
1267
- });
1268
- }
1269
- if (result.targetMismatch) {
1270
- throw errorConfigValidation("contract.target", {
1271
- why: `Contract target '${result.targetMismatch.actual}' does not match CLI target '${result.targetMismatch.expected}'.`
1272
- });
1273
- }
1274
- if (result.missingExtensionPackIds.length > 0) {
1275
- throw errorContractMissingExtensionPacks({
1276
- missingExtensionPacks: result.missingExtensionPackIds,
1277
- providedComponentIds: [...providedComponentIds]
1278
- });
1279
- }
1280
- }
1281
-
1282
- // src/control-api/operations/db-init.ts
1283
- import { notOk as notOk2, ok as ok2 } from "@prisma-next/utils/result";
1284
- async function executeDbInit(options) {
1285
- const { driver, familyInstance, contractIR, mode, migrations, frameworkComponents, onProgress } = options;
1286
- const planner = migrations.createPlanner(familyInstance);
1287
- const runner = migrations.createRunner(familyInstance);
1288
- const introspectSpanId = "introspect";
1289
- onProgress?.({
1290
- action: "dbInit",
1291
- kind: "spanStart",
1292
- spanId: introspectSpanId,
1293
- label: "Introspecting database schema"
1294
- });
1295
- const schemaIR = await familyInstance.introspect({ driver });
1296
- onProgress?.({
1297
- action: "dbInit",
1298
- kind: "spanEnd",
1299
- spanId: introspectSpanId,
1300
- outcome: "ok"
1301
- });
1302
- const policy = { allowedOperationClasses: ["additive"] };
1303
- const planSpanId = "plan";
1304
- onProgress?.({
1305
- action: "dbInit",
1306
- kind: "spanStart",
1307
- spanId: planSpanId,
1308
- label: "Planning migration"
1309
- });
1310
- const plannerResult = await planner.plan({
1311
- contract: contractIR,
1312
- schema: schemaIR,
1313
- policy,
1314
- frameworkComponents
1315
- });
1316
- if (plannerResult.kind === "failure") {
1317
- onProgress?.({
1318
- action: "dbInit",
1319
- kind: "spanEnd",
1320
- spanId: planSpanId,
1321
- outcome: "error"
1322
- });
1323
- return notOk2({
1324
- code: "PLANNING_FAILED",
1325
- summary: "Migration planning failed due to conflicts",
1326
- conflicts: plannerResult.conflicts,
1327
- why: void 0,
1328
- meta: void 0
1329
- });
1330
- }
1331
- const migrationPlan = plannerResult.plan;
1332
- onProgress?.({
1333
- action: "dbInit",
1334
- kind: "spanEnd",
1335
- spanId: planSpanId,
1336
- outcome: "ok"
1337
- });
1338
- const checkMarkerSpanId = "checkMarker";
1339
- onProgress?.({
1340
- action: "dbInit",
1341
- kind: "spanStart",
1342
- spanId: checkMarkerSpanId,
1343
- label: "Checking contract marker"
1344
- });
1345
- const existingMarker = await familyInstance.readMarker({ driver });
1346
- if (existingMarker) {
1347
- const markerMatchesDestination = existingMarker.coreHash === migrationPlan.destination.coreHash && (!migrationPlan.destination.profileHash || existingMarker.profileHash === migrationPlan.destination.profileHash);
1348
- if (markerMatchesDestination) {
1349
- onProgress?.({
1350
- action: "dbInit",
1351
- kind: "spanEnd",
1352
- spanId: checkMarkerSpanId,
1353
- outcome: "skipped"
1354
- });
1355
- const result2 = {
1356
- mode,
1357
- plan: { operations: [] },
1358
- ...mode === "apply" ? {
1359
- execution: { operationsPlanned: 0, operationsExecuted: 0 },
1360
- marker: {
1361
- coreHash: existingMarker.coreHash,
1362
- profileHash: existingMarker.profileHash
1363
- }
1364
- } : {},
1365
- summary: "Database already at target contract state"
1366
- };
1367
- return ok2(result2);
1368
- }
1369
- onProgress?.({
1370
- action: "dbInit",
1371
- kind: "spanEnd",
1372
- spanId: checkMarkerSpanId,
1373
- outcome: "error"
1374
- });
1375
- return notOk2({
1376
- code: "MARKER_ORIGIN_MISMATCH",
1377
- summary: "Existing contract marker does not match plan destination",
1378
- marker: {
1379
- coreHash: existingMarker.coreHash,
1380
- profileHash: existingMarker.profileHash
1381
- },
1382
- destination: {
1383
- coreHash: migrationPlan.destination.coreHash,
1384
- profileHash: migrationPlan.destination.profileHash
1385
- },
1386
- why: void 0,
1387
- conflicts: void 0,
1388
- meta: void 0
1389
- });
1390
- }
1391
- onProgress?.({
1392
- action: "dbInit",
1393
- kind: "spanEnd",
1394
- spanId: checkMarkerSpanId,
1395
- outcome: "ok"
1396
- });
1397
- if (mode === "plan") {
1398
- const result2 = {
1399
- mode: "plan",
1400
- plan: { operations: migrationPlan.operations },
1401
- summary: `Planned ${migrationPlan.operations.length} operation(s)`
1402
- };
1403
- return ok2(result2);
1404
- }
1405
- const applySpanId = "apply";
1406
- onProgress?.({
1407
- action: "dbInit",
1408
- kind: "spanStart",
1409
- spanId: applySpanId,
1410
- label: "Applying migration plan"
1411
- });
1412
- const callbacks = onProgress ? {
1413
- onOperationStart: (op) => {
1414
- onProgress({
1415
- action: "dbInit",
1416
- kind: "spanStart",
1417
- spanId: `operation:${op.id}`,
1418
- parentSpanId: applySpanId,
1419
- label: op.label
1420
- });
1421
- },
1422
- onOperationComplete: (op) => {
1423
- onProgress({
1424
- action: "dbInit",
1425
- kind: "spanEnd",
1426
- spanId: `operation:${op.id}`,
1427
- outcome: "ok"
1428
- });
1429
- }
1430
- } : void 0;
1431
- const runnerResult = await runner.execute({
1432
- plan: migrationPlan,
1433
- driver,
1434
- destinationContract: contractIR,
1435
- policy,
1436
- ...callbacks ? { callbacks } : {},
1437
- // db init plans and applies back-to-back from a fresh introspection, so per-operation
1438
- // pre/postchecks and the idempotency probe are usually redundant overhead. We still
1439
- // enforce marker/origin compatibility and a full schema verification after apply.
1440
- executionChecks: {
1441
- prechecks: false,
1442
- postchecks: false,
1443
- idempotencyChecks: false
1444
- },
1445
- frameworkComponents
1446
- });
1447
- if (!runnerResult.ok) {
1448
- onProgress?.({
1449
- action: "dbInit",
1450
- kind: "spanEnd",
1451
- spanId: applySpanId,
1452
- outcome: "error"
1453
- });
1454
- return notOk2({
1455
- code: "RUNNER_FAILED",
1456
- summary: runnerResult.failure.summary,
1457
- why: runnerResult.failure.why,
1458
- meta: runnerResult.failure.meta,
1459
- conflicts: void 0
1460
- });
1461
- }
1462
- const execution = runnerResult.value;
1463
- onProgress?.({
1464
- action: "dbInit",
1465
- kind: "spanEnd",
1466
- spanId: applySpanId,
1467
- outcome: "ok"
1468
- });
1469
- const result = {
1470
- mode: "apply",
1471
- plan: { operations: migrationPlan.operations },
1472
- execution: {
1473
- operationsPlanned: execution.operationsPlanned,
1474
- operationsExecuted: execution.operationsExecuted
1475
- },
1476
- marker: migrationPlan.destination.profileHash ? {
1477
- coreHash: migrationPlan.destination.coreHash,
1478
- profileHash: migrationPlan.destination.profileHash
1479
- } : { coreHash: migrationPlan.destination.coreHash },
1480
- summary: `Applied ${execution.operationsExecuted} operation(s), marker written`
1481
- };
1482
- return ok2(result);
1483
- }
1484
-
1485
- // src/control-api/client.ts
1486
- function createControlClient(options) {
1487
- return new ControlClientImpl(options);
1488
- }
1489
- var ControlClientImpl = class {
1490
- options;
1491
- stack = null;
1492
- driver = null;
1493
- familyInstance = null;
1494
- frameworkComponents = null;
1495
- initialized = false;
1496
- defaultConnection;
1497
- constructor(options) {
1498
- this.options = options;
1499
- this.defaultConnection = options.connection;
1500
- }
1501
- init() {
1502
- if (this.initialized) {
1503
- return;
1504
- }
1505
- this.stack = createControlPlaneStack2({
1506
- target: this.options.target,
1507
- adapter: this.options.adapter,
1508
- driver: this.options.driver,
1509
- extensionPacks: this.options.extensionPacks
1510
- });
1511
- this.familyInstance = this.options.family.create(this.stack);
1512
- const rawComponents = [
1513
- this.options.target,
1514
- this.options.adapter,
1515
- ...this.options.extensionPacks ?? []
1516
- ];
1517
- this.frameworkComponents = assertFrameworkComponentsCompatible(
1518
- this.options.family.familyId,
1519
- this.options.target.targetId,
1520
- rawComponents
1521
- );
1522
- this.initialized = true;
1523
- }
1524
- async connect(connection) {
1525
- this.init();
1526
- if (this.driver) {
1527
- throw new Error("Already connected. Call close() before reconnecting.");
1528
- }
1529
- const resolvedConnection = connection ?? this.defaultConnection;
1530
- if (resolvedConnection === void 0) {
1531
- throw new Error(
1532
- "No connection provided. Pass a connection to connect() or provide a default connection when creating the client."
1533
- );
1534
- }
1535
- if (!this.stack?.driver) {
1536
- throw new Error(
1537
- "Driver is not configured. Pass a driver descriptor when creating the control client to enable database operations."
1538
- );
1539
- }
1540
- this.driver = await this.stack?.driver.create(resolvedConnection);
1541
- }
1542
- async close() {
1543
- if (this.driver) {
1544
- await this.driver.close();
1545
- this.driver = null;
1546
- }
1547
- }
1548
- async ensureConnected() {
1549
- this.init();
1550
- if (!this.driver && this.defaultConnection !== void 0) {
1551
- await this.connect(this.defaultConnection);
1552
- }
1553
- if (!this.driver || !this.familyInstance || !this.frameworkComponents) {
1554
- throw new Error("Not connected. Call connect(connection) first.");
1555
- }
1556
- return {
1557
- driver: this.driver,
1558
- familyInstance: this.familyInstance,
1559
- frameworkComponents: this.frameworkComponents
1560
- };
1561
- }
1562
- async verify(options) {
1563
- const { driver, familyInstance } = await this.ensureConnected();
1564
- const contractIR = familyInstance.validateContractIR(options.contractIR);
1565
- return familyInstance.verify({
1566
- driver,
1567
- contractIR,
1568
- expectedTargetId: this.options.target.targetId,
1569
- contractPath: ""
1570
- });
1571
- }
1572
- async schemaVerify(options) {
1573
- const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
1574
- const contractIR = familyInstance.validateContractIR(options.contractIR);
1575
- return familyInstance.schemaVerify({
1576
- driver,
1577
- contractIR,
1578
- strict: options.strict ?? false,
1579
- contractPath: "",
1580
- frameworkComponents
1581
- });
1582
- }
1583
- async sign(options) {
1584
- const { driver, familyInstance } = await this.ensureConnected();
1585
- const contractIR = familyInstance.validateContractIR(options.contractIR);
1586
- return familyInstance.sign({
1587
- driver,
1588
- contractIR,
1589
- contractPath: ""
1590
- });
1591
- }
1592
- async dbInit(options) {
1593
- const { onProgress } = options;
1594
- if (options.connection !== void 0) {
1595
- onProgress?.({
1596
- action: "dbInit",
1597
- kind: "spanStart",
1598
- spanId: "connect",
1599
- label: "Connecting to database..."
1600
- });
1601
- try {
1602
- await this.connect(options.connection);
1603
- onProgress?.({
1604
- action: "dbInit",
1605
- kind: "spanEnd",
1606
- spanId: "connect",
1607
- outcome: "ok"
1608
- });
1609
- } catch (error) {
1610
- onProgress?.({
1611
- action: "dbInit",
1612
- kind: "spanEnd",
1613
- spanId: "connect",
1614
- outcome: "error"
1615
- });
1616
- throw error;
1617
- }
1618
- }
1619
- const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
1620
- if (!this.options.target.migrations) {
1621
- throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
1622
- }
1623
- const contractIR = familyInstance.validateContractIR(options.contractIR);
1624
- return executeDbInit({
1625
- driver,
1626
- familyInstance,
1627
- contractIR,
1628
- mode: options.mode,
1629
- migrations: this.options.target.migrations,
1630
- frameworkComponents,
1631
- ...onProgress ? { onProgress } : {}
1632
- });
1633
- }
1634
- async introspect(options) {
1635
- const { driver, familyInstance } = await this.ensureConnected();
1636
- const _schema = options?.schema;
1637
- void _schema;
1638
- return familyInstance.introspect({ driver });
1639
- }
1640
- };
1641
-
1642
- // src/utils/progress-adapter.ts
1643
- import ora2 from "ora";
1644
- function createProgressAdapter(options) {
1645
- const { flags } = options;
1646
- const shouldShowProgress = !flags.quiet && flags.json !== "object" && process.stdout.isTTY;
1647
- if (!shouldShowProgress) {
1648
- return () => {
1649
- };
1650
- }
1651
- const activeSpans = /* @__PURE__ */ new Map();
1652
- return (event) => {
1653
- if (event.kind === "spanStart") {
1654
- if (event.parentSpanId) {
1655
- console.log(` \u2192 ${event.label}...`);
1656
- return;
1657
- }
1658
- const spinner = ora2({
1659
- text: event.label,
1660
- color: flags.color !== false ? "cyan" : false
1661
- }).start();
1662
- activeSpans.set(event.spanId, {
1663
- spinner,
1664
- startTime: Date.now()
1665
- });
1666
- } else if (event.kind === "spanEnd") {
1667
- const spanState = activeSpans.get(event.spanId);
1668
- if (spanState) {
1669
- const elapsed = Date.now() - spanState.startTime;
1670
- if (event.outcome === "error") {
1671
- spanState.spinner.fail(`${spanState.spinner.text} (failed)`);
1672
- } else if (event.outcome === "skipped") {
1673
- spanState.spinner.info(`${spanState.spinner.text} (skipped)`);
1674
- } else {
1675
- spanState.spinner.succeed(`${spanState.spinner.text} (${elapsed}ms)`);
1676
- }
1677
- activeSpans.delete(event.spanId);
1678
- }
1679
- }
1680
- };
1681
- }
1682
-
1683
- // src/commands/db-init.ts
1684
- function mapDbInitFailure(failure) {
1685
- if (failure.code === "PLANNING_FAILED") {
1686
- return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
1687
- }
1688
- if (failure.code === "MARKER_ORIGIN_MISMATCH") {
1689
- const mismatchParts = [];
1690
- if (failure.marker?.coreHash !== failure.destination?.coreHash && failure.marker?.coreHash && failure.destination?.coreHash) {
1691
- mismatchParts.push(
1692
- `coreHash (marker: ${failure.marker.coreHash}, destination: ${failure.destination.coreHash})`
1693
- );
1694
- }
1695
- if (failure.marker?.profileHash !== failure.destination?.profileHash && failure.marker?.profileHash && failure.destination?.profileHash) {
1696
- mismatchParts.push(
1697
- `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`
1698
- );
1699
- }
1700
- return errorRuntime(
1701
- `Existing contract marker does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(" and ")}.` : ""}`,
1702
- {
1703
- why: "Database has an existing contract marker that does not match the target contract",
1704
- fix: "If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow",
1705
- meta: {
1706
- code: "MARKER_ORIGIN_MISMATCH",
1707
- ...failure.marker?.coreHash ? { markerCoreHash: failure.marker.coreHash } : {},
1708
- ...failure.destination?.coreHash ? { destinationCoreHash: failure.destination.coreHash } : {},
1709
- ...failure.marker?.profileHash ? { markerProfileHash: failure.marker.profileHash } : {},
1710
- ...failure.destination?.profileHash ? { destinationProfileHash: failure.destination.profileHash } : {}
1711
- }
1712
- }
1713
- );
1714
- }
1715
- if (failure.code === "RUNNER_FAILED") {
1716
- return errorRuntime(failure.summary, {
1717
- why: failure.why ?? "Migration runner failed",
1718
- fix: "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`",
1719
- meta: {
1720
- code: "RUNNER_FAILED",
1721
- ...failure.meta ?? {}
1722
- }
1723
- });
1724
- }
1725
- const exhaustive = failure.code;
1726
- throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);
1727
- }
1728
- async function executeDbInitCommand(options, flags, startTime) {
1729
- const config = await loadConfig(options.config);
1730
- const configPath = options.config ? relative3(process.cwd(), resolve3(options.config)) : "prisma-next.config.ts";
1731
- const contractPathAbsolute = config.contract?.output ? resolve3(config.contract.output) : resolve3("src/prisma/contract.json");
1732
- const contractPath = relative3(process.cwd(), contractPathAbsolute);
1733
- if (flags.json !== "object" && !flags.quiet) {
1734
- const details = [
1735
- { label: "config", value: configPath },
1736
- { label: "contract", value: contractPath }
1737
- ];
1738
- if (options.db) {
1739
- details.push({ label: "database", value: options.db });
1740
- }
1741
- if (options.plan) {
1742
- details.push({ label: "mode", value: "plan (dry run)" });
1743
- }
1744
- const header = formatStyledHeader({
1745
- command: "db init",
1746
- description: "Bootstrap a database to match the current contract",
1747
- url: "https://pris.ly/db-init",
1748
- details,
1749
- flags
1750
- });
1751
- console.log(header);
1752
- }
1753
- let contractJsonContent;
1754
- try {
1755
- contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
1756
- } catch (error) {
1757
- if (error instanceof Error && error.code === "ENOENT") {
1758
- return notOk3(
1759
- errorFileNotFound(contractPathAbsolute, {
1760
- why: `Contract file not found at ${contractPathAbsolute}`,
1761
- fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
1762
- })
1763
- );
1764
- }
1765
- return notOk3(
1766
- errorUnexpected2(error instanceof Error ? error.message : String(error), {
1767
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
1768
- })
1769
- );
1770
- }
1771
- let contractJson;
1772
- try {
1773
- contractJson = JSON.parse(contractJsonContent);
1774
- } catch (error) {
1775
- return notOk3(
1776
- errorContractValidationFailed(
1777
- `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
1778
- { where: { path: contractPathAbsolute } }
1779
- )
1780
- );
1781
- }
1782
- const dbConnection = options.db ?? config.db?.connection;
1783
- if (!dbConnection) {
1784
- return notOk3(
1785
- errorDatabaseConnectionRequired({
1786
- why: `Database connection is required for db init (set db.connection in ${configPath}, or pass --db <url>)`
1787
- })
1788
- );
1789
- }
1790
- if (!config.driver) {
1791
- return notOk3(errorDriverRequired({ why: "Config.driver is required for db init" }));
1792
- }
1793
- if (!config.target.migrations) {
1794
- return notOk3(
1795
- errorTargetMigrationNotSupported({
1796
- why: `Target "${config.target.id}" does not support migrations`
1797
- })
1798
- );
1799
- }
1800
- const client = createControlClient({
1801
- family: config.family,
1802
- target: config.target,
1803
- adapter: config.adapter,
1804
- driver: config.driver,
1805
- extensionPacks: config.extensionPacks ?? []
1806
- });
1807
- const onProgress = createProgressAdapter({ flags });
1808
- try {
1809
- const result = await client.dbInit({
1810
- contractIR: contractJson,
1811
- mode: options.plan ? "plan" : "apply",
1812
- connection: dbConnection,
1813
- onProgress
1814
- });
1815
- if (!result.ok) {
1816
- return notOk3(mapDbInitFailure(result.failure));
1817
- }
1818
- const profileHash = result.value.marker?.profileHash;
1819
- const dbInitResult = {
1820
- ok: true,
1821
- mode: result.value.mode,
1822
- plan: {
1823
- targetId: config.target.targetId,
1824
- destination: {
1825
- coreHash: result.value.marker?.coreHash ?? "",
1826
- ...profileHash ? { profileHash } : {}
1827
- },
1828
- operations: result.value.plan.operations.map((op) => ({
1829
- id: op.id,
1830
- label: op.label,
1831
- operationClass: op.operationClass
1832
- }))
1833
- },
1834
- ...result.value.execution ? {
1835
- execution: {
1836
- operationsPlanned: result.value.execution.operationsPlanned,
1837
- operationsExecuted: result.value.execution.operationsExecuted
1838
- }
1839
- } : {},
1840
- ...result.value.marker ? {
1841
- marker: {
1842
- coreHash: result.value.marker.coreHash,
1843
- ...result.value.marker.profileHash ? { profileHash: result.value.marker.profileHash } : {}
1844
- }
1845
- } : {},
1846
- summary: result.value.summary,
1847
- timings: { total: Date.now() - startTime }
1848
- };
1849
- return ok3(dbInitResult);
1850
- } catch (error) {
1851
- if (CliStructuredError.is(error)) {
1852
- return notOk3(error);
1853
- }
1854
- return notOk3(
1855
- errorUnexpected2(error instanceof Error ? error.message : String(error), {
1856
- why: `Unexpected error during db init: ${error instanceof Error ? error.message : String(error)}`
1857
- })
1858
- );
1859
- } finally {
1860
- await client.close();
1861
- }
1862
- }
1863
- function createDbInitCommand() {
1864
- const command = new Command2("init");
1865
- setCommandDescriptions(
1866
- command,
1867
- "Bootstrap a database to match the current contract and write the contract marker",
1868
- "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."
1869
- );
1870
- command.configureHelp({
1871
- formatHelp: (cmd) => {
1872
- const flags = parseGlobalFlags({});
1873
- return formatCommandHelp({ command: cmd, flags });
1874
- }
1875
- }).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) => {
1876
- const flags = parseGlobalFlags(options);
1877
- const startTime = Date.now();
1878
- if (flags.json === "ndjson") {
1879
- const result2 = notOk3(
1880
- errorJsonFormatNotSupported({
1881
- command: "db init",
1882
- format: "ndjson",
1883
- supportedFormats: ["object"]
1884
- })
1885
- );
1886
- const exitCode2 = handleResult(result2, flags);
1887
- process.exit(exitCode2);
1888
- }
1889
- const result = await executeDbInitCommand(options, flags, startTime);
1890
- const exitCode = handleResult(result, flags, (dbInitResult) => {
1891
- if (flags.json === "object") {
1892
- console.log(formatDbInitJson(dbInitResult));
1893
- } else {
1894
- const output = dbInitResult.mode === "plan" ? formatDbInitPlanOutput(dbInitResult, flags) : formatDbInitApplyOutput(dbInitResult, flags);
1895
- if (output) {
1896
- console.log(output);
1897
- }
1898
- }
1899
- });
1900
- process.exit(exitCode);
1901
- });
1902
- return command;
1903
- }
1904
-
1905
- // src/commands/db-introspect.ts
1906
- import { readFile as readFile2 } from "fs/promises";
1907
- import { relative as relative4, resolve as resolve4 } from "path";
1908
- import {
1909
- errorDatabaseConnectionRequired as errorDatabaseConnectionRequired2,
1910
- errorDriverRequired as errorDriverRequired2,
1911
- errorRuntime as errorRuntime2,
1912
- errorUnexpected as errorUnexpected3
1913
- } from "@prisma-next/core-control-plane/errors";
1914
- import { createControlPlaneStack as createControlPlaneStack3 } from "@prisma-next/core-control-plane/types";
1915
- import { Command as Command3 } from "commander";
1916
- function createDbIntrospectCommand() {
1917
- const command = new Command3("introspect");
1918
- setCommandDescriptions(
1919
- command,
1920
- "Inspect the database schema",
1921
- "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."
1922
- );
1923
- command.configureHelp({
1924
- formatHelp: (cmd) => {
1925
- const flags = parseGlobalFlags({});
1926
- return formatCommandHelp({ command: cmd, flags });
1927
- }
1928
- }).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) => {
1929
- const flags = parseGlobalFlags(options);
1930
- const result = await performAction(async () => {
1931
- const startTime = Date.now();
1932
- const config = await loadConfig(options.config);
1933
- const configPath = options.config ? relative4(process.cwd(), resolve4(options.config)) : "prisma-next.config.ts";
1934
- let contractIR;
1935
- if (config.contract?.output) {
1936
- const contractPath = resolve4(config.contract.output);
1937
- try {
1938
- const contractJsonContent = await readFile2(contractPath, "utf-8");
1939
- contractIR = JSON.parse(contractJsonContent);
1940
- } catch (error) {
1941
- if (error instanceof Error && error.code !== "ENOENT") {
1942
- throw errorUnexpected3(error.message, {
1943
- why: `Failed to read contract file: ${error.message}`
1944
- });
1945
- }
1946
- }
1947
- }
1948
- if (flags.json !== "object" && !flags.quiet) {
1949
- const details = [
1950
- { label: "config", value: configPath }
1951
- ];
1952
- if (options.db) {
1953
- const maskedUrl = options.db.replace(/:([^:@]+)@/, ":****@");
1954
- details.push({ label: "database", value: maskedUrl });
1955
- } else if (config.db?.connection && typeof config.db.connection === "string") {
1956
- const maskedUrl = config.db.connection.replace(/:([^:@]+)@/, ":****@");
1957
- details.push({ label: "database", value: maskedUrl });
1958
- }
1959
- const header = formatStyledHeader({
1960
- command: "db introspect",
1961
- description: "Inspect the database schema",
1962
- url: "https://pris.ly/db-introspect",
1963
- details,
1964
- flags
1965
- });
1966
- console.log(header);
1967
- }
1968
- const dbConnection = options.db ?? config.db?.connection;
1969
- if (!dbConnection) {
1970
- throw errorDatabaseConnectionRequired2();
1971
- }
1972
- if (!config.driver) {
1973
- throw errorDriverRequired2();
1974
- }
1975
- const driverDescriptor = config.driver;
1976
- const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {
1977
- message: "Connecting to database...",
1978
- flags
1979
- });
1980
- try {
1981
- const stack = createControlPlaneStack3({
1982
- target: config.target,
1983
- adapter: config.adapter,
1984
- driver: driverDescriptor,
1985
- extensionPacks: config.extensionPacks
1986
- });
1987
- const familyInstance = config.family.create(stack);
1988
- if (contractIR) {
1989
- const validatedContract = familyInstance.validateContractIR(contractIR);
1990
- assertContractRequirementsSatisfied({ contract: validatedContract, stack });
1991
- contractIR = validatedContract;
1992
- }
1993
- let schemaIR;
1994
- try {
1995
- schemaIR = await withSpinner(
1996
- () => familyInstance.introspect({
1997
- driver,
1998
- contractIR
1999
- }),
2000
- {
2001
- message: "Introspecting database schema...",
2002
- flags
2003
- }
2004
- );
2005
- } catch (error) {
2006
- throw errorRuntime2(error instanceof Error ? error.message : String(error), {
2007
- why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`
2008
- });
2009
- }
2010
- let schemaView;
2011
- if (familyInstance.toSchemaView) {
2012
- try {
2013
- schemaView = familyInstance.toSchemaView(schemaIR);
2014
- } catch (error) {
2015
- if (flags.verbose) {
2016
- console.error(
2017
- `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`
2018
- );
2019
- }
2020
- }
2021
- }
2022
- const totalTime = Date.now() - startTime;
2023
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2024
- console.log("");
2025
- }
2026
- const connectionForMeta = typeof dbConnection === "string" ? dbConnection.replace(/:([^:@]+)@/, ":****@") : void 0;
2027
- const introspectResult = {
2028
- ok: true,
2029
- summary: "Schema introspected successfully",
2030
- target: {
2031
- familyId: config.family.familyId,
2032
- id: config.target.targetId
2033
- },
2034
- schema: schemaIR,
2035
- ...configPath || connectionForMeta ? {
2036
- meta: {
2037
- ...configPath ? { configPath } : {},
2038
- ...connectionForMeta ? { dbUrl: connectionForMeta } : {}
2039
- }
2040
- } : {},
2041
- timings: {
2042
- total: totalTime
2043
- }
2044
- };
2045
- return { introspectResult, schemaView };
2046
- } finally {
2047
- await driver.close();
2048
- }
2049
- });
2050
- const exitCode = handleResult(result, flags, (value) => {
2051
- const { introspectResult, schemaView } = value;
2052
- if (flags.json === "object") {
2053
- console.log(formatIntrospectJson(introspectResult));
2054
- } else {
2055
- const output = formatIntrospectOutput(introspectResult, schemaView, flags);
2056
- if (output) {
2057
- console.log(output);
2058
- }
2059
- }
2060
- });
2061
- process.exit(exitCode);
2062
- });
2063
- return command;
2064
- }
2065
-
2066
- // src/commands/db-schema-verify.ts
2067
- import { readFile as readFile3 } from "fs/promises";
2068
- import { relative as relative5, resolve as resolve5 } from "path";
2069
- import {
2070
- errorDatabaseConnectionRequired as errorDatabaseConnectionRequired3,
2071
- errorDriverRequired as errorDriverRequired3,
2072
- errorFileNotFound as errorFileNotFound2,
2073
- errorRuntime as errorRuntime3,
2074
- errorUnexpected as errorUnexpected4
2075
- } from "@prisma-next/core-control-plane/errors";
2076
- import { createControlPlaneStack as createControlPlaneStack4 } from "@prisma-next/core-control-plane/types";
2077
- import { Command as Command4 } from "commander";
2078
- function createDbSchemaVerifyCommand() {
2079
- const command = new Command4("schema-verify");
2080
- setCommandDescriptions(
2081
- command,
2082
- "Check whether the database schema satisfies your contract",
2083
- "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."
2084
- );
2085
- command.configureHelp({
2086
- formatHelp: (cmd) => {
2087
- const flags = parseGlobalFlags({});
2088
- return formatCommandHelp({ command: cmd, flags });
2089
- }
2090
- }).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) => {
2091
- const flags = parseGlobalFlags(options);
2092
- const result = await performAction(async () => {
2093
- const config = await loadConfig(options.config);
2094
- const configPath = options.config ? relative5(process.cwd(), resolve5(options.config)) : "prisma-next.config.ts";
2095
- const contractPathAbsolute = config.contract?.output ? resolve5(config.contract.output) : resolve5("src/prisma/contract.json");
2096
- const contractPath = relative5(process.cwd(), contractPathAbsolute);
2097
- if (flags.json !== "object" && !flags.quiet) {
2098
- const details = [
2099
- { label: "config", value: configPath },
2100
- { label: "contract", value: contractPath }
2101
- ];
2102
- if (options.db) {
2103
- details.push({ label: "database", value: options.db });
2104
- }
2105
- const header = formatStyledHeader({
2106
- command: "db schema-verify",
2107
- description: "Check whether the database schema satisfies your contract",
2108
- url: "https://pris.ly/db-schema-verify",
2109
- details,
2110
- flags
2111
- });
2112
- console.log(header);
2113
- }
2114
- let contractJsonContent;
2115
- try {
2116
- contractJsonContent = await readFile3(contractPathAbsolute, "utf-8");
2117
- } catch (error) {
2118
- if (error instanceof Error && error.code === "ENOENT") {
2119
- throw errorFileNotFound2(contractPathAbsolute, {
2120
- why: `Contract file not found at ${contractPathAbsolute}`
2121
- });
2122
- }
2123
- throw errorUnexpected4(error instanceof Error ? error.message : String(error), {
2124
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
2125
- });
2126
- }
2127
- const contractJson = JSON.parse(contractJsonContent);
2128
- if (!config.driver) {
2129
- throw errorDriverRequired3();
2130
- }
2131
- const driverDescriptor = config.driver;
2132
- const stack = createControlPlaneStack4({
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
- const dbConnection = options.db ?? config.db?.connection;
2142
- if (!dbConnection) {
2143
- throw errorDatabaseConnectionRequired3();
2144
- }
2145
- const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {
2146
- message: "Connecting to database...",
2147
- flags
2148
- });
2149
- try {
2150
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
2151
- const frameworkComponents = assertFrameworkComponentsCompatible(
2152
- config.family.familyId,
2153
- config.target.targetId,
2154
- rawComponents
2155
- );
2156
- let schemaVerifyResult;
2157
- try {
2158
- schemaVerifyResult = await withSpinner(
2159
- () => familyInstance.schemaVerify({
2160
- driver,
2161
- contractIR,
2162
- strict: options.strict ?? false,
2163
- contractPath: contractPathAbsolute,
2164
- configPath,
2165
- frameworkComponents
2166
- }),
2167
- {
2168
- message: "Verifying database schema...",
2169
- flags
2170
- }
2171
- );
2172
- } catch (error) {
2173
- throw errorRuntime3(error instanceof Error ? error.message : String(error), {
2174
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
2175
- });
2176
- }
2177
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2178
- console.log("");
2179
- }
2180
- return schemaVerifyResult;
2181
- } finally {
2182
- await driver.close();
2183
- }
2184
- });
2185
- const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
2186
- if (flags.json === "object") {
2187
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
2188
- } else {
2189
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
2190
- if (output) {
2191
- console.log(output);
2192
- }
2193
- }
2194
- });
2195
- if (result.ok && !result.value.ok) {
2196
- process.exit(1);
2197
- } else {
2198
- process.exit(exitCode);
2199
- }
2200
- });
2201
- return command;
2202
- }
2203
-
2204
- // src/commands/db-sign.ts
2205
- import { readFile as readFile4 } from "fs/promises";
2206
- import { relative as relative6, resolve as resolve6 } from "path";
2207
- import {
2208
- errorDatabaseConnectionRequired as errorDatabaseConnectionRequired4,
2209
- errorDriverRequired as errorDriverRequired4,
2210
- errorFileNotFound as errorFileNotFound3,
2211
- errorRuntime as errorRuntime4,
2212
- errorUnexpected as errorUnexpected5
2213
- } from "@prisma-next/core-control-plane/errors";
2214
- import { createControlPlaneStack as createControlPlaneStack5 } from "@prisma-next/core-control-plane/types";
2215
- import { Command as Command5 } from "commander";
2216
- function createDbSignCommand() {
2217
- const command = new Command5("sign");
2218
- setCommandDescriptions(
2219
- command,
2220
- "Sign the database with your contract so you can safely run queries",
2221
- "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."
2222
- );
2223
- command.configureHelp({
2224
- formatHelp: (cmd) => {
2225
- const flags = parseGlobalFlags({});
2226
- return formatCommandHelp({ command: cmd, flags });
2227
- }
2228
- }).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) => {
2229
- const flags = parseGlobalFlags(options);
2230
- const result = await performAction(async () => {
2231
- const config = await loadConfig(options.config);
2232
- const configPath = options.config ? relative6(process.cwd(), resolve6(options.config)) : "prisma-next.config.ts";
2233
- const contractPathAbsolute = config.contract?.output ? resolve6(config.contract.output) : resolve6("src/prisma/contract.json");
2234
- const contractPath = relative6(process.cwd(), contractPathAbsolute);
2235
- if (flags.json !== "object" && !flags.quiet) {
2236
- const details = [
2237
- { label: "config", value: configPath },
2238
- { label: "contract", value: contractPath }
2239
- ];
2240
- if (options.db) {
2241
- details.push({ label: "database", value: options.db });
2242
- }
2243
- const header = formatStyledHeader({
2244
- command: "db sign",
2245
- description: "Sign the database with your contract so you can safely run queries",
2246
- url: "https://pris.ly/db-sign",
2247
- details,
2248
- flags
2249
- });
2250
- console.log(header);
2251
- }
2252
- let contractJsonContent;
2253
- try {
2254
- contractJsonContent = await readFile4(contractPathAbsolute, "utf-8");
2255
- } catch (error) {
2256
- if (error instanceof Error && error.code === "ENOENT") {
2257
- throw errorFileNotFound3(contractPathAbsolute, {
2258
- why: `Contract file not found at ${contractPathAbsolute}`
2259
- });
2260
- }
2261
- throw errorUnexpected5(error instanceof Error ? error.message : String(error), {
2262
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
2263
- });
2264
- }
2265
- const contractJson = JSON.parse(contractJsonContent);
2266
- const dbConnection = options.db ?? config.db?.connection;
2267
- if (!dbConnection) {
2268
- throw errorDatabaseConnectionRequired4();
2269
- }
2270
- if (!config.driver) {
2271
- throw errorDriverRequired4();
2272
- }
2273
- const driverDescriptor = config.driver;
2274
- const stack = createControlPlaneStack5({
2275
- target: config.target,
2276
- adapter: config.adapter,
2277
- driver: driverDescriptor,
2278
- extensionPacks: config.extensionPacks
2279
- });
2280
- const familyInstance = config.family.create(stack);
2281
- const contractIR = familyInstance.validateContractIR(contractJson);
2282
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
2283
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
2284
- const frameworkComponents = assertFrameworkComponentsCompatible(
2285
- config.family.familyId,
2286
- config.target.targetId,
2287
- rawComponents
2288
- );
2289
- const driver = await driverDescriptor.create(dbConnection);
2290
- try {
2291
- let schemaVerifyResult;
2292
- try {
2293
- schemaVerifyResult = await withSpinner(
2294
- () => familyInstance.schemaVerify({
2295
- driver,
2296
- contractIR,
2297
- strict: false,
2298
- contractPath: contractPathAbsolute,
2299
- configPath,
2300
- frameworkComponents
2301
- }),
2302
- {
2303
- message: "Verifying database satisfies contract",
2304
- flags
2305
- }
2306
- );
2307
- } catch (error) {
2308
- throw errorRuntime4(error instanceof Error ? error.message : String(error), {
2309
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
2310
- });
2311
- }
2312
- if (!schemaVerifyResult.ok) {
2313
- return { schemaVerifyResult, signResult: void 0 };
2314
- }
2315
- let signResult;
2316
- try {
2317
- signResult = await withSpinner(
2318
- () => familyInstance.sign({
2319
- driver,
2320
- contractIR,
2321
- contractPath: contractPathAbsolute,
2322
- configPath
2323
- }),
2324
- {
2325
- message: "Signing database...",
2326
- flags
2327
- }
2328
- );
2329
- } catch (error) {
2330
- throw errorRuntime4(error instanceof Error ? error.message : String(error), {
2331
- why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`
2332
- });
2333
- }
2334
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2335
- console.log("");
2336
- }
2337
- return { schemaVerifyResult: void 0, signResult };
2338
- } finally {
2339
- await driver.close();
2340
- }
2341
- });
2342
- const exitCode = handleResult(result, flags, (value) => {
2343
- const { schemaVerifyResult, signResult } = value;
2344
- if (schemaVerifyResult && !schemaVerifyResult.ok) {
2345
- if (flags.json === "object") {
2346
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
2347
- } else {
2348
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
2349
- if (output) {
2350
- console.log(output);
2351
- }
2352
- }
2353
- return;
2354
- }
2355
- if (signResult) {
2356
- if (flags.json === "object") {
2357
- console.log(formatSignJson(signResult));
2358
- } else {
2359
- const output = formatSignOutput(signResult, flags);
2360
- if (output) {
2361
- console.log(output);
2362
- }
2363
- }
2364
- }
2365
- });
2366
- if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {
2367
- process.exit(1);
2368
- } else {
2369
- process.exit(exitCode);
2370
- }
2371
- });
2372
- return command;
2373
- }
2374
-
2375
- // src/commands/db-verify.ts
2376
- import { readFile as readFile5 } from "fs/promises";
2377
- import { relative as relative7, resolve as resolve7 } from "path";
2378
- import {
2379
- errorDatabaseConnectionRequired as errorDatabaseConnectionRequired5,
2380
- errorDriverRequired as errorDriverRequired5,
2381
- errorFileNotFound as errorFileNotFound4,
2382
- errorHashMismatch as errorHashMismatch2,
2383
- errorMarkerMissing as errorMarkerMissing2,
2384
- errorRuntime as errorRuntime5,
2385
- errorTargetMismatch as errorTargetMismatch2,
2386
- errorUnexpected as errorUnexpected6
2387
- } from "@prisma-next/core-control-plane/errors";
2388
- import { createControlPlaneStack as createControlPlaneStack6 } from "@prisma-next/core-control-plane/types";
2389
- import { Command as Command6 } from "commander";
2390
- function createDbVerifyCommand() {
2391
- const command = new Command6("verify");
2392
- setCommandDescriptions(
2393
- command,
2394
- "Check whether the database has been signed with your contract",
2395
- "Verifies that your database schema matches the emitted contract. Checks table structures,\ncolumn types, constraints, and codec coverage. Reports any mismatches or missing codecs."
2396
- );
2397
- command.configureHelp({
2398
- formatHelp: (cmd) => {
2399
- const flags = parseGlobalFlags({});
2400
- return formatCommandHelp({ command: cmd, flags });
2401
- }
2402
- }).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) => {
2403
- const flags = parseGlobalFlags(options);
2404
- const result = await performAction(async () => {
2405
- const config = await loadConfig(options.config);
2406
- const configPath = options.config ? relative7(process.cwd(), resolve7(options.config)) : "prisma-next.config.ts";
2407
- const contractPathAbsolute = config.contract?.output ? resolve7(config.contract.output) : resolve7("src/prisma/contract.json");
2408
- const contractPath = relative7(process.cwd(), contractPathAbsolute);
2409
- if (flags.json !== "object" && !flags.quiet) {
2410
- const details = [
2411
- { label: "config", value: configPath },
2412
- { label: "contract", value: contractPath }
2413
- ];
2414
- if (options.db) {
2415
- details.push({ label: "database", value: options.db });
2416
- }
2417
- const header = formatStyledHeader({
2418
- command: "db verify",
2419
- description: "Check whether the database has been signed with your contract",
2420
- url: "https://pris.ly/db-verify",
2421
- details,
2422
- flags
2423
- });
2424
- console.log(header);
2425
- }
2426
- let contractJsonContent;
2427
- try {
2428
- contractJsonContent = await readFile5(contractPathAbsolute, "utf-8");
2429
- } catch (error) {
2430
- if (error instanceof Error && error.code === "ENOENT") {
2431
- throw errorFileNotFound4(contractPathAbsolute, {
2432
- why: `Contract file not found at ${contractPathAbsolute}`
2433
- });
2434
- }
2435
- throw errorUnexpected6(error instanceof Error ? error.message : String(error), {
2436
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
2437
- });
2438
- }
2439
- const contractJson = JSON.parse(contractJsonContent);
2440
- const dbConnection = options.db ?? config.db?.connection;
2441
- if (!dbConnection) {
2442
- throw errorDatabaseConnectionRequired5();
2443
- }
2444
- if (!config.driver) {
2445
- throw errorDriverRequired5();
2446
- }
2447
- const driverDescriptor = config.driver;
2448
- const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {
2449
- message: "Connecting to database...",
2450
- flags
2451
- });
2452
- try {
2453
- const stack = createControlPlaneStack6({
2454
- target: config.target,
2455
- adapter: config.adapter,
2456
- driver: driverDescriptor,
2457
- extensionPacks: config.extensionPacks
2458
- });
2459
- const familyInstance = config.family.create(stack);
2460
- const contractIR = familyInstance.validateContractIR(contractJson);
2461
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
2462
- let verifyResult;
2463
- try {
2464
- verifyResult = await withSpinner(
2465
- () => familyInstance.verify({
2466
- driver,
2467
- contractIR,
2468
- expectedTargetId: config.target.targetId,
2469
- contractPath: contractPathAbsolute,
2470
- configPath
2471
- }),
2472
- {
2473
- message: "Verifying database schema...",
2474
- flags
2475
- }
2476
- );
2477
- } catch (error) {
2478
- throw errorUnexpected6(error instanceof Error ? error.message : String(error), {
2479
- why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`
2480
- });
2481
- }
2482
- if (!verifyResult.ok && verifyResult.code) {
2483
- if (verifyResult.code === "PN-RTM-3001") {
2484
- throw errorMarkerMissing2();
2485
- }
2486
- if (verifyResult.code === "PN-RTM-3002") {
2487
- throw errorHashMismatch2({
2488
- expected: verifyResult.contract.coreHash,
2489
- ...verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}
2490
- });
2491
- }
2492
- if (verifyResult.code === "PN-RTM-3003") {
2493
- throw errorTargetMismatch2(
2494
- verifyResult.target.expected,
2495
- verifyResult.target.actual ?? "unknown"
2496
- );
2497
- }
2498
- throw errorRuntime5(verifyResult.summary);
2499
- }
2500
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2501
- console.log("");
2502
- }
2503
- return verifyResult;
2504
- } finally {
2505
- await driver.close();
2506
- }
2507
- });
2508
- const exitCode = handleResult(result, flags, (verifyResult) => {
2509
- if (flags.json === "object") {
2510
- console.log(formatVerifyJson(verifyResult));
2511
- } else {
2512
- const output = formatVerifyOutput(verifyResult, flags);
2513
- if (output) {
2514
- console.log(output);
2515
- }
2516
- }
2517
- });
2518
- process.exit(exitCode);
2519
- });
2520
- return command;
2521
- }
2522
-
2523
- // src/cli.ts
2524
- var program = new Command7();
2525
- program.name("prisma-next").description("Prisma Next CLI").version("0.0.1");
2526
- var versionOption = program.options.find((opt) => opt.flags.includes("--version"));
2527
- if (versionOption) {
2528
- versionOption.description = "Output the version number";
2529
- }
2530
- program.configureOutput({
2531
- writeErr: () => {
2532
- },
2533
- writeOut: () => {
2534
- }
2535
- });
2536
- var rootHelpFormatter = (cmd) => {
2537
- const flags = parseGlobalFlags({});
2538
- return formatRootHelp({ program: cmd, flags });
2539
- };
2540
- program.configureHelp({
2541
- formatHelp: rootHelpFormatter,
2542
- subcommandDescription: () => ""
2543
- });
2544
- program.exitOverride((err) => {
2545
- if (err) {
2546
- const errorCode = err.code;
2547
- const errorMessage = String(err.message ?? "");
2548
- const errorName = err.name ?? "";
2549
- const isUnknownCommandError = errorCode === "commander.unknownCommand" || errorCode === "commander.unknownArgument" || errorName === "CommanderError" && (errorMessage.includes("unknown command") || errorMessage.includes("unknown argument"));
2550
- if (isUnknownCommandError) {
2551
- const flags = parseGlobalFlags({});
2552
- const match = errorMessage.match(/unknown command ['"]([^'"]+)['"]/);
2553
- const commandName = match ? match[1] : process.argv[3] || process.argv[2] || "unknown";
2554
- const firstArg = process.argv[2];
2555
- const parentCommand = firstArg ? program.commands.find((cmd) => cmd.name() === firstArg) : void 0;
2556
- if (parentCommand && commandName !== firstArg) {
2557
- console.error(`Unknown command: ${commandName}`);
2558
- console.error("");
2559
- const helpText = formatCommandHelp({ command: parentCommand, flags });
2560
- console.log(helpText);
2561
- } else {
2562
- console.error(`Unknown command: ${commandName}`);
2563
- console.error("");
2564
- const helpText = formatRootHelp({ program, flags });
2565
- console.log(helpText);
2566
- }
2567
- process.exit(1);
2568
- return;
2569
- }
2570
- const isHelpError = errorCode === "commander.help" || errorCode === "commander.helpDisplayed" || errorCode === "outputHelp" || errorMessage === "(outputHelp)" || errorMessage.includes("outputHelp") || errorName === "CommanderError" && errorMessage.includes("outputHelp");
2571
- if (isHelpError) {
2572
- process.exit(0);
2573
- return;
2574
- }
2575
- const isMissingArgumentError = errorCode === "commander.missingArgument" || errorCode === "commander.missingMandatoryOptionValue" || errorName === "CommanderError" && (errorMessage.includes("missing") || errorMessage.includes("required"));
2576
- if (isMissingArgumentError) {
2577
- process.exit(0);
2578
- return;
2579
- }
2580
- console.error(`Unhandled error: ${err.message}`);
2581
- if (err.stack) {
2582
- console.error(err.stack);
2583
- }
2584
- process.exit(1);
2585
- }
2586
- process.exit(0);
2587
- });
2588
- var contractCommand = new Command7("contract");
2589
- setCommandDescriptions(
2590
- contractCommand,
2591
- "Contract management commands",
2592
- "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."
2593
- );
2594
- contractCommand.configureHelp({
2595
- formatHelp: (cmd) => {
2596
- const flags = parseGlobalFlags({});
2597
- return formatCommandHelp({ command: cmd, flags });
2598
- },
2599
- subcommandDescription: () => ""
2600
- });
2601
- var contractEmitCommand = createContractEmitCommand();
2602
- contractCommand.addCommand(contractEmitCommand);
2603
- program.addCommand(contractCommand);
2604
- var dbCommand = new Command7("db");
2605
- setCommandDescriptions(
2606
- dbCommand,
2607
- "Database management commands",
2608
- "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."
2609
- );
2610
- dbCommand.configureHelp({
2611
- formatHelp: (cmd) => {
2612
- const flags = parseGlobalFlags({});
2613
- return formatCommandHelp({ command: cmd, flags });
2614
- },
2615
- subcommandDescription: () => ""
2616
- });
2617
- var dbVerifyCommand = createDbVerifyCommand();
2618
- dbCommand.addCommand(dbVerifyCommand);
2619
- var dbInitCommand = createDbInitCommand();
2620
- dbCommand.addCommand(dbInitCommand);
2621
- var dbIntrospectCommand = createDbIntrospectCommand();
2622
- dbCommand.addCommand(dbIntrospectCommand);
2623
- var dbSchemaVerifyCommand = createDbSchemaVerifyCommand();
2624
- dbCommand.addCommand(dbSchemaVerifyCommand);
2625
- var dbSignCommand = createDbSignCommand();
2626
- dbCommand.addCommand(dbSignCommand);
2627
- program.addCommand(dbCommand);
2628
- var helpCommand = new Command7("help").description("Show usage instructions").configureHelp({
2629
- formatHelp: (cmd) => {
2630
- const flags = parseGlobalFlags({});
2631
- return formatCommandHelp({ command: cmd, flags });
2632
- }
2633
- }).action(() => {
2634
- const flags = parseGlobalFlags({});
2635
- const helpText = formatRootHelp({ program, flags });
2636
- console.log(helpText);
2637
- process.exit(0);
2638
- });
2639
- program.addCommand(helpCommand);
2640
- program.action(() => {
2641
- const flags = parseGlobalFlags({});
2642
- const helpText = formatRootHelp({ program, flags });
2643
- console.log(helpText);
2644
- process.exit(0);
2645
- });
2646
- var args = process.argv.slice(2);
2647
- if (args.length > 0) {
2648
- const commandName = args[0];
2649
- if (commandName === "--version" || commandName === "-V") {
2650
- console.log(program.version());
2651
- process.exit(0);
2652
- }
2653
- const isGlobalOption = commandName === "--help" || commandName === "-h";
2654
- if (!isGlobalOption) {
2655
- const command = program.commands.find((cmd) => cmd.name() === commandName);
2656
- if (!command) {
2657
- const flags = parseGlobalFlags({});
2658
- console.error(`Unknown command: ${commandName}`);
2659
- console.error("");
2660
- const helpText = formatRootHelp({ program, flags });
2661
- console.log(helpText);
2662
- process.exit(1);
2663
- } else if (command.commands.length > 0 && args.length === 1) {
2664
- const flags = parseGlobalFlags({});
2665
- const helpText = formatCommandHelp({ command, flags });
2666
- console.log(helpText);
2667
- process.exit(0);
2668
- }
2669
- }
2670
- }
2671
- program.parse();
2672
- //# sourceMappingURL=cli.js.map
2
+ import './cli.mjs';