@prisma-next/cli 0.3.0-dev.12 → 0.3.0-dev.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +470 -134
  3. package/dist/cli-errors-ByGuoqNj.mjs +3 -0
  4. package/dist/cli-errors-D6HxRn3A.d.mts +2 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.js +1 -2350
  7. package/dist/cli.mjs +242 -0
  8. package/dist/cli.mjs.map +1 -0
  9. package/dist/client-612RJJD_.mjs +1069 -0
  10. package/dist/client-612RJJD_.mjs.map +1 -0
  11. package/dist/commands/contract-emit.d.mts +7 -0
  12. package/dist/commands/contract-emit.d.mts.map +1 -0
  13. package/dist/commands/contract-emit.mjs +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 +311 -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 +241 -0
  40. package/dist/commands/migration-apply.mjs.map +1 -0
  41. package/dist/commands/migration-plan.d.mts +47 -0
  42. package/dist/commands/migration-plan.d.mts.map +1 -0
  43. package/dist/commands/migration-plan.mjs +288 -0
  44. package/dist/commands/migration-plan.mjs.map +1 -0
  45. package/dist/commands/migration-ref.d.mts +43 -0
  46. package/dist/commands/migration-ref.d.mts.map +1 -0
  47. package/dist/commands/migration-ref.mjs +194 -0
  48. package/dist/commands/migration-ref.mjs.map +1 -0
  49. package/dist/commands/migration-show.d.mts +28 -0
  50. package/dist/commands/migration-show.d.mts.map +1 -0
  51. package/dist/commands/migration-show.mjs +139 -0
  52. package/dist/commands/migration-show.mjs.map +1 -0
  53. package/dist/commands/migration-status.d.mts +85 -0
  54. package/dist/commands/migration-status.d.mts.map +1 -0
  55. package/dist/commands/migration-status.mjs +8 -0
  56. package/dist/commands/migration-verify.d.mts +16 -0
  57. package/dist/commands/migration-verify.d.mts.map +1 -0
  58. package/dist/commands/migration-verify.mjs +87 -0
  59. package/dist/commands/migration-verify.mjs.map +1 -0
  60. package/dist/config-loader-d_KF19Tw.mjs +43 -0
  61. package/dist/config-loader-d_KF19Tw.mjs.map +1 -0
  62. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  63. package/dist/config-loader.d.mts.map +1 -0
  64. package/dist/config-loader.mjs +3 -0
  65. package/dist/contract-emit-CVv7dbQ9.mjs +187 -0
  66. package/dist/contract-emit-CVv7dbQ9.mjs.map +1 -0
  67. package/dist/contract-infer-Bvw8u8Eu.mjs +83 -0
  68. package/dist/contract-infer-Bvw8u8Eu.mjs.map +1 -0
  69. package/dist/exports/config-types.d.mts +2 -0
  70. package/dist/exports/config-types.mjs +3 -0
  71. package/dist/exports/control-api.d.mts +626 -0
  72. package/dist/exports/control-api.d.mts.map +1 -0
  73. package/dist/exports/control-api.mjs +107 -0
  74. package/dist/exports/control-api.mjs.map +1 -0
  75. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  76. package/dist/exports/index.d.mts.map +1 -0
  77. package/dist/exports/index.mjs +134 -0
  78. package/dist/exports/index.mjs.map +1 -0
  79. package/dist/extract-sql-ddl-Jf5blEO0.mjs +26 -0
  80. package/dist/extract-sql-ddl-Jf5blEO0.mjs.map +1 -0
  81. package/dist/framework-components-M2j-qPfr.mjs +59 -0
  82. package/dist/framework-components-M2j-qPfr.mjs.map +1 -0
  83. package/dist/inspect-live-schema-BQe5i4YE.mjs +90 -0
  84. package/dist/inspect-live-schema-BQe5i4YE.mjs.map +1 -0
  85. package/dist/migration-command-scaffold-SLrjcKXS.mjs +104 -0
  86. package/dist/migration-command-scaffold-SLrjcKXS.mjs.map +1 -0
  87. package/dist/migration-status-B7OVZ-Ka.mjs +1576 -0
  88. package/dist/migration-status-B7OVZ-Ka.mjs.map +1 -0
  89. package/dist/migrations-Db_ea9eE.mjs +173 -0
  90. package/dist/migrations-Db_ea9eE.mjs.map +1 -0
  91. package/dist/progress-adapter-DRNe2idZ.mjs +43 -0
  92. package/dist/progress-adapter-DRNe2idZ.mjs.map +1 -0
  93. package/dist/terminal-ui-DAcMBRKf.mjs +980 -0
  94. package/dist/terminal-ui-DAcMBRKf.mjs.map +1 -0
  95. package/dist/verify-DXKxBFvU.mjs +385 -0
  96. package/dist/verify-DXKxBFvU.mjs.map +1 -0
  97. package/package.json +85 -40
  98. package/src/cli.ts +109 -58
  99. package/src/commands/contract-emit.ts +236 -143
  100. package/src/commands/contract-infer-paths.ts +32 -0
  101. package/src/commands/contract-infer.ts +131 -0
  102. package/src/commands/db-init.ts +211 -425
  103. package/src/commands/db-schema.ts +77 -0
  104. package/src/commands/db-sign.ts +207 -228
  105. package/src/commands/db-update.ts +236 -0
  106. package/src/commands/db-verify.ts +484 -186
  107. package/src/commands/inspect-live-schema.ts +171 -0
  108. package/src/commands/migration-apply.ts +416 -0
  109. package/src/commands/migration-plan.ts +451 -0
  110. package/src/commands/migration-ref.ts +305 -0
  111. package/src/commands/migration-show.ts +246 -0
  112. package/src/commands/migration-status.ts +838 -0
  113. package/src/commands/migration-verify.ts +134 -0
  114. package/src/config-loader.ts +13 -3
  115. package/src/control-api/client.ts +614 -0
  116. package/src/control-api/contract-enrichment.ts +135 -0
  117. package/src/control-api/errors.ts +9 -0
  118. package/src/control-api/operations/contract-emit.ts +173 -0
  119. package/src/control-api/operations/db-init.ts +286 -0
  120. package/src/control-api/operations/db-update.ts +221 -0
  121. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  122. package/src/control-api/operations/migration-apply.ts +194 -0
  123. package/src/control-api/operations/migration-helpers.ts +49 -0
  124. package/src/control-api/types.ts +683 -0
  125. package/src/exports/config-types.ts +4 -3
  126. package/src/exports/control-api.ts +56 -0
  127. package/src/load-ts-contract.ts +16 -11
  128. package/src/utils/cli-errors.ts +5 -2
  129. package/src/utils/command-helpers.ts +293 -3
  130. package/src/utils/formatters/emit.ts +67 -0
  131. package/src/utils/formatters/errors.ts +82 -0
  132. package/src/utils/formatters/graph-migration-mapper.ts +220 -0
  133. package/src/utils/formatters/graph-render.ts +1317 -0
  134. package/src/utils/formatters/graph-types.ts +114 -0
  135. package/src/utils/formatters/help.ts +380 -0
  136. package/src/utils/formatters/helpers.ts +28 -0
  137. package/src/utils/formatters/migrations.ts +346 -0
  138. package/src/utils/formatters/styled.ts +212 -0
  139. package/src/utils/formatters/verify.ts +620 -0
  140. package/src/utils/global-flags.ts +41 -23
  141. package/src/utils/migration-command-scaffold.ts +187 -0
  142. package/src/utils/migration-types.ts +12 -0
  143. package/src/utils/progress-adapter.ts +75 -0
  144. package/src/utils/result-handler.ts +12 -13
  145. package/src/utils/shutdown.ts +92 -0
  146. package/src/utils/suggest-command.ts +31 -0
  147. package/src/utils/terminal-ui.ts +276 -0
  148. package/dist/chunk-BZMBKEEQ.js +0 -997
  149. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  150. package/dist/chunk-CVNWLFXO.js +0 -91
  151. package/dist/chunk-CVNWLFXO.js.map +0 -1
  152. package/dist/chunk-HWYQOCAJ.js +0 -47
  153. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  154. package/dist/chunk-QUPBU4KV.js +0 -131
  155. package/dist/chunk-QUPBU4KV.js.map +0 -1
  156. package/dist/cli.d.ts +0 -2
  157. package/dist/cli.d.ts.map +0 -1
  158. package/dist/cli.js.map +0 -1
  159. package/dist/commands/contract-emit.d.ts +0 -3
  160. package/dist/commands/contract-emit.d.ts.map +0 -1
  161. package/dist/commands/contract-emit.js +0 -9
  162. package/dist/commands/contract-emit.js.map +0 -1
  163. package/dist/commands/db-init.d.ts +0 -3
  164. package/dist/commands/db-init.d.ts.map +0 -1
  165. package/dist/commands/db-init.js +0 -337
  166. package/dist/commands/db-init.js.map +0 -1
  167. package/dist/commands/db-introspect.d.ts +0 -3
  168. package/dist/commands/db-introspect.d.ts.map +0 -1
  169. package/dist/commands/db-introspect.js +0 -186
  170. package/dist/commands/db-introspect.js.map +0 -1
  171. package/dist/commands/db-schema-verify.d.ts +0 -3
  172. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  173. package/dist/commands/db-schema-verify.js +0 -160
  174. package/dist/commands/db-schema-verify.js.map +0 -1
  175. package/dist/commands/db-sign.d.ts +0 -3
  176. package/dist/commands/db-sign.d.ts.map +0 -1
  177. package/dist/commands/db-sign.js +0 -195
  178. package/dist/commands/db-sign.js.map +0 -1
  179. package/dist/commands/db-verify.d.ts +0 -3
  180. package/dist/commands/db-verify.d.ts.map +0 -1
  181. package/dist/commands/db-verify.js +0 -169
  182. package/dist/commands/db-verify.js.map +0 -1
  183. package/dist/config-loader.d.ts.map +0 -1
  184. package/dist/config-loader.js +0 -7
  185. package/dist/config-loader.js.map +0 -1
  186. package/dist/exports/config-types.d.ts +0 -3
  187. package/dist/exports/config-types.d.ts.map +0 -1
  188. package/dist/exports/config-types.js +0 -6
  189. package/dist/exports/config-types.js.map +0 -1
  190. package/dist/exports/index.d.ts +0 -4
  191. package/dist/exports/index.d.ts.map +0 -1
  192. package/dist/exports/index.js +0 -175
  193. package/dist/exports/index.js.map +0 -1
  194. package/dist/load-ts-contract.d.ts.map +0 -1
  195. package/dist/utils/action.d.ts +0 -16
  196. package/dist/utils/action.d.ts.map +0 -1
  197. package/dist/utils/cli-errors.d.ts +0 -7
  198. package/dist/utils/cli-errors.d.ts.map +0 -1
  199. package/dist/utils/command-helpers.d.ts +0 -12
  200. package/dist/utils/command-helpers.d.ts.map +0 -1
  201. package/dist/utils/framework-components.d.ts +0 -70
  202. package/dist/utils/framework-components.d.ts.map +0 -1
  203. package/dist/utils/global-flags.d.ts +0 -25
  204. package/dist/utils/global-flags.d.ts.map +0 -1
  205. package/dist/utils/output.d.ts +0 -142
  206. package/dist/utils/output.d.ts.map +0 -1
  207. package/dist/utils/result-handler.d.ts +0 -15
  208. package/dist/utils/result-handler.d.ts.map +0 -1
  209. package/dist/utils/spinner.d.ts +0 -29
  210. package/dist/utils/spinner.d.ts.map +0 -1
  211. package/src/commands/db-introspect.ts +0 -256
  212. package/src/commands/db-schema-verify.ts +0 -232
  213. package/src/utils/action.ts +0 -43
  214. package/src/utils/output.ts +0 -1471
  215. package/src/utils/spinner.ts +0 -67
@@ -0,0 +1,77 @@
1
+ import type { IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';
2
+ import { Command } from 'commander';
3
+ import {
4
+ addGlobalOptions,
5
+ setCommandDescriptions,
6
+ setCommandExamples,
7
+ } from '../utils/command-helpers';
8
+ import { formatIntrospectJson, formatIntrospectOutput } from '../utils/formatters/verify';
9
+ import { parseGlobalFlags } from '../utils/global-flags';
10
+ import { handleResult } from '../utils/result-handler';
11
+ import { TerminalUI } from '../utils/terminal-ui';
12
+ import {
13
+ type InspectLiveSchemaOptions,
14
+ type InspectLiveSchemaResult,
15
+ inspectLiveSchema,
16
+ } from './inspect-live-schema';
17
+
18
+ function toIntrospectSchemaResult(
19
+ result: InspectLiveSchemaResult,
20
+ ): IntrospectSchemaResult<unknown> {
21
+ return {
22
+ ok: true,
23
+ summary: 'Schema read successfully',
24
+ target: result.target,
25
+ schema: result.schema,
26
+ meta: result.meta,
27
+ timings: result.timings,
28
+ };
29
+ }
30
+
31
+ export function createDbSchemaCommand(): Command {
32
+ const command = new Command('schema');
33
+ setCommandDescriptions(
34
+ command,
35
+ 'Inspect the live database schema',
36
+ 'Reads the live database schema and prints it as a tree by default or as JSON with\n' +
37
+ '--json. This command is always read-only and never writes files. To save machine-\n' +
38
+ 'readable output, use shell redirection, for example `prisma-next db schema --json > schema.json`.',
39
+ );
40
+ setCommandExamples(command, [
41
+ 'prisma-next db schema --db $DATABASE_URL',
42
+ 'prisma-next db schema --db $DATABASE_URL --json',
43
+ 'prisma-next db schema --db $DATABASE_URL --json > schema.json',
44
+ ]);
45
+ addGlobalOptions(command)
46
+ .option('--db <url>', 'Database connection string')
47
+ .option('--config <path>', 'Path to prisma-next.config.ts')
48
+ .action(async (options: InspectLiveSchemaOptions) => {
49
+ const flags = parseGlobalFlags(options);
50
+ const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
51
+ const startTime = Date.now();
52
+
53
+ const result = await inspectLiveSchema(options, flags, ui, startTime, {
54
+ commandName: 'db schema',
55
+ description: 'Inspect the live database schema',
56
+ url: 'https://pris.ly/db-schema',
57
+ });
58
+
59
+ const exitCode = handleResult(result, flags, ui, (value) => {
60
+ const introspectResult = toIntrospectSchemaResult(value);
61
+
62
+ if (flags.json) {
63
+ ui.output(formatIntrospectJson(introspectResult));
64
+ return;
65
+ }
66
+
67
+ const output = formatIntrospectOutput(introspectResult, value.schemaView, flags);
68
+ if (output) {
69
+ ui.log(output);
70
+ }
71
+ });
72
+
73
+ process.exit(exitCode);
74
+ });
75
+
76
+ return command;
77
+ }
@@ -1,50 +1,196 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { relative, resolve } from 'node:path';
3
- import {
4
- errorDatabaseUrlRequired,
5
- errorDriverRequired,
6
- errorFileNotFound,
7
- errorRuntime,
8
- errorUnexpected,
9
- } from '@prisma-next/core-control-plane/errors';
10
2
  import type {
11
3
  SignDatabaseResult,
12
4
  VerifyDatabaseSchemaResult,
13
5
  } from '@prisma-next/core-control-plane/types';
14
- import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
6
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
15
7
  import { Command } from 'commander';
8
+ import { relative, resolve } from 'pathe';
16
9
  import { loadConfig } from '../config-loader';
17
- import { performAction } from '../utils/action';
18
- import { setCommandDescriptions } from '../utils/command-helpers';
10
+ import { createControlClient } from '../control-api/client';
11
+ import { ContractValidationError } from '../control-api/errors';
12
+ import {
13
+ CliStructuredError,
14
+ errorContractValidationFailed,
15
+ errorDatabaseConnectionRequired,
16
+ errorDriverRequired,
17
+ errorFileNotFound,
18
+ errorUnexpected,
19
+ } from '../utils/cli-errors';
19
20
  import {
20
- assertContractRequirementsSatisfied,
21
- assertFrameworkComponentsCompatible,
22
- } from '../utils/framework-components';
23
- import { parseGlobalFlags } from '../utils/global-flags';
21
+ addGlobalOptions,
22
+ maskConnectionUrl,
23
+ resolveContractPath,
24
+ setCommandDescriptions,
25
+ setCommandExamples,
26
+ } from '../utils/command-helpers';
27
+ import { formatStyledHeader } from '../utils/formatters/styled';
24
28
  import {
25
- formatCommandHelp,
26
29
  formatSchemaVerifyJson,
27
30
  formatSchemaVerifyOutput,
28
31
  formatSignJson,
29
32
  formatSignOutput,
30
- formatStyledHeader,
31
- } from '../utils/output';
33
+ } from '../utils/formatters/verify';
34
+ import type { CommonCommandOptions } from '../utils/global-flags';
35
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
36
+ import { createProgressAdapter } from '../utils/progress-adapter';
32
37
  import { handleResult } from '../utils/result-handler';
33
- import { withSpinner } from '../utils/spinner';
38
+ import { TerminalUI } from '../utils/terminal-ui';
34
39
 
35
- interface DbSignOptions {
40
+ interface DbSignOptions extends CommonCommandOptions {
36
41
  readonly db?: string;
37
42
  readonly config?: string;
38
- readonly json?: string | boolean;
39
- readonly quiet?: boolean;
40
- readonly q?: boolean;
41
- readonly verbose?: boolean;
42
- readonly v?: boolean;
43
- readonly vv?: boolean;
44
- readonly trace?: boolean;
45
- readonly timestamps?: boolean;
46
- readonly color?: boolean;
47
- readonly 'no-color'?: boolean;
43
+ }
44
+
45
+ /**
46
+ * Failure type for db sign command.
47
+ * Either an infrastructure error (CliStructuredError) or a logical failure (schema verification failed).
48
+ */
49
+ type DbSignFailure = CliStructuredError | VerifyDatabaseSchemaResult;
50
+
51
+ /**
52
+ * Executes the db sign command and returns a structured Result.
53
+ * Success: SignDatabaseResult (sign happened)
54
+ * Failure: CliStructuredError (infra error) or VerifyDatabaseSchemaResult (schema mismatch)
55
+ */
56
+ async function executeDbSignCommand(
57
+ options: DbSignOptions,
58
+ flags: GlobalFlags,
59
+ ui: TerminalUI,
60
+ ): Promise<Result<SignDatabaseResult, DbSignFailure>> {
61
+ // Load config
62
+ const config = await loadConfig(options.config);
63
+ const configPath = options.config
64
+ ? relative(process.cwd(), resolve(options.config))
65
+ : 'prisma-next.config.ts';
66
+ const contractPathAbsolute = resolveContractPath(config);
67
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
68
+
69
+ // Output header
70
+ if (!flags.json && !flags.quiet) {
71
+ const details: Array<{ label: string; value: string }> = [
72
+ { label: 'config', value: configPath },
73
+ { label: 'contract', value: contractPath },
74
+ ];
75
+ if (options.db) {
76
+ details.push({ label: 'database', value: maskConnectionUrl(options.db) });
77
+ }
78
+ const header = formatStyledHeader({
79
+ command: 'db sign',
80
+ description: 'Sign the database with your contract so you can safely run queries',
81
+ url: 'https://pris.ly/db-sign',
82
+ details,
83
+ flags,
84
+ });
85
+ ui.stderr(header);
86
+ }
87
+
88
+ // Load contract file
89
+ let contractJsonContent: string;
90
+ try {
91
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
92
+ } catch (error) {
93
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
94
+ return notOk(
95
+ errorFileNotFound(contractPathAbsolute, {
96
+ why: `Contract file not found at ${contractPathAbsolute}`,
97
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
98
+ }),
99
+ );
100
+ }
101
+ return notOk(
102
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
103
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
104
+ }),
105
+ );
106
+ }
107
+
108
+ let contractJson: Record<string, unknown>;
109
+ try {
110
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
111
+ } catch (error) {
112
+ return notOk(
113
+ errorContractValidationFailed(
114
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
115
+ { where: { path: contractPathAbsolute } },
116
+ ),
117
+ );
118
+ }
119
+
120
+ // Resolve database connection (--db flag or config.db.connection)
121
+ const dbConnection = options.db ?? config.db?.connection;
122
+ if (!dbConnection) {
123
+ return notOk(
124
+ errorDatabaseConnectionRequired({
125
+ why: `Database connection is required for db sign (set db.connection in ${configPath}, or pass --db <url>)`,
126
+ commandName: 'db sign',
127
+ }),
128
+ );
129
+ }
130
+
131
+ // Check for driver
132
+ if (!config.driver) {
133
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db sign' }));
134
+ }
135
+
136
+ // Create control client
137
+ const client = createControlClient({
138
+ family: config.family,
139
+ target: config.target,
140
+ adapter: config.adapter,
141
+ driver: config.driver,
142
+ extensionPacks: config.extensionPacks ?? [],
143
+ });
144
+
145
+ // Create progress adapter
146
+ const onProgress = createProgressAdapter({ ui, flags });
147
+
148
+ try {
149
+ // Step 1: Schema verification - connect here
150
+ const schemaVerifyResult = await client.schemaVerify({
151
+ contractIR: contractJson,
152
+ strict: false,
153
+ connection: dbConnection,
154
+ onProgress,
155
+ });
156
+
157
+ // If schema verification failed, return as failure
158
+ if (!schemaVerifyResult.ok) {
159
+ return notOk(schemaVerifyResult);
160
+ }
161
+
162
+ // Step 2: Sign (already connected from schemaVerify)
163
+ const signResult = await client.sign({
164
+ contractIR: contractJson,
165
+ contractPath,
166
+ configPath,
167
+ onProgress,
168
+ });
169
+
170
+ return ok(signResult);
171
+ } catch (error) {
172
+ // Driver already throws CliStructuredError for connection failures
173
+ if (error instanceof CliStructuredError) {
174
+ return notOk(error);
175
+ }
176
+
177
+ if (error instanceof ContractValidationError) {
178
+ return notOk(
179
+ errorContractValidationFailed(`Contract validation failed: ${error.message}`, {
180
+ where: { path: contractPathAbsolute },
181
+ }),
182
+ );
183
+ }
184
+
185
+ // Wrap unexpected errors
186
+ return notOk(
187
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
188
+ why: `Unexpected error during db sign: ${error instanceof Error ? error.message : String(error)}`,
189
+ }),
190
+ );
191
+ } finally {
192
+ await client.close();
193
+ }
48
194
  }
49
195
 
50
196
  export function createDbSignCommand(): Command {
@@ -53,220 +199,53 @@ export function createDbSignCommand(): Command {
53
199
  command,
54
200
  'Sign the database with your contract so you can safely run queries',
55
201
  'Verifies that your database schema satisfies the emitted contract, and if so, writes or\n' +
56
- 'updates the contract marker in the database. This command is idempotent and safe to run\n' +
57
- 'in CI/deployment pipelines. The marker records that this database instance is aligned\n' +
202
+ 'updates the database signature. This command is idempotent and safe to run\n' +
203
+ 'in CI/deployment pipelines. The signature records that this database instance is aligned\n' +
58
204
  'with a specific contract version.',
59
205
  );
60
- command
61
- .configureHelp({
62
- formatHelp: (cmd) => {
63
- const flags = parseGlobalFlags({});
64
- return formatCommandHelp({ command: cmd, flags });
65
- },
66
- })
206
+ setCommandExamples(command, ['prisma-next db sign --db $DATABASE_URL']);
207
+ addGlobalOptions(command)
67
208
  .option('--db <url>', 'Database connection string')
68
209
  .option('--config <path>', 'Path to prisma-next.config.ts')
69
- .option('--json [format]', 'Output as JSON (object or ndjson)', false)
70
- .option('-q, --quiet', 'Quiet mode: errors only')
71
- .option('-v, --verbose', 'Verbose output: debug info, timings')
72
- .option('-vv, --trace', 'Trace output: deep internals, stack traces')
73
- .option('--timestamps', 'Add timestamps to output')
74
- .option('--color', 'Force color output')
75
- .option('--no-color', 'Disable color output')
76
210
  .action(async (options: DbSignOptions) => {
77
211
  const flags = parseGlobalFlags(options);
78
212
 
79
- const result = await performAction(async () => {
80
- // Load config (file I/O)
81
- const config = await loadConfig(options.config);
82
- // Normalize config path for display (match contract path format - no ./ prefix)
83
- const configPath = options.config
84
- ? relative(process.cwd(), resolve(options.config))
85
- : 'prisma-next.config.ts';
86
- const contractPathAbsolute = config.contract?.output
87
- ? resolve(config.contract.output)
88
- : resolve('src/prisma/contract.json');
89
- // Convert to relative path for display
90
- const contractPath = relative(process.cwd(), contractPathAbsolute);
91
-
92
- // Output header (only for human-readable output)
93
- if (flags.json !== 'object' && !flags.quiet) {
94
- const details: Array<{ label: string; value: string }> = [
95
- { label: 'config', value: configPath },
96
- { label: 'contract', value: contractPath },
97
- ];
98
- if (options.db) {
99
- details.push({ label: 'database', value: options.db });
100
- }
101
- const header = formatStyledHeader({
102
- command: 'db sign',
103
- description: 'Sign the database with your contract so you can safely run queries',
104
- url: 'https://pris.ly/db-sign',
105
- details,
106
- flags,
107
- });
108
- console.log(header);
109
- }
110
-
111
- // Load contract file (file I/O)
112
- let contractJsonContent: string;
113
- try {
114
- contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
115
- } catch (error) {
116
- if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
117
- throw errorFileNotFound(contractPathAbsolute, {
118
- why: `Contract file not found at ${contractPathAbsolute}`,
119
- });
120
- }
121
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
122
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
123
- });
124
- }
125
- const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
126
-
127
- // Resolve database URL
128
- const dbUrl = options.db ?? config.db?.url;
129
- if (!dbUrl) {
130
- throw errorDatabaseUrlRequired();
131
- }
132
-
133
- // Check for driver
134
- if (!config.driver) {
135
- throw errorDriverRequired();
136
- }
137
-
138
- // Store driver descriptor after null check
139
- const driverDescriptor = config.driver;
140
-
141
- // Create family instance (needed for contract validation - no DB connection required)
142
- const stack = createControlPlaneStack({
143
- target: config.target,
144
- adapter: config.adapter,
145
- driver: driverDescriptor,
146
- extensionPacks: config.extensionPacks,
147
- });
148
- const familyInstance = config.family.create(stack);
149
-
150
- // Validate contract using instance validator (fail-fast before DB connection)
151
- const contractIR = familyInstance.validateContractIR(contractJson);
152
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
153
-
154
- const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
155
- const frameworkComponents = assertFrameworkComponentsCompatible(
156
- config.family.familyId,
157
- config.target.targetId,
158
- rawComponents,
159
- );
213
+ const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
160
214
 
161
- // Create driver (expensive operation - done after validation)
162
- const driver = await driverDescriptor.create(dbUrl);
163
-
164
- try {
165
- // Schema verification precondition with spinner
166
- let schemaVerifyResult: VerifyDatabaseSchemaResult;
167
- try {
168
- schemaVerifyResult = await withSpinner(
169
- () =>
170
- familyInstance.schemaVerify({
171
- driver,
172
- contractIR,
173
- strict: false,
174
- contractPath: contractPathAbsolute,
175
- configPath,
176
- frameworkComponents,
177
- }),
178
- {
179
- message: 'Verifying database satisfies contract',
180
- flags,
181
- },
182
- );
183
- } catch (error) {
184
- // Wrap errors from schemaVerify() in structured error
185
- throw errorRuntime(error instanceof Error ? error.message : String(error), {
186
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,
187
- });
188
- }
189
-
190
- // If schema verification failed, return both results for handling outside performAction
191
- if (!schemaVerifyResult.ok) {
192
- return { schemaVerifyResult, signResult: undefined };
193
- }
194
-
195
- // Schema verification passed - proceed with signing
196
- let signResult: SignDatabaseResult;
197
- try {
198
- signResult = await withSpinner(
199
- () =>
200
- familyInstance.sign({
201
- driver,
202
- contractIR,
203
- contractPath: contractPathAbsolute,
204
- configPath,
205
- }),
206
- {
207
- message: 'Signing database...',
208
- flags,
209
- },
210
- );
211
- } catch (error) {
212
- // Wrap errors from sign() in structured error
213
- throw errorRuntime(error instanceof Error ? error.message : String(error), {
214
- why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`,
215
- });
216
- }
215
+ const result = await executeDbSignCommand(options, flags, ui);
217
216
 
218
- // Add blank line after all async operations if spinners were shown
219
- if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
220
- console.log('');
217
+ if (result.ok) {
218
+ // Success - format sign output
219
+ if (flags.json) {
220
+ ui.output(formatSignJson(result.value));
221
+ } else {
222
+ const output = formatSignOutput(result.value, flags);
223
+ if (output) {
224
+ ui.log(output);
221
225
  }
222
-
223
- return { schemaVerifyResult: undefined, signResult };
224
- } finally {
225
- // Ensure driver connection is closed
226
- await driver.close();
227
226
  }
228
- });
229
-
230
- // Handle result - formats output and returns exit code
231
- const exitCode = handleResult(result, flags, (value) => {
232
- const { schemaVerifyResult, signResult } = value;
227
+ process.exit(0);
228
+ }
233
229
 
234
- // If schema verification failed, format and print schema verification output
235
- if (schemaVerifyResult && !schemaVerifyResult.ok) {
236
- if (flags.json === 'object') {
237
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
238
- } else {
239
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
240
- if (output) {
241
- console.log(output);
242
- }
243
- }
244
- // Don't proceed to sign output formatting
245
- return;
246
- }
230
+ // Failure - determine type and handle appropriately
231
+ const failure = result.failure;
247
232
 
248
- // Schema verification passed - format sign output
249
- if (signResult) {
250
- if (flags.json === 'object') {
251
- console.log(formatSignJson(signResult));
252
- } else {
253
- const output = formatSignOutput(signResult, flags);
254
- if (output) {
255
- console.log(output);
256
- }
257
- }
258
- }
259
- });
233
+ if (failure instanceof CliStructuredError) {
234
+ // Infrastructure error - use standard handler
235
+ const exitCode = handleResult(result as Result<never, CliStructuredError>, flags, ui);
236
+ process.exit(exitCode);
237
+ }
260
238
 
261
- // For logical schema mismatches, check if schema verification passed
262
- // Infra errors already handled by handleResult (returns non-zero exit code)
263
- if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {
264
- // Schema verification failed - exit with code 1
265
- process.exit(1);
239
+ // Schema verification failed - format and print schema verification output
240
+ if (flags.json) {
241
+ ui.output(formatSchemaVerifyJson(failure));
266
242
  } else {
267
- // Success or infra error - use exit code from handleResult
268
- process.exit(exitCode);
243
+ const output = formatSchemaVerifyOutput(failure, flags);
244
+ if (output) {
245
+ ui.log(output);
246
+ }
269
247
  }
248
+ process.exit(1);
270
249
  });
271
250
 
272
251
  return command;