@prisma-next/cli 0.2.0 → 0.3.0-dev.10

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 (85) hide show
  1. package/README.md +83 -56
  2. package/dist/{chunk-C7QQMZ3I.js → chunk-CVNWLFXO.js} +6 -9
  3. package/dist/chunk-CVNWLFXO.js.map +1 -0
  4. package/dist/{chunk-464LNZCE.js → chunk-QUPBU4KV.js} +5 -8
  5. package/dist/chunk-QUPBU4KV.js.map +1 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +34 -60
  9. package/dist/cli.js.map +1 -1
  10. package/dist/commands/contract-emit.d.ts +2 -4
  11. package/dist/commands/contract-emit.d.ts.map +1 -0
  12. package/dist/commands/contract-emit.js +1 -1
  13. package/dist/commands/db-init.d.ts +2 -4
  14. package/dist/commands/db-init.d.ts.map +1 -0
  15. package/dist/commands/db-init.js +6 -10
  16. package/dist/commands/db-init.js.map +1 -1
  17. package/dist/commands/db-introspect.d.ts +2 -4
  18. package/dist/commands/db-introspect.d.ts.map +1 -0
  19. package/dist/commands/db-introspect.js +6 -10
  20. package/dist/commands/db-introspect.js.map +1 -1
  21. package/dist/commands/db-schema-verify.d.ts +2 -4
  22. package/dist/commands/db-schema-verify.d.ts.map +1 -0
  23. package/dist/commands/db-schema-verify.js +6 -10
  24. package/dist/commands/db-schema-verify.js.map +1 -1
  25. package/dist/commands/db-sign.d.ts +2 -4
  26. package/dist/commands/db-sign.d.ts.map +1 -0
  27. package/dist/commands/db-sign.js +6 -10
  28. package/dist/commands/db-sign.js.map +1 -1
  29. package/dist/commands/db-verify.d.ts +2 -4
  30. package/dist/commands/db-verify.d.ts.map +1 -0
  31. package/dist/commands/db-verify.js +6 -10
  32. package/dist/commands/db-verify.js.map +1 -1
  33. package/dist/config-loader.d.ts +3 -5
  34. package/dist/config-loader.d.ts.map +1 -0
  35. package/dist/exports/config-types.d.ts +3 -0
  36. package/dist/exports/config-types.d.ts.map +1 -0
  37. package/dist/exports/config-types.js.map +1 -0
  38. package/dist/exports/index.d.ts +4 -0
  39. package/dist/exports/index.d.ts.map +1 -0
  40. package/dist/{index.js → exports/index.js} +3 -3
  41. package/dist/exports/index.js.map +1 -0
  42. package/dist/{index.d.ts → load-ts-contract.d.ts} +4 -8
  43. package/dist/load-ts-contract.d.ts.map +1 -0
  44. package/dist/utils/action.d.ts +16 -0
  45. package/dist/utils/action.d.ts.map +1 -0
  46. package/dist/utils/cli-errors.d.ts +7 -0
  47. package/dist/utils/cli-errors.d.ts.map +1 -0
  48. package/dist/utils/command-helpers.d.ts +12 -0
  49. package/dist/utils/command-helpers.d.ts.map +1 -0
  50. package/dist/utils/framework-components.d.ts +70 -0
  51. package/dist/utils/framework-components.d.ts.map +1 -0
  52. package/dist/utils/global-flags.d.ts +25 -0
  53. package/dist/utils/global-flags.d.ts.map +1 -0
  54. package/dist/utils/output.d.ts +142 -0
  55. package/dist/utils/output.d.ts.map +1 -0
  56. package/dist/utils/result-handler.d.ts +15 -0
  57. package/dist/utils/result-handler.d.ts.map +1 -0
  58. package/dist/utils/spinner.d.ts +29 -0
  59. package/dist/utils/spinner.d.ts.map +1 -0
  60. package/package.json +22 -22
  61. package/src/cli.ts +260 -0
  62. package/src/commands/contract-emit.ts +182 -0
  63. package/src/commands/db-init.ts +452 -0
  64. package/src/commands/db-introspect.ts +256 -0
  65. package/src/commands/db-schema-verify.ts +232 -0
  66. package/src/commands/db-sign.ts +273 -0
  67. package/src/commands/db-verify.ts +229 -0
  68. package/src/config-loader.ts +76 -0
  69. package/src/exports/config-types.ts +6 -0
  70. package/src/exports/index.ts +4 -0
  71. package/src/load-ts-contract.ts +217 -0
  72. package/src/utils/action.ts +43 -0
  73. package/src/utils/cli-errors.ts +26 -0
  74. package/src/utils/command-helpers.ts +26 -0
  75. package/src/utils/framework-components.ts +177 -0
  76. package/src/utils/global-flags.ts +75 -0
  77. package/src/utils/output.ts +1471 -0
  78. package/src/utils/result-handler.ts +44 -0
  79. package/src/utils/spinner.ts +67 -0
  80. package/dist/chunk-464LNZCE.js.map +0 -1
  81. package/dist/chunk-C7QQMZ3I.js.map +0 -1
  82. package/dist/config-types.d.ts +0 -1
  83. package/dist/config-types.js.map +0 -1
  84. package/dist/index.js.map +0 -1
  85. /package/dist/{config-types.js → exports/config-types.js} +0 -0
@@ -0,0 +1,256 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import {
4
+ errorDatabaseUrlRequired,
5
+ errorDriverRequired,
6
+ errorRuntime,
7
+ errorUnexpected,
8
+ } from '@prisma-next/core-control-plane/errors';
9
+ import type { CoreSchemaView } from '@prisma-next/core-control-plane/schema-view';
10
+ import type { IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';
11
+ import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
12
+ import { Command } from 'commander';
13
+ import { loadConfig } from '../config-loader';
14
+ import { performAction } from '../utils/action';
15
+ import { setCommandDescriptions } from '../utils/command-helpers';
16
+ import { assertContractRequirementsSatisfied } from '../utils/framework-components';
17
+ import { parseGlobalFlags } from '../utils/global-flags';
18
+ import {
19
+ formatCommandHelp,
20
+ formatIntrospectJson,
21
+ formatIntrospectOutput,
22
+ formatStyledHeader,
23
+ } from '../utils/output';
24
+ import { handleResult } from '../utils/result-handler';
25
+ import { withSpinner } from '../utils/spinner';
26
+
27
+ interface DbIntrospectOptions {
28
+ readonly db?: string;
29
+ readonly config?: string;
30
+ readonly json?: string | boolean;
31
+ readonly quiet?: boolean;
32
+ readonly q?: boolean;
33
+ readonly verbose?: boolean;
34
+ readonly v?: boolean;
35
+ readonly vv?: boolean;
36
+ readonly trace?: boolean;
37
+ readonly timestamps?: boolean;
38
+ readonly color?: boolean;
39
+ readonly 'no-color'?: boolean;
40
+ }
41
+
42
+ export function createDbIntrospectCommand(): Command {
43
+ const command = new Command('introspect');
44
+ setCommandDescriptions(
45
+ command,
46
+ 'Inspect the database schema',
47
+ 'Reads the live database schema and displays it as a tree structure. This command\n' +
48
+ 'does not check the schema against your contract - it only shows what exists in\n' +
49
+ 'the database. Use `db verify` or `db schema-verify` to compare against your contract.',
50
+ );
51
+ command
52
+ .configureHelp({
53
+ formatHelp: (cmd) => {
54
+ const flags = parseGlobalFlags({});
55
+ return formatCommandHelp({ command: cmd, flags });
56
+ },
57
+ })
58
+ .option('--db <url>', 'Database connection string')
59
+ .option('--config <path>', 'Path to prisma-next.config.ts')
60
+ .option('--json [format]', 'Output as JSON (object or ndjson)', false)
61
+ .option('-q, --quiet', 'Quiet mode: errors only')
62
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
63
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
64
+ .option('--timestamps', 'Add timestamps to output')
65
+ .option('--color', 'Force color output')
66
+ .option('--no-color', 'Disable color output')
67
+ .action(async (options: DbIntrospectOptions) => {
68
+ const flags = parseGlobalFlags(options);
69
+
70
+ const result = await performAction(async () => {
71
+ const startTime = Date.now();
72
+
73
+ // Load config (file I/O)
74
+ const config = await loadConfig(options.config);
75
+ // Normalize config path for display (match contract path format - no ./ prefix)
76
+ const configPath = options.config
77
+ ? relative(process.cwd(), resolve(options.config))
78
+ : 'prisma-next.config.ts';
79
+
80
+ // Optionally load contract if contract config exists
81
+ let contractIR: unknown | undefined;
82
+ if (config.contract?.output) {
83
+ const contractPath = resolve(config.contract.output);
84
+ try {
85
+ const contractJsonContent = await readFile(contractPath, 'utf-8');
86
+ contractIR = JSON.parse(contractJsonContent);
87
+ } catch (error) {
88
+ // Contract file is optional for introspection - don't fail if it doesn't exist
89
+ if (error instanceof Error && (error as { code?: string }).code !== 'ENOENT') {
90
+ throw errorUnexpected(error.message, {
91
+ why: `Failed to read contract file: ${error.message}`,
92
+ });
93
+ }
94
+ }
95
+ }
96
+
97
+ // Output header (only for human-readable output)
98
+ if (flags.json !== 'object' && !flags.quiet) {
99
+ const details: Array<{ label: string; value: string }> = [
100
+ { label: 'config', value: configPath },
101
+ ];
102
+ if (options.db) {
103
+ // Mask password in URL for security
104
+ const maskedUrl = options.db.replace(/:([^:@]+)@/, ':****@');
105
+ details.push({ label: 'database', value: maskedUrl });
106
+ } else if (config.db?.url) {
107
+ // Mask password in URL for security
108
+ const maskedUrl = config.db.url.replace(/:([^:@]+)@/, ':****@');
109
+ details.push({ label: 'database', value: maskedUrl });
110
+ }
111
+ const header = formatStyledHeader({
112
+ command: 'db introspect',
113
+ description: 'Inspect the database schema',
114
+ url: 'https://pris.ly/db-introspect',
115
+ details,
116
+ flags,
117
+ });
118
+ console.log(header);
119
+ }
120
+
121
+ // Resolve database URL
122
+ const dbUrl = options.db ?? config.db?.url;
123
+ if (!dbUrl) {
124
+ throw errorDatabaseUrlRequired();
125
+ }
126
+
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
+ // Create driver
136
+ const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
137
+ message: 'Connecting to database...',
138
+ flags,
139
+ });
140
+
141
+ try {
142
+ // Create family instance
143
+ const stack = createControlPlaneStack({
144
+ target: config.target,
145
+ adapter: config.adapter,
146
+ driver: driverDescriptor,
147
+ extensionPacks: config.extensionPacks,
148
+ });
149
+ const familyInstance = config.family.create(stack);
150
+
151
+ // Validate contract IR if we loaded it
152
+ if (contractIR) {
153
+ const validatedContract = familyInstance.validateContractIR(contractIR);
154
+ assertContractRequirementsSatisfied({ contract: validatedContract, stack });
155
+ contractIR = validatedContract;
156
+ }
157
+
158
+ // Call family instance introspect method
159
+ let schemaIR: unknown;
160
+ try {
161
+ schemaIR = await withSpinner(
162
+ () =>
163
+ familyInstance.introspect({
164
+ driver,
165
+ contractIR,
166
+ }),
167
+ {
168
+ message: 'Introspecting database schema...',
169
+ flags,
170
+ },
171
+ );
172
+ } catch (error) {
173
+ // Wrap errors from introspect() in structured error
174
+ throw errorRuntime(error instanceof Error ? error.message : String(error), {
175
+ why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`,
176
+ });
177
+ }
178
+
179
+ // Optionally call toSchemaView if available
180
+ let schemaView: CoreSchemaView | undefined;
181
+ if (familyInstance.toSchemaView) {
182
+ try {
183
+ schemaView = familyInstance.toSchemaView(schemaIR);
184
+ } catch (error) {
185
+ // Schema view projection is optional - log but don't fail
186
+ if (flags.verbose) {
187
+ console.error(
188
+ `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`,
189
+ );
190
+ }
191
+ }
192
+ }
193
+
194
+ const totalTime = Date.now() - startTime;
195
+
196
+ // Add blank line after all async operations if spinners were shown
197
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
198
+ console.log('');
199
+ }
200
+
201
+ // Build result envelope
202
+ const introspectResult: IntrospectSchemaResult<unknown> = {
203
+ ok: true,
204
+ summary: 'Schema introspected successfully',
205
+ target: {
206
+ familyId: config.family.familyId,
207
+ id: config.target.targetId,
208
+ },
209
+ schema: schemaIR,
210
+ ...(configPath || options.db || config.db?.url
211
+ ? {
212
+ meta: {
213
+ ...(configPath ? { configPath } : {}),
214
+ ...(options.db || config.db?.url
215
+ ? {
216
+ dbUrl: (options.db ?? config.db?.url ?? '').replace(
217
+ /:([^:@]+)@/,
218
+ ':****@',
219
+ ),
220
+ }
221
+ : {}),
222
+ },
223
+ }
224
+ : {}),
225
+ timings: {
226
+ total: totalTime,
227
+ },
228
+ };
229
+
230
+ return { introspectResult, schemaView };
231
+ } finally {
232
+ // Ensure driver connection is closed
233
+ await driver.close();
234
+ }
235
+ });
236
+
237
+ // Handle result - formats output and returns exit code
238
+ const exitCode = handleResult(result, flags, (value) => {
239
+ const { introspectResult, schemaView } = value;
240
+ // Output based on flags
241
+ if (flags.json === 'object') {
242
+ // JSON output to stdout
243
+ console.log(formatIntrospectJson(introspectResult));
244
+ } else {
245
+ // Human-readable output to stdout
246
+ const output = formatIntrospectOutput(introspectResult, schemaView, flags);
247
+ if (output) {
248
+ console.log(output);
249
+ }
250
+ }
251
+ });
252
+ process.exit(exitCode);
253
+ });
254
+
255
+ return command;
256
+ }
@@ -0,0 +1,232 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import type { ContractIR } from '@prisma-next/contract/ir';
4
+ import {
5
+ errorDatabaseUrlRequired,
6
+ errorDriverRequired,
7
+ errorFileNotFound,
8
+ errorRuntime,
9
+ errorUnexpected,
10
+ } from '@prisma-next/core-control-plane/errors';
11
+ import type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';
12
+ import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
13
+ import { Command } from 'commander';
14
+ import { loadConfig } from '../config-loader';
15
+ import { performAction } from '../utils/action';
16
+ import { setCommandDescriptions } from '../utils/command-helpers';
17
+ import {
18
+ assertContractRequirementsSatisfied,
19
+ assertFrameworkComponentsCompatible,
20
+ } from '../utils/framework-components';
21
+ import { parseGlobalFlags } from '../utils/global-flags';
22
+ import {
23
+ formatCommandHelp,
24
+ formatSchemaVerifyJson,
25
+ formatSchemaVerifyOutput,
26
+ formatStyledHeader,
27
+ } from '../utils/output';
28
+ import { handleResult } from '../utils/result-handler';
29
+ import { withSpinner } from '../utils/spinner';
30
+
31
+ interface DbSchemaVerifyOptions {
32
+ readonly db?: string;
33
+ readonly config?: string;
34
+ readonly json?: string | boolean;
35
+ readonly strict?: boolean;
36
+ readonly quiet?: boolean;
37
+ readonly q?: boolean;
38
+ readonly verbose?: boolean;
39
+ readonly v?: boolean;
40
+ readonly vv?: boolean;
41
+ readonly trace?: boolean;
42
+ readonly timestamps?: boolean;
43
+ readonly color?: boolean;
44
+ readonly 'no-color'?: boolean;
45
+ }
46
+
47
+ export function createDbSchemaVerifyCommand(): Command {
48
+ const command = new Command('schema-verify');
49
+ setCommandDescriptions(
50
+ command,
51
+ 'Check whether the database schema satisfies your contract',
52
+ 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\n' +
53
+ 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\n' +
54
+ 'verification tree. This is a read-only operation that does not modify the database.',
55
+ );
56
+ command
57
+ .configureHelp({
58
+ formatHelp: (cmd) => {
59
+ const flags = parseGlobalFlags({});
60
+ return formatCommandHelp({ command: cmd, flags });
61
+ },
62
+ })
63
+ .option('--db <url>', 'Database connection string')
64
+ .option('--config <path>', 'Path to prisma-next.config.ts')
65
+ .option('--json [format]', 'Output as JSON (object or ndjson)', false)
66
+ .option('--strict', 'Strict mode: extra schema elements cause failures', false)
67
+ .option('-q, --quiet', 'Quiet mode: errors only')
68
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
69
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
70
+ .option('--timestamps', 'Add timestamps to output')
71
+ .option('--color', 'Force color output')
72
+ .option('--no-color', 'Disable color output')
73
+ .action(async (options: DbSchemaVerifyOptions) => {
74
+ const flags = parseGlobalFlags(options);
75
+
76
+ const result = await performAction(async () => {
77
+ // Load config (file I/O)
78
+ const config = await loadConfig(options.config);
79
+ // Normalize config path for display (match contract path format - no ./ prefix)
80
+ const configPath = options.config
81
+ ? relative(process.cwd(), resolve(options.config))
82
+ : 'prisma-next.config.ts';
83
+ const contractPathAbsolute = config.contract?.output
84
+ ? resolve(config.contract.output)
85
+ : resolve('src/prisma/contract.json');
86
+ // Convert to relative path for display
87
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
88
+
89
+ // Output header (only for human-readable output)
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 schema-verify',
100
+ description: 'Check whether the database schema satisfies your contract',
101
+ url: 'https://pris.ly/db-schema-verify',
102
+ details,
103
+ flags,
104
+ });
105
+ console.log(header);
106
+ }
107
+
108
+ // Load contract file (file I/O)
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
+ throw errorFileNotFound(contractPathAbsolute, {
115
+ why: `Contract file not found at ${contractPathAbsolute}`,
116
+ });
117
+ }
118
+ throw errorUnexpected(error instanceof Error ? error.message : String(error), {
119
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
120
+ });
121
+ }
122
+ const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
123
+
124
+ // Check for driver (needed for family instance creation)
125
+ if (!config.driver) {
126
+ throw errorDriverRequired();
127
+ }
128
+
129
+ // Store driver descriptor after null check
130
+ const driverDescriptor = config.driver;
131
+
132
+ // Create family instance (needed for contract validation)
133
+ const stack = createControlPlaneStack({
134
+ target: config.target,
135
+ adapter: config.adapter,
136
+ driver: driverDescriptor,
137
+ extensionPacks: config.extensionPacks,
138
+ });
139
+ const familyInstance = config.family.create(stack);
140
+
141
+ // Validate contract using instance validator
142
+ const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;
143
+
144
+ // Validate contract requirements fail-fast before connecting to database
145
+ assertContractRequirementsSatisfied({ contract: contractIR, stack });
146
+
147
+ // Resolve database URL
148
+ const dbUrl = options.db ?? config.db?.url;
149
+ if (!dbUrl) {
150
+ throw errorDatabaseUrlRequired();
151
+ }
152
+
153
+ // Create driver
154
+ const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
155
+ message: 'Connecting to database...',
156
+ flags,
157
+ });
158
+
159
+ try {
160
+ const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
161
+ const frameworkComponents = assertFrameworkComponentsCompatible(
162
+ config.family.familyId,
163
+ config.target.targetId,
164
+ rawComponents,
165
+ );
166
+
167
+ // Call family instance schemaVerify method
168
+ let schemaVerifyResult: VerifyDatabaseSchemaResult;
169
+ try {
170
+ schemaVerifyResult = await withSpinner(
171
+ () =>
172
+ familyInstance.schemaVerify({
173
+ driver,
174
+ contractIR,
175
+ strict: options.strict ?? false,
176
+ contractPath: contractPathAbsolute,
177
+ configPath,
178
+ frameworkComponents,
179
+ }),
180
+ {
181
+ message: 'Verifying database schema...',
182
+ flags,
183
+ },
184
+ );
185
+ } catch (error) {
186
+ // Wrap errors from schemaVerify() in structured error
187
+ throw errorRuntime(error instanceof Error ? error.message : String(error), {
188
+ why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,
189
+ });
190
+ }
191
+
192
+ // Add blank line after all async operations if spinners were shown
193
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
194
+ console.log('');
195
+ }
196
+
197
+ // Return result (don't throw for logical mismatches - handle exit code separately)
198
+ return schemaVerifyResult;
199
+ } finally {
200
+ // Ensure driver connection is closed
201
+ await driver.close();
202
+ }
203
+ });
204
+
205
+ // Handle result - formats output and returns exit code
206
+ const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
207
+ // Output based on flags
208
+ if (flags.json === 'object') {
209
+ // JSON output to stdout
210
+ console.log(formatSchemaVerifyJson(schemaVerifyResult));
211
+ } else {
212
+ // Human-readable output to stdout
213
+ const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
214
+ if (output) {
215
+ console.log(output);
216
+ }
217
+ }
218
+ });
219
+
220
+ // For logical schema mismatches, check if verification passed
221
+ // Infra errors already handled by handleResult (returns non-zero exit code)
222
+ if (result.ok && !result.value.ok) {
223
+ // Schema verification failed - exit with code 1
224
+ process.exit(1);
225
+ } else {
226
+ // Success or infra error - use exit code from handleResult
227
+ process.exit(exitCode);
228
+ }
229
+ });
230
+
231
+ return command;
232
+ }