@prisma-next/cli 0.3.0-dev.17 → 0.3.0-dev.18

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 (45) hide show
  1. package/dist/chunk-BO73VO4I.js +45 -0
  2. package/dist/chunk-BO73VO4I.js.map +1 -0
  3. package/dist/{chunk-VI2YETW7.js → chunk-MPSJAVF6.js} +4 -2
  4. package/dist/{chunk-U6QI3AZ3.js → chunk-RIONCN4I.js} +45 -6
  5. package/dist/chunk-RIONCN4I.js.map +1 -0
  6. package/dist/{chunk-74IELXRA.js → chunk-RPYY5SM7.js} +273 -19
  7. package/dist/chunk-RPYY5SM7.js.map +1 -0
  8. package/dist/cli.js +708 -551
  9. package/dist/cli.js.map +1 -1
  10. package/dist/commands/contract-emit.js +2 -3
  11. package/dist/commands/db-init.js +5 -46
  12. package/dist/commands/db-init.js.map +1 -1
  13. package/dist/commands/db-introspect.d.ts.map +1 -1
  14. package/dist/commands/db-introspect.js +107 -133
  15. package/dist/commands/db-introspect.js.map +1 -1
  16. package/dist/commands/db-schema-verify.d.ts.map +1 -1
  17. package/dist/commands/db-schema-verify.js +119 -107
  18. package/dist/commands/db-schema-verify.js.map +1 -1
  19. package/dist/commands/db-sign.d.ts.map +1 -1
  20. package/dist/commands/db-sign.js +151 -150
  21. package/dist/commands/db-sign.js.map +1 -1
  22. package/dist/commands/db-verify.d.ts.map +1 -1
  23. package/dist/commands/db-verify.js +141 -116
  24. package/dist/commands/db-verify.js.map +1 -1
  25. package/dist/control-api/client.d.ts.map +1 -1
  26. package/dist/control-api/types.d.ts +41 -0
  27. package/dist/control-api/types.d.ts.map +1 -1
  28. package/dist/exports/control-api.js +2 -3
  29. package/dist/exports/index.js +2 -3
  30. package/dist/exports/index.js.map +1 -1
  31. package/package.json +10 -10
  32. package/src/commands/contract-emit.ts +1 -1
  33. package/src/commands/db-introspect.ts +151 -178
  34. package/src/commands/db-schema-verify.ts +150 -143
  35. package/src/commands/db-sign.ts +202 -196
  36. package/src/commands/db-verify.ts +179 -149
  37. package/src/control-api/client.ts +256 -22
  38. package/src/control-api/types.ts +42 -0
  39. package/dist/chunk-5MPKZYVI.js +0 -47
  40. package/dist/chunk-5MPKZYVI.js.map +0 -1
  41. package/dist/chunk-6EPKRATC.js +0 -91
  42. package/dist/chunk-6EPKRATC.js.map +0 -1
  43. package/dist/chunk-74IELXRA.js.map +0 -1
  44. package/dist/chunk-U6QI3AZ3.js.map +0 -1
  45. /package/dist/{chunk-VI2YETW7.js.map → chunk-MPSJAVF6.js.map} +0 -0
@@ -1,26 +1,24 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { relative, resolve } from 'node:path';
3
- import {
4
- errorDatabaseConnectionRequired,
5
- errorDriverRequired,
6
- errorFileNotFound,
7
- errorRuntime,
8
- errorUnexpected,
9
- } from '@prisma-next/core-control-plane/errors';
10
3
  import type {
11
4
  SignDatabaseResult,
12
5
  VerifyDatabaseSchemaResult,
13
6
  } from '@prisma-next/core-control-plane/types';
14
- import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
7
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
15
8
  import { Command } from 'commander';
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';
19
11
  import {
20
- assertContractRequirementsSatisfied,
21
- assertFrameworkComponentsCompatible,
22
- } from '../utils/framework-components';
23
- import { parseGlobalFlags } from '../utils/global-flags';
12
+ CliStructuredError,
13
+ errorContractValidationFailed,
14
+ errorDatabaseConnectionRequired,
15
+ errorDriverRequired,
16
+ errorFileNotFound,
17
+ errorJsonFormatNotSupported,
18
+ errorUnexpected,
19
+ } from '../utils/cli-errors';
20
+ import { setCommandDescriptions } from '../utils/command-helpers';
21
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
24
22
  import {
25
23
  formatCommandHelp,
26
24
  formatSchemaVerifyJson,
@@ -29,8 +27,8 @@ import {
29
27
  formatSignOutput,
30
28
  formatStyledHeader,
31
29
  } from '../utils/output';
30
+ import { createProgressAdapter } from '../utils/progress-adapter';
32
31
  import { handleResult } from '../utils/result-handler';
33
- import { withSpinner } from '../utils/spinner';
34
32
 
35
33
  interface DbSignOptions {
36
34
  readonly db?: string;
@@ -47,6 +45,158 @@ interface DbSignOptions {
47
45
  readonly 'no-color'?: boolean;
48
46
  }
49
47
 
48
+ /**
49
+ * Failure type for db sign command.
50
+ * Either an infrastructure error (CliStructuredError) or a logical failure (schema verification failed).
51
+ */
52
+ type DbSignFailure = CliStructuredError | VerifyDatabaseSchemaResult;
53
+
54
+ /**
55
+ * Executes the db sign command and returns a structured Result.
56
+ * Success: SignDatabaseResult (sign happened)
57
+ * Failure: CliStructuredError (infra error) or VerifyDatabaseSchemaResult (schema mismatch)
58
+ */
59
+ async function executeDbSignCommand(
60
+ options: DbSignOptions,
61
+ flags: GlobalFlags,
62
+ ): Promise<Result<SignDatabaseResult, DbSignFailure>> {
63
+ // Load config
64
+ const config = await loadConfig(options.config);
65
+ const configPath = options.config
66
+ ? relative(process.cwd(), resolve(options.config))
67
+ : 'prisma-next.config.ts';
68
+ const contractPathAbsolute = config.contract?.output
69
+ ? resolve(config.contract.output)
70
+ : resolve('src/prisma/contract.json');
71
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
72
+
73
+ // Output header
74
+ if (flags.json !== 'object' && !flags.quiet) {
75
+ const details: Array<{ label: string; value: string }> = [
76
+ { label: 'config', value: configPath },
77
+ { label: 'contract', value: contractPath },
78
+ ];
79
+ if (options.db) {
80
+ details.push({ label: 'database', value: options.db });
81
+ }
82
+ const header = formatStyledHeader({
83
+ command: 'db sign',
84
+ description: 'Sign the database with your contract so you can safely run queries',
85
+ url: 'https://pris.ly/db-sign',
86
+ details,
87
+ flags,
88
+ });
89
+ console.log(header);
90
+ }
91
+
92
+ // Load contract file
93
+ let contractJsonContent: string;
94
+ try {
95
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
96
+ } catch (error) {
97
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
98
+ return notOk(
99
+ errorFileNotFound(contractPathAbsolute, {
100
+ why: `Contract file not found at ${contractPathAbsolute}`,
101
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
102
+ }),
103
+ );
104
+ }
105
+ return notOk(
106
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
107
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
108
+ }),
109
+ );
110
+ }
111
+
112
+ let contractJson: Record<string, unknown>;
113
+ try {
114
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
115
+ } catch (error) {
116
+ return notOk(
117
+ errorContractValidationFailed(
118
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
119
+ { where: { path: contractPathAbsolute } },
120
+ ),
121
+ );
122
+ }
123
+
124
+ // Resolve database connection (--db flag or config.db.connection)
125
+ const dbConnection = options.db ?? config.db?.connection;
126
+ if (!dbConnection) {
127
+ return notOk(
128
+ errorDatabaseConnectionRequired({
129
+ why: `Database connection is required for db sign (set db.connection in ${configPath}, or pass --db <url>)`,
130
+ }),
131
+ );
132
+ }
133
+
134
+ // Check for driver
135
+ if (!config.driver) {
136
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db sign' }));
137
+ }
138
+
139
+ // Create control client
140
+ const client = createControlClient({
141
+ family: config.family,
142
+ target: config.target,
143
+ adapter: config.adapter,
144
+ driver: config.driver,
145
+ extensionPacks: config.extensionPacks ?? [],
146
+ });
147
+
148
+ // Create progress adapter
149
+ const onProgress = createProgressAdapter({ flags });
150
+
151
+ try {
152
+ // Step 1: Schema verification - connect here
153
+ const schemaVerifyResult = await client.schemaVerify({
154
+ contractIR: contractJson,
155
+ strict: false,
156
+ connection: dbConnection,
157
+ onProgress,
158
+ });
159
+
160
+ // If schema verification failed, return as failure
161
+ if (!schemaVerifyResult.ok) {
162
+ // Add blank line after all async operations if spinners were shown
163
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
164
+ console.log('');
165
+ }
166
+ return notOk(schemaVerifyResult);
167
+ }
168
+
169
+ // Step 2: Sign (already connected from schemaVerify)
170
+ const signResult = await client.sign({
171
+ contractIR: contractJson,
172
+ contractPath,
173
+ configPath,
174
+ onProgress,
175
+ });
176
+
177
+ // Add blank line after all async operations if spinners were shown
178
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
179
+ console.log('');
180
+ }
181
+
182
+ return ok(signResult);
183
+ } catch (error) {
184
+ // Driver already throws CliStructuredError for connection failures
185
+ if (error instanceof CliStructuredError) {
186
+ return notOk(error);
187
+ }
188
+
189
+ // Wrap unexpected errors
190
+ return notOk(
191
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
192
+ why: `Unexpected error during db sign: ${error instanceof Error ? error.message : String(error)}`,
193
+ }),
194
+ );
195
+ } finally {
196
+ await client.close();
197
+ }
198
+ }
199
+
50
200
  export function createDbSignCommand(): Command {
51
201
  const command = new Command('sign');
52
202
  setCommandDescriptions(
@@ -66,7 +216,7 @@ export function createDbSignCommand(): Command {
66
216
  })
67
217
  .option('--db <url>', 'Database connection string')
68
218
  .option('--config <path>', 'Path to prisma-next.config.ts')
69
- .option('--json [format]', 'Output as JSON (object or ndjson)', false)
219
+ .option('--json [format]', 'Output as JSON (object)', false)
70
220
  .option('-q, --quiet', 'Quiet mode: errors only')
71
221
  .option('-v, --verbose', 'Verbose output: debug info, timings')
72
222
  .option('-vv, --trace', 'Trace output: deep internals, stack traces')
@@ -76,197 +226,53 @@ export function createDbSignCommand(): Command {
76
226
  .action(async (options: DbSignOptions) => {
77
227
  const flags = parseGlobalFlags(options);
78
228
 
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({
229
+ // Validate JSON format option
230
+ if (flags.json === 'ndjson') {
231
+ const result = notOk(
232
+ errorJsonFormatNotSupported({
102
233
  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 connection (--db flag or config.db.connection)
128
- const dbConnection = options.db ?? config.db?.connection;
129
- if (!dbConnection) {
130
- throw errorDatabaseConnectionRequired();
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,
234
+ format: 'ndjson',
235
+ supportedFormats: ['object'],
236
+ }),
159
237
  );
238
+ const exitCode = handleResult(result, flags);
239
+ process.exit(exitCode);
240
+ }
160
241
 
161
- // Create driver (expensive operation - done after validation)
162
- const driver = await driverDescriptor.create(dbConnection);
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
- }
242
+ const result = await executeDbSignCommand(options, flags);
217
243
 
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('');
244
+ if (result.ok) {
245
+ // Success - format sign output
246
+ if (flags.json === 'object') {
247
+ console.log(formatSignJson(result.value));
248
+ } else {
249
+ const output = formatSignOutput(result.value, flags);
250
+ if (output) {
251
+ console.log(output);
221
252
  }
222
-
223
- return { schemaVerifyResult: undefined, signResult };
224
- } finally {
225
- // Ensure driver connection is closed
226
- await driver.close();
227
253
  }
228
- });
229
-
230
- // Handle result - formats output and returns exit code
231
- const exitCode = handleResult(result, flags, (value) => {
232
- const { schemaVerifyResult, signResult } = value;
254
+ process.exit(0);
255
+ }
233
256
 
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
- }
257
+ // Failure - determine type and handle appropriately
258
+ const failure = result.failure;
247
259
 
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
- });
260
+ if (failure instanceof CliStructuredError) {
261
+ // Infrastructure error - use standard handler
262
+ const exitCode = handleResult(result as Result<never, CliStructuredError>, flags);
263
+ process.exit(exitCode);
264
+ }
260
265
 
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);
266
+ // Schema verification failed - format and print schema verification output
267
+ if (flags.json === 'object') {
268
+ console.log(formatSchemaVerifyJson(failure));
266
269
  } else {
267
- // Success or infra error - use exit code from handleResult
268
- process.exit(exitCode);
270
+ const output = formatSchemaVerifyOutput(failure, flags);
271
+ if (output) {
272
+ console.log(output);
273
+ }
269
274
  }
275
+ process.exit(1);
270
276
  });
271
277
 
272
278
  return command;