prisma-next 0.12.0-dev.12 → 0.12.0-dev.14
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/dist/cli.mjs +177 -160
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-CDr4o07S.mjs → client-Cdxcme1x.mjs} +4 -4
- package/dist/{client-CDr4o07S.mjs.map → client-Cdxcme1x.mjs.map} +1 -1
- package/dist/{command-helpers-Bbw1GbwL.mjs → command-helpers-Cmdqyhz9.mjs} +32 -2
- package/dist/{command-helpers-Bbw1GbwL.mjs.map → command-helpers-Cmdqyhz9.mjs.map} +1 -1
- package/dist/commands/contract-emit.mjs +1 -1
- package/dist/commands/contract-infer.mjs +1 -1
- package/dist/commands/db-init.mjs +4 -4
- package/dist/commands/db-schema.mjs +3 -3
- package/dist/commands/db-sign.mjs +4 -4
- package/dist/commands/db-update.mjs +5 -5
- package/dist/commands/db-verify.mjs +1 -1
- package/dist/commands/migrate.d.mts +1 -1
- package/dist/commands/migrate.mjs +5 -5
- package/dist/commands/migration-check.mjs +1 -1
- package/dist/commands/migration-graph.d.mts +4 -4
- package/dist/commands/migration-graph.mjs +1 -1
- package/dist/commands/migration-list.d.mts +3 -3
- package/dist/commands/migration-list.mjs +2 -2
- package/dist/commands/migration-log.d.mts +3 -3
- package/dist/commands/migration-log.mjs +3 -3
- package/dist/commands/migration-new.mjs +3 -3
- package/dist/commands/migration-plan.d.mts +1 -1
- package/dist/commands/migration-plan.mjs +1 -1
- package/dist/commands/migration-show.d.mts +1 -1
- package/dist/commands/migration-show.mjs +3 -3
- package/dist/commands/migration-status.d.mts +1 -1
- package/dist/commands/migration-status.mjs +3 -3
- package/dist/commands/ref.d.mts +1 -1
- package/dist/commands/ref.mjs +2 -2
- package/dist/commands/telemetry/index.d.mts +7 -0
- package/dist/commands/telemetry/index.d.mts.map +1 -0
- package/dist/commands/telemetry/index.mjs +2 -0
- package/dist/{contract-at-errors-BxP-TOMl.mjs → contract-at-errors-Cz0z5PJi.mjs} +2 -2
- package/dist/{contract-at-errors-BxP-TOMl.mjs.map → contract-at-errors-Cz0z5PJi.mjs.map} +1 -1
- package/dist/{contract-emit-D-4jrNve.mjs → contract-emit-CC9jDOmu.mjs} +3 -3
- package/dist/{contract-emit-D-4jrNve.mjs.map → contract-emit-CC9jDOmu.mjs.map} +1 -1
- package/dist/{contract-emit-DxcGl4Uq.mjs → contract-emit-DPMij44i.mjs} +3 -3
- package/dist/{contract-emit-DxcGl4Uq.mjs.map → contract-emit-DPMij44i.mjs.map} +1 -1
- package/dist/{contract-infer-C8J1WMvO.mjs → contract-infer-DaFPNrZH.mjs} +3 -3
- package/dist/{contract-infer-C8J1WMvO.mjs.map → contract-infer-DaFPNrZH.mjs.map} +1 -1
- package/dist/{contract-space-aggregate-loader-DvZwdkrr.mjs → contract-space-aggregate-loader-CirAEsM8.mjs} +2 -2
- package/dist/{contract-space-aggregate-loader-DvZwdkrr.mjs.map → contract-space-aggregate-loader-CirAEsM8.mjs.map} +1 -1
- package/dist/{db-verify-BeRHwN8M.mjs → db-verify-BSA1a_W_.mjs} +4 -4
- package/dist/{db-verify-BeRHwN8M.mjs.map → db-verify-BSA1a_W_.mjs.map} +1 -1
- package/dist/exports/control-api.d.mts +1 -1
- package/dist/exports/control-api.mjs +2 -2
- package/dist/exports/index.mjs +1 -1
- package/dist/exports/init-output.mjs +1 -1
- package/dist/{framework-components-fYXjz_in.mjs → framework-components-DynSvww4.mjs} +2 -2
- package/dist/{framework-components-fYXjz_in.mjs.map → framework-components-DynSvww4.mjs.map} +1 -1
- package/dist/{global-flags-DEHjV8_s.d.mts → global-flags-DG4uY5tV.d.mts} +1 -1
- package/dist/{global-flags-DEHjV8_s.d.mts.map → global-flags-DG4uY5tV.d.mts.map} +1 -1
- package/dist/{init-Cv9UzWL5.mjs → init-B6kKrmf7.mjs} +5 -58
- package/dist/init-B6kKrmf7.mjs.map +1 -0
- package/dist/{inspect-live-schema-BlKR2Zln.mjs → inspect-live-schema-Dn56wDhG.mjs} +3 -3
- package/dist/{inspect-live-schema-BlKR2Zln.mjs.map → inspect-live-schema-Dn56wDhG.mjs.map} +1 -1
- package/dist/{migration-check-BiBJoYYW.mjs → migration-check-DzH1u-O1.mjs} +2 -2
- package/dist/{migration-check-BiBJoYYW.mjs.map → migration-check-DzH1u-O1.mjs.map} +1 -1
- package/dist/{migration-command-scaffold-BAGUiGOK.mjs → migration-command-scaffold-V52dV2Tv.mjs} +3 -3
- package/dist/{migration-command-scaffold-BAGUiGOK.mjs.map → migration-command-scaffold-V52dV2Tv.mjs.map} +1 -1
- package/dist/{migration-graph-C9WC-7eO.mjs → migration-graph-Cm3oee8C.mjs} +3 -3
- package/dist/{migration-graph-C9WC-7eO.mjs.map → migration-graph-Cm3oee8C.mjs.map} +1 -1
- package/dist/{migration-plan-9DJ7q7_z.mjs → migration-plan-CaeKCKp4.mjs} +5 -5
- package/dist/{migration-plan-9DJ7q7_z.mjs.map → migration-plan-CaeKCKp4.mjs.map} +1 -1
- package/dist/{migration-types-D2FW63pr.d.mts → migration-types-CAQ-0TEE.d.mts} +1 -1
- package/dist/{migration-types-D2FW63pr.d.mts.map → migration-types-CAQ-0TEE.d.mts.map} +1 -1
- package/dist/{migrations-Cv2jxNNK.mjs → migrations-DQ1t3XFL.mjs} +2 -2
- package/dist/{migrations-Cv2jxNNK.mjs.map → migrations-DQ1t3XFL.mjs.map} +1 -1
- package/dist/{output-B60Gw5fu.mjs → output-CF_hqzI-.mjs} +1 -1
- package/dist/{output-B60Gw5fu.mjs.map → output-CF_hqzI-.mjs.map} +1 -1
- package/dist/telemetry-Q88WHwlv.mjs +122 -0
- package/dist/telemetry-Q88WHwlv.mjs.map +1 -0
- package/dist/{terminal-ui-5Y6mrg93.d.mts → terminal-ui-C3xGyxW-.d.mts} +1 -1
- package/dist/{terminal-ui-5Y6mrg93.d.mts.map → terminal-ui-C3xGyxW-.d.mts.map} +1 -1
- package/dist/{types-CeC5ec2Y.d.mts → types-DiC683UW.d.mts} +1 -1
- package/dist/{types-CeC5ec2Y.d.mts.map → types-DiC683UW.d.mts.map} +1 -1
- package/dist/{verify-DCA9Sldu.mjs → verify-CreSJ1Mz.mjs} +2 -2
- package/dist/{verify-DCA9Sldu.mjs.map → verify-CreSJ1Mz.mjs.map} +1 -1
- package/package.json +11 -11
- package/dist/init-Cv9UzWL5.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contract-infer-
|
|
1
|
+
{"version":3,"file":"contract-infer-DaFPNrZH.mjs","names":[],"sources":["../src/commands/contract-infer-paths.ts","../src/commands/contract-infer.ts"],"sourcesContent":["import { dirname, resolve } from 'pathe';\n\ninterface ContractInferPathOptions {\n readonly output?: string;\n readonly config?: string;\n}\n\n/**\n * Resolves the output path for the inferred PSL contract.\n *\n * Priority:\n * 1. --output <path> flag (resolved relative to cwd)\n * 2. contract.prisma next to config.contract.output\n * 3. Canonical default: contract.prisma in the config directory\n */\nexport function resolveContractInferOutputPath(\n options: ContractInferPathOptions,\n contractOutput: string | undefined,\n): string {\n const configDir = options.config\n ? dirname(resolve(process.cwd(), options.config))\n : process.cwd();\n\n if (options.output) {\n return resolve(process.cwd(), options.output);\n }\n if (contractOutput) {\n const contractPath = resolve(configDir, contractOutput);\n return resolve(dirname(contractPath), 'contract.prisma');\n }\n return resolve(configDir, 'contract.prisma');\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { errorRuntime } from '@prisma-next/errors/execution';\nimport { printPsl } from '@prisma-next/psl-printer';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, relative } from 'pathe';\nimport type { CliStructuredError } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\nimport { resolveContractInferOutputPath } from './contract-infer-paths';\nimport {\n type InspectLiveSchemaOptions,\n type InspectLiveSchemaResult,\n inspectLiveSchema,\n} from './inspect-live-schema';\n\ninterface ContractInferOptions extends InspectLiveSchemaOptions {\n readonly output?: string;\n}\n\ninterface ContractInferSuccessResult {\n readonly ok: true;\n readonly summary: string;\n readonly target: InspectLiveSchemaResult['target'];\n readonly psl: {\n readonly path: string;\n };\n readonly meta: InspectLiveSchemaResult['meta'];\n readonly timings: {\n readonly total: number;\n };\n}\n\nasync function executeContractInferCommand(\n options: ContractInferOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<ContractInferSuccessResult, CliStructuredError>> {\n const inspectResult = await inspectLiveSchema(options, flags, ui, startTime, {\n commandName: 'contract infer',\n description: 'Infer a PSL contract from the live database schema',\n url: 'https://pris.ly/contract-infer',\n });\n\n if (!inspectResult.ok) {\n return inspectResult;\n }\n\n const { config, target, meta, pslContractAst } = inspectResult.value;\n\n if (!pslContractAst) {\n return notOk(\n errorRuntime('contract infer is not supported for this family', {\n why: 'The configured family does not implement the PslContractInferCapable capability, so an inferred PSL contract cannot be produced from the live database schema.',\n fix: 'Use a family that supports contract inference (e.g. SQL/Postgres).',\n }),\n );\n }\n\n const outputPath = resolveContractInferOutputPath(options, config.contract?.output);\n const pslContent = printPsl(pslContractAst);\n\n if (existsSync(outputPath) && !flags.json && !flags.quiet) {\n ui.stderr(`\\u26A0 Overwriting existing file: ${relative(process.cwd(), outputPath)}`);\n }\n\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, pslContent, 'utf-8');\n\n const pslPath = relative(process.cwd(), outputPath);\n if (!flags.json && !flags.quiet) {\n ui.stderr(`\\u2714 Contract written to ${pslPath}`);\n }\n\n return ok({\n ok: true,\n summary: 'Contract inferred successfully',\n target,\n psl: {\n path: pslPath,\n },\n meta,\n timings: {\n total: Date.now() - startTime,\n },\n });\n}\n\nexport function createContractInferCommand(): Command {\n const command = new Command('infer');\n setCommandDescriptions(\n command,\n 'Infer a PSL contract from the live database schema',\n 'Reads the live database schema and writes an inferred PSL contract to disk.\\n' +\n 'This command stops at `contract.prisma`; follow it with `contract emit` and\\n' +\n '`db sign` as separate steps.',\n );\n setCommandExamples(command, [\n 'prisma-next contract infer --db $DATABASE_URL',\n 'prisma-next contract infer --db $DATABASE_URL --output ./src/prisma/contract.prisma',\n 'prisma-next contract infer --db $DATABASE_URL --json',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--output <path>', 'Write the inferred PSL contract to the specified path')\n .action(async (options: ContractInferOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const startTime = Date.now();\n\n const result = await executeContractInferCommand(options, flags, ui, startTime);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,SAAgB,+BACd,SACA,gBACQ;CACR,MAAM,YAAY,QAAQ,SACtB,QAAQ,QAAQ,QAAQ,IAAI,GAAG,QAAQ,MAAM,CAAC,IAC9C,QAAQ,IAAI;CAEhB,IAAI,QAAQ,QACV,OAAO,QAAQ,QAAQ,IAAI,GAAG,QAAQ,MAAM;CAE9C,IAAI,gBAEF,OAAO,QAAQ,QADM,QAAQ,WAAW,cACN,CAAC,GAAG,iBAAiB;CAEzD,OAAO,QAAQ,WAAW,iBAAiB;AAC7C;;;ACQA,eAAe,4BACb,SACA,OACA,IACA,WACiE;CACjE,MAAM,gBAAgB,MAAM,kBAAkB,SAAS,OAAO,IAAI,WAAW;EAC3E,aAAa;EACb,aAAa;EACb,KAAK;CACP,CAAC;CAED,IAAI,CAAC,cAAc,IACjB,OAAO;CAGT,MAAM,EAAE,QAAQ,QAAQ,MAAM,mBAAmB,cAA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
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as readContractEnvelope, j as CliStructuredError, nt as errorUnexpected, o as resolveContractPath, rt as mapMigrationToolsError } from "./command-helpers-Cmdqyhz9.mjs";
|
|
2
2
|
import { t as toDeclaredExtensionsFromRaw } from "./extension-pack-inputs-IDvjRCi3.mjs";
|
|
3
3
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
@@ -244,4 +244,4 @@ async function buildReadAggregate(config, options) {
|
|
|
244
244
|
//#endregion
|
|
245
245
|
export { loadContractSpaceAggregateForCli as a, loadContractRawSafely as i, buildContractSpaceAggregate as n, refuseContractSpaceIntegrity as o, buildReadAggregate as r, refusePackageCorruptionOnAggregate as s, appContractStandInFromIdentity as t };
|
|
246
246
|
|
|
247
|
-
//# sourceMappingURL=contract-space-aggregate-loader-
|
|
247
|
+
//# sourceMappingURL=contract-space-aggregate-loader-CirAEsM8.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contract-space-aggregate-loader-DvZwdkrr.mjs","names":[],"sources":["../src/utils/contract-space-aggregate-loader.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { PrismaNextConfig } from '@prisma-next/config/config-types';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { ControlExtensionDescriptor } from '@prisma-next/framework-components/control';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport type {\n ContractSpaceAggregate,\n DeclaredExtensionEntry,\n IntegrityQueryOptions,\n IntegrityViolation,\n} from '@prisma-next/migration-tools/aggregate';\nimport { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { CliStructuredError, errorUnexpected, mapMigrationToolsError } from './cli-errors';\nimport { readContractEnvelope, resolveContractPath } from './command-helpers';\nimport { toDeclaredExtensionsFromRaw } from './extension-pack-inputs';\n\nconst CONTRACT_SPACES_DOCS_URL = 'https://pris.ly/contract-spaces';\n\nfunction contractSpaceError5002(\n summary: string,\n options: {\n readonly why: string;\n readonly fix: string;\n readonly violations: readonly IntegrityViolation[];\n },\n): CliStructuredError {\n return new CliStructuredError('5002', summary, {\n domain: 'MIG',\n why: options.why,\n fix: options.fix,\n docsUrl: CONTRACT_SPACES_DOCS_URL,\n meta: { violations: options.violations },\n });\n}\n\n/**\n * Build the `5002` structured-error envelope for a contract-space\n * target mismatch. Shared between the declared-extension precheck (the\n * descriptor's configured target disagrees with the project target) and\n * the on-disk-contract check surfaced by `checkIntegrity`.\n */\nfunction targetMismatchError(\n spaceId: string,\n expected: string,\n actual: string,\n): CliStructuredError {\n return contractSpaceError5002(`Contract-space target mismatch for \"${spaceId}\"`, {\n why: `Space \"${spaceId}\" targets \"${actual}\" but the project's adapter targets \"${expected}\".`,\n fix: 'Update the extension descriptor to target the configured database, or change the project adapter.',\n violations: [{ kind: 'targetMismatch', spaceId, expected, actual }],\n });\n}\n\n/**\n * Human-readable detail for an integrity violation, used as the `why`\n * of the `integrityFailure` envelope. Mirrors the messages the prior\n * throw-on-load loader produced so downstream consumers see the same\n * text for the same on-disk state.\n */\nfunction describeIntegrityViolation(violation: IntegrityViolation): string {\n switch (violation.kind) {\n case 'hashMismatch':\n return `Migration \"${violation.dirName}\" stored hash \"${violation.stored}\" does not match computed hash \"${violation.computed}\".`;\n case 'providedInvariantsMismatch':\n return `Migration \"${violation.dirName}\" providedInvariants in migration.json disagrees with ops.json.`;\n case 'packageUnloadable':\n return `Migration \"${violation.dirName}\" could not be loaded: ${violation.detail}`;\n case 'sameSourceAndTarget':\n return `Migration \"${violation.dirName}\" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`;\n case 'headRefMissing':\n return `Head ref \\`refs/head.json\\` is missing for contract space \"${violation.spaceId}\".`;\n case 'headRefNotInGraph':\n return `Head ref ${violation.hash} for contract space \"${violation.spaceId}\" is not present in the migration graph.`;\n case 'refUnreadable':\n return `Ref \"${violation.refName}\" for contract space \"${violation.spaceId}\" is unreadable: ${violation.detail}`;\n case 'duplicateMigrationHash':\n return `Multiple migrations in space \"${violation.spaceId}\" share migrationHash \"${violation.migrationHash}\" (${violation.dirNames.join(', ')}).`;\n default: {\n const spaceId = 'spaceId' in violation ? violation.spaceId : '*';\n return `Integrity violation \"${violation.kind}\" for contract space \"${spaceId}\".`;\n }\n }\n}\n\n/**\n * Map the integrity violations `checkIntegrity` reports into a single\n * CLI structured-error envelope, preserving the error codes the prior\n * throw-on-load loader emitted: `5001` (layout drift, bundled) and\n * `5002` (target / disjointness / contract-validation / structural\n * integrity). Returns `null` when there is nothing to refuse on.\n *\n * Precedence reproduces the prior loader's first-failure ordering:\n * layout drift first (every offence bundled into one envelope), then\n * target mismatch, then disjointness, then a contract-validation\n * failure, then any remaining structural integrity violation.\n */\nexport function mapIntegrityViolations(\n violations: readonly IntegrityViolation[],\n): CliStructuredError | null {\n if (violations.length === 0) return null;\n\n const layout = violations.filter(\n (v): v is Extract<IntegrityViolation, { kind: 'orphanSpaceDir' | 'declaredButUnmigrated' }> =>\n v.kind === 'orphanSpaceDir' || v.kind === 'declaredButUnmigrated',\n );\n if (layout.length > 0) {\n const lines = layout.map((v) => `- [${v.kind}] ${v.spaceId}`);\n const summary =\n layout.length === 1\n ? 'Contract-space layout violation detected'\n : `Contract-space layout violations detected (${layout.length})`;\n return new CliStructuredError('5001', summary, {\n domain: 'MIG',\n why: `The on-disk \\`migrations/\\` directory and your \\`extensionPacks\\` declaration are not in agreement.\\n${lines.join('\\n')}`,\n fix: 'Declare the extension in `extensionPacks` and re-emit its contract-space artefacts, or remove the orphan `migrations/<space>` directory.',\n docsUrl: CONTRACT_SPACES_DOCS_URL,\n meta: { violations: layout },\n });\n }\n\n const targetMismatch = violations.find((v) => v.kind === 'targetMismatch');\n if (targetMismatch && targetMismatch.kind === 'targetMismatch') {\n return targetMismatchError(\n targetMismatch.spaceId,\n targetMismatch.expected,\n targetMismatch.actual,\n );\n }\n\n const disjointness = violations.find((v) => v.kind === 'disjointness');\n if (disjointness && disjointness.kind === 'disjointness') {\n return contractSpaceError5002(\n `Contract-space disjointness violation: storage element \"${disjointness.element}\" claimed by multiple spaces`,\n {\n why: `Spaces ${disjointness.claimedBy.map((s) => `\"${s}\"`).join(', ')} all claim the storage element \"${disjointness.element}\". Each storage element must be owned by exactly one contract space.`,\n fix: 'Update the conflicting contracts so each storage element is claimed by exactly one space.',\n violations: [disjointness],\n },\n );\n }\n\n const contractUnreadable = violations.find((v) => v.kind === 'contractUnreadable');\n if (contractUnreadable && contractUnreadable.kind === 'contractUnreadable') {\n return contractSpaceError5002(\n `Contract-space contract validation failed for \"${contractUnreadable.spaceId}\"`,\n {\n why: contractUnreadable.detail,\n fix: 'Re-emit the extension contract with `prisma-next contract emit`, or fix the extension pack descriptor producing the invalid contract.',\n violations: [contractUnreadable],\n },\n );\n }\n\n // Any remaining recoverable structural violation refuses as an\n // integrity failure, surfacing the first one's detail (every violation\n // is still computed; the gate just renders one envelope).\n const structural = violations[0]!;\n const spaceId = 'spaceId' in structural ? structural.spaceId : '*';\n return contractSpaceError5002(`Contract-space integrity failure for \"${spaceId}\"`, {\n why: describeIntegrityViolation(structural),\n fix: 'Re-emit the affected migration package(s) or restore the on-disk `migrations/` directory from version control.',\n violations: [structural],\n });\n}\n\n/**\n * Inputs needed to compose the aggregate loader at the CLI surface.\n *\n * Keeps the loader framework-neutral (no `Config` import) by accepting\n * already-resolved structural inputs: validated app contract, target\n * id, migrations root directory, and the set of extension descriptors.\n */\nexport interface BuildAggregateInputs<TFamilyId extends string, TTargetId extends string> {\n readonly targetId: TTargetId;\n readonly migrationsDir: string;\n readonly appContract: Contract;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly deserializeContract: (contractJson: unknown) => Contract;\n}\n\nfunction declaredExtensionsFromInputs(\n extensionPacks: BuildAggregateInputs<string, string>['extensionPacks'],\n): readonly DeclaredExtensionEntry[] {\n return toDeclaredExtensionsFromRaw(extensionPacks as ReadonlyArray<unknown>);\n}\n\n/**\n * Reject extension descriptors whose configured target disagrees with\n * the project target before any on-disk read.\n */\nexport function refuseDeclaredExtensionTargetMismatch<\n TFamilyId extends string,\n TTargetId extends string,\n>(inputs: BuildAggregateInputs<TFamilyId, TTargetId>): CliStructuredError | null {\n for (const declared of declaredExtensionsFromInputs(inputs.extensionPacks)) {\n if (declared.targetId !== inputs.targetId) {\n return targetMismatchError(declared.id, inputs.targetId, declared.targetId);\n }\n }\n return null;\n}\n\n/**\n * Load the tolerant {@link ContractSpaceAggregate} once at the CLI\n * surface. Construction never throws on disk content; callers query\n * {@link ContractSpaceAggregate.app} / extension facets instead of\n * re-reading `migrations/`.\n */\nexport async function loadContractSpaceAggregateForCli<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n inputs: BuildAggregateInputs<TFamilyId, TTargetId>,\n): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {\n const targetFailure = refuseDeclaredExtensionTargetMismatch(inputs);\n if (targetFailure) {\n return notOk(targetFailure);\n }\n\n const aggregate = await loadContractSpaceAggregate({\n migrationsDir: inputs.migrationsDir,\n deserializeContract: inputs.deserializeContract,\n appContract: inputs.appContract,\n });\n return ok(aggregate);\n}\n\n/**\n * Run `checkIntegrity` on a loaded aggregate and map violations into\n * the contract-space refusal envelope, or return `null` when the model\n * is acceptable for the requested check scope.\n */\nexport function refuseContractSpaceIntegrity(\n aggregate: ContractSpaceAggregate,\n options: IntegrityQueryOptions,\n): CliStructuredError | null {\n return mapIntegrityViolations(aggregate.checkIntegrity(options));\n}\n\nconst PACKAGE_CORRUPTION_KINDS = new Set<IntegrityViolation['kind']>([\n 'hashMismatch',\n 'providedInvariantsMismatch',\n 'packageUnloadable',\n]);\n\n/**\n * Reader-subset integrity refusal for `migration status`: package\n * corruptions only (`hashMismatch`, `providedInvariantsMismatch`,\n * `packageUnloadable`).\n */\nexport function refusePackageCorruptionOnAggregate(\n aggregate: ContractSpaceAggregate,\n): CliStructuredError | null {\n const corruption = aggregate.checkIntegrity().filter((v) => PACKAGE_CORRUPTION_KINDS.has(v.kind));\n return mapIntegrityViolations(corruption);\n}\n\n/**\n * Construct the tolerant {@link ContractSpaceAggregate} at the CLI\n * surface and apply the explicit integrity refusal.\n *\n * App-space migration packages are read from `migrations/<app>/` by the\n * loader itself; callers no longer thread them through.\n */\nexport async function buildContractSpaceAggregate<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n inputs: BuildAggregateInputs<TFamilyId, TTargetId>,\n): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {\n const declaredExtensions = declaredExtensionsFromInputs(inputs.extensionPacks);\n const loaded = await loadContractSpaceAggregateForCli(inputs);\n if (!loaded.ok) {\n return loaded;\n }\n const failure = refuseContractSpaceIntegrity(loaded.value, {\n declaredExtensions,\n checkContracts: true,\n });\n if (failure) {\n return notOk(failure);\n }\n return ok(loaded.value);\n}\n\n/**\n * Build a minimal app {@link Contract} carrying only the project's\n * contract-identity (`storage.storageHash` + `target` / `targetFamily`)\n * when the real `contract.json` is absent or undeserializable.\n *\n * `loadContractSpaceAggregate` requires an `appContract` to synthesise the\n * app space's head ref from its storage hash. Read commands query only that\n * hash and the target — never `models` — so an empty-`models` stand-in is\n * sufficient for them. It is *not* a valid contract for any consumer that\n * reads schema, which is why this is confined to the read-aggregate path.\n */\nexport function appContractStandInFromIdentity(args: {\n readonly contractHash: string;\n readonly targetId: string;\n readonly targetFamily: string;\n}): Contract {\n return blindCast<\n Contract,\n 'read-aggregate consumers query only storage.storageHash and target; empty models stand in for an unreadable contract.json'\n >({\n storage: { storageHash: args.contractHash },\n schemaVersion: '0.0.0',\n target: args.targetId,\n targetFamily: args.targetFamily,\n models: {},\n profileHash: EMPTY_CONTRACT_HASH,\n });\n}\n\nexport async function loadContractRawSafely(config: {\n contract?: { output?: string };\n}): Promise<unknown | null> {\n try {\n const path = resolveContractPath(config);\n const raw = await readFile(path, 'utf-8');\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\n/**\n * Tolerant {@link ContractSpaceAggregate} assembly for read-only CLI\n * commands. No integrity gate — callers query `aggregate.app` (or other\n * facets) without re-reading `migrations/`. When `contract.json` is absent\n * or undeserializable, the app contract falls back to an identity-only\n * stand-in ({@link appContractStandInFromIdentity}), so these commands\n * load without requiring a readable contract.\n */\nexport async function buildReadAggregate(\n config: PrismaNextConfig,\n options: { readonly migrationsDir: string },\n): Promise<\n Result<\n { readonly aggregate: ContractSpaceAggregate; readonly contractHash: string },\n CliStructuredError\n >\n> {\n let contractHash: string = EMPTY_CONTRACT_HASH;\n try {\n const envelope = await readContractEnvelope(config);\n contractHash = envelope.storageHash;\n } catch {\n // Contract unreadable — marker uses EMPTY_CONTRACT_HASH\n }\n\n try {\n const contractRawForAggregate = await loadContractRawSafely(config);\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n const deserializeContract = (json: unknown): Contract =>\n familyInstance.deserializeContract(json);\n let appContractForLoad: Contract = appContractStandInFromIdentity({\n contractHash,\n targetId: config.target.id,\n targetFamily: config.target.familyId,\n });\n if (contractRawForAggregate !== null) {\n try {\n appContractForLoad = deserializeContract(contractRawForAggregate);\n } catch {\n // Deserialization failed — identity-only stand-in fallback\n }\n }\n\n const loaded = await loadContractSpaceAggregateForCli({\n targetId: config.target.id,\n migrationsDir: options.migrationsDir,\n appContract: appContractForLoad,\n extensionPacks: config.extensionPacks ?? [],\n deserializeContract,\n });\n if (!loaded.ok) {\n return loaded;\n }\n return ok({ aggregate: loaded.value, contractHash });\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,\n }),\n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EA,eAAsB,sBAAsB,QAEhB;CAC1B,IAAI;EAEF,MAAM,MAAM,MAAM,SADL,oBAAoB,MACH,GAAG,OAAO;EACxC,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;AAUA,eAAsB,mBACpB,QACA,SAMA;CACA,IAAI,eAAuB;CAC3B,IAAI;EAEF,gBAAe,MADQ,qBAAqB,MAAM,GAC1B;CAC1B,QAAQ,CAER;CAEA,IAAI;EACF,MAAM,0BAA0B,MAAM,sBAAsB,MAAM;EAClE,MAAM,QAAQ,mBAAmB,MAAM;EACvC,MAAM,iBAAiB,OAAO,OAAO,OAAO,KAAK;EACjD,MAAM,uBAAuB,SAC3B,eAAe,oBAAoB,IAAI;EACzC,IAAI,qBAA+B,+BAA+B;GAChE;GACA,UAAU,OAAO,OAAO;GACxB,cAAc,OAAO,OAAO;EAC9B,CAAC;EACD,IAAI,4BAA4B,MAC9B,IAAI;GACF,qBAAqB,oBAAoB,uBAAuB;EAClE,QAAQ,CAER;EAGF,MAAM,SAAS,MAAM,iCAAiC;GACpD,UAAU,OAAO,OAAO;GACxB,eAAe,QAAQ;GACvB,aAAa;GACb,gBAAgB,OAAO,kBAAkB,CAAC;GAC1C;EACF,CAAC;EACD,IAAI,CAAC,OAAO,IACV,OAAO;EAET,OAAO,GAAG;GAAE,WAAW,OAAO;GAAO;EAAa,CAAC;CACrD,SAAS,OAAO;EACd,IAAI,oBAAoB,GAAG,KAAK,GAC9B,OAAO,MAAM,uBAAuB,KAAK,CAAC;EAE5C,OAAO,MACL,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,EACtE,KAAK,wCAAwC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,IACpG,CAAC,CACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"contract-space-aggregate-loader-CirAEsM8.mjs","names":[],"sources":["../src/utils/contract-space-aggregate-loader.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { PrismaNextConfig } from '@prisma-next/config/config-types';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { ControlExtensionDescriptor } from '@prisma-next/framework-components/control';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport type {\n ContractSpaceAggregate,\n DeclaredExtensionEntry,\n IntegrityQueryOptions,\n IntegrityViolation,\n} from '@prisma-next/migration-tools/aggregate';\nimport { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { CliStructuredError, errorUnexpected, mapMigrationToolsError } from './cli-errors';\nimport { readContractEnvelope, resolveContractPath } from './command-helpers';\nimport { toDeclaredExtensionsFromRaw } from './extension-pack-inputs';\n\nconst CONTRACT_SPACES_DOCS_URL = 'https://pris.ly/contract-spaces';\n\nfunction contractSpaceError5002(\n summary: string,\n options: {\n readonly why: string;\n readonly fix: string;\n readonly violations: readonly IntegrityViolation[];\n },\n): CliStructuredError {\n return new CliStructuredError('5002', summary, {\n domain: 'MIG',\n why: options.why,\n fix: options.fix,\n docsUrl: CONTRACT_SPACES_DOCS_URL,\n meta: { violations: options.violations },\n });\n}\n\n/**\n * Build the `5002` structured-error envelope for a contract-space\n * target mismatch. Shared between the declared-extension precheck (the\n * descriptor's configured target disagrees with the project target) and\n * the on-disk-contract check surfaced by `checkIntegrity`.\n */\nfunction targetMismatchError(\n spaceId: string,\n expected: string,\n actual: string,\n): CliStructuredError {\n return contractSpaceError5002(`Contract-space target mismatch for \"${spaceId}\"`, {\n why: `Space \"${spaceId}\" targets \"${actual}\" but the project's adapter targets \"${expected}\".`,\n fix: 'Update the extension descriptor to target the configured database, or change the project adapter.',\n violations: [{ kind: 'targetMismatch', spaceId, expected, actual }],\n });\n}\n\n/**\n * Human-readable detail for an integrity violation, used as the `why`\n * of the `integrityFailure` envelope. Mirrors the messages the prior\n * throw-on-load loader produced so downstream consumers see the same\n * text for the same on-disk state.\n */\nfunction describeIntegrityViolation(violation: IntegrityViolation): string {\n switch (violation.kind) {\n case 'hashMismatch':\n return `Migration \"${violation.dirName}\" stored hash \"${violation.stored}\" does not match computed hash \"${violation.computed}\".`;\n case 'providedInvariantsMismatch':\n return `Migration \"${violation.dirName}\" providedInvariants in migration.json disagrees with ops.json.`;\n case 'packageUnloadable':\n return `Migration \"${violation.dirName}\" could not be loaded: ${violation.detail}`;\n case 'sameSourceAndTarget':\n return `Migration \"${violation.dirName}\" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`;\n case 'headRefMissing':\n return `Head ref \\`refs/head.json\\` is missing for contract space \"${violation.spaceId}\".`;\n case 'headRefNotInGraph':\n return `Head ref ${violation.hash} for contract space \"${violation.spaceId}\" is not present in the migration graph.`;\n case 'refUnreadable':\n return `Ref \"${violation.refName}\" for contract space \"${violation.spaceId}\" is unreadable: ${violation.detail}`;\n case 'duplicateMigrationHash':\n return `Multiple migrations in space \"${violation.spaceId}\" share migrationHash \"${violation.migrationHash}\" (${violation.dirNames.join(', ')}).`;\n default: {\n const spaceId = 'spaceId' in violation ? violation.spaceId : '*';\n return `Integrity violation \"${violation.kind}\" for contract space \"${spaceId}\".`;\n }\n }\n}\n\n/**\n * Map the integrity violations `checkIntegrity` reports into a single\n * CLI structured-error envelope, preserving the error codes the prior\n * throw-on-load loader emitted: `5001` (layout drift, bundled) and\n * `5002` (target / disjointness / contract-validation / structural\n * integrity). Returns `null` when there is nothing to refuse on.\n *\n * Precedence reproduces the prior loader's first-failure ordering:\n * layout drift first (every offence bundled into one envelope), then\n * target mismatch, then disjointness, then a contract-validation\n * failure, then any remaining structural integrity violation.\n */\nexport function mapIntegrityViolations(\n violations: readonly IntegrityViolation[],\n): CliStructuredError | null {\n if (violations.length === 0) return null;\n\n const layout = violations.filter(\n (v): v is Extract<IntegrityViolation, { kind: 'orphanSpaceDir' | 'declaredButUnmigrated' }> =>\n v.kind === 'orphanSpaceDir' || v.kind === 'declaredButUnmigrated',\n );\n if (layout.length > 0) {\n const lines = layout.map((v) => `- [${v.kind}] ${v.spaceId}`);\n const summary =\n layout.length === 1\n ? 'Contract-space layout violation detected'\n : `Contract-space layout violations detected (${layout.length})`;\n return new CliStructuredError('5001', summary, {\n domain: 'MIG',\n why: `The on-disk \\`migrations/\\` directory and your \\`extensionPacks\\` declaration are not in agreement.\\n${lines.join('\\n')}`,\n fix: 'Declare the extension in `extensionPacks` and re-emit its contract-space artefacts, or remove the orphan `migrations/<space>` directory.',\n docsUrl: CONTRACT_SPACES_DOCS_URL,\n meta: { violations: layout },\n });\n }\n\n const targetMismatch = violations.find((v) => v.kind === 'targetMismatch');\n if (targetMismatch && targetMismatch.kind === 'targetMismatch') {\n return targetMismatchError(\n targetMismatch.spaceId,\n targetMismatch.expected,\n targetMismatch.actual,\n );\n }\n\n const disjointness = violations.find((v) => v.kind === 'disjointness');\n if (disjointness && disjointness.kind === 'disjointness') {\n return contractSpaceError5002(\n `Contract-space disjointness violation: storage element \"${disjointness.element}\" claimed by multiple spaces`,\n {\n why: `Spaces ${disjointness.claimedBy.map((s) => `\"${s}\"`).join(', ')} all claim the storage element \"${disjointness.element}\". Each storage element must be owned by exactly one contract space.`,\n fix: 'Update the conflicting contracts so each storage element is claimed by exactly one space.',\n violations: [disjointness],\n },\n );\n }\n\n const contractUnreadable = violations.find((v) => v.kind === 'contractUnreadable');\n if (contractUnreadable && contractUnreadable.kind === 'contractUnreadable') {\n return contractSpaceError5002(\n `Contract-space contract validation failed for \"${contractUnreadable.spaceId}\"`,\n {\n why: contractUnreadable.detail,\n fix: 'Re-emit the extension contract with `prisma-next contract emit`, or fix the extension pack descriptor producing the invalid contract.',\n violations: [contractUnreadable],\n },\n );\n }\n\n // Any remaining recoverable structural violation refuses as an\n // integrity failure, surfacing the first one's detail (every violation\n // is still computed; the gate just renders one envelope).\n const structural = violations[0]!;\n const spaceId = 'spaceId' in structural ? structural.spaceId : '*';\n return contractSpaceError5002(`Contract-space integrity failure for \"${spaceId}\"`, {\n why: describeIntegrityViolation(structural),\n fix: 'Re-emit the affected migration package(s) or restore the on-disk `migrations/` directory from version control.',\n violations: [structural],\n });\n}\n\n/**\n * Inputs needed to compose the aggregate loader at the CLI surface.\n *\n * Keeps the loader framework-neutral (no `Config` import) by accepting\n * already-resolved structural inputs: validated app contract, target\n * id, migrations root directory, and the set of extension descriptors.\n */\nexport interface BuildAggregateInputs<TFamilyId extends string, TTargetId extends string> {\n readonly targetId: TTargetId;\n readonly migrationsDir: string;\n readonly appContract: Contract;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly deserializeContract: (contractJson: unknown) => Contract;\n}\n\nfunction declaredExtensionsFromInputs(\n extensionPacks: BuildAggregateInputs<string, string>['extensionPacks'],\n): readonly DeclaredExtensionEntry[] {\n return toDeclaredExtensionsFromRaw(extensionPacks as ReadonlyArray<unknown>);\n}\n\n/**\n * Reject extension descriptors whose configured target disagrees with\n * the project target before any on-disk read.\n */\nexport function refuseDeclaredExtensionTargetMismatch<\n TFamilyId extends string,\n TTargetId extends string,\n>(inputs: BuildAggregateInputs<TFamilyId, TTargetId>): CliStructuredError | null {\n for (const declared of declaredExtensionsFromInputs(inputs.extensionPacks)) {\n if (declared.targetId !== inputs.targetId) {\n return targetMismatchError(declared.id, inputs.targetId, declared.targetId);\n }\n }\n return null;\n}\n\n/**\n * Load the tolerant {@link ContractSpaceAggregate} once at the CLI\n * surface. Construction never throws on disk content; callers query\n * {@link ContractSpaceAggregate.app} / extension facets instead of\n * re-reading `migrations/`.\n */\nexport async function loadContractSpaceAggregateForCli<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n inputs: BuildAggregateInputs<TFamilyId, TTargetId>,\n): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {\n const targetFailure = refuseDeclaredExtensionTargetMismatch(inputs);\n if (targetFailure) {\n return notOk(targetFailure);\n }\n\n const aggregate = await loadContractSpaceAggregate({\n migrationsDir: inputs.migrationsDir,\n deserializeContract: inputs.deserializeContract,\n appContract: inputs.appContract,\n });\n return ok(aggregate);\n}\n\n/**\n * Run `checkIntegrity` on a loaded aggregate and map violations into\n * the contract-space refusal envelope, or return `null` when the model\n * is acceptable for the requested check scope.\n */\nexport function refuseContractSpaceIntegrity(\n aggregate: ContractSpaceAggregate,\n options: IntegrityQueryOptions,\n): CliStructuredError | null {\n return mapIntegrityViolations(aggregate.checkIntegrity(options));\n}\n\nconst PACKAGE_CORRUPTION_KINDS = new Set<IntegrityViolation['kind']>([\n 'hashMismatch',\n 'providedInvariantsMismatch',\n 'packageUnloadable',\n]);\n\n/**\n * Reader-subset integrity refusal for `migration status`: package\n * corruptions only (`hashMismatch`, `providedInvariantsMismatch`,\n * `packageUnloadable`).\n */\nexport function refusePackageCorruptionOnAggregate(\n aggregate: ContractSpaceAggregate,\n): CliStructuredError | null {\n const corruption = aggregate.checkIntegrity().filter((v) => PACKAGE_CORRUPTION_KINDS.has(v.kind));\n return mapIntegrityViolations(corruption);\n}\n\n/**\n * Construct the tolerant {@link ContractSpaceAggregate} at the CLI\n * surface and apply the explicit integrity refusal.\n *\n * App-space migration packages are read from `migrations/<app>/` by the\n * loader itself; callers no longer thread them through.\n */\nexport async function buildContractSpaceAggregate<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n inputs: BuildAggregateInputs<TFamilyId, TTargetId>,\n): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {\n const declaredExtensions = declaredExtensionsFromInputs(inputs.extensionPacks);\n const loaded = await loadContractSpaceAggregateForCli(inputs);\n if (!loaded.ok) {\n return loaded;\n }\n const failure = refuseContractSpaceIntegrity(loaded.value, {\n declaredExtensions,\n checkContracts: true,\n });\n if (failure) {\n return notOk(failure);\n }\n return ok(loaded.value);\n}\n\n/**\n * Build a minimal app {@link Contract} carrying only the project's\n * contract-identity (`storage.storageHash` + `target` / `targetFamily`)\n * when the real `contract.json` is absent or undeserializable.\n *\n * `loadContractSpaceAggregate` requires an `appContract` to synthesise the\n * app space's head ref from its storage hash. Read commands query only that\n * hash and the target — never `models` — so an empty-`models` stand-in is\n * sufficient for them. It is *not* a valid contract for any consumer that\n * reads schema, which is why this is confined to the read-aggregate path.\n */\nexport function appContractStandInFromIdentity(args: {\n readonly contractHash: string;\n readonly targetId: string;\n readonly targetFamily: string;\n}): Contract {\n return blindCast<\n Contract,\n 'read-aggregate consumers query only storage.storageHash and target; empty models stand in for an unreadable contract.json'\n >({\n storage: { storageHash: args.contractHash },\n schemaVersion: '0.0.0',\n target: args.targetId,\n targetFamily: args.targetFamily,\n models: {},\n profileHash: EMPTY_CONTRACT_HASH,\n });\n}\n\nexport async function loadContractRawSafely(config: {\n contract?: { output?: string };\n}): Promise<unknown | null> {\n try {\n const path = resolveContractPath(config);\n const raw = await readFile(path, 'utf-8');\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\n/**\n * Tolerant {@link ContractSpaceAggregate} assembly for read-only CLI\n * commands. No integrity gate — callers query `aggregate.app` (or other\n * facets) without re-reading `migrations/`. When `contract.json` is absent\n * or undeserializable, the app contract falls back to an identity-only\n * stand-in ({@link appContractStandInFromIdentity}), so these commands\n * load without requiring a readable contract.\n */\nexport async function buildReadAggregate(\n config: PrismaNextConfig,\n options: { readonly migrationsDir: string },\n): Promise<\n Result<\n { readonly aggregate: ContractSpaceAggregate; readonly contractHash: string },\n CliStructuredError\n >\n> {\n let contractHash: string = EMPTY_CONTRACT_HASH;\n try {\n const envelope = await readContractEnvelope(config);\n contractHash = envelope.storageHash;\n } catch {\n // Contract unreadable — marker uses EMPTY_CONTRACT_HASH\n }\n\n try {\n const contractRawForAggregate = await loadContractRawSafely(config);\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n const deserializeContract = (json: unknown): Contract =>\n familyInstance.deserializeContract(json);\n let appContractForLoad: Contract = appContractStandInFromIdentity({\n contractHash,\n targetId: config.target.id,\n targetFamily: config.target.familyId,\n });\n if (contractRawForAggregate !== null) {\n try {\n appContractForLoad = deserializeContract(contractRawForAggregate);\n } catch {\n // Deserialization failed — identity-only stand-in fallback\n }\n }\n\n const loaded = await loadContractSpaceAggregateForCli({\n targetId: config.target.id,\n migrationsDir: options.migrationsDir,\n appContract: appContractForLoad,\n extensionPacks: config.extensionPacks ?? [],\n deserializeContract,\n });\n if (!loaded.ok) {\n return loaded;\n }\n return ok({ aggregate: loaded.value, contractHash });\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,2BAA2B;AAEjC,SAAS,uBACP,SACA,SAKoB;CACpB,OAAO,IAAI,mBAAmB,QAAQ,SAAS;EAC7C,QAAQ;EACR,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,SAAS;EACT,MAAM,EAAE,YAAY,QAAQ,WAAW;CACzC,CAAC;AACH;;;;;;;AAQA,SAAS,oBACP,SACA,UACA,QACoB;CACpB,OAAO,uBAAuB,uCAAuC,QAAQ,IAAI;EAC/E,KAAK,UAAU,QAAQ,aAAa,OAAO,uCAAuC,SAAS;EAC3F,KAAK;EACL,YAAY,CAAC;GAAE,MAAM;GAAkB;GAAS;GAAU;EAAO,CAAC;CACpE,CAAC;AACH;;;;;;;AAQA,SAAS,2BAA2B,WAAuC;CACzE,QAAQ,UAAU,MAAlB;EACE,KAAK,gBACH,OAAO,cAAc,UAAU,QAAQ,iBAAiB,UAAU,OAAO,kCAAkC,UAAU,SAAS;EAChI,KAAK,8BACH,OAAO,cAAc,UAAU,QAAQ;EACzC,KAAK,qBACH,OAAO,cAAc,UAAU,QAAQ,yBAAyB,UAAU;EAC5E,KAAK,uBACH,OAAO,cAAc,UAAU,QA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,kBAAkB,CAAC;GAC1C;EACF,CAAC;EACD,IAAI,CAAC,OAAO,IACV,OAAO;EAET,OAAO,GAAG;GAAE,WAAW,OAAO;GAAO;EAAa,CAAC;CACrD,SAAS,OAAO;EACd,IAAI,oBAAoB,GAAG,KAAK,GAC9B,OAAO,MAAM,uBAAuB,KAAK,CAAC;EAE5C,OAAO,MACL,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,EACtE,KAAK,wCAAwC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,IACpG,CAAC,CACH;CACF;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { B as errorHashMismatch, E as formatStyledHeader, F as errorContractValidationFailed, I as errorDatabaseConnectionRequired, R as errorDriverRequired, U as errorMarkerMissing, Z as errorRuntime, _ as parseGlobalFlagsOrExit, b as handleResult, i as maskConnectionUrl, j as CliStructuredError, l as setCommandDescriptions, nt as errorUnexpected, o as resolveContractPath, s as resolveMigrationPaths, t as addGlobalOptions, tt as errorTargetMismatch, u as setCommandExamples, v as createTerminalUI, z as errorFileNotFound } from "./command-helpers-Cmdqyhz9.mjs";
|
|
3
3
|
import { t as createProgressAdapter } from "./progress-adapter-C644QK8l.mjs";
|
|
4
|
-
import { a as ContractValidationError, t as createControlClient } from "./client-
|
|
5
|
-
import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "./verify-
|
|
4
|
+
import { a as ContractValidationError, t as createControlClient } from "./client-Cdxcme1x.mjs";
|
|
5
|
+
import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "./verify-CreSJ1Mz.mjs";
|
|
6
6
|
import { Command } from "commander";
|
|
7
7
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
8
8
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -398,4 +398,4 @@ function createDbVerifyCommand() {
|
|
|
398
398
|
//#endregion
|
|
399
399
|
export { createDbVerifyCommand as t };
|
|
400
400
|
|
|
401
|
-
//# sourceMappingURL=db-verify-
|
|
401
|
+
//# sourceMappingURL=db-verify-BSA1a_W_.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db-verify-BeRHwN8M.mjs","names":[],"sources":["../src/utils/combine-schema-results.ts","../src/commands/db-verify.ts"],"sourcesContent":["import type { VerifyDatabaseSchemaResult } from '@prisma-next/framework-components/control';\n\n/**\n * Collapse the aggregate verifier's per-space schema results into a\n * single {@link VerifyDatabaseSchemaResult} for the existing CLI\n * display surface. Concatenates issues across members; sums counts;\n * uses the app member's result as the structural envelope (storage\n * hash, target).\n *\n * **Summary policy.** Preserve the per-family phrasing whenever the\n * combined `ok` flag agrees with the app member's `ok` flag — this is\n * the common case (single-family deployments, single-app deployments)\n * and the family's \"satisfies / does not satisfy contract\" phrasing\n * stays user-visible. When the app passes but an extension fails (or\n * vice versa) the app's summary contradicts the envelope, so fall back\n * to the first failing member's summary. This keeps family phrasing\n * intact and the envelope internally consistent (`ok: false` ↔ failure\n * summary).\n */\nexport function combineSchemaResults(\n perSpace: ReadonlyMap<string, VerifyDatabaseSchemaResult>,\n appSpaceId: string,\n strict: boolean,\n): VerifyDatabaseSchemaResult {\n const appResult = perSpace.get(appSpaceId) ?? perSpace.values().next().value;\n if (appResult === undefined) {\n throw new Error('Aggregate verifier returned no schema results — this is a wiring bug.');\n }\n\n let okAll = true;\n let firstFailure: VerifyDatabaseSchemaResult | undefined;\n let issues: VerifyDatabaseSchemaResult['schema']['issues'] = [];\n const counts = { pass: 0, warn: 0, fail: 0, totalNodes: 0 };\n const childRoots: Array<VerifyDatabaseSchemaResult['schema']['root']> = [];\n for (const [, result] of perSpace) {\n if (!result.ok) {\n okAll = false;\n if (firstFailure === undefined) firstFailure = result;\n }\n issues = [...issues, ...result.schema.issues];\n counts.pass += result.schema.counts.pass;\n counts.warn += result.schema.counts.warn;\n counts.fail += result.schema.counts.fail;\n counts.totalNodes += result.schema.counts.totalNodes;\n childRoots.push(result.schema.root);\n }\n\n // When `okAll !== appResult.ok`, exactly one shape is reachable: app passes\n // (`appResult.ok === true`) and at least one other member failed\n // (`okAll === false`). In that shape the failure was assigned to\n // `firstFailure` during iteration, so non-null assertion is safe. The mirror\n // shape (app fails while every member passes) is impossible because\n // `appResult` either *is* a member of `perSpace` or is the first iterator\n // value; either way its `ok` flag participates in `okAll`.\n const summary =\n okAll === appResult.ok\n ? appResult.summary\n : (firstFailure as VerifyDatabaseSchemaResult).summary;\n\n return {\n ok: okAll,\n ...(okAll ? {} : { code: appResult.code ?? 'PN-RUN-3010' }),\n summary,\n contract: appResult.contract,\n target: appResult.target,\n schema: {\n issues,\n root: {\n status: okAll ? 'pass' : 'fail',\n kind: 'aggregate',\n name: 'aggregate',\n contractPath: '',\n code: 'AGGREGATE',\n message: okAll ? 'Aggregate schema matches' : 'Aggregate schema mismatch',\n expected: undefined,\n actual: undefined,\n children: childRoots,\n },\n counts,\n },\n meta: { strict },\n timings: { total: 0 },\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n VerifyDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport {\n createControlStack,\n VERIFY_CODE_HASH_MISMATCH,\n VERIFY_CODE_MARKER_MISSING,\n VERIFY_CODE_TARGET_MISMATCH,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport { ContractValidationError } from '../control-api/errors';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorHashMismatch,\n errorMarkerMissing,\n errorRuntime,\n errorTargetMismatch,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { combineSchemaResults } from '../utils/combine-schema-results';\nimport {\n addGlobalOptions,\n maskConnectionUrl,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport {\n type DbVerifyCommandSuccessResult,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatVerifyJson,\n formatVerifyOutput,\n} from '../utils/formatters/verify';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface DbVerifyOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly markerOnly?: boolean;\n readonly schemaOnly?: boolean;\n readonly strict?: boolean;\n}\n\ntype DbVerifyMode = 'full' | 'marker-only' | 'schema-only';\n\n/**\n * Maps a VerifyDatabaseResult failure to a CliStructuredError.\n */\nfunction mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {\n if (!verifyResult.ok && verifyResult.code) {\n if (verifyResult.code === VERIFY_CODE_MARKER_MISSING) {\n return errorMarkerMissing();\n }\n if (verifyResult.code === VERIFY_CODE_HASH_MISMATCH) {\n const storageMatch = verifyResult.marker?.storageHash === verifyResult.contract.storageHash;\n const profileMatch =\n !verifyResult.contract.profileHash ||\n verifyResult.marker?.profileHash === verifyResult.contract.profileHash;\n\n if (!storageMatch) {\n return errorHashMismatch({\n why: 'Contract storageHash does not match database marker',\n expected: verifyResult.contract.storageHash,\n ...ifDefined('actual', verifyResult.marker?.storageHash),\n });\n }\n\n return errorHashMismatch({\n why: profileMatch\n ? 'Contract hash does not match database marker'\n : 'Contract profileHash does not match database marker',\n ...ifDefined('expected', verifyResult.contract.profileHash),\n ...ifDefined('actual', verifyResult.marker?.profileHash),\n });\n }\n if (verifyResult.code === VERIFY_CODE_TARGET_MISMATCH) {\n return errorTargetMismatch(\n verifyResult.target.expected,\n verifyResult.target.actual ?? 'unknown',\n );\n }\n // Unknown code - fall through to runtime error\n }\n return errorRuntime(verifyResult.summary);\n}\n\ntype DbVerifyFailure = CliStructuredError | VerifyDatabaseSchemaResult;\n\nfunction errorInvalidVerifyMode(options: {\n readonly why: string;\n readonly fix: string;\n}): CliStructuredError {\n return new CliStructuredError('4012', 'Invalid verify mode', {\n domain: 'CLI',\n why: options.why,\n fix: options.fix,\n docsUrl: 'https://pris.ly/db-verify',\n });\n}\n\nfunction resolveDbVerifyMode(options: DbVerifyOptions): Result<DbVerifyMode, CliStructuredError> {\n if (options.markerOnly && options.schemaOnly) {\n return notOk(\n errorInvalidVerifyMode({\n why: '`--marker-only` and `--schema-only` cannot be used together',\n fix: 'Choose one mode: omit both to check the marker and schema, use `--marker-only` to check only the marker, or use `--schema-only` to check only the live schema.',\n }),\n );\n }\n\n if (options.markerOnly && options.strict) {\n return notOk(\n errorInvalidVerifyMode({\n why: '`--strict` requires schema verification, but `--marker-only` skips it',\n fix: 'Remove `--strict`, or use `db verify` / `db verify --schema-only` when you want to check the live schema in strict mode.',\n }),\n );\n }\n\n if (options.schemaOnly) {\n return ok('schema-only');\n }\n\n if (options.markerOnly) {\n return ok('marker-only');\n }\n\n return ok('full');\n}\n\nfunction formatDbVerifyModeLabel(mode: DbVerifyMode, strict: boolean): string {\n if (mode === 'marker-only') {\n return 'marker only';\n }\n\n if (mode === 'schema-only') {\n return `schema only (${strict ? 'strict' : 'tolerant'})`;\n }\n\n return `full (marker + schema, ${strict ? 'strict' : 'tolerant'})`;\n}\n\nfunction formatDbVerifyInvocation(mode: DbVerifyMode, strict: boolean): string {\n const args = ['db verify'];\n\n if (mode === 'marker-only') {\n args.push('--marker-only');\n }\n\n if (mode === 'schema-only') {\n args.push('--schema-only');\n }\n\n if (strict) {\n args.push('--strict');\n }\n\n return args.join(' ');\n}\n\nfunction createDbVerifyConnectionRequiredError(options: {\n readonly configPath: string;\n readonly mode: DbVerifyMode;\n readonly strict: boolean;\n}): CliStructuredError {\n const invocation = formatDbVerifyInvocation(options.mode, options.strict);\n return errorDatabaseConnectionRequired({\n why: `Database connection is required for ${invocation} (set db.connection in ${options.configPath}, or pass --db <url>)`,\n retryCommand: `prisma-next ${invocation} --db <url>`,\n });\n}\n\nfunction renderVerifyHeader(\n paths: { configPath: string; contractPath: string },\n options: DbVerifyOptions,\n mode: DbVerifyMode,\n flags: GlobalFlags,\n ui: TerminalUI,\n): void {\n if (flags.json || flags.quiet) return;\n\n const description =\n mode === 'schema-only'\n ? 'Check whether the live database schema matches your contract'\n : mode === 'marker-only'\n ? 'Check whether the database marker matches your contract'\n : 'Check whether the database marker and live schema match your contract';\n\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: paths.configPath },\n { label: 'contract', value: paths.contractPath },\n { label: 'mode', value: formatDbVerifyModeLabel(mode, options.strict ?? false) },\n ];\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n }\n\n ui.stderr(\n formatStyledHeader({\n command: 'db verify',\n description,\n url: 'https://pris.ly/db-verify',\n details,\n flags,\n }),\n );\n}\n\nasync function resolveVerifyPaths(options: DbVerifyOptions) {\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 = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n return { config, configPath, contractPathAbsolute, contractPath };\n}\n\ntype VerifyPaths = Awaited<ReturnType<typeof resolveVerifyPaths>>;\n\ninterface VerifySetup extends VerifyPaths {\n readonly contractJson: Contract;\n readonly dbConnection: string;\n}\n\nasync function resolveVerifySetup(\n paths: VerifyPaths,\n options: DbVerifyOptions,\n mode: DbVerifyMode,\n): Promise<Result<VerifySetup, CliStructuredError>> {\n const { config, configPath, contractPathAbsolute, contractPath } = paths;\n\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 // Cross the family `deserializeContract` seam at the read site, just\n // like every other CLI on-disk read (TML-2536). The downstream\n // `dbVerify` op accepts the hydrated `Contract` directly and no\n // longer re-deserializes.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n\n let contractJson: Contract;\n try {\n contractJson = familyInstance.deserializeContract(JSON.parse(contractJsonContent) as unknown);\n } catch (error) {\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\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 const dbConnection = options.db ?? config.db?.connection;\n if (typeof dbConnection !== 'string' || dbConnection.length === 0) {\n return notOk(\n createDbVerifyConnectionRequiredError({\n configPath,\n mode,\n strict: options.strict ?? false,\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: `Config.driver is required for ${formatDbVerifyInvocation(mode, options.strict ?? false)}`,\n }),\n );\n }\n\n return ok({ ...paths, contractJson, dbConnection });\n}\n\nfunction createVerifyClient(setup: VerifySetup) {\n return createControlClient({\n family: setup.config.family,\n target: setup.config.target,\n adapter: setup.config.adapter,\n driver: setup.config.driver!,\n extensionPacks: setup.config.extensionPacks ?? [],\n });\n}\n\nfunction wrapVerifyError(\n error: unknown,\n contractPathAbsolute: string,\n modeLabel: string,\n): Result<never, CliStructuredError> {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during ${modeLabel}: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n}\n\n/**\n * Executes the db verify command and returns a structured Result.\n */\nasync function executeDbVerifyCommand(\n options: DbVerifyOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n mode: Extract<DbVerifyMode, 'full' | 'marker-only'>,\n): Promise<Result<DbVerifyCommandSuccessResult, DbVerifyFailure>> {\n const startTime = Date.now();\n const paths = await resolveVerifyPaths(options);\n renderVerifyHeader(paths, options, mode, flags, ui);\n\n const setupResult = await resolveVerifySetup(paths, options, mode);\n if (!setupResult.ok) return setupResult;\n const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;\n const { migrationsDir } = resolveMigrationPaths(options.config, setupResult.value.config);\n\n const client = createVerifyClient(setupResult.value);\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n // Single-contract marker verification preserved for the existing\n // marker / target / hash failure surface (`PN-RUN-3001/3002/3003`).\n // The aggregate verifier (run below for the per-space marker /\n // schema checks) does not duplicate this: it concerns itself with\n // marker-vs-on-disk and orphan-marker drift, not the\n // hash-mismatch-against-the-app-contract lane that today's\n // `client.verify` covers.\n const verifyResult = await client.verify({\n contract: contractJson,\n connection: dbConnection,\n onProgress,\n });\n\n if (!verifyResult.ok) {\n return notOk(mapVerifyFailure(verifyResult));\n }\n\n // Aggregate verifier (loader → verifier pipeline). Runs the layout\n // precheck, marker-aware per-space verifier, and (full mode only)\n // per-space pre-projected schema verification (closes F23).\n const aggregateResult = await client.dbVerify({\n contract: contractJson,\n migrationsDir,\n strict: options.strict ?? false,\n skipSchema: mode === 'marker-only',\n skipMarker: false,\n onProgress,\n });\n if (!aggregateResult.ok) return notOk(aggregateResult.failure);\n\n if (mode === 'marker-only') {\n return ok({\n ok: true,\n mode: 'marker-only',\n summary: 'Database marker matches contract',\n contract: verifyResult.contract,\n marker: verifyResult.marker,\n target: verifyResult.target,\n ...ifDefined('missingCodecs', verifyResult.missingCodecs),\n ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),\n warning: 'Schema verification skipped because --marker-only was provided',\n meta: {\n ...(verifyResult.meta ?? {}),\n schemaVerification: 'skipped',\n },\n timings: { total: Date.now() - startTime },\n });\n }\n\n const combined = combineSchemaResults(\n aggregateResult.value.schemaResults,\n aggregateResult.value.appSpaceId,\n options.strict ?? false,\n );\n if (!combined.ok) {\n return notOk(combined);\n }\n\n return ok({\n ok: true,\n mode: 'full',\n summary: 'Database marker and schema match contract',\n contract: verifyResult.contract,\n marker: verifyResult.marker,\n target: verifyResult.target,\n ...ifDefined('missingCodecs', verifyResult.missingCodecs),\n ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),\n schema: {\n summary: combined.summary,\n counts: combined.schema.counts,\n strict: combined.meta?.strict ?? false,\n },\n meta: {\n ...(verifyResult.meta ?? {}),\n schemaVerification: 'performed',\n },\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n return wrapVerifyError(error, contractPathAbsolute, 'db verify');\n } finally {\n await client.close();\n }\n}\n\nasync function executeDbSchemaOnlyVerifyCommand(\n options: DbVerifyOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<VerifyDatabaseSchemaResult, CliStructuredError>> {\n const paths = await resolveVerifyPaths(options);\n renderVerifyHeader(paths, options, 'schema-only', flags, ui);\n\n const setupResult = await resolveVerifySetup(paths, options, 'schema-only');\n if (!setupResult.ok) return setupResult;\n const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;\n const { migrationsDir } = resolveMigrationPaths(options.config, setupResult.value.config);\n\n const client = createVerifyClient(setupResult.value);\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n await client.connect(dbConnection);\n const aggregateResult = await client.dbVerify({\n contract: contractJson,\n migrationsDir,\n strict: options.strict ?? false,\n skipSchema: false,\n skipMarker: true,\n onProgress,\n });\n if (!aggregateResult.ok) return notOk(aggregateResult.failure);\n\n return ok(\n combineSchemaResults(\n aggregateResult.value.schemaResults,\n aggregateResult.value.appSpaceId,\n options.strict ?? false,\n ),\n );\n } catch (error) {\n return wrapVerifyError(error, contractPathAbsolute, 'db verify --schema-only');\n } finally {\n await client.close();\n }\n}\n\nexport function createDbVerifyCommand(): Command {\n const command = new Command('verify');\n setCommandDescriptions(\n command,\n 'Check whether the database marker and live schema match your contract',\n 'Verifies the database marker first, then checks the database schema matches your contract.\\n' +\n 'Use `--marker-only` for marker-only verification, `--schema-only` to skip marker checks and\\n' +\n 'inspect only the live schema, and `--strict` to fail if the database includes elements\\n' +\n 'not present in the contract.',\n );\n setCommandExamples(command, [\n 'prisma-next db verify --db $DATABASE_URL',\n 'prisma-next db verify --db $DATABASE_URL --strict',\n 'prisma-next db verify --db $DATABASE_URL --schema-only',\n 'prisma-next db verify --db $DATABASE_URL --schema-only --strict',\n 'prisma-next db verify --db $DATABASE_URL --marker-only',\n 'prisma-next db verify --db $DATABASE_URL --json',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--marker-only', 'Skip schema verification and only check the database marker')\n .option(\n '--schema-only',\n 'Skip marker verification and only check whether the live schema satisfies the contract',\n )\n .option(\n '--strict',\n 'Strict mode: schema elements not present in the contract are considered an error',\n false,\n )\n .action(async (options: DbVerifyOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n\n const modeResult = resolveDbVerifyMode(options);\n if (!modeResult.ok) {\n const exitCode = handleResult(modeResult as Result<never, CliStructuredError>, flags, ui);\n process.exit(exitCode);\n }\n\n const mode = modeResult.value;\n\n if (mode === 'schema-only') {\n const result = await executeDbSchemaOnlyVerifyCommand(options, flags, ui);\n const exitCode = handleResult(result, flags, ui, (schemaVerifyResult) => {\n if (flags.json) {\n ui.output(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n ui.log(output);\n }\n }\n });\n\n if (result.ok && !result.value.ok) {\n process.exit(1);\n }\n\n process.exit(exitCode);\n }\n\n const result = await executeDbVerifyCommand(options, flags, ui, mode);\n\n if (result.ok) {\n if (flags.json) {\n ui.output(formatVerifyJson(result.value));\n } else {\n const output = formatVerifyOutput(result.value, flags);\n if (output) {\n ui.log(output);\n }\n }\n process.exit(0);\n }\n\n if (CliStructuredError.is(result.failure)) {\n const exitCode = handleResult(result as Result<never, CliStructuredError>, flags, ui);\n process.exit(exitCode);\n }\n\n if (flags.json) {\n ui.output(formatSchemaVerifyJson(result.failure));\n } else {\n // Always show schema-drift failures, even in quiet mode — exiting 1 without\n // diagnostics is unhelpful.\n const output = formatSchemaVerifyOutput(result.failure, { ...flags, quiet: false });\n if (output) {\n ui.log(output);\n }\n }\n process.exit(1);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBACd,UACA,YACA,QAC4B;CAC5B,MAAM,YAAY,SAAS,IAAI,UAAU,KAAK,SAAS,OAAO,EAAE,KAAK,EAAE;CACvE,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,MAAM,uEAAuE;CAGzF,IAAI,QAAQ;CACZ,IAAI;CACJ,IAAI,SAAyD,CAAC;CAC9D,MAAM,SAAS;EAAE,MAAM;EAAG,MAAM;EAAG,MAAM;EAAG,YAAY;CAAE;CAC1D,MAAM,aAAkE,CAAC;CACzE,KAAK,MAAM,GAAG,WAAW,UAAU;EACjC,IAAI,CAAC,OAAO,IAAI;GACd,QAAQ;GACR,IAAI,iBAAi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AAM,uBAAuB,SAAS,OAAO,IAAI,IAAI;EAEpE,IAAI,OAAO,IAAI;GACb,IAAI,MAAM,MACR,GAAG,OAAO,iBAAiB,OAAO,KAAK,CAAC;QACnC;IACL,MAAM,SAAS,mBAAmB,OAAO,OAAO,KAAK;IACrD,IAAI,QACF,GAAG,IAAI,MAAM;GAEjB;GACA,QAAQ,KAAK,CAAC;EAChB;EAEA,IAAI,mBAAmB,GAAG,OAAO,OAAO,GAAG;GACzC,MAAM,WAAW,aAAa,QAA6C,OAAO,EAAE;GACpF,QAAQ,KAAK,QAAQ;EACvB;EAEA,IAAI,MAAM,MACR,GAAG,OAAO,uBAAuB,OAAO,OAAO,CAAC;OAC3C;GAGL,MAAM,SAAS,yBAAyB,OAAO,SAAS;IAAE,GAAG;IAAO,OAAO;GAAM,CAAC;GAClF,IAAI,QACF,GAAG,IAAI,MAAM;EAEjB;EACA,QAAQ,KAAK,CAAC;CAChB,CAAC;CAEH,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"db-verify-BSA1a_W_.mjs","names":[],"sources":["../src/utils/combine-schema-results.ts","../src/commands/db-verify.ts"],"sourcesContent":["import type { VerifyDatabaseSchemaResult } from '@prisma-next/framework-components/control';\n\n/**\n * Collapse the aggregate verifier's per-space schema results into a\n * single {@link VerifyDatabaseSchemaResult} for the existing CLI\n * display surface. Concatenates issues across members; sums counts;\n * uses the app member's result as the structural envelope (storage\n * hash, target).\n *\n * **Summary policy.** Preserve the per-family phrasing whenever the\n * combined `ok` flag agrees with the app member's `ok` flag — this is\n * the common case (single-family deployments, single-app deployments)\n * and the family's \"satisfies / does not satisfy contract\" phrasing\n * stays user-visible. When the app passes but an extension fails (or\n * vice versa) the app's summary contradicts the envelope, so fall back\n * to the first failing member's summary. This keeps family phrasing\n * intact and the envelope internally consistent (`ok: false` ↔ failure\n * summary).\n */\nexport function combineSchemaResults(\n perSpace: ReadonlyMap<string, VerifyDatabaseSchemaResult>,\n appSpaceId: string,\n strict: boolean,\n): VerifyDatabaseSchemaResult {\n const appResult = perSpace.get(appSpaceId) ?? perSpace.values().next().value;\n if (appResult === undefined) {\n throw new Error('Aggregate verifier returned no schema results — this is a wiring bug.');\n }\n\n let okAll = true;\n let firstFailure: VerifyDatabaseSchemaResult | undefined;\n let issues: VerifyDatabaseSchemaResult['schema']['issues'] = [];\n const counts = { pass: 0, warn: 0, fail: 0, totalNodes: 0 };\n const childRoots: Array<VerifyDatabaseSchemaResult['schema']['root']> = [];\n for (const [, result] of perSpace) {\n if (!result.ok) {\n okAll = false;\n if (firstFailure === undefined) firstFailure = result;\n }\n issues = [...issues, ...result.schema.issues];\n counts.pass += result.schema.counts.pass;\n counts.warn += result.schema.counts.warn;\n counts.fail += result.schema.counts.fail;\n counts.totalNodes += result.schema.counts.totalNodes;\n childRoots.push(result.schema.root);\n }\n\n // When `okAll !== appResult.ok`, exactly one shape is reachable: app passes\n // (`appResult.ok === true`) and at least one other member failed\n // (`okAll === false`). In that shape the failure was assigned to\n // `firstFailure` during iteration, so non-null assertion is safe. The mirror\n // shape (app fails while every member passes) is impossible because\n // `appResult` either *is* a member of `perSpace` or is the first iterator\n // value; either way its `ok` flag participates in `okAll`.\n const summary =\n okAll === appResult.ok\n ? appResult.summary\n : (firstFailure as VerifyDatabaseSchemaResult).summary;\n\n return {\n ok: okAll,\n ...(okAll ? {} : { code: appResult.code ?? 'PN-RUN-3010' }),\n summary,\n contract: appResult.contract,\n target: appResult.target,\n schema: {\n issues,\n root: {\n status: okAll ? 'pass' : 'fail',\n kind: 'aggregate',\n name: 'aggregate',\n contractPath: '',\n code: 'AGGREGATE',\n message: okAll ? 'Aggregate schema matches' : 'Aggregate schema mismatch',\n expected: undefined,\n actual: undefined,\n children: childRoots,\n },\n counts,\n },\n meta: { strict },\n timings: { total: 0 },\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n VerifyDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport {\n createControlStack,\n VERIFY_CODE_HASH_MISMATCH,\n VERIFY_CODE_MARKER_MISSING,\n VERIFY_CODE_TARGET_MISMATCH,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport { ContractValidationError } from '../control-api/errors';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorHashMismatch,\n errorMarkerMissing,\n errorRuntime,\n errorTargetMismatch,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { combineSchemaResults } from '../utils/combine-schema-results';\nimport {\n addGlobalOptions,\n maskConnectionUrl,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport {\n type DbVerifyCommandSuccessResult,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatVerifyJson,\n formatVerifyOutput,\n} from '../utils/formatters/verify';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface DbVerifyOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly markerOnly?: boolean;\n readonly schemaOnly?: boolean;\n readonly strict?: boolean;\n}\n\ntype DbVerifyMode = 'full' | 'marker-only' | 'schema-only';\n\n/**\n * Maps a VerifyDatabaseResult failure to a CliStructuredError.\n */\nfunction mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {\n if (!verifyResult.ok && verifyResult.code) {\n if (verifyResult.code === VERIFY_CODE_MARKER_MISSING) {\n return errorMarkerMissing();\n }\n if (verifyResult.code === VERIFY_CODE_HASH_MISMATCH) {\n const storageMatch = verifyResult.marker?.storageHash === verifyResult.contract.storageHash;\n const profileMatch =\n !verifyResult.contract.profileHash ||\n verifyResult.marker?.profileHash === verifyResult.contract.profileHash;\n\n if (!storageMatch) {\n return errorHashMismatch({\n why: 'Contract storageHash does not match database marker',\n expected: verifyResult.contract.storageHash,\n ...ifDefined('actual', verifyResult.marker?.storageHash),\n });\n }\n\n return errorHashMismatch({\n why: profileMatch\n ? 'Contract hash does not match database marker'\n : 'Contract profileHash does not match database marker',\n ...ifDefined('expected', verifyResult.contract.profileHash),\n ...ifDefined('actual', verifyResult.marker?.profileHash),\n });\n }\n if (verifyResult.code === VERIFY_CODE_TARGET_MISMATCH) {\n return errorTargetMismatch(\n verifyResult.target.expected,\n verifyResult.target.actual ?? 'unknown',\n );\n }\n // Unknown code - fall through to runtime error\n }\n return errorRuntime(verifyResult.summary);\n}\n\ntype DbVerifyFailure = CliStructuredError | VerifyDatabaseSchemaResult;\n\nfunction errorInvalidVerifyMode(options: {\n readonly why: string;\n readonly fix: string;\n}): CliStructuredError {\n return new CliStructuredError('4012', 'Invalid verify mode', {\n domain: 'CLI',\n why: options.why,\n fix: options.fix,\n docsUrl: 'https://pris.ly/db-verify',\n });\n}\n\nfunction resolveDbVerifyMode(options: DbVerifyOptions): Result<DbVerifyMode, CliStructuredError> {\n if (options.markerOnly && options.schemaOnly) {\n return notOk(\n errorInvalidVerifyMode({\n why: '`--marker-only` and `--schema-only` cannot be used together',\n fix: 'Choose one mode: omit both to check the marker and schema, use `--marker-only` to check only the marker, or use `--schema-only` to check only the live schema.',\n }),\n );\n }\n\n if (options.markerOnly && options.strict) {\n return notOk(\n errorInvalidVerifyMode({\n why: '`--strict` requires schema verification, but `--marker-only` skips it',\n fix: 'Remove `--strict`, or use `db verify` / `db verify --schema-only` when you want to check the live schema in strict mode.',\n }),\n );\n }\n\n if (options.schemaOnly) {\n return ok('schema-only');\n }\n\n if (options.markerOnly) {\n return ok('marker-only');\n }\n\n return ok('full');\n}\n\nfunction formatDbVerifyModeLabel(mode: DbVerifyMode, strict: boolean): string {\n if (mode === 'marker-only') {\n return 'marker only';\n }\n\n if (mode === 'schema-only') {\n return `schema only (${strict ? 'strict' : 'tolerant'})`;\n }\n\n return `full (marker + schema, ${strict ? 'strict' : 'tolerant'})`;\n}\n\nfunction formatDbVerifyInvocation(mode: DbVerifyMode, strict: boolean): string {\n const args = ['db verify'];\n\n if (mode === 'marker-only') {\n args.push('--marker-only');\n }\n\n if (mode === 'schema-only') {\n args.push('--schema-only');\n }\n\n if (strict) {\n args.push('--strict');\n }\n\n return args.join(' ');\n}\n\nfunction createDbVerifyConnectionRequiredError(options: {\n readonly configPath: string;\n readonly mode: DbVerifyMode;\n readonly strict: boolean;\n}): CliStructuredError {\n const invocation = formatDbVerifyInvocation(options.mode, options.strict);\n return errorDatabaseConnectionRequired({\n why: `Database connection is required for ${invocation} (set db.connection in ${options.configPath}, or pass --db <url>)`,\n retryCommand: `prisma-next ${invocation} --db <url>`,\n });\n}\n\nfunction renderVerifyHeader(\n paths: { configPath: string; contractPath: string },\n options: DbVerifyOptions,\n mode: DbVerifyMode,\n flags: GlobalFlags,\n ui: TerminalUI,\n): void {\n if (flags.json || flags.quiet) return;\n\n const description =\n mode === 'schema-only'\n ? 'Check whether the live database schema matches your contract'\n : mode === 'marker-only'\n ? 'Check whether the database marker matches your contract'\n : 'Check whether the database marker and live schema match your contract';\n\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: paths.configPath },\n { label: 'contract', value: paths.contractPath },\n { label: 'mode', value: formatDbVerifyModeLabel(mode, options.strict ?? false) },\n ];\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n }\n\n ui.stderr(\n formatStyledHeader({\n command: 'db verify',\n description,\n url: 'https://pris.ly/db-verify',\n details,\n flags,\n }),\n );\n}\n\nasync function resolveVerifyPaths(options: DbVerifyOptions) {\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 = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n return { config, configPath, contractPathAbsolute, contractPath };\n}\n\ntype VerifyPaths = Awaited<ReturnType<typeof resolveVerifyPaths>>;\n\ninterface VerifySetup extends VerifyPaths {\n readonly contractJson: Contract;\n readonly dbConnection: string;\n}\n\nasync function resolveVerifySetup(\n paths: VerifyPaths,\n options: DbVerifyOptions,\n mode: DbVerifyMode,\n): Promise<Result<VerifySetup, CliStructuredError>> {\n const { config, configPath, contractPathAbsolute, contractPath } = paths;\n\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 // Cross the family `deserializeContract` seam at the read site, just\n // like every other CLI on-disk read (TML-2536). The downstream\n // `dbVerify` op accepts the hydrated `Contract` directly and no\n // longer re-deserializes.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n\n let contractJson: Contract;\n try {\n contractJson = familyInstance.deserializeContract(JSON.parse(contractJsonContent) as unknown);\n } catch (error) {\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\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 const dbConnection = options.db ?? config.db?.connection;\n if (typeof dbConnection !== 'string' || dbConnection.length === 0) {\n return notOk(\n createDbVerifyConnectionRequiredError({\n configPath,\n mode,\n strict: options.strict ?? false,\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: `Config.driver is required for ${formatDbVerifyInvocation(mode, options.strict ?? false)}`,\n }),\n );\n }\n\n return ok({ ...paths, contractJson, dbConnection });\n}\n\nfunction createVerifyClient(setup: VerifySetup) {\n return createControlClient({\n family: setup.config.family,\n target: setup.config.target,\n adapter: setup.config.adapter,\n driver: setup.config.driver!,\n extensionPacks: setup.config.extensionPacks ?? [],\n });\n}\n\nfunction wrapVerifyError(\n error: unknown,\n contractPathAbsolute: string,\n modeLabel: string,\n): Result<never, CliStructuredError> {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during ${modeLabel}: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n}\n\n/**\n * Executes the db verify command and returns a structured Result.\n */\nasync function executeDbVerifyCommand(\n options: DbVerifyOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n mode: Extract<DbVerifyMode, 'full' | 'marker-only'>,\n): Promise<Result<DbVerifyCommandSuccessResult, DbVerifyFailure>> {\n const startTime = Date.now();\n const paths = await resolveVerifyPaths(options);\n renderVerifyHeader(paths, options, mode, flags, ui);\n\n const setupResult = await resolveVerifySetup(paths, options, mode);\n if (!setupResult.ok) return setupResult;\n const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;\n const { migrationsDir } = resolveMigrationPaths(options.config, setupResult.value.config);\n\n const client = createVerifyClient(setupResult.value);\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n // Single-contract marker verification preserved for the existing\n // marker / target / hash failure surface (`PN-RUN-3001/3002/3003`).\n // The aggregate verifier (run below for the per-space marker /\n // schema checks) does not duplicate this: it concerns itself with\n // marker-vs-on-disk and orphan-marker drift, not the\n // hash-mismatch-against-the-app-contract lane that today's\n // `client.verify` covers.\n const verifyResult = await client.verify({\n contract: contractJson,\n connection: dbConnection,\n onProgress,\n });\n\n if (!verifyResult.ok) {\n return notOk(mapVerifyFailure(verifyResult));\n }\n\n // Aggregate verifier (loader → verifier pipeline). Runs the layout\n // precheck, marker-aware per-space verifier, and (full mode only)\n // per-space pre-projected schema verification (closes F23).\n const aggregateResult = await client.dbVerify({\n contract: contractJson,\n migrationsDir,\n strict: options.strict ?? false,\n skipSchema: mode === 'marker-only',\n skipMarker: false,\n onProgress,\n });\n if (!aggregateResult.ok) return notOk(aggregateResult.failure);\n\n if (mode === 'marker-only') {\n return ok({\n ok: true,\n mode: 'marker-only',\n summary: 'Database marker matches contract',\n contract: verifyResult.contract,\n marker: verifyResult.marker,\n target: verifyResult.target,\n ...ifDefined('missingCodecs', verifyResult.missingCodecs),\n ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),\n warning: 'Schema verification skipped because --marker-only was provided',\n meta: {\n ...(verifyResult.meta ?? {}),\n schemaVerification: 'skipped',\n },\n timings: { total: Date.now() - startTime },\n });\n }\n\n const combined = combineSchemaResults(\n aggregateResult.value.schemaResults,\n aggregateResult.value.appSpaceId,\n options.strict ?? false,\n );\n if (!combined.ok) {\n return notOk(combined);\n }\n\n return ok({\n ok: true,\n mode: 'full',\n summary: 'Database marker and schema match contract',\n contract: verifyResult.contract,\n marker: verifyResult.marker,\n target: verifyResult.target,\n ...ifDefined('missingCodecs', verifyResult.missingCodecs),\n ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),\n schema: {\n summary: combined.summary,\n counts: combined.schema.counts,\n strict: combined.meta?.strict ?? false,\n },\n meta: {\n ...(verifyResult.meta ?? {}),\n schemaVerification: 'performed',\n },\n timings: { total: Date.now() - startTime },\n });\n } catch (error) {\n return wrapVerifyError(error, contractPathAbsolute, 'db verify');\n } finally {\n await client.close();\n }\n}\n\nasync function executeDbSchemaOnlyVerifyCommand(\n options: DbVerifyOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<VerifyDatabaseSchemaResult, CliStructuredError>> {\n const paths = await resolveVerifyPaths(options);\n renderVerifyHeader(paths, options, 'schema-only', flags, ui);\n\n const setupResult = await resolveVerifySetup(paths, options, 'schema-only');\n if (!setupResult.ok) return setupResult;\n const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;\n const { migrationsDir } = resolveMigrationPaths(options.config, setupResult.value.config);\n\n const client = createVerifyClient(setupResult.value);\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n await client.connect(dbConnection);\n const aggregateResult = await client.dbVerify({\n contract: contractJson,\n migrationsDir,\n strict: options.strict ?? false,\n skipSchema: false,\n skipMarker: true,\n onProgress,\n });\n if (!aggregateResult.ok) return notOk(aggregateResult.failure);\n\n return ok(\n combineSchemaResults(\n aggregateResult.value.schemaResults,\n aggregateResult.value.appSpaceId,\n options.strict ?? false,\n ),\n );\n } catch (error) {\n return wrapVerifyError(error, contractPathAbsolute, 'db verify --schema-only');\n } finally {\n await client.close();\n }\n}\n\nexport function createDbVerifyCommand(): Command {\n const command = new Command('verify');\n setCommandDescriptions(\n command,\n 'Check whether the database marker and live schema match your contract',\n 'Verifies the database marker first, then checks the database schema matches your contract.\\n' +\n 'Use `--marker-only` for marker-only verification, `--schema-only` to skip marker checks and\\n' +\n 'inspect only the live schema, and `--strict` to fail if the database includes elements\\n' +\n 'not present in the contract.',\n );\n setCommandExamples(command, [\n 'prisma-next db verify --db $DATABASE_URL',\n 'prisma-next db verify --db $DATABASE_URL --strict',\n 'prisma-next db verify --db $DATABASE_URL --schema-only',\n 'prisma-next db verify --db $DATABASE_URL --schema-only --strict',\n 'prisma-next db verify --db $DATABASE_URL --marker-only',\n 'prisma-next db verify --db $DATABASE_URL --json',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--marker-only', 'Skip schema verification and only check the database marker')\n .option(\n '--schema-only',\n 'Skip marker verification and only check whether the live schema satisfies the contract',\n )\n .option(\n '--strict',\n 'Strict mode: schema elements not present in the contract are considered an error',\n false,\n )\n .action(async (options: DbVerifyOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n\n const modeResult = resolveDbVerifyMode(options);\n if (!modeResult.ok) {\n const exitCode = handleResult(modeResult as Result<never, CliStructuredError>, flags, ui);\n process.exit(exitCode);\n }\n\n const mode = modeResult.value;\n\n if (mode === 'schema-only') {\n const result = await executeDbSchemaOnlyVerifyCommand(options, flags, ui);\n const exitCode = handleResult(result, flags, ui, (schemaVerifyResult) => {\n if (flags.json) {\n ui.output(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n ui.log(output);\n }\n }\n });\n\n if (result.ok && !result.value.ok) {\n process.exit(1);\n }\n\n process.exit(exitCode);\n }\n\n const result = await executeDbVerifyCommand(options, flags, ui, mode);\n\n if (result.ok) {\n if (flags.json) {\n ui.output(formatVerifyJson(result.value));\n } else {\n const output = formatVerifyOutput(result.value, flags);\n if (output) {\n ui.log(output);\n }\n }\n process.exit(0);\n }\n\n if (CliStructuredError.is(result.failure)) {\n const exitCode = handleResult(result as Result<never, CliStructuredError>, flags, ui);\n process.exit(exitCode);\n }\n\n if (flags.json) {\n ui.output(formatSchemaVerifyJson(result.failure));\n } else {\n // Always show schema-drift failures, even in quiet mode — exiting 1 without\n // diagnostics is unhelpful.\n const output = formatSchemaVerifyOutput(result.failure, { ...flags, quiet: false });\n if (output) {\n ui.log(output);\n }\n }\n process.exit(1);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBACd,UACA,YACA,QAC4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Ae;GAC1B,MAAM,SAAS,MAAM,iCAAiC,SAAS,OAAO,EAAE;GACxE,MAAM,WAAW,aAAa,QAAQ,OAAO,KAAK,uBAAuB;IACvE,IAAI,MAAM,MACR,GAAG,OAAO,uBAAuB,kBAAkB,CAAC;SAC/C;KACL,MAAM,SAAS,yBAAyB,oBAAoB,KAAK;KACjE,IAAI,QACF,GAAG,IAAI,MAAM;IAEjB;GACF,CAAC;GAED,IAAI,OAAO,MAAM,CAAC,OAAO,MAAM,IAC7B,QAAQ,KAAK,CAAC;GAGhB,QAAQ,KAAK,QAAQ;EACvB;EAEA,MAAM,SAAS,MAAM,uBAAuB,SAAS,OAAO,IAAI,IAAI;EAEpE,IAAI,OAAO,IAAI;GACb,IAAI,MAAM,MACR,GAAG,OAAO,iBAAiB,OAAO,KAAK,CAAC;QACnC;IACL,MAAM,SAAS,mBAAmB,OAAO,OAAO,KAAK;IACrD,IAAI,QACF,GAAG,IAAI,MAAM;GAEjB;GACA,QAAQ,KAAK,CAAC;EAChB;EAEA,IAAI,mBAAmB,GAAG,OAAO,OAAO,GAAG;GACzC,MAAM,WAAW,aAAa,QAA6C,OAAO,EAAE;GACpF,QAAQ,KAAK,QAAQ;EACvB;EAEA,IAAI,MAAM,MACR,GAAG,OAAO,uBAAuB,OAAO,OAAO,CAAC;OAC3C;GAGL,MAAM,SAAS,yBAAyB,OAAO,SAAS;IAAE,GAAG;IAAO,OAAO;GAAM,CAAC;GAClF,IAAI,QACF,GAAG,IAAI,MAAM;EAEjB;EACA,QAAQ,KAAK,CAAC;CAChB,CAAC;CAEH,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as ExecuteDbVerifyOptions, C as IntrospectOptions, D as SchemaVerifyOptions, M as executeDbVerify, O as SignOptions, S as EmitSuccess, T as OnControlProgress, _ as EmitContractConfig, a as ControlClientOptions, b as EmitOptions, c as DbInitFailureCode, d as DbInitSuccess, f as DbUpdateFailure, g as DbUpdateSuccess, h as DbUpdateResult, i as ControlClient, j as ExecuteDbVerifyResult, k as VerifyOptions, l as DbInitOptions, m as DbUpdateOptions, n as ContractEmitResult, o as ControlProgressEvent, p as DbUpdateFailureCode, r as ControlActionName, s as DbInitFailure, t as ContractEmitOptions, u as DbInitResult, v as EmitFailure, x as EmitResult, y as EmitFailureCode } from "../types-
|
|
1
|
+
import { A as ExecuteDbVerifyOptions, C as IntrospectOptions, D as SchemaVerifyOptions, M as executeDbVerify, O as SignOptions, S as EmitSuccess, T as OnControlProgress, _ as EmitContractConfig, a as ControlClientOptions, b as EmitOptions, c as DbInitFailureCode, d as DbInitSuccess, f as DbUpdateFailure, g as DbUpdateSuccess, h as DbUpdateResult, i as ControlClient, j as ExecuteDbVerifyResult, k as VerifyOptions, l as DbInitOptions, m as DbUpdateOptions, n as ContractEmitResult, o as ControlProgressEvent, p as DbUpdateFailureCode, r as ControlActionName, s as DbInitFailure, t as ContractEmitOptions, u as DbInitResult, v as EmitFailure, x as EmitResult, y as EmitFailureCode } from "../types-DiC683UW.mjs";
|
|
2
2
|
import { ControlDriverInstance, ControlExtensionDescriptor, ControlFamilyInstance, ControlStack, SignDatabaseResult, TargetMigrationsCapability, VerifyDatabaseResult, VerifyDatabaseSchemaResult } from "@prisma-next/framework-components/control";
|
|
3
3
|
import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
|
|
4
4
|
import { Contract } from "@prisma-next/contract/types";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as executeContractEmit, r as disposeEmitQueue } from "../contract-emit-
|
|
1
|
+
import { n as executeContractEmit, r as disposeEmitQueue } from "../contract-emit-CC9jDOmu.mjs";
|
|
2
2
|
import { t as enrichContract } from "../contract-enrichment-a0V5Y_mL.mjs";
|
|
3
|
-
import { i as executeDbInit, n as executeDbVerify, r as executeDbUpdate, t as createControlClient } from "../client-
|
|
3
|
+
import { i as executeDbInit, n as executeDbVerify, r as executeDbUpdate, t as createControlClient } from "../client-Cdxcme1x.mjs";
|
|
4
4
|
export { createControlClient, disposeEmitQueue, enrichContract, executeContractEmit, executeDbInit, executeDbUpdate, executeDbVerify };
|
package/dist/exports/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as createContractEmitCommand } from "../contract-emit-
|
|
1
|
+
import { t as createContractEmitCommand } from "../contract-emit-DPMij44i.mjs";
|
|
2
2
|
import { join, resolve } from "pathe";
|
|
3
3
|
import { existsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as InitOutputSchema } from "../output-
|
|
1
|
+
import { t as InitOutputSchema } from "../output-CF_hqzI-.mjs";
|
|
2
2
|
export { InitOutputSchema };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { N as errorConfigValidation } from "./command-helpers-Cmdqyhz9.mjs";
|
|
2
2
|
import "@prisma-next/framework-components/components";
|
|
3
3
|
//#region src/utils/framework-components.ts
|
|
4
4
|
/**
|
|
@@ -55,4 +55,4 @@ function assertFrameworkComponentsCompatible(expectedFamilyId, expectedTargetId,
|
|
|
55
55
|
//#endregion
|
|
56
56
|
export { assertFrameworkComponentsCompatible as t };
|
|
57
57
|
|
|
58
|
-
//# sourceMappingURL=framework-components-
|
|
58
|
+
//# sourceMappingURL=framework-components-DynSvww4.mjs.map
|
package/dist/{framework-components-fYXjz_in.mjs.map → framework-components-DynSvww4.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-components-
|
|
1
|
+
{"version":3,"file":"framework-components-DynSvww4.mjs","names":[],"sources":["../src/utils/framework-components.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n checkContractComponentRequirements,\n type TargetBoundComponentDescriptor,\n} from '@prisma-next/framework-components/components';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport { errorConfigValidation, errorContractMissingExtensionPacks } from './cli-errors';\n\n/**\n * Asserts that all framework components are compatible with the expected family and target.\n *\n * This function validates that each component in the framework components array:\n * - Has kind 'target', 'adapter', 'extension', or 'driver'\n * - Has familyId matching expectedFamilyId\n * - Has targetId matching expectedTargetId\n *\n * This validation happens at the CLI composition boundary, before passing components\n * to typed planner/runner instances. It fills the gap between runtime validation\n * (via `validateConfig()`) and compile-time type enforcement.\n *\n * @param expectedFamilyId - The expected family ID (e.g., 'sql')\n * @param expectedTargetId - The expected target ID (e.g., 'postgres')\n * @param frameworkComponents - Array of framework components to validate\n * @returns The same array typed as TargetBoundComponentDescriptor\n * @throws CliStructuredError if any component is incompatible\n *\n * @example\n * ```ts\n * const config = await loadConfig();\n * const frameworkComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n *\n * // Validate and type-narrow components before passing to planner\n * const typedComponents = assertFrameworkComponentsCompatible(\n * config.family.familyId,\n * config.target.targetId,\n * frameworkComponents\n * );\n *\n * const planner = target.migrations.createPlanner(familyInstance);\n * planner.plan({ contract, schema, policy, frameworkComponents: typedComponents });\n * ```\n */\nexport function assertFrameworkComponentsCompatible<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n expectedFamilyId: TFamilyId,\n expectedTargetId: TTargetId,\n frameworkComponents: ReadonlyArray<unknown>,\n): ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>> {\n for (let i = 0; i < frameworkComponents.length; i++) {\n const component = frameworkComponents[i];\n\n // Check that component is an object\n if (typeof component !== 'object' || component === null) {\n throw errorConfigValidation('frameworkComponents[]', {\n why: `Framework component at index ${i} must be an object`,\n });\n }\n\n const record = component as Record<string, unknown>;\n\n // Check kind\n if (!Object.hasOwn(record, 'kind')) {\n throw errorConfigValidation('frameworkComponents[].kind', {\n why: `Framework component at index ${i} must have 'kind' property`,\n });\n }\n\n const kind = record['kind'];\n if (kind !== 'target' && kind !== 'adapter' && kind !== 'extension' && kind !== 'driver') {\n throw errorConfigValidation('frameworkComponents[].kind', {\n why: `Framework component at index ${i} has invalid kind '${String(kind)}' (must be 'target', 'adapter', 'extension', or 'driver')`,\n });\n }\n\n // Check familyId\n if (!Object.hasOwn(record, 'familyId')) {\n throw errorConfigValidation('frameworkComponents[].familyId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'familyId' property`,\n });\n }\n\n const familyId = record['familyId'];\n if (familyId !== expectedFamilyId) {\n throw errorConfigValidation('frameworkComponents[].familyId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) has familyId '${String(familyId)}' but expected '${expectedFamilyId}'`,\n });\n }\n\n // Check targetId\n if (!Object.hasOwn(record, 'targetId')) {\n throw errorConfigValidation('frameworkComponents[].targetId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'targetId' property`,\n });\n }\n\n const targetId = record['targetId'];\n if (targetId !== expectedTargetId) {\n throw errorConfigValidation('frameworkComponents[].targetId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) has targetId '${String(targetId)}' but expected '${expectedTargetId}'`,\n });\n }\n }\n\n // Type assertion is safe because we've validated all components above\n return frameworkComponents as ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n}\n\n/**\n * Validates that a contract is compatible with the configured target, adapter,\n * and extension packs. Throws on family/target mismatches or missing extension packs.\n *\n * This check ensures the emitted contract matches the CLI config before running\n * commands that depend on the contract (e.g., db verify, db sign).\n *\n * @param contract - The contract to validate (must include targetFamily, target, extensionPacks).\n * @param stack - The control plane stack (target, adapter, driver, extensionPacks).\n *\n * @throws {CliStructuredError} errorConfigValidation when contract.targetFamily or contract.target\n * doesn't match the configured family/target.\n * @throws {CliStructuredError} errorContractMissingExtensionPacks when the contract requires\n * extension packs that are not provided in the config (includes all missing packs in error.meta).\n *\n * @example\n * ```ts\n * import { assertContractRequirementsSatisfied } from './framework-components';\n *\n * const config = await loadConfig();\n * const contract = await loadContractJson(config.contract.output);\n * const stack = createControlStack({ family: config.family, target: config.target, adapter: config.adapter, ... });\n *\n * // Throws if contract is incompatible with config\n * assertContractRequirementsSatisfied({ contract, stack });\n * ```\n */\nexport function assertContractRequirementsSatisfied<\n TFamilyId extends string,\n TTargetId extends string,\n>({\n contract,\n stack,\n}: {\n readonly contract: Pick<Contract, 'targetFamily' | 'target' | 'extensionPacks'>;\n readonly stack: ControlStack<TFamilyId, TTargetId>;\n}): void {\n const providedComponentIds = new Set<string>([\n stack.target.id,\n ...(stack.adapter ? [stack.adapter.id] : []),\n ]);\n for (const extension of stack.extensionPacks) {\n providedComponentIds.add(extension.id);\n }\n\n const result = checkContractComponentRequirements({\n contract,\n expectedTargetFamily: stack.target.familyId,\n expectedTargetId: stack.target.targetId,\n providedComponentIds,\n });\n\n if (result.familyMismatch) {\n throw errorConfigValidation('contract.targetFamily', {\n why: `Contract was emitted for family '${result.familyMismatch.actual}' but CLI config is wired to '${result.familyMismatch.expected}'.`,\n });\n }\n\n if (result.targetMismatch) {\n throw errorConfigValidation('contract.target', {\n why: `Contract target '${result.targetMismatch.actual}' does not match CLI target '${result.targetMismatch.expected}'.`,\n });\n }\n\n if (result.missingExtensionPackIds.length > 0) {\n throw errorContractMissingExtensionPacks({\n missingExtensionPacks: result.missingExtensionPackIds,\n providedComponentIds: [...providedComponentIds],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,oCAId,kBACA,kBACA,qBACqE;CACrE,KAAK,IAAI,IAAI,GAAG,IAAI,oBAAoB,QAAQ,KAAK;EACnD,MAAM,YAAY,oBAAoB;EAGtC,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,sBAAsB,yBAAyB,EACnD,KAAK,gCAAgC,EAAE,oBACzC,CAAC;EAGH,MAAM,SAAS;EAGf,IAAI,CAAC,OAAO,OAAO,QAAQ,MAAM,GAC/B,MAAM,sBAAsB,8BAA8B,EACxD,KAAK,gCAAgC,EAAE,4BACzC,CAAC;EAGH,MAAM,OAAO,OAAO;EACpB,IAAI,SAAS,YAAY,SAAS,aA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A;EAAA,SACA,KAAA;EAAA,SACA,UAAA;EAAA,SACA,WAAA;EAAA,SACA,gBAAA;EAAA,SACA,GAAA;EAAA,SACA,CAAA;AAAA"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { S as formatErrorOutput, j as CliStructuredError, v as createTerminalUI, x as formatErrorJson } from "./command-helpers-Cmdqyhz9.mjs";
|
|
2
2
|
import { a as starterSchema, c as version, i as schemaSample, n as dbFile, o as targetLabel, r as defaultSchemaPath, s as targetPackageName, t as configFile } from "./cli.mjs";
|
|
3
|
-
import { i as renderInitOutro, n as buildNextSteps, r as formatInitJson, t as InitOutputSchema } from "./output-
|
|
3
|
+
import { i as renderInitOutro, n as buildNextSteps, r as formatInitJson, t as InitOutputSchema } from "./output-CF_hqzI-.mjs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { basename, dirname, extname, isAbsolute, join, normalize } from "pathe";
|
|
6
6
|
import * as clack from "@clack/prompts";
|
|
7
7
|
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
8
|
-
import { readUserConfig, resolveGating, writeUserConfig } from "@prisma-next/cli-telemetry";
|
|
9
8
|
import { execFile } from "node:child_process";
|
|
10
9
|
import { promisify } from "node:util";
|
|
11
10
|
import { detect, getUserAgent } from "package-manager-detector/detect";
|
|
@@ -646,11 +645,6 @@ const AUTHORING_VALUES = new Map([
|
|
|
646
645
|
["typescript", "typescript"],
|
|
647
646
|
["ts", "typescript"]
|
|
648
647
|
]);
|
|
649
|
-
const TELEMETRY_CONSENT_MESSAGE = [
|
|
650
|
-
"Help us prioritize features by sharing anonymous CLI usage data?",
|
|
651
|
-
"The telemetry implementation is open source and fully transparent.",
|
|
652
|
-
"(packages/1-framework/3-tooling/cli-telemetry and apps/telemetry-backend)."
|
|
653
|
-
].join(" ");
|
|
654
648
|
/**
|
|
655
649
|
* Resolves every required input for `runInit`. In interactive mode, missing
|
|
656
650
|
* inputs are prompted via clack; in non-interactive mode, missing required
|
|
@@ -698,10 +692,6 @@ async function resolveInitInputs(ctx) {
|
|
|
698
692
|
canPrompt,
|
|
699
693
|
autoAcceptPrompts
|
|
700
694
|
});
|
|
701
|
-
const enableTelemetry = await resolveTelemetryConsent({
|
|
702
|
-
canPrompt,
|
|
703
|
-
autoAcceptPrompts
|
|
704
|
-
});
|
|
705
695
|
const installProjectSkill = options.skill !== false;
|
|
706
696
|
return {
|
|
707
697
|
target: finalTarget,
|
|
@@ -713,49 +703,9 @@ async function resolveInitInputs(ctx) {
|
|
|
713
703
|
strictProbe: Boolean(options.strictProbe),
|
|
714
704
|
reinit,
|
|
715
705
|
removePreviousFacade,
|
|
716
|
-
enableTelemetry,
|
|
717
706
|
installProjectSkill
|
|
718
707
|
};
|
|
719
708
|
}
|
|
720
|
-
/**
|
|
721
|
-
* The interactive telemetry consent prompt. Shown as the last
|
|
722
|
-
* question of the `init` sequence iff:
|
|
723
|
-
* 1. `canPrompt === true` (interactive stdin / stdout combo),
|
|
724
|
-
* 2. `autoAcceptPrompts === false` (the user did not pass `--yes`),
|
|
725
|
-
* 3. neither telemetry env opt-out is active,
|
|
726
|
-
* 4. the process is not running in CI,
|
|
727
|
-
* 5. the stored `enableTelemetry` value is `undefined` (the user
|
|
728
|
-
* has never been asked, or skipped the prompt previously).
|
|
729
|
-
*
|
|
730
|
-
* Outside that intersection the function returns `null` and leaves the
|
|
731
|
-
* stored preference untouched. Inside it, the user's answer is
|
|
732
|
-
* persisted via `writeUserConfig({ enableTelemetry })` before this
|
|
733
|
-
* function returns; on an affirmative answer `writeUserConfig`
|
|
734
|
-
* generates and stores the v4 `installationId` in the same write.
|
|
735
|
-
*
|
|
736
|
-
* The wording names CLI usage data and points to the open-source
|
|
737
|
-
* client/backend paths. Default value is `true` to match precedent
|
|
738
|
-
* and to make the consent answer a single keystroke once it's been
|
|
739
|
-
* disclosed.
|
|
740
|
-
*/
|
|
741
|
-
async function resolveTelemetryConsent(opts) {
|
|
742
|
-
if (!opts.canPrompt || opts.autoAcceptPrompts || isCI()) return null;
|
|
743
|
-
const config = readUserConfig();
|
|
744
|
-
const gating = resolveGating({
|
|
745
|
-
env: process.env,
|
|
746
|
-
config
|
|
747
|
-
});
|
|
748
|
-
if (!gating.enabled && gating.reason === "env-override") return null;
|
|
749
|
-
if (config.enableTelemetry !== void 0) return null;
|
|
750
|
-
const result = await clack.confirm({
|
|
751
|
-
message: TELEMETRY_CONSENT_MESSAGE,
|
|
752
|
-
initialValue: true,
|
|
753
|
-
output: process.stderr
|
|
754
|
-
});
|
|
755
|
-
if (clack.isCancel(result)) throw errorInitUserAborted();
|
|
756
|
-
writeUserConfig({ enableTelemetry: Boolean(result) });
|
|
757
|
-
return Boolean(result);
|
|
758
|
-
}
|
|
759
709
|
async function resolveWriteEnv(opts) {
|
|
760
710
|
if (opts.flag !== void 0) return Boolean(opts.flag);
|
|
761
711
|
if (!opts.canPrompt || opts.autoAcceptPrompts) return false;
|
|
@@ -1679,7 +1629,7 @@ function mergeTypesArray(existing) {
|
|
|
1679
1629
|
* function does no flag parsing of its own.
|
|
1680
1630
|
*/
|
|
1681
1631
|
async function runInit(baseDir, runOptions) {
|
|
1682
|
-
const { options, flags, canPrompt, probeOverrides
|
|
1632
|
+
const { options, flags, canPrompt, probeOverrides } = runOptions;
|
|
1683
1633
|
const ui = createTerminalUI(flags);
|
|
1684
1634
|
const warnings = [];
|
|
1685
1635
|
const filesWritten = [];
|
|
@@ -1697,9 +1647,6 @@ async function runInit(baseDir, runOptions) {
|
|
|
1697
1647
|
if (CliStructuredError.is(error)) return emitError(ui, flags, error);
|
|
1698
1648
|
throw error;
|
|
1699
1649
|
}
|
|
1700
|
-
if (inputs.enableTelemetry === true && afterFirstTelemetryConsent !== void 0) try {
|
|
1701
|
-
await afterFirstTelemetryConsent(inputs);
|
|
1702
|
-
} catch {}
|
|
1703
1650
|
const pm = await detectPackageManager(baseDir);
|
|
1704
1651
|
const pkgRun = formatRunCommand(pm, "prisma-next", "").trimEnd();
|
|
1705
1652
|
const schemaDir = dirname(inputs.schemaPath);
|
|
@@ -2198,7 +2145,7 @@ async function runEmit(ctx) {
|
|
|
2198
2145
|
const spinner = ctx.ui.spinner();
|
|
2199
2146
|
spinner.start("Emitting contract...");
|
|
2200
2147
|
try {
|
|
2201
|
-
const { executeContractEmit } = await import("./contract-emit-
|
|
2148
|
+
const { executeContractEmit } = await import("./contract-emit-CC9jDOmu.mjs").then((n) => n.t);
|
|
2202
2149
|
await executeContractEmit({ configPath: join(ctx.baseDir, "prisma-next.config.ts") });
|
|
2203
2150
|
spinner.stop("Contract emitted");
|
|
2204
2151
|
} catch (err) {
|
|
@@ -2251,4 +2198,4 @@ function sanitisePackageName(raw) {
|
|
|
2251
2198
|
//#endregion
|
|
2252
2199
|
export { runInit };
|
|
2253
2200
|
|
|
2254
|
-
//# sourceMappingURL=init-
|
|
2201
|
+
//# sourceMappingURL=init-B6kKrmf7.mjs.map
|