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

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 (58) hide show
  1. package/dist/{chunk-ZG5T6OB5.js → chunk-AGOTG4L3.js} +43 -1
  2. package/dist/chunk-AGOTG4L3.js.map +1 -0
  3. package/dist/chunk-HLLI4YL7.js +180 -0
  4. package/dist/chunk-HLLI4YL7.js.map +1 -0
  5. package/dist/chunk-VG2R7DGF.js +735 -0
  6. package/dist/chunk-VG2R7DGF.js.map +1 -0
  7. package/dist/cli.js +1621 -1382
  8. package/dist/cli.js.map +1 -1
  9. package/dist/commands/contract-emit.d.ts.map +1 -1
  10. package/dist/commands/contract-emit.js +3 -4
  11. package/dist/commands/db-init.js +4 -49
  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 +106 -136
  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 +118 -110
  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 +150 -153
  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 +140 -119
  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 +132 -1
  27. package/dist/control-api/types.d.ts.map +1 -1
  28. package/dist/exports/control-api.d.ts +1 -1
  29. package/dist/exports/control-api.d.ts.map +1 -1
  30. package/dist/exports/control-api.js +1 -3
  31. package/dist/exports/index.js +3 -4
  32. package/dist/exports/index.js.map +1 -1
  33. package/package.json +10 -10
  34. package/src/commands/contract-emit.ts +179 -102
  35. package/src/commands/db-introspect.ts +151 -178
  36. package/src/commands/db-schema-verify.ts +150 -143
  37. package/src/commands/db-sign.ts +202 -196
  38. package/src/commands/db-verify.ts +179 -149
  39. package/src/control-api/client.ts +352 -22
  40. package/src/control-api/types.ts +149 -1
  41. package/src/exports/control-api.ts +9 -0
  42. package/dist/chunk-5MPKZYVI.js +0 -47
  43. package/dist/chunk-5MPKZYVI.js.map +0 -1
  44. package/dist/chunk-6EPKRATC.js +0 -91
  45. package/dist/chunk-6EPKRATC.js.map +0 -1
  46. package/dist/chunk-74IELXRA.js +0 -371
  47. package/dist/chunk-74IELXRA.js.map +0 -1
  48. package/dist/chunk-U6QI3AZ3.js +0 -133
  49. package/dist/chunk-U6QI3AZ3.js.map +0 -1
  50. package/dist/chunk-VI2YETW7.js +0 -38
  51. package/dist/chunk-VI2YETW7.js.map +0 -1
  52. package/dist/chunk-ZG5T6OB5.js.map +0 -1
  53. package/dist/utils/action.d.ts +0 -16
  54. package/dist/utils/action.d.ts.map +0 -1
  55. package/dist/utils/spinner.d.ts +0 -29
  56. package/dist/utils/spinner.d.ts.map +0 -1
  57. package/src/utils/action.ts +0 -43
  58. package/src/utils/spinner.ts +0 -67
@@ -1,32 +1,33 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { relative, resolve } from 'node:path';
3
- import type { ContractIR } from '@prisma-next/contract/ir';
3
+ import type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';
4
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
5
+ import { Command } from 'commander';
6
+ import { loadConfig } from '../config-loader';
7
+ import { createControlClient } from '../control-api/client';
4
8
  import {
9
+ CliStructuredError,
10
+ errorContractValidationFailed,
5
11
  errorDatabaseConnectionRequired,
6
12
  errorDriverRequired,
7
13
  errorFileNotFound,
8
14
  errorHashMismatch,
15
+ errorJsonFormatNotSupported,
9
16
  errorMarkerMissing,
10
17
  errorRuntime,
11
18
  errorTargetMismatch,
12
19
  errorUnexpected,
13
- } from '@prisma-next/core-control-plane/errors';
14
- import type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';
15
- import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
16
- import { Command } from 'commander';
17
- import { loadConfig } from '../config-loader';
18
- import { performAction } from '../utils/action';
20
+ } from '../utils/cli-errors';
19
21
  import { setCommandDescriptions } from '../utils/command-helpers';
20
- import { assertContractRequirementsSatisfied } from '../utils/framework-components';
21
- import { parseGlobalFlags } from '../utils/global-flags';
22
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
22
23
  import {
23
24
  formatCommandHelp,
24
25
  formatStyledHeader,
25
26
  formatVerifyJson,
26
27
  formatVerifyOutput,
27
28
  } from '../utils/output';
29
+ import { createProgressAdapter } from '../utils/progress-adapter';
28
30
  import { handleResult } from '../utils/result-handler';
29
- import { withSpinner } from '../utils/spinner';
30
31
 
31
32
  interface DbVerifyOptions {
32
33
  readonly db?: string;
@@ -43,6 +44,161 @@ interface DbVerifyOptions {
43
44
  readonly 'no-color'?: boolean;
44
45
  }
45
46
 
47
+ /**
48
+ * Maps a VerifyDatabaseResult failure to a CliStructuredError.
49
+ */
50
+ function mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {
51
+ if (!verifyResult.ok && verifyResult.code) {
52
+ if (verifyResult.code === 'PN-RTM-3001') {
53
+ return errorMarkerMissing();
54
+ }
55
+ if (verifyResult.code === 'PN-RTM-3002') {
56
+ return errorHashMismatch({
57
+ expected: verifyResult.contract.coreHash,
58
+ ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),
59
+ });
60
+ }
61
+ if (verifyResult.code === 'PN-RTM-3003') {
62
+ return errorTargetMismatch(
63
+ verifyResult.target.expected,
64
+ verifyResult.target.actual ?? 'unknown',
65
+ );
66
+ }
67
+ // Unknown code - fall through to runtime error
68
+ }
69
+ return errorRuntime(verifyResult.summary);
70
+ }
71
+
72
+ /**
73
+ * Executes the db verify command and returns a structured Result.
74
+ */
75
+ async function executeDbVerifyCommand(
76
+ options: DbVerifyOptions,
77
+ flags: GlobalFlags,
78
+ ): Promise<Result<VerifyDatabaseResult, CliStructuredError>> {
79
+ // Load config
80
+ const config = await loadConfig(options.config);
81
+ const configPath = options.config
82
+ ? relative(process.cwd(), resolve(options.config))
83
+ : 'prisma-next.config.ts';
84
+ const contractPathAbsolute = config.contract?.output
85
+ ? resolve(config.contract.output)
86
+ : resolve('src/prisma/contract.json');
87
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
88
+
89
+ // Output header
90
+ if (flags.json !== 'object' && !flags.quiet) {
91
+ const details: Array<{ label: string; value: string }> = [
92
+ { label: 'config', value: configPath },
93
+ { label: 'contract', value: contractPath },
94
+ ];
95
+ if (options.db) {
96
+ details.push({ label: 'database', value: options.db });
97
+ }
98
+ const header = formatStyledHeader({
99
+ command: 'db verify',
100
+ description: 'Check whether the database has been signed with your contract',
101
+ url: 'https://pris.ly/db-verify',
102
+ details,
103
+ flags,
104
+ });
105
+ console.log(header);
106
+ }
107
+
108
+ // Load contract file
109
+ let contractJsonContent: string;
110
+ try {
111
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
112
+ } catch (error) {
113
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
114
+ return notOk(
115
+ errorFileNotFound(contractPathAbsolute, {
116
+ why: `Contract file not found at ${contractPathAbsolute}`,
117
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
118
+ }),
119
+ );
120
+ }
121
+ return notOk(
122
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
123
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
124
+ }),
125
+ );
126
+ }
127
+
128
+ let contractJson: Record<string, unknown>;
129
+ try {
130
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
131
+ } catch (error) {
132
+ return notOk(
133
+ errorContractValidationFailed(
134
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
135
+ { where: { path: contractPathAbsolute } },
136
+ ),
137
+ );
138
+ }
139
+
140
+ // Resolve database connection (--db flag or config.db.connection)
141
+ const dbConnection = options.db ?? config.db?.connection;
142
+ if (!dbConnection) {
143
+ return notOk(
144
+ errorDatabaseConnectionRequired({
145
+ why: `Database connection is required for db verify (set db.connection in ${configPath}, or pass --db <url>)`,
146
+ }),
147
+ );
148
+ }
149
+
150
+ // Check for driver
151
+ if (!config.driver) {
152
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db verify' }));
153
+ }
154
+
155
+ // Create control client
156
+ const client = createControlClient({
157
+ family: config.family,
158
+ target: config.target,
159
+ adapter: config.adapter,
160
+ driver: config.driver,
161
+ extensionPacks: config.extensionPacks ?? [],
162
+ });
163
+
164
+ // Create progress adapter
165
+ const onProgress = createProgressAdapter({ flags });
166
+
167
+ try {
168
+ const verifyResult = await client.verify({
169
+ contractIR: contractJson,
170
+ connection: dbConnection,
171
+ onProgress,
172
+ });
173
+
174
+ // Add blank line after all async operations if spinners were shown
175
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
176
+ console.log('');
177
+ }
178
+
179
+ // If verification failed, map to CLI structured error
180
+ if (!verifyResult.ok) {
181
+ return notOk(mapVerifyFailure(verifyResult));
182
+ }
183
+
184
+ return ok(verifyResult);
185
+ } catch (error) {
186
+ // Driver already throws CliStructuredError for connection failures
187
+ if (error instanceof CliStructuredError) {
188
+ return notOk(error);
189
+ }
190
+
191
+ // Wrap unexpected errors
192
+ return notOk(
193
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
194
+ why: `Unexpected error during db verify: ${error instanceof Error ? error.message : String(error)}`,
195
+ }),
196
+ );
197
+ } finally {
198
+ await client.close();
199
+ }
200
+ }
201
+
46
202
  export function createDbVerifyCommand(): Command {
47
203
  const command = new Command('verify');
48
204
  setCommandDescriptions(
@@ -60,7 +216,7 @@ export function createDbVerifyCommand(): Command {
60
216
  })
61
217
  .option('--db <url>', 'Database connection string')
62
218
  .option('--config <path>', 'Path to prisma-next.config.ts')
63
- .option('--json [format]', 'Output as JSON (object or ndjson)', false)
219
+ .option('--json [format]', 'Output as JSON (object)', false)
64
220
  .option('-q, --quiet', 'Quiet mode: errors only')
65
221
  .option('-v, --verbose', 'Verbose output: debug info, timings')
66
222
  .option('-vv, --trace', 'Trace output: deep internals, stack traces')
@@ -70,151 +226,25 @@ export function createDbVerifyCommand(): Command {
70
226
  .action(async (options: DbVerifyOptions) => {
71
227
  const flags = parseGlobalFlags(options);
72
228
 
73
- const result = await performAction(async () => {
74
- // Load config (file I/O)
75
- const config = await loadConfig(options.config);
76
- // Normalize config path for display (match contract path format - no ./ prefix)
77
- const configPath = options.config
78
- ? relative(process.cwd(), resolve(options.config))
79
- : 'prisma-next.config.ts';
80
- const contractPathAbsolute = config.contract?.output
81
- ? resolve(config.contract.output)
82
- : resolve('src/prisma/contract.json');
83
- // Convert to relative path for display
84
- const contractPath = relative(process.cwd(), contractPathAbsolute);
85
-
86
- // Output header (only for human-readable output)
87
- if (flags.json !== 'object' && !flags.quiet) {
88
- const details: Array<{ label: string; value: string }> = [
89
- { label: 'config', value: configPath },
90
- { label: 'contract', value: contractPath },
91
- ];
92
- if (options.db) {
93
- details.push({ label: 'database', value: options.db });
94
- }
95
- const header = formatStyledHeader({
229
+ // Validate JSON format option
230
+ if (flags.json === 'ndjson') {
231
+ const result = notOk(
232
+ errorJsonFormatNotSupported({
96
233
  command: 'db verify',
97
- description: 'Check whether the database has been signed with your contract',
98
- url: 'https://pris.ly/db-verify',
99
- details,
100
- flags,
101
- });
102
- console.log(header);
103
- }
104
-
105
- // Load contract file (file I/O)
106
- let contractJsonContent: string;
107
- try {
108
- contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
109
- } catch (error) {
110
- if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
111
- throw errorFileNotFound(contractPathAbsolute, {
112
- why: `Contract file not found at ${contractPathAbsolute}`,
113
- });
114
- }
115
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
116
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
117
- });
118
- }
119
- const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
120
-
121
- // Resolve database connection (--db flag or config.db.connection)
122
- const dbConnection = options.db ?? config.db?.connection;
123
- if (!dbConnection) {
124
- throw errorDatabaseConnectionRequired();
125
- }
234
+ format: 'ndjson',
235
+ supportedFormats: ['object'],
236
+ }),
237
+ );
238
+ const exitCode = handleResult(result, flags);
239
+ process.exit(exitCode);
240
+ }
126
241
 
127
- // Check for driver
128
- if (!config.driver) {
129
- throw errorDriverRequired();
130
- }
131
-
132
- // Store driver descriptor after null check
133
- const driverDescriptor = config.driver;
134
-
135
- const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {
136
- message: 'Connecting to database...',
137
- flags,
138
- });
139
-
140
- try {
141
- // Create family instance
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
151
- const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;
152
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
153
-
154
- // Call family instance verify method
155
- let verifyResult: VerifyDatabaseResult;
156
- try {
157
- verifyResult = await withSpinner(
158
- () =>
159
- familyInstance.verify({
160
- driver,
161
- contractIR,
162
- expectedTargetId: config.target.targetId,
163
- contractPath: contractPathAbsolute,
164
- configPath,
165
- }),
166
- {
167
- message: 'Verifying database schema...',
168
- flags,
169
- },
170
- );
171
- } catch (error) {
172
- // Wrap errors from verify() in structured error
173
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
174
- why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`,
175
- });
176
- }
177
-
178
- // If verification failed, throw structured error
179
- if (!verifyResult.ok && verifyResult.code) {
180
- if (verifyResult.code === 'PN-RTM-3001') {
181
- throw errorMarkerMissing();
182
- }
183
- if (verifyResult.code === 'PN-RTM-3002') {
184
- throw errorHashMismatch({
185
- expected: verifyResult.contract.coreHash,
186
- ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),
187
- });
188
- }
189
- if (verifyResult.code === 'PN-RTM-3003') {
190
- throw errorTargetMismatch(
191
- verifyResult.target.expected,
192
- verifyResult.target.actual ?? 'unknown',
193
- );
194
- }
195
- throw errorRuntime(verifyResult.summary);
196
- }
197
-
198
- // Add blank line after all async operations if spinners were shown
199
- if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
200
- console.log('');
201
- }
202
-
203
- return verifyResult;
204
- } finally {
205
- // Ensure driver connection is closed
206
- await driver.close();
207
- }
208
- });
242
+ const result = await executeDbVerifyCommand(options, flags);
209
243
 
210
- // Handle result - formats output and returns exit code
211
244
  const exitCode = handleResult(result, flags, (verifyResult) => {
212
- // Output based on flags
213
245
  if (flags.json === 'object') {
214
- // JSON output to stdout
215
246
  console.log(formatVerifyJson(verifyResult));
216
247
  } else {
217
- // Human-readable output to stdout
218
248
  const output = formatVerifyOutput(verifyResult, flags);
219
249
  if (output) {
220
250
  console.log(output);