@prisma-next/cli 0.3.0-dev.3 → 0.3.0-dev.31
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.
- package/README.md +111 -27
- package/dist/{chunk-BZMBKEEQ.js → chunk-AGOTG4L3.js} +44 -76
- package/dist/chunk-AGOTG4L3.js.map +1 -0
- package/dist/chunk-HLLI4YL7.js +180 -0
- package/dist/chunk-HLLI4YL7.js.map +1 -0
- package/dist/chunk-VG2R7DGF.js +735 -0
- package/dist/chunk-VG2R7DGF.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +1502 -968
- package/dist/cli.js.map +1 -1
- package/dist/commands/contract-emit.d.ts +2 -4
- package/dist/commands/contract-emit.d.ts.map +1 -0
- package/dist/commands/contract-emit.js +3 -2
- package/dist/commands/db-init.d.ts +2 -4
- package/dist/commands/db-init.d.ts.map +1 -0
- package/dist/commands/db-init.js +205 -289
- package/dist/commands/db-init.js.map +1 -1
- package/dist/commands/db-introspect.d.ts +2 -4
- package/dist/commands/db-introspect.d.ts.map +1 -0
- package/dist/commands/db-introspect.js +108 -143
- package/dist/commands/db-introspect.js.map +1 -1
- package/dist/commands/db-schema-verify.d.ts +2 -4
- package/dist/commands/db-schema-verify.d.ts.map +1 -0
- package/dist/commands/db-schema-verify.js +120 -113
- package/dist/commands/db-schema-verify.js.map +1 -1
- package/dist/commands/db-sign.d.ts +2 -4
- package/dist/commands/db-sign.d.ts.map +1 -0
- package/dist/commands/db-sign.js +152 -156
- package/dist/commands/db-sign.js.map +1 -1
- package/dist/commands/db-verify.d.ts +2 -4
- package/dist/commands/db-verify.d.ts.map +1 -0
- package/dist/commands/db-verify.js +142 -122
- package/dist/commands/db-verify.js.map +1 -1
- package/dist/config-loader.d.ts +3 -5
- package/dist/config-loader.d.ts.map +1 -0
- package/dist/control-api/client.d.ts +13 -0
- package/dist/control-api/client.d.ts.map +1 -0
- package/dist/control-api/operations/db-init.d.ts +29 -0
- package/dist/control-api/operations/db-init.d.ts.map +1 -0
- package/dist/control-api/types.d.ts +387 -0
- package/dist/control-api/types.d.ts.map +1 -0
- package/dist/exports/config-types.d.ts +3 -0
- package/dist/exports/config-types.d.ts.map +1 -0
- package/dist/exports/config-types.js.map +1 -0
- package/dist/exports/control-api.d.ts +13 -0
- package/dist/exports/control-api.d.ts.map +1 -0
- package/dist/exports/control-api.js +7 -0
- package/dist/exports/control-api.js.map +1 -0
- package/dist/exports/index.d.ts +4 -0
- package/dist/exports/index.d.ts.map +1 -0
- package/dist/{index.js → exports/index.js} +4 -3
- package/dist/exports/index.js.map +1 -0
- package/dist/{index.d.ts → load-ts-contract.d.ts} +4 -8
- package/dist/load-ts-contract.d.ts.map +1 -0
- package/dist/utils/cli-errors.d.ts +7 -0
- package/dist/utils/cli-errors.d.ts.map +1 -0
- package/dist/utils/command-helpers.d.ts +12 -0
- package/dist/utils/command-helpers.d.ts.map +1 -0
- package/dist/utils/framework-components.d.ts +70 -0
- package/dist/utils/framework-components.d.ts.map +1 -0
- package/dist/utils/global-flags.d.ts +25 -0
- package/dist/utils/global-flags.d.ts.map +1 -0
- package/dist/utils/output.d.ts +142 -0
- package/dist/utils/output.d.ts.map +1 -0
- package/dist/utils/progress-adapter.d.ts +26 -0
- package/dist/utils/progress-adapter.d.ts.map +1 -0
- package/dist/utils/result-handler.d.ts +15 -0
- package/dist/utils/result-handler.d.ts.map +1 -0
- package/package.json +30 -26
- package/src/cli.ts +260 -0
- package/src/commands/contract-emit.ts +259 -0
- package/src/commands/db-init.ts +360 -0
- package/src/commands/db-introspect.ts +227 -0
- package/src/commands/db-schema-verify.ts +238 -0
- package/src/commands/db-sign.ts +279 -0
- package/src/commands/db-verify.ts +258 -0
- package/src/config-loader.ts +76 -0
- package/src/control-api/client.ts +589 -0
- package/src/control-api/operations/db-init.ts +281 -0
- package/src/control-api/types.ts +461 -0
- package/src/exports/config-types.ts +6 -0
- package/src/exports/control-api.ts +46 -0
- package/src/exports/index.ts +4 -0
- package/src/load-ts-contract.ts +217 -0
- package/src/utils/cli-errors.ts +26 -0
- package/src/utils/command-helpers.ts +26 -0
- package/src/utils/framework-components.ts +177 -0
- package/src/utils/global-flags.ts +75 -0
- package/src/utils/output.ts +1471 -0
- package/src/utils/progress-adapter.ts +86 -0
- package/src/utils/result-handler.ts +44 -0
- package/dist/chunk-464LNZCE.js +0 -134
- package/dist/chunk-464LNZCE.js.map +0 -1
- package/dist/chunk-BZMBKEEQ.js.map +0 -1
- package/dist/chunk-ZKYEJROM.js +0 -94
- package/dist/chunk-ZKYEJROM.js.map +0 -1
- package/dist/config-types.d.ts +0 -1
- package/dist/config-types.js.map +0 -1
- package/dist/index.js.map +0 -1
- /package/dist/{config-types.js → exports/config-types.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-schema-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseUrlRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('--strict', 'Strict mode: extra schema elements cause failures', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Check for driver (needed for family instance creation)\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation)\n const familyInstance = config.family.create({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Validate contract using instance validator\n const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Validate contract requirements fail-fast before connecting to database\n assertContractRequirementsSatisfied({\n contract: contractIR,\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n extensionPacks: config.extensionPacks,\n });\n\n // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Create driver\n const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Call family instance schemaVerify method\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: options.strict ?? false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n // Return result (don't throw for logical mismatches - handle exit code separately)\n return schemaVerifyResult;\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,eAAe;AAkCjB,SAAS,8BAAuC;AACrD,QAAM,UAAU,IAAI,QAAQ,eAAe;AAC3C;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAGF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,O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;AAAA,YACF,CAAC;AAAA,YACH;AAAA,cACE,SAAS;AAAA,cACT;AAAA,YACF;AAAA,UACF;AAAA,QACF,SAAS,OAAO;AAEd,gBAAM,aAAa,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;AAAA,YACzE,KAAK,qCAAqC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,UAClG,CAAC;AAAA,QACH;AAGA,YAAI,CAAC,MAAM,SAAS,MAAM,SAAS,YAAY,QAAQ,OAAO,OAAO;AACnE,kBAAQ,IAAI,EAAE;AAAA,QAChB;AAGA,eAAO;AAAA,MACT,UAAE;AAEA,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,uBAAuB;AAEnE,UAAI,MAAM,SAAS,UAAU;AAE3B,gBAAQ,IAAI,uBAAuB,kBAAkB,CAAC;AAAA,MACxD,OAAO;AAEL,cAAM,SAAS,yBAAyB,oBAAoB,KAAK;AACjE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,CAAC,OAAO,MAAM,IAAI;AAEjC,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-schema-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorJsonFormatNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\n/**\n * Executes the db schema-verify command and returns a structured Result.\n */\nasync function executeDbSchemaVerifyCommand(\n options: DbSchemaVerifyOptions,\n flags: GlobalFlags,\n): Promise<Result<VerifyDatabaseSchemaResult, CliStructuredError>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for db schema-verify (set db.connection in ${configPath}, or pass --db <url>)`,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(errorDriverRequired({ why: 'Config.driver is required for db schema-verify' }));\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ flags });\n\n try {\n const schemaVerifyResult = await client.schemaVerify({\n contractIR: contractJson,\n strict: options.strict ?? false,\n connection: dbConnection,\n onProgress,\n });\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return ok(schemaVerifyResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n if (error instanceof CliStructuredError) {\n return notOk(error);\n }\n\n // Wrap unexpected errors\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during db schema-verify: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object)', false)\n .option('--strict', 'Strict mode: extra schema elements cause failures', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n // Validate JSON format option\n if (flags.json === 'ndjson') {\n const result = notOk(\n errorJsonFormatNotSupported({\n command: 'db schema-verify',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbSchemaVerifyCommand(options, flags);\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n if (flags.json === 'object') {\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC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BAAyB,oBAAoB,KAAK;AACjE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,CAAC,OAAO,MAAM,IAAI;AAEjC,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":["result","exitCode"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db-sign.d.ts","sourceRoot":"","sources":["../../src/commands/db-sign.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAgMpC,wBAAgB,mBAAmB,IAAI,OAAO,CA+E7C"}
|
package/dist/commands/db-sign.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
assertFrameworkComponentsCompatible
|
|
4
|
-
} from "../chunk-ZKYEJROM.js";
|
|
5
|
-
import {
|
|
2
|
+
createProgressAdapter,
|
|
6
3
|
formatCommandHelp,
|
|
7
4
|
formatSchemaVerifyJson,
|
|
8
5
|
formatSchemaVerifyOutput,
|
|
@@ -11,25 +8,133 @@ import {
|
|
|
11
8
|
formatStyledHeader,
|
|
12
9
|
handleResult,
|
|
13
10
|
parseGlobalFlags,
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
withSpinner
|
|
17
|
-
} from "../chunk-BZMBKEEQ.js";
|
|
11
|
+
setCommandDescriptions
|
|
12
|
+
} from "../chunk-AGOTG4L3.js";
|
|
18
13
|
import {
|
|
19
14
|
loadConfig
|
|
20
15
|
} from "../chunk-HWYQOCAJ.js";
|
|
21
|
-
|
|
22
|
-
// src/commands/db-sign.ts
|
|
23
|
-
import { readFile } from "fs/promises";
|
|
24
|
-
import { relative, resolve } from "path";
|
|
25
16
|
import {
|
|
26
|
-
|
|
17
|
+
CliStructuredError,
|
|
18
|
+
createControlClient,
|
|
19
|
+
errorContractValidationFailed,
|
|
20
|
+
errorDatabaseConnectionRequired,
|
|
27
21
|
errorDriverRequired,
|
|
28
22
|
errorFileNotFound,
|
|
29
|
-
|
|
23
|
+
errorJsonFormatNotSupported,
|
|
30
24
|
errorUnexpected
|
|
31
|
-
} from "
|
|
25
|
+
} from "../chunk-VG2R7DGF.js";
|
|
26
|
+
|
|
27
|
+
// src/commands/db-sign.ts
|
|
28
|
+
import { readFile } from "fs/promises";
|
|
29
|
+
import { relative, resolve } from "path";
|
|
30
|
+
import { notOk, ok } from "@prisma-next/utils/result";
|
|
32
31
|
import { Command } from "commander";
|
|
32
|
+
async function executeDbSignCommand(options, flags) {
|
|
33
|
+
const config = await loadConfig(options.config);
|
|
34
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
35
|
+
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
36
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
37
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
38
|
+
const details = [
|
|
39
|
+
{ label: "config", value: configPath },
|
|
40
|
+
{ label: "contract", value: contractPath }
|
|
41
|
+
];
|
|
42
|
+
if (options.db) {
|
|
43
|
+
details.push({ label: "database", value: options.db });
|
|
44
|
+
}
|
|
45
|
+
const header = formatStyledHeader({
|
|
46
|
+
command: "db sign",
|
|
47
|
+
description: "Sign the database with your contract so you can safely run queries",
|
|
48
|
+
url: "https://pris.ly/db-sign",
|
|
49
|
+
details,
|
|
50
|
+
flags
|
|
51
|
+
});
|
|
52
|
+
console.log(header);
|
|
53
|
+
}
|
|
54
|
+
let contractJsonContent;
|
|
55
|
+
try {
|
|
56
|
+
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (error instanceof Error && error.code === "ENOENT") {
|
|
59
|
+
return notOk(
|
|
60
|
+
errorFileNotFound(contractPathAbsolute, {
|
|
61
|
+
why: `Contract file not found at ${contractPathAbsolute}`,
|
|
62
|
+
fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
|
|
63
|
+
})
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
return notOk(
|
|
67
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
68
|
+
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
69
|
+
})
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
let contractJson;
|
|
73
|
+
try {
|
|
74
|
+
contractJson = JSON.parse(contractJsonContent);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
return notOk(
|
|
77
|
+
errorContractValidationFailed(
|
|
78
|
+
`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
79
|
+
{ where: { path: contractPathAbsolute } }
|
|
80
|
+
)
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const dbConnection = options.db ?? config.db?.connection;
|
|
84
|
+
if (!dbConnection) {
|
|
85
|
+
return notOk(
|
|
86
|
+
errorDatabaseConnectionRequired({
|
|
87
|
+
why: `Database connection is required for db sign (set db.connection in ${configPath}, or pass --db <url>)`
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
if (!config.driver) {
|
|
92
|
+
return notOk(errorDriverRequired({ why: "Config.driver is required for db sign" }));
|
|
93
|
+
}
|
|
94
|
+
const client = createControlClient({
|
|
95
|
+
family: config.family,
|
|
96
|
+
target: config.target,
|
|
97
|
+
adapter: config.adapter,
|
|
98
|
+
driver: config.driver,
|
|
99
|
+
extensionPacks: config.extensionPacks ?? []
|
|
100
|
+
});
|
|
101
|
+
const onProgress = createProgressAdapter({ flags });
|
|
102
|
+
try {
|
|
103
|
+
const schemaVerifyResult = await client.schemaVerify({
|
|
104
|
+
contractIR: contractJson,
|
|
105
|
+
strict: false,
|
|
106
|
+
connection: dbConnection,
|
|
107
|
+
onProgress
|
|
108
|
+
});
|
|
109
|
+
if (!schemaVerifyResult.ok) {
|
|
110
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
111
|
+
console.log("");
|
|
112
|
+
}
|
|
113
|
+
return notOk(schemaVerifyResult);
|
|
114
|
+
}
|
|
115
|
+
const signResult = await client.sign({
|
|
116
|
+
contractIR: contractJson,
|
|
117
|
+
contractPath,
|
|
118
|
+
configPath,
|
|
119
|
+
onProgress
|
|
120
|
+
});
|
|
121
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
122
|
+
console.log("");
|
|
123
|
+
}
|
|
124
|
+
return ok(signResult);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (error instanceof CliStructuredError) {
|
|
127
|
+
return notOk(error);
|
|
128
|
+
}
|
|
129
|
+
return notOk(
|
|
130
|
+
errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
131
|
+
why: `Unexpected error during db sign: ${error instanceof Error ? error.message : String(error)}`
|
|
132
|
+
})
|
|
133
|
+
);
|
|
134
|
+
} finally {
|
|
135
|
+
await client.close();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
33
138
|
function createDbSignCommand() {
|
|
34
139
|
const command = new Command("sign");
|
|
35
140
|
setCommandDescriptions(
|
|
@@ -42,154 +147,45 @@ function createDbSignCommand() {
|
|
|
42
147
|
const flags = parseGlobalFlags({});
|
|
43
148
|
return formatCommandHelp({ command: cmd, flags });
|
|
44
149
|
}
|
|
45
|
-
}).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object
|
|
150
|
+
}).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").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) => {
|
|
46
151
|
const flags = parseGlobalFlags(options);
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
51
|
-
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
52
|
-
if (flags.json !== "object" && !flags.quiet) {
|
|
53
|
-
const details = [
|
|
54
|
-
{ label: "config", value: configPath },
|
|
55
|
-
{ label: "contract", value: contractPath }
|
|
56
|
-
];
|
|
57
|
-
if (options.db) {
|
|
58
|
-
details.push({ label: "database", value: options.db });
|
|
59
|
-
}
|
|
60
|
-
const header = formatStyledHeader({
|
|
152
|
+
if (flags.json === "ndjson") {
|
|
153
|
+
const result2 = notOk(
|
|
154
|
+
errorJsonFormatNotSupported({
|
|
61
155
|
command: "db sign",
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
flags
|
|
66
|
-
});
|
|
67
|
-
console.log(header);
|
|
68
|
-
}
|
|
69
|
-
let contractJsonContent;
|
|
70
|
-
try {
|
|
71
|
-
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
72
|
-
} catch (error) {
|
|
73
|
-
if (error instanceof Error && error.code === "ENOENT") {
|
|
74
|
-
throw errorFileNotFound(contractPathAbsolute, {
|
|
75
|
-
why: `Contract file not found at ${contractPathAbsolute}`
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
throw errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
79
|
-
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
const contractJson = JSON.parse(contractJsonContent);
|
|
83
|
-
const dbUrl = options.db ?? config.db?.url;
|
|
84
|
-
if (!dbUrl) {
|
|
85
|
-
throw errorDatabaseUrlRequired();
|
|
86
|
-
}
|
|
87
|
-
if (!config.driver) {
|
|
88
|
-
throw errorDriverRequired();
|
|
89
|
-
}
|
|
90
|
-
const driverDescriptor = config.driver;
|
|
91
|
-
const familyInstance = config.family.create({
|
|
92
|
-
target: config.target,
|
|
93
|
-
adapter: config.adapter,
|
|
94
|
-
driver: driverDescriptor,
|
|
95
|
-
extensionPacks: config.extensionPacks ?? []
|
|
96
|
-
});
|
|
97
|
-
const contractIR = familyInstance.validateContractIR(contractJson);
|
|
98
|
-
assertContractRequirementsSatisfied({
|
|
99
|
-
contract: contractIR,
|
|
100
|
-
family: config.family,
|
|
101
|
-
target: config.target,
|
|
102
|
-
adapter: config.adapter,
|
|
103
|
-
extensionPacks: config.extensionPacks
|
|
104
|
-
});
|
|
105
|
-
const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
|
|
106
|
-
const frameworkComponents = assertFrameworkComponentsCompatible(
|
|
107
|
-
config.family.familyId,
|
|
108
|
-
config.target.targetId,
|
|
109
|
-
rawComponents
|
|
156
|
+
format: "ndjson",
|
|
157
|
+
supportedFormats: ["object"]
|
|
158
|
+
})
|
|
110
159
|
);
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
frameworkComponents
|
|
123
|
-
}),
|
|
124
|
-
{
|
|
125
|
-
message: "Verifying database satisfies contract",
|
|
126
|
-
flags
|
|
127
|
-
}
|
|
128
|
-
);
|
|
129
|
-
} catch (error) {
|
|
130
|
-
throw errorRuntime(error instanceof Error ? error.message : String(error), {
|
|
131
|
-
why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
if (!schemaVerifyResult.ok) {
|
|
135
|
-
return { schemaVerifyResult, signResult: void 0 };
|
|
136
|
-
}
|
|
137
|
-
let signResult;
|
|
138
|
-
try {
|
|
139
|
-
signResult = await withSpinner(
|
|
140
|
-
() => familyInstance.sign({
|
|
141
|
-
driver,
|
|
142
|
-
contractIR,
|
|
143
|
-
contractPath: contractPathAbsolute,
|
|
144
|
-
configPath
|
|
145
|
-
}),
|
|
146
|
-
{
|
|
147
|
-
message: "Signing database...",
|
|
148
|
-
flags
|
|
149
|
-
}
|
|
150
|
-
);
|
|
151
|
-
} catch (error) {
|
|
152
|
-
throw errorRuntime(error instanceof Error ? error.message : String(error), {
|
|
153
|
-
why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
157
|
-
console.log("");
|
|
158
|
-
}
|
|
159
|
-
return { schemaVerifyResult: void 0, signResult };
|
|
160
|
-
} finally {
|
|
161
|
-
await driver.close();
|
|
162
|
-
}
|
|
163
|
-
});
|
|
164
|
-
const exitCode = handleResult(result, flags, (value) => {
|
|
165
|
-
const { schemaVerifyResult, signResult } = value;
|
|
166
|
-
if (schemaVerifyResult && !schemaVerifyResult.ok) {
|
|
167
|
-
if (flags.json === "object") {
|
|
168
|
-
console.log(formatSchemaVerifyJson(schemaVerifyResult));
|
|
169
|
-
} else {
|
|
170
|
-
const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
|
|
171
|
-
if (output) {
|
|
172
|
-
console.log(output);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
if (signResult) {
|
|
178
|
-
if (flags.json === "object") {
|
|
179
|
-
console.log(formatSignJson(signResult));
|
|
180
|
-
} else {
|
|
181
|
-
const output = formatSignOutput(signResult, flags);
|
|
182
|
-
if (output) {
|
|
183
|
-
console.log(output);
|
|
184
|
-
}
|
|
160
|
+
const exitCode = handleResult(result2, flags);
|
|
161
|
+
process.exit(exitCode);
|
|
162
|
+
}
|
|
163
|
+
const result = await executeDbSignCommand(options, flags);
|
|
164
|
+
if (result.ok) {
|
|
165
|
+
if (flags.json === "object") {
|
|
166
|
+
console.log(formatSignJson(result.value));
|
|
167
|
+
} else {
|
|
168
|
+
const output = formatSignOutput(result.value, flags);
|
|
169
|
+
if (output) {
|
|
170
|
+
console.log(output);
|
|
185
171
|
}
|
|
186
172
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
173
|
+
process.exit(0);
|
|
174
|
+
}
|
|
175
|
+
const failure = result.failure;
|
|
176
|
+
if (failure instanceof CliStructuredError) {
|
|
177
|
+
const exitCode = handleResult(result, flags);
|
|
191
178
|
process.exit(exitCode);
|
|
192
179
|
}
|
|
180
|
+
if (flags.json === "object") {
|
|
181
|
+
console.log(formatSchemaVerifyJson(failure));
|
|
182
|
+
} else {
|
|
183
|
+
const output = formatSchemaVerifyOutput(failure, flags);
|
|
184
|
+
if (output) {
|
|
185
|
+
console.log(output);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
process.exit(1);
|
|
193
189
|
});
|
|
194
190
|
return command;
|
|
195
191
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/db-sign.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport {\n errorDatabaseUrlRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type {\n SignDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatSignJson,\n formatSignOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSignOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbSignCommand(): Command {\n const command = new Command('sign');\n setCommandDescriptions(\n command,\n 'Sign the database with your contract so you can safely run queries',\n 'Verifies that your database schema satisfies the emitted contract, and if so, writes or\\n' +\n 'updates the contract marker in the database. This command is idempotent and safe to run\\n' +\n 'in CI/deployment pipelines. The marker records that this database instance is aligned\\n' +\n 'with a specific contract version.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSignOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db sign',\n description: 'Sign the database with your contract so you can safely run queries',\n url: 'https://pris.ly/db-sign',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation - no DB connection required)\n const familyInstance = config.family.create({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Validate contract using instance validator (fail-fast before DB connection)\n const contractIR = familyInstance.validateContractIR(contractJson);\n assertContractRequirementsSatisfied({\n contract: contractIR,\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n extensionPacks: config.extensionPacks,\n });\n\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Create driver (expensive operation - done after validation)\n const driver = await driverDescriptor.create(dbUrl);\n\n try {\n // Schema verification precondition with spinner\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database satisfies contract',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // If schema verification failed, return both results for handling outside performAction\n if (!schemaVerifyResult.ok) {\n return { schemaVerifyResult, signResult: undefined };\n }\n\n // Schema verification passed - proceed with signing\n let signResult: SignDatabaseResult;\n try {\n signResult = await withSpinner(\n () =>\n familyInstance.sign({\n driver,\n contractIR,\n contractPath: contractPathAbsolute,\n configPath,\n }),\n {\n message: 'Signing database...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from sign() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return { schemaVerifyResult: undefined, signResult };\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (value) => {\n const { schemaVerifyResult, signResult } = value;\n\n // If schema verification failed, format and print schema verification output\n if (schemaVerifyResult && !schemaVerifyResult.ok) {\n if (flags.json === 'object') {\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n // Don't proceed to sign output formatting\n return;\n }\n\n // Schema verification passed - format sign output\n if (signResult) {\n if (flags.json === 'object') {\n console.log(formatSignJson(signResult));\n } else {\n const output = formatSignOutput(signResult, flags);\n if (output) {\n console.log(output);\n }\n }\n }\n });\n\n // For logical schema mismatches, check if schema verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,eAAe;AAmCjB,SAAS,sBAA+B;AAC7C,QAAM,UAAU,IAAI,QAAQ,MAAM;AAClC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAIF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,qCAAqC,KAAK,EACpE,OAAO,eAAe,yBAAyB,EAC/C,OAAO,iBAAiB,qCAAqC,EAC7D,OAAO,gBAAgB,4CAA4C,EACnE,OAAO,gBAAgB,0BAA0B,EACjD,OAAO,WAAW,oBAAoB,EACtC,OAAO,cAAc,sBAAsB,EAC3C,OAAO,OAAO,YAA2B;AACxC,UAAM,QAAQ,iBAAiB,OAAO;AAEtC,UAAM,SAAS,MAAM,cAAc,YAAY;AAE7C,YAAM,SAAS,MAAM,WAAW,QAAQ,MAAM;AAE9C,YAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;AACJ,YAAM,uBAAuB,OAAO,UAAU,SAC1C,QAAQ,OAAO,SAAS,MAAM,IAC9B,QAAQ,0BAA0B;AAEtC,YAAM,eAAe,SAAS,QAAQ,IAAI,GAAG,oBAAoB;AAGjE,UAAI,MAAM,SAAS,YAAY,CAAC,MAAM,OAAO;AAC3C,cAAM,UAAmD;AAAA,UACvD,EAAE,OAAO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SAAS,YAAY,QAAQ,OAAO,OAAO;AACnE,kBAAQ,IAAI,EAAE;AAAA,QAChB;AAEA,eAAO,EAAE,oBAAoB,QAAW,WAAW;AAAA,MACrD,UAAE;AAEA,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,UAAU;AACtD,YAAM,EAAE,oBAAoB,WAAW,IAAI;AAG3C,UAAI,sBAAsB,CAAC,mBAAmB,IAAI;AAChD,YAAI,MAAM,SAAS,UAAU;AAC3B,kBAAQ,IAAI,uBAAuB,kBAAkB,CAAC;AAAA,QACxD,OAAO;AACL,gBAAM,SAAS,yBAAyB,oBAAoB,KAAK;AACjE,cAAI,QAAQ;AACV,oBAAQ,IAAI,MAAM;AAAA,UACpB;AAAA,QACF;AAEA;AAAA,MACF;AAGA,UAAI,YAAY;AACd,YAAI,MAAM,SAAS,UAAU;AAC3B,kBAAQ,IAAI,eAAe,UAAU,CAAC;AAAA,QACxC,OAAO;AACL,gBAAM,SAAS,iBAAiB,YAAY,KAAK;AACjD,cAAI,QAAQ;AACV,oBAAQ,IAAI,MAAM;AAAA,UACpB;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,OAAO,MAAM,sBAAsB,CAAC,OAAO,MAAM,mBAAmB,IAAI;AAEvF,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-sign.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type {\n SignDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/core-control-plane/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorJsonFormatNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatSignJson,\n formatSignOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbSignOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\n/**\n * Failure type for db sign command.\n * Either an infrastructure error (CliStructuredError) or a logical failure (schema verification failed).\n */\ntype DbSignFailure = CliStructuredError | VerifyDatabaseSchemaResult;\n\n/**\n * Executes the db sign command and returns a structured Result.\n * Success: SignDatabaseResult (sign happened)\n * Failure: CliStructuredError (infra error) or VerifyDatabaseSchemaResult (schema mismatch)\n */\nasync function executeDbSignCommand(\n options: DbSignOptions,\n flags: GlobalFlags,\n): Promise<Result<SignDatabaseResult, DbSignFailure>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db sign',\n description: 'Sign the database with your contract so you can safely run queries',\n url: 'https://pris.ly/db-sign',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for db sign (set db.connection in ${configPath}, or pass --db <url>)`,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(errorDriverRequired({ why: 'Config.driver is required for db sign' }));\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ flags });\n\n try {\n // Step 1: Schema verification - connect here\n const schemaVerifyResult = await client.schemaVerify({\n contractIR: contractJson,\n strict: false,\n connection: dbConnection,\n onProgress,\n });\n\n // If schema verification failed, return as failure\n if (!schemaVerifyResult.ok) {\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n return notOk(schemaVerifyResult);\n }\n\n // Step 2: Sign (already connected from schemaVerify)\n const signResult = await client.sign({\n contractIR: contractJson,\n contractPath,\n configPath,\n onProgress,\n });\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return ok(signResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n if (error instanceof CliStructuredError) {\n return notOk(error);\n }\n\n // Wrap unexpected errors\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during db sign: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbSignCommand(): Command {\n const command = new Command('sign');\n setCommandDescriptions(\n command,\n 'Sign the database with your contract so you can safely run queries',\n 'Verifies that your database schema satisfies the emitted contract, and if so, writes or\\n' +\n 'updates the contract marker in the database. This command is idempotent and safe to run\\n' +\n 'in CI/deployment pipelines. The marker records that this database instance is aligned\\n' +\n 'with a specific contract version.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object)', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSignOptions) => {\n const flags = parseGlobalFlags(options);\n\n // Validate JSON format option\n if (flags.json === 'ndjson') {\n const result = notOk(\n errorJsonFormatNotSupported({\n command: 'db sign',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbSignCommand(options, flags);\n\n if (result.ok) {\n // Success - format sign output\n if (flags.json === 'object') {\n console.log(formatSignJson(result.value));\n } else {\n const output = formatSignOutput(result.value, flags);\n if (output) {\n console.log(output);\n }\n }\n process.exit(0);\n }\n\n // Failure - determine type and handle appropriately\n const failure = result.failure;\n\n if (failure instanceof CliStructuredError) {\n // Infrastructure error - use standard handler\n const exitCode = handleResult(result as Result<never, CliStructuredError>, flags);\n process.exit(exitCode);\n }\n\n // Schema verification failed - format and print schema verification output\n if (flags.json === 'object') {\n console.log(formatSchemaVerifyJson(failure));\n } else {\n const output = formatSchemaVerifyOutput(failure, flags);\n if (output) {\n console.log(output);\n }\n }\n process.exit(1);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAKlC,SAAS,OAAO,UAAuB;AACvC,SAAS,eAAe;AAmDxB,eAAe,qBACb,SACA,OACoD;AAEpD,QAAM,SAAS,MAAM,WAAW,QAAQ,MAAM;AAC9C,QAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;AACJ,QAAM,uBAAuB,OAAO,UAAU,SAC1C,QAAQ,OAAO,SAAS,MAAM,IAC9B,QAAQ,0BAA0B;AACtC,QAAM,eAAe,SAAS,QAAQ,IAAI,GAAG,oBAAoB;AAGjE,MAAI,MAAM,SAAS,YAAY,CAAC,MAAM,OAAO;AAC3C,UAAM,UAAmD;AAAA,MACvD,EAAE,OAAO,UAAU,OAAO,WAAW;AAAA,MACrC,EAAE,OAAO,YAAY,OAAO,aAAa;AAAA,IAC3C;AACA,QAAI,QAAQ,IAAI;AACd,cAAQ,KAAK,EAAE,OAAO,YAAY,OAAO,QAAQ,GAAG,CAAC;AAAA,IACvD;AACA,UAAM,SAAS,mBAAmB;AAAA,MAChC,SAAS;AAAA,MACT,aAAa;AAAA,MACb,KAAK;AAAA,MACL;AAAA,MACA;AAAA,IACF,CAAC;AACD,Y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