@prisma-next/cli 0.10.0-dev.9 → 0.11.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{cli-errors-CF60g2cG.mjs → cli-errors-Djtz98Vm.mjs} +3 -3
- package/dist/cli-errors-Djtz98Vm.mjs.map +1 -0
- package/dist/cli.mjs +296 -53
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-Brv4qlfB.mjs → client-oXO2WCPD.mjs} +6 -5
- package/dist/client-oXO2WCPD.mjs.map +1 -0
- package/dist/{command-helpers-Dvgul7UA.mjs → command-helpers-DtavI0wJ.mjs} +108 -11
- package/dist/command-helpers-DtavI0wJ.mjs.map +1 -0
- package/dist/commands/contract-emit.mjs +1 -1
- package/dist/commands/contract-infer.mjs +1 -1
- package/dist/commands/db-init.d.mts.map +1 -1
- package/dist/commands/db-init.mjs +19 -20
- package/dist/commands/db-init.mjs.map +1 -1
- package/dist/commands/db-schema.mjs +6 -10
- package/dist/commands/db-schema.mjs.map +1 -1
- package/dist/commands/db-sign.mjs +7 -11
- package/dist/commands/db-sign.mjs.map +1 -1
- package/dist/commands/db-update.d.mts.map +1 -1
- package/dist/commands/db-update.mjs +16 -17
- package/dist/commands/db-update.mjs.map +1 -1
- package/dist/commands/db-verify.mjs +1 -1
- package/dist/commands/migrate.d.mts +1 -1
- package/dist/commands/migrate.mjs +7 -11
- package/dist/commands/migrate.mjs.map +1 -1
- package/dist/commands/migration-check.mjs +4 -7
- package/dist/commands/migration-check.mjs.map +1 -1
- package/dist/commands/migration-graph.d.mts +1 -1
- package/dist/commands/migration-graph.mjs +6 -10
- package/dist/commands/migration-graph.mjs.map +1 -1
- package/dist/commands/migration-list.mjs +5 -9
- package/dist/commands/migration-list.mjs.map +1 -1
- package/dist/commands/migration-log.d.mts.map +1 -1
- package/dist/commands/migration-log.mjs +7 -10
- package/dist/commands/migration-log.mjs.map +1 -1
- package/dist/commands/migration-new.mjs +6 -10
- package/dist/commands/migration-new.mjs.map +1 -1
- 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 +8 -12
- package/dist/commands/migration-show.mjs.map +1 -1
- package/dist/commands/migration-status.d.mts +1 -1
- package/dist/commands/migration-status.d.mts.map +1 -1
- package/dist/commands/migration-status.mjs +36 -14
- package/dist/commands/migration-status.mjs.map +1 -1
- package/dist/commands/ref.d.mts +1 -1
- package/dist/commands/ref.mjs +9 -19
- package/dist/commands/ref.mjs.map +1 -1
- package/dist/{contract-emit-iynA3BCA.mjs → contract-emit-bcrpT-wD.mjs} +3 -3
- package/dist/{contract-emit-iynA3BCA.mjs.map → contract-emit-bcrpT-wD.mjs.map} +1 -1
- package/dist/{contract-emit-BDBzHlaC.mjs → contract-emit-uwT-Mj8-.mjs} +7 -12
- package/dist/contract-emit-uwT-Mj8-.mjs.map +1 -0
- package/dist/{contract-infer-Dm8pBZMR.mjs → contract-infer-pKkiCt7C.mjs} +9 -14
- package/dist/contract-infer-pKkiCt7C.mjs.map +1 -0
- package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs → contract-space-aggregate-loader-BmNQwlws.mjs} +2 -2
- package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs.map → contract-space-aggregate-loader-BmNQwlws.mjs.map} +1 -1
- package/dist/{db-verify-CW8DR5Ei.mjs → db-verify-AoIUriL4.mjs} +9 -13
- package/dist/db-verify-AoIUriL4.mjs.map +1 -0
- 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-xFLFpZUO.mjs → framework-components-65gOHkHB.mjs} +2 -2
- package/dist/{framework-components-xFLFpZUO.mjs.map → framework-components-65gOHkHB.mjs.map} +1 -1
- package/dist/{global-flags-DGmw6Kqg.d.mts → global-flags-CdE7M0d9.d.mts} +4 -1
- package/dist/global-flags-CdE7M0d9.d.mts.map +1 -0
- package/dist/{graph-render-eJDcLWny.mjs → graph-render-DJVv0_uf.mjs} +1 -1
- package/dist/{graph-render-eJDcLWny.mjs.map → graph-render-DJVv0_uf.mjs.map} +1 -1
- package/dist/{init-CxS9eqbQ.mjs → init-YX6lCJpG.mjs} +140 -301
- package/dist/init-YX6lCJpG.mjs.map +1 -0
- package/dist/{inspect-live-schema-iETRZ_59.mjs → inspect-live-schema-LeWvkZVz.mjs} +4 -4
- package/dist/{inspect-live-schema-iETRZ_59.mjs.map → inspect-live-schema-LeWvkZVz.mjs.map} +1 -1
- package/dist/{migration-command-scaffold-BlgVj_Pn.mjs → migration-command-scaffold-BtkunvFQ.mjs} +4 -4
- package/dist/{migration-command-scaffold-BlgVj_Pn.mjs.map → migration-command-scaffold-BtkunvFQ.mjs.map} +1 -1
- package/dist/{migration-plan-BSzcWsvm.mjs → migration-plan-C2jeH1J5.mjs} +8 -12
- package/dist/migration-plan-C2jeH1J5.mjs.map +1 -0
- package/dist/{migration-types-D2FW63pr.d.mts → migration-types-BXWvz12q.d.mts} +1 -1
- package/dist/{migration-types-D2FW63pr.d.mts.map → migration-types-BXWvz12q.d.mts.map} +1 -1
- package/dist/{migrations-CgANWI0w.mjs → migrations-CwZMa1Ck.mjs} +2 -2
- package/dist/{migrations-CgANWI0w.mjs.map → migrations-CwZMa1Ck.mjs.map} +1 -1
- package/dist/{output-B60Gw5fu.mjs → output-BlsrGMEF.mjs} +1 -1
- package/dist/{output-B60Gw5fu.mjs.map → output-BlsrGMEF.mjs.map} +1 -1
- package/dist/readme-mongo.md +35 -0
- package/dist/readme-postgres.md +34 -0
- package/dist/{terminal-ui-XtOQsqe9.mjs → terminal-ui-BiB_8KNo.mjs} +131 -24
- package/dist/terminal-ui-BiB_8KNo.mjs.map +1 -0
- package/dist/{types-0aS865QN.d.mts → types--CqjMdk0.d.mts} +2 -2
- package/dist/{types-0aS865QN.d.mts.map → types--CqjMdk0.d.mts.map} +1 -1
- package/dist/{verify-nlzO0uIY.mjs → verify-Bom75OYI.mjs} +2 -2
- package/dist/{verify-nlzO0uIY.mjs.map → verify-Bom75OYI.mjs.map} +1 -1
- package/package.json +18 -18
- package/src/cli.ts +36 -9
- package/src/commands/contract-emit.ts +4 -4
- package/src/commands/contract-infer.ts +7 -7
- package/src/commands/db-init.ts +13 -5
- package/src/commands/db-schema.ts +4 -4
- package/src/commands/db-sign.ts +4 -4
- package/src/commands/db-update.ts +13 -5
- package/src/commands/db-verify.ts +5 -5
- package/src/commands/init/detect-package-manager.ts +15 -0
- package/src/commands/init/errors.ts +31 -0
- package/src/commands/init/hygiene-gitattributes.ts +2 -2
- package/src/commands/init/index.ts +4 -3
- package/src/commands/init/init.ts +33 -17
- package/src/commands/init/inputs.ts +6 -4
- package/src/commands/init/output.ts +1 -1
- package/src/commands/init/skill-install.ts +37 -26
- package/src/commands/init/templates/code-templates.ts +8 -14
- package/src/commands/init/templates/env.ts +8 -1
- package/src/commands/init/templates/readme-mongo.md +35 -0
- package/src/commands/init/templates/readme-postgres.md +34 -0
- package/src/commands/init/templates/readme.ts +62 -0
- package/src/commands/migrate.ts +4 -7
- package/src/commands/migration-check.ts +4 -4
- package/src/commands/migration-graph.ts +4 -4
- package/src/commands/migration-list.ts +4 -4
- package/src/commands/migration-log.ts +6 -5
- package/src/commands/migration-new.ts +4 -4
- package/src/commands/migration-plan.ts +4 -4
- package/src/commands/migration-show.ts +4 -4
- package/src/commands/migration-status.ts +49 -6
- package/src/commands/ref.ts +8 -8
- package/src/control-api/operations/apply-aggregate.ts +1 -0
- package/src/utils/cli-errors.ts +4 -0
- package/src/utils/command-helpers.ts +14 -6
- package/src/utils/global-flags.ts +102 -17
- package/src/utils/telemetry.ts +27 -52
- package/src/utils/terminal-ui.ts +44 -23
- package/dist/cli-errors-CF60g2cG.mjs.map +0 -1
- package/dist/client-Brv4qlfB.mjs.map +0 -1
- package/dist/command-helpers-Dvgul7UA.mjs.map +0 -1
- package/dist/contract-emit-BDBzHlaC.mjs.map +0 -1
- package/dist/contract-infer-Dm8pBZMR.mjs.map +0 -1
- package/dist/db-verify-CW8DR5Ei.mjs.map +0 -1
- package/dist/errors-BYAXmyRJ.mjs +0 -56
- package/dist/errors-BYAXmyRJ.mjs.map +0 -1
- package/dist/global-flags-DGmw6Kqg.d.mts.map +0 -1
- package/dist/init-CxS9eqbQ.mjs.map +0 -1
- package/dist/is-ci-YyvQBBke.mjs +0 -44
- package/dist/is-ci-YyvQBBke.mjs.map +0 -1
- package/dist/migration-plan-BSzcWsvm.mjs.map +0 -1
- package/dist/result-handler-CG3vVoKf.mjs +0 -25
- package/dist/result-handler-CG3vVoKf.mjs.map +0 -1
- package/dist/terminal-ui-XtOQsqe9.mjs.map +0 -1
- /package/dist/{cli-errors-DdcjVLJV.d.mts → cli-errors-Czmx92Zy.d.mts} +0 -0
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":["CLI_VERSION","packageJson.version"],"sources":["../package.json","../src/utils/telemetry.ts","../src/commands/init/index.ts","../src/utils/suggest-command.ts","../src/cli.ts"],"sourcesContent":["","import { fileURLToPath } from 'node:url';\nimport {\n type CommanderOptionShape,\n type CommanderResultShape,\n readUserConfig,\n resolveGating,\n runTelemetry,\n type TelemetryRunOutcome,\n type UserConfig,\n} from '@prisma-next/cli-telemetry';\nimport type { Command } from 'commander';\nimport { version as CLI_VERSION } from '../../package.json' with { type: 'json' };\nimport { loadConfig } from '../config-loader';\nimport { isCI } from './is-ci';\n\ninterface TelemetryFields {\n readonly databaseTarget: string | null;\n readonly extensions: readonly string[];\n}\n\ntype TelemetryGate =\n | { readonly enabled: true; readonly userConfig: UserConfig }\n | { readonly enabled: false; readonly outcome: TelemetryRunOutcome };\n\n/**\n * Resolve the commander command path from a leaf `Command`, walking up\n * the parent chain. Result is rooted at the program name and ends at\n * the leaf — `['prisma-next', 'migration', 'new']` for\n * `prisma-next migration new …`.\n */\nfunction commandPathFor(actionCommand: Command): string[] {\n const path: string[] = [];\n let cursor: Command | null = actionCommand;\n while (cursor !== null) {\n path.unshift(cursor.name());\n cursor = cursor.parent;\n }\n return path;\n}\n\nfunction commanderOptionSnapshots(actionCommand: Command): CommanderOptionShape[] {\n return actionCommand.options.map((option) => {\n const attributeName = option.attributeName();\n return {\n attributeName,\n longName: option.long ?? null,\n source: actionCommand.getOptionValueSource(attributeName) ?? null,\n };\n });\n}\n\n/**\n * Project commander's leaf `Command` into the wire-shape snapshot the\n * telemetry sanitiser consumes. Pure projection — no env, no I/O.\n */\nexport function commanderSnapshotForTelemetry(actionCommand: Command): CommanderResultShape {\n return {\n commandPath: commandPathFor(actionCommand),\n positionalArgs: actionCommand.args,\n options: commanderOptionSnapshots(actionCommand),\n };\n}\n\nfunction resolveTelemetryGate(): TelemetryGate {\n if (isCI()) {\n return { enabled: false, outcome: { spawned: false, reason: 'ci' } };\n }\n const userConfig = readUserConfig();\n const gating = resolveGating({ env: process.env, config: userConfig });\n if (!gating.enabled) {\n return { enabled: false, outcome: { spawned: false, reason: 'gated-off' } };\n }\n return { enabled: true, userConfig };\n}\n\n/**\n * Best-effort extraction of `databaseTarget` and `extensions` from the\n * project config. Loads via the same `c12`-backed loader the action\n * handlers use so we honour the same lookup rules. Every failure mode\n * (no config file, malformed config, async load reject) collapses to\n * `(null, [])` because telemetry is non-blocking and may fire for\n * commands that legitimately don't have a config (e.g. `init`).\n */\nasync function loadConfigForTelemetry(): Promise<TelemetryFields> {\n try {\n const config = await loadConfig();\n const target = config.target as { readonly targetId?: unknown } | undefined;\n const databaseTarget =\n target !== undefined && typeof target.targetId === 'string' ? target.targetId : null;\n const extensionPacks = (config.extensionPacks ?? []) as ReadonlyArray<{\n readonly id?: unknown;\n }>;\n const extensions = extensionPacks\n .map((pack) => pack.id)\n .filter((id): id is string => typeof id === 'string');\n return { databaseTarget, extensions };\n } catch {\n return { databaseTarget: null, extensions: [] };\n }\n}\n\n/**\n * Path to the compiled sender script inside `@prisma-next/cli-telemetry`'s\n * `dist/`. Resolved off this module's `import.meta.url` via the package\n * specifier `@prisma-next/cli-telemetry/sender`, so the consumer pays\n * no attention to internal package layout.\n */\nfunction senderPath(): string {\n return fileURLToPath(new URL(import.meta.resolve('@prisma-next/cli-telemetry/sender')));\n}\n\nfunction fireTelemetryWithFields(\n actionCommand: Command,\n fields: TelemetryFields,\n userConfig: UserConfig,\n): TelemetryRunOutcome {\n return runTelemetry({\n command: commanderSnapshotForTelemetry(actionCommand),\n version: CLI_VERSION,\n databaseTarget: fields.databaseTarget,\n extensions: fields.extensions,\n projectRoot: process.cwd(),\n senderPath: senderPath(),\n isCI: isCI(),\n env: process.env,\n userConfig,\n });\n}\n\n/**\n * preAction-stage entry point: resolve env/CI/user-consent gates first,\n * then (only when enabled) load project config for database target and\n * extension metadata, then fork the detached sender. The early gate is\n * privacy- and UX-critical: config loading can execute user code and\n * must never happen before opt-out/default-off checks have resolved.\n */\nexport async function fireTelemetryFromPreAction(\n actionCommand: Command,\n): Promise<TelemetryRunOutcome> {\n const gate = resolveTelemetryGate();\n if (!gate.enabled) {\n return gate.outcome;\n }\n const fields = await loadConfigForTelemetry();\n return fireTelemetryWithFields(actionCommand, fields, gate.userConfig);\n}\n\n/**\n * Manual one-shot telemetry path for the first `init` run where the user\n * explicitly answers Yes to the consent prompt. The preAction hook for\n * that same run has already resolved before consent existed, so it is\n * default-off. After consent is persisted, `runInit` calls this helper\n * exactly for that first affirmative answer; subsequent init runs skip\n * it because the prompt is not shown again.\n */\nexport function fireTelemetryAfterInitConsent(\n actionCommand: Command,\n inputs: { readonly databaseTarget: string },\n): TelemetryRunOutcome {\n const userConfig = readUserConfig();\n return fireTelemetryWithFields(\n actionCommand,\n { databaseTarget: inputs.databaseTarget, extensions: [] },\n userConfig,\n );\n}\n","import { Command } from 'commander';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../../utils/command-helpers';\nimport { type CommonCommandOptions, parseGlobalFlags } from '../../utils/global-flags';\nimport { fireTelemetryAfterInitConsent } from '../../utils/telemetry';\nimport {\n INIT_EXIT_EMIT_FAILED,\n INIT_EXIT_INSTALL_FAILED,\n INIT_EXIT_INTERNAL_ERROR,\n INIT_EXIT_OK,\n INIT_EXIT_PRECONDITION,\n INIT_EXIT_SKILL_INSTALL_FAILED,\n INIT_EXIT_USER_ABORTED,\n} from './exit-codes';\n\n/**\n * Commander.js parsed options for `init`. The init-specific options live\n * alongside the inherited `CommonCommandOptions` global flags.\n *\n * `target` and `authoring` are typed as plain `string` here because\n * Commander.js does not enforce enums at parse time — the validation /\n * normalisation happens in `inputs.ts::resolveInitInputs`, which can\n * raise a structured `errorInitInvalidFlagValue` with the full set of\n * allowed values.\n */\ninterface InitCommandOptions extends CommonCommandOptions {\n readonly target?: string;\n readonly authoring?: string;\n readonly schemaPath?: string;\n readonly force?: boolean;\n readonly writeEnv?: boolean;\n readonly probeDb?: boolean;\n readonly strictProbe?: boolean;\n readonly install?: boolean;\n readonly skill?: boolean;\n}\n\nexport function createInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Initialize a new Prisma Next project',\n 'Scaffolds config, schema, and runtime files, installs dependencies,\\n' +\n 'and emits the contract. Gets you from zero to typed queries in one step.\\n' +\n '\\n' +\n 'Run interactively for a guided experience, or supply --target / --authoring\\n' +\n 'and --yes for a fully scriptable run (CI, AI coding agents, automation).\\n' +\n '\\n' +\n 'Exit codes (see CLI Style Guide § Exit Codes):\\n' +\n ` ${INIT_EXIT_OK} OK Init succeeded.\\n` +\n ` ${INIT_EXIT_INTERNAL_ERROR} INTERNAL_ERROR Unexpected bug in prisma-next (please report).\\n` +\n ` ${INIT_EXIT_PRECONDITION} PRECONDITION Bad flags / missing prerequisite (e.g. no package.json).\\n` +\n ` ${INIT_EXIT_USER_ABORTED} USER_ABORTED User cancelled an interactive prompt.\\n` +\n ` ${INIT_EXIT_INSTALL_FAILED} INSTALL_FAILED Dependency installation failed (init-specific).\\n` +\n ` ${INIT_EXIT_EMIT_FAILED} EMIT_FAILED \\`contract emit\\` failed after install (init-specific).\\n` +\n ` ${INIT_EXIT_SKILL_INSTALL_FAILED} SKILL_INSTALL_FAILED Agent-skill install failed (re-run with --no-skill to skip).`,\n );\n setCommandExamples(command, [\n 'prisma-next init',\n 'prisma-next init --yes --target postgres --authoring psl',\n 'prisma-next init --yes --target mongodb --authoring typescript --json',\n 'prisma-next init --yes --force --target postgres --authoring psl # overwrite an existing scaffold',\n 'prisma-next init --no-install # skip pnpm/npm install + emit',\n 'prisma-next init --no-skill # skip the skills install (air-gapped / restricted env)',\n ]);\n\n return addGlobalOptions(command)\n .option('--target <db>', 'Database target: postgres or mongodb')\n .option('--authoring <style>', 'Schema authoring style: psl or typescript')\n .option(\n '--schema-path <path>',\n 'Where to write the starter schema (default: prisma/contract.prisma)',\n )\n .option('--force', 'Overwrite an existing scaffold without prompting')\n .option(\n '--write-env',\n 'Write a .env file from .env.example (gitignored; default: only .env.example)',\n )\n .option(\n '--probe-db',\n 'Connect to DATABASE_URL once and check the server version against the target minimum (opt-in; off by default)',\n )\n .option(\n '--strict-probe',\n 'Treat a failed --probe-db as fatal (no-op without --probe-db; init is offline-by-default)',\n )\n .option('--no-install', 'Skip dependency installation and contract emission')\n .option(\n '--no-skill',\n 'Skip Prisma Next skills install (air-gapped CI, restricted registries, etc.)',\n )\n .action(async (options: InitCommandOptions, actionCommand: Command) => {\n const { runInit } = await import('./init');\n const flags = parseGlobalFlags(options);\n const canPrompt = deriveCanPrompt({\n flagsInteractive: flags.interactive,\n optionInteractive: options.interactive,\n stdinIsTTY: Boolean(process.stdin.isTTY),\n });\n const exitCode = await runInit(process.cwd(), {\n options,\n flags,\n canPrompt,\n afterFirstTelemetryConsent: (inputs) => {\n fireTelemetryAfterInitConsent(actionCommand, { databaseTarget: inputs.target });\n },\n });\n process.exit(exitCode);\n });\n}\n\n/**\n * Bridges the action handler's two TTY checks (stdout via `flags`, stdin\n * via `process.stdin.isTTY`) into the `canPrompt` boolean `runInit`\n * consumes.\n *\n * Per the [Style Guide § Interactivity](../../../../../../../docs/CLI%20Style%20Guide.md#interactivity):\n *\n * - `flags.interactive` governs *decoration* (TerminalUI, intro/outro,\n * spinners) and is derived from stdout-TTY by `parseGlobalFlags`,\n * honouring `--interactive` / `--no-interactive`.\n * - Prompting additionally requires a stdin TTY — closing stdin is a\n * common signal in CI / agent environments even when stdout stays\n * attached.\n * - `--interactive` is the explicit override: when the user passes it,\n * we honour it (e.g. testing flows where stdin is stubbed).\n *\n * Exported so callers and tests can derive the same value without\n * touching `process` globals.\n */\nexport function deriveCanPrompt(opts: {\n readonly flagsInteractive: boolean | undefined;\n readonly optionInteractive: boolean | undefined;\n readonly stdinIsTTY: boolean;\n}): boolean {\n if (opts.optionInteractive === true) return true;\n if (opts.flagsInteractive === false) return false;\n return opts.stdinIsTTY;\n}\n","import { distance } from 'closest-match';\n\n/**\n * Suggests similar command names for a mistyped input.\n *\n * Uses Levenshtein distance to find close matches. Only suggests commands\n * within a reasonable distance threshold (40% of the input length, minimum 2).\n * Returns up to 3 suggestions in case of ties.\n *\n * @returns Array of suggested command names (empty if nothing is close enough).\n */\nexport function suggestCommands(input: string, candidates: readonly string[]): string[] {\n if (candidates.length === 0) return [];\n\n // Threshold: at most 40% of the input length (min 2) to avoid absurd suggestions\n const maxDistance = Math.max(2, Math.ceil(input.length * 0.4));\n\n const scored = candidates\n .map((name) => ({ name, dist: distance(input, name) }))\n .filter((entry) => entry.dist <= maxDistance)\n .sort((a, b) => a.dist - b.dist);\n\n if (scored.length === 0) return [];\n\n // Take the best distance, then include ties (up to 3)\n const bestDist = scored[0]!.dist;\n return scored\n .filter((entry) => entry.dist === bestDist)\n .slice(0, 3)\n .map((entry) => entry.name);\n}\n","import { Command } from 'commander';\nimport packageJson from '../package.json' with { type: 'json' };\nimport { createContractEmitCommand } from './commands/contract-emit';\nimport { createContractInferCommand } from './commands/contract-infer';\nimport { createInitCommand } from './commands/init';\nimport { installShutdownHandlers } from './utils/shutdown';\n\n// Install SIGINT/SIGTERM handlers before anything else\ninstallShutdownHandlers();\n\nimport { createDbInitCommand } from './commands/db-init';\nimport { createDbSchemaCommand } from './commands/db-schema';\nimport { createDbSignCommand } from './commands/db-sign';\nimport { createDbUpdateCommand } from './commands/db-update';\nimport { createDbVerifyCommand } from './commands/db-verify';\nimport { createMigrateCommand } from './commands/migrate';\nimport { createMigrationCheckCommand } from './commands/migration-check';\nimport { createMigrationGraphCommand } from './commands/migration-graph';\nimport { createMigrationListCommand } from './commands/migration-list';\nimport { createMigrationLogCommand } from './commands/migration-log';\nimport { createMigrationNewCommand } from './commands/migration-new';\nimport { createMigrationPlanCommand } from './commands/migration-plan';\nimport { createMigrationShowCommand } from './commands/migration-show';\nimport { createMigrationStatusCommand } from './commands/migration-status';\nimport { createRefCommand } from './commands/ref';\nimport { setCommandDescriptions } from './utils/command-helpers';\nimport { formatCommandHelp, formatRootHelp } from './utils/formatters/help';\nimport { parseGlobalFlags } from './utils/global-flags';\nimport { suggestCommands } from './utils/suggest-command';\nimport { fireTelemetryFromPreAction } from './utils/telemetry';\n\n/**\n * Lookup table mapping removed subcommands to their replacement verbs.\n * Keyed by `<parent>:<subcommand>` (e.g. `migration:apply`).\n * The handler consults this before falling back to the fuzzy suggest engine.\n */\nconst removedVerbRedirects: Record<string, string> = {\n 'migration:apply': 'Use `prisma-next migrate --to <contract>` instead.',\n 'migration:ref': 'Use `prisma-next ref set|list|delete` instead.',\n};\n\n/**\n * Removed flags on specific subcommands. Keyed by `<parent>:<sub>:<flag>`.\n * Checked during the pre-parse argv scan before commander sees the flags.\n */\nconst removedFlagRedirects: Record<string, string> = {\n 'migration:status:graph': 'Use `prisma-next migration graph` to view the migration graph.',\n 'migration:status:all':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:limit':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:ref': 'Use `--to <contract>` instead of `--ref`.',\n};\n\n/**\n * Formats the \"Did you mean ...?\" hint for an unknown command.\n */\nfunction formatSuggestion(input: string, candidates: readonly string[]): string {\n const suggestions = suggestCommands(\n input,\n candidates.map((c) => c),\n );\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `\\nDid you mean ${suggestions[0]}?\\n`;\n return `\\nDid you mean one of these?\\n${suggestions.map((s) => ` ${s}`).join('\\n')}\\n`;\n}\n\nconst program = new Command();\n\nprogram.name('prisma-next').description('Prisma Next CLI').version(packageJson.version);\n\n// Telemetry hook — fires at command start, before the action body\n// runs. Every failure mode is swallowed inside `runTelemetry`; the\n// hook never throws and never blocks long enough to be perceptible.\n//\n// Fire-and-forget: `fireTelemetryFromPreAction` `await`s a c12 config\n// load before forking the sender, so awaiting it here would block the\n// command's action body behind telemetry. Use `void` to dispatch in\n// parallel; the existing `.catch(() => {})` keeps errors swallowed.\nprogram.hook('preAction', (_thisCommand, actionCommand) => {\n void fireTelemetryFromPreAction(actionCommand).catch(() => {\n // defence-in-depth — runTelemetry already swallows internally.\n });\n});\n\n// Override version option description to match capitalization style\nconst versionOption = program.options.find((opt) => opt.flags.includes('--version'));\nif (versionOption) {\n versionOption.description = 'Output the version number';\n}\n\nprogram.configureOutput({\n writeErr: () => {\n // Suppress all default error output - we handle errors in exitOverride\n },\n writeOut: (str) => {\n // Commander routes explicitly-requested `--help` (success-path help)\n // through writeOut; per the Style Guide § Output Conventions rule 8,\n // user-requested help is data and goes to stdout. Error-path help\n // (e.g. usage shown after an unknown command) goes through writeErr,\n // which stays suppressed because we render that ourselves with the\n // matching error envelope.\n //\n // Explicit `--version` is short-circuited before `program.parse()`\n // (see the argv pre-scan at the bottom of this file), so it does not\n // reach this writer.\n process.stdout.write(str);\n },\n});\n\n// Customize root help output to use our styled format\nconst rootHelpFormatter = (cmd: Command) => {\n const flags = parseGlobalFlags({});\n return formatRootHelp({ program: cmd, flags });\n};\n\nprogram.configureHelp({\n formatHelp: rootHelpFormatter,\n subcommandDescription: () => '',\n});\n\n// Override exit to handle unhandled errors (fail fast cases)\n// Commands handle structured errors themselves via process.exit()\nprogram.exitOverride((err) => {\n if (err) {\n const errorCode = (err as { code?: string }).code;\n const errorMessage = String(err.message ?? '');\n const errorName = err.name ?? '';\n\n // Unknown command/argument → exit 2 (CLI usage error)\n const isUnknownCommandError =\n errorCode === 'commander.unknownCommand' ||\n errorCode === 'commander.unknownArgument' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('unknown command') || errorMessage.includes('unknown argument')));\n if (isUnknownCommandError) {\n const flags = parseGlobalFlags({});\n const match = errorMessage.match(/unknown command ['\"]([^'\"]+)['\"]/);\n const commandName = match ? match[1] : process.argv[3] || process.argv[2] || 'unknown';\n\n const firstArg = process.argv[2];\n const parentCommand = firstArg\n ? program.commands.find((cmd) => cmd.name() === firstArg)\n : undefined;\n\n if (parentCommand && commandName !== firstArg) {\n const subNames = parentCommand.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, subNames)}\\n`,\n );\n const helpText = formatCommandHelp({ command: parentCommand, flags });\n process.stderr.write(`${helpText}\\n`);\n } else {\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n }\n process.exit(2);\n return;\n }\n\n // Help requests → exit 0\n const isHelpError =\n errorCode === 'commander.help' ||\n errorCode === 'commander.helpDisplayed' ||\n errorCode === 'outputHelp' ||\n errorMessage === '(outputHelp)' ||\n errorMessage.includes('outputHelp') ||\n (errorName === 'CommanderError' && errorMessage.includes('outputHelp'));\n if (isHelpError) {\n process.exit(0);\n return;\n }\n\n // Missing required arguments → exit 2 (CLI usage error)\n const isMissingArgumentError =\n errorCode === 'commander.missingArgument' ||\n errorCode === 'commander.missingMandatoryOptionValue' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('missing') || errorMessage.includes('required')));\n if (isMissingArgumentError) {\n process.exit(2);\n return;\n }\n\n // Unhandled error → exit 1\n process.stderr.write(`Unhandled error: ${err.message}\\n`);\n if (err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n process.exit(1);\n }\n process.exit(0);\n});\n\n// Register contract subcommand\nconst contractCommand = new Command('contract');\nsetCommandDescriptions(\n contractCommand,\n 'Contract management commands',\n 'Define and emit your application data contract. The contract describes your schema as a\\n' +\n 'declarative data structure that can be signed and verified against your database.',\n);\ncontractCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add emit subcommand to contract\nconst contractEmitCommand = createContractEmitCommand();\ncontractCommand.addCommand(contractEmitCommand);\n\n// Add infer subcommand to contract\nconst contractInferCommand = createContractInferCommand();\ncontractCommand.addCommand(contractInferCommand);\n\n// Register db subcommand\nconst dbCommand = new Command('db');\nsetCommandDescriptions(\n dbCommand,\n 'Database management commands',\n 'Verify and sign your database with your contract. Ensure your database schema matches\\n' +\n 'your contract, and sign it to record the contract hash for future verification.',\n);\ndbCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add verify subcommand to db\nconst dbVerifyCommand = createDbVerifyCommand();\ndbCommand.addCommand(dbVerifyCommand);\n\n// Add init subcommand to db\nconst dbInitCommand = createDbInitCommand();\ndbCommand.addCommand(dbInitCommand);\n\n// Add update subcommand to db\nconst dbUpdateCommand = createDbUpdateCommand();\ndbCommand.addCommand(dbUpdateCommand);\n\n// Add schema subcommand to db\nconst dbSchemaCommand = createDbSchemaCommand();\ndbCommand.addCommand(dbSchemaCommand);\n\n// Add sign subcommand to db\nconst dbSignCommand = createDbSignCommand();\ndbCommand.addCommand(dbSignCommand);\n\n// Register migration subcommand\nconst migrationCommand = new Command('migration');\nsetCommandDescriptions(\n migrationCommand,\n 'On-disk migration management commands',\n 'Plan, apply, and scaffold on-disk migration packages. Migrations are\\n' +\n 'contract-to-contract edges stored as versioned directories under migrations/.',\n);\nmigrationCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\nconst migrationPlanCommand = createMigrationPlanCommand();\nmigrationCommand.addCommand(migrationPlanCommand);\n\nconst migrationNewCommand = createMigrationNewCommand();\nmigrationCommand.addCommand(migrationNewCommand);\n\nconst migrationShowCommand = createMigrationShowCommand();\nmigrationCommand.addCommand(migrationShowCommand);\n\nconst migrationStatusCommand = createMigrationStatusCommand();\nmigrationCommand.addCommand(migrationStatusCommand);\n\nconst migrationLogCommand = createMigrationLogCommand();\nmigrationCommand.addCommand(migrationLogCommand);\n\nconst migrationListCommand = createMigrationListCommand();\nmigrationCommand.addCommand(migrationListCommand);\n\nconst migrationGraphCommand = createMigrationGraphCommand();\nmigrationCommand.addCommand(migrationGraphCommand);\n\nconst migrationCheckCommand = createMigrationCheckCommand();\nmigrationCommand.addCommand(migrationCheckCommand);\n\n// Top-level migrate command\nconst migrateCommand = createMigrateCommand();\n\n// Top-level ref command (replaces `migration ref`)\nconst refCommand = createRefCommand();\n\n// Top-level init command\nconst initCommand = createInitCommand();\n\n// Register top-level commands in the order the spec's intended-surface\n// diagram lists them: verbs (init, migrate) first, then subject\n// namespaces (contract, db, migration, ref). The order shows up in\n// `prisma-next --help` and is the first thing a new user sees, so it\n// matches the order spec.md uses to introduce the surface.\nprogram.addCommand(initCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(contractCommand);\nprogram.addCommand(dbCommand);\nprogram.addCommand(migrationCommand);\nprogram.addCommand(refCommand);\n\n// Create help command\nconst helpCommand = new Command('help')\n .description('Show usage instructions')\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n // The `help` command was invoked explicitly: help is the data the\n // caller asked for. Per Style Guide § Output Conventions rule 8,\n // explicit help goes to stdout with exit code 0.\n process.stdout.write(`${helpText}\\n`);\n process.exit(0);\n });\n\nprogram.addCommand(helpCommand);\n\n// Set help as the default action when no command is provided. The user\n// did not invoke `--help`; we are voluntarily showing usage to help them\n// recover from an underspecified invocation, so the help text is\n// decoration around an implicit \"what did you want me to do?\" and goes\n// to stderr (Style Guide § Output Conventions rule 8).\n//\n// FOLLOW-UP: the exit code here is 0 today, but a no-arg invocation is\n// arguably a usage error (PRECONDITION → exit 2) for consistency with\n// the unknown-command path. Out of scope for the explicit-help routing\n// work; revisit when tightening exit-code semantics across the CLI.\nprogram.action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n});\n\n// Check if a command was invoked with no arguments (just the command name)\n// or if an unrecognized command was provided\nconst args = process.argv.slice(2);\nif (args.length > 0) {\n const commandName = args[0];\n // Handle version option explicitly since we suppress default output\n if (commandName === '--version' || commandName === '-V') {\n // Version is data → stdout\n process.stdout.write(`${program.version()}\\n`);\n process.exit(0);\n }\n // Skip command check for global options like --help, -h\n const isGlobalOption = commandName === '--help' || commandName === '-h';\n if (!isGlobalOption) {\n // Check if this is a recognized command\n const command = program.commands.find((cmd) => cmd.name() === commandName);\n\n if (!command) {\n // Unrecognized command → exit 2 (CLI usage error)\n const flags = parseGlobalFlags({});\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(2);\n } else if (command.commands.length > 0 && args.length >= 2) {\n const subcommandName = args[1];\n const redirectKey = `${commandName}:${subcommandName}`;\n const redirect = removedVerbRedirects[redirectKey];\n if (redirect) {\n process.stderr.write(`Unknown command: ${subcommandName}\\n${redirect}\\n`);\n process.exit(2);\n }\n for (let i = 2; i < args.length; i++) {\n const arg = args[i]!;\n if (!arg.startsWith('--')) continue;\n const flagName = arg.slice(2);\n const flagKey = `${commandName}:${subcommandName}:${flagName}`;\n const flagRedirect = removedFlagRedirects[flagKey];\n if (flagRedirect) {\n process.stderr.write(`Unknown option: ${arg}\\n${flagRedirect}\\n`);\n process.exit(2);\n }\n }\n }\n\n if (command.commands.length > 0 && args.length === 1) {\n // Parent command called with no subcommand. Same shape as the\n // no-args case above: the user did not request help, we are\n // voluntarily rendering it as decoration around an underspecified\n // invocation, so it goes to stderr per Style Guide § Output\n // Conventions rule 8. Exit code 0 today; the FOLLOW-UP note on\n // `program.action` applies here too (arguably should be 2).\n const flags = parseGlobalFlags({});\n const helpText = formatCommandHelp({ command, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n }\n }\n}\n\nprogram.parse();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC8BA,SAAS,eAAe,eAAkC;CACxD,MAAM,OAAiB,EAAE;CACzB,IAAI,SAAyB;CAC7B,OAAO,WAAW,MAAM;EACtB,KAAK,QAAQ,OAAO,MAAM,CAAC;EAC3B,SAAS,OAAO;;CAElB,OAAO;;AAGT,SAAS,yBAAyB,eAAgD;CAChF,OAAO,cAAc,QAAQ,KAAK,WAAW;EAC3C,MAAM,gBAAgB,OAAO,eAAe;EAC5C,OAAO;GACL;GACA,UAAU,OAAO,QAAQ;GACzB,QAAQ,cAAc,qBAAqB,cAAc,IAAI;GAC9D;GACD;;;;;;AAOJ,SAAgB,8BAA8B,eAA8C;CAC1F,OAAO;EACL,aAAa,eAAe,cAAc;EAC1C,gBAAgB,cAAc;EAC9B,SAAS,yBAAyB,cAAc;EACjD;;AAGH,SAAS,uBAAsC;CAC7C,IAAI,MAAM,EACR,OAAO;EAAE,SAAS;EAAO,SAAS;GAAE,SAAS;GAAO,QAA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AChB,QAAQ,OAAO,MAAM,mBAAmB,IAAI,IAAI,aAAa,IAAI;KACjE,QAAQ,KAAK,EAAE;;;;EAKrB,IAAI,QAAQ,SAAS,SAAS,KAAK,KAAK,WAAW,GAAG;GAQpD,MAAM,WAAW,kBAAkB;IAAE;IAAS,OADhC,iBAAiB,EAAE,CACkB;IAAE,CAAC;GACtD,QAAQ,OAAO,MAAM,GAAG,SAAS,IAAI;GACrC,QAAQ,KAAK,EAAE;;;;AAKrB,QAAQ,OAAO"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":["CLI_VERSION","packageJson.version"],"sources":["../package.json","../src/utils/telemetry.ts","../src/commands/init/templates/code-templates.ts","../src/commands/init/index.ts","../src/utils/suggest-command.ts","../src/cli.ts"],"sourcesContent":["","import { fileURLToPath } from 'node:url';\nimport {\n type CommanderOptionShape,\n type CommanderResultShape,\n readUserConfig,\n resolveGating,\n runTelemetry,\n type TelemetryRunOutcome,\n type UserConfig,\n} from '@prisma-next/cli-telemetry';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Command } from 'commander';\nimport { version as CLI_VERSION } from '../../package.json' with { type: 'json' };\nimport { isCI } from './is-ci';\n\ntype TelemetryGate =\n | { readonly enabled: true; readonly userConfig: UserConfig }\n | { readonly enabled: false; readonly outcome: TelemetryRunOutcome };\n\n/**\n * Resolve the commander command path from a leaf `Command`, walking up\n * the parent chain. Result is rooted at the program name and ends at\n * the leaf — `['prisma-next', 'migration', 'new']` for\n * `prisma-next migration new …`.\n */\nfunction commandPathFor(actionCommand: Command): string[] {\n const path: string[] = [];\n let cursor: Command | null = actionCommand;\n while (cursor !== null) {\n path.unshift(cursor.name());\n cursor = cursor.parent;\n }\n return path;\n}\n\nfunction commanderOptionSnapshots(actionCommand: Command): CommanderOptionShape[] {\n return actionCommand.options.map((option) => {\n const attributeName = option.attributeName();\n return {\n attributeName,\n longName: option.long ?? null,\n source: actionCommand.getOptionValueSource(attributeName) ?? null,\n };\n });\n}\n\n/**\n * Project commander's leaf `Command` into the wire-shape snapshot the\n * telemetry sanitiser consumes. Pure projection — no env, no I/O.\n */\nexport function commanderSnapshotForTelemetry(actionCommand: Command): CommanderResultShape {\n return {\n commandPath: commandPathFor(actionCommand),\n positionalArgs: actionCommand.args,\n options: commanderOptionSnapshots(actionCommand),\n };\n}\n\nfunction resolveTelemetryGate(): TelemetryGate {\n if (isCI()) {\n return { enabled: false, outcome: { spawned: false, reason: 'ci' } };\n }\n const userConfig = readUserConfig();\n const gating = resolveGating({ env: process.env, config: userConfig });\n if (!gating.enabled) {\n return { enabled: false, outcome: { spawned: false, reason: 'gated-off' } };\n }\n return { enabled: true, userConfig };\n}\n\n/**\n * Path to the compiled sender script inside `@prisma-next/cli-telemetry`'s\n * `dist/`. Resolved off this module's `import.meta.url` via the package\n * specifier `@prisma-next/cli-telemetry/sender`, so the consumer pays\n * no attention to internal package layout.\n */\nfunction senderPath(): string {\n return fileURLToPath(new URL(import.meta.resolve('@prisma-next/cli-telemetry/sender')));\n}\n\nfunction fireTelemetry(\n actionCommand: Command,\n userConfig: UserConfig,\n overrides: { readonly databaseTarget?: string } = {},\n): TelemetryRunOutcome {\n return runTelemetry({\n command: commanderSnapshotForTelemetry(actionCommand),\n version: CLI_VERSION,\n projectRoot: process.cwd(),\n senderPath: senderPath(),\n isCI: isCI(),\n env: process.env,\n userConfig,\n ...ifDefined('databaseTarget', overrides.databaseTarget),\n });\n}\n\n/**\n * preAction-stage entry point. Synchronous by construction: resolve\n * env/CI/user-consent gates (cheap, all in-memory and a single tiny\n * user-config read), then — only when enabled — `fork()` the detached\n * sender script. The forked child loads `prisma-next.config.*` via\n * c12 on its own (see `loadProjectConfig` in cli-telemetry); the\n * parent does no project-config I/O on the command's hot path.\n *\n * Privacy invariant: gate resolution always happens before any project\n * config touches disk. The child loading user TS code is acceptable\n * only because it's gated behind the same resolved-enabled signal.\n */\nexport function fireTelemetryFromPreAction(actionCommand: Command): TelemetryRunOutcome {\n const gate = resolveTelemetryGate();\n if (!gate.enabled) {\n return gate.outcome;\n }\n return fireTelemetry(actionCommand, gate.userConfig);\n}\n\n/**\n * Manual one-shot telemetry path for the first `init` run where the user\n * explicitly answers Yes to the consent prompt. The preAction hook for\n * that same run has already resolved before consent existed, so it is\n * default-off. After consent is persisted, `runInit` calls this helper\n * exactly for that first affirmative answer; subsequent init runs skip\n * it because the prompt is not shown again.\n *\n * The child's c12 load would return `databaseTarget: null` for this\n * specific invocation because `prisma-next.config.*` is not yet on\n * disk (init writes it later in the same run). To preserve the\n * prompt-chosen target in the first-init telemetry event, this\n * helper forwards the value as a parent-side IPC override on\n * `ParentToSenderPayload.databaseTarget` — the child consults the\n * override first and falls back to its c12 result when absent.\n */\nexport function fireTelemetryAfterInitConsent(\n actionCommand: Command,\n inputs: { readonly databaseTarget: string },\n): TelemetryRunOutcome {\n return fireTelemetry(actionCommand, readUserConfig(), {\n databaseTarget: inputs.databaseTarget,\n });\n}\n","import { DEFAULT_CONTRACT_SOURCE_DIR } from '@prisma-next/config/config-types';\n\nexport type TargetId = 'postgres' | 'mongo';\nexport type AuthoringId = 'psl' | 'typescript';\n\nexport function targetPackageName(target: TargetId): string {\n return target === 'postgres' ? '@prisma-next/postgres' : '@prisma-next/mongo';\n}\n\nexport function targetLabel(target: TargetId): string {\n return target === 'postgres' ? 'PostgreSQL' : 'MongoDB';\n}\n\nexport function defaultSchemaPath(authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return `${DEFAULT_CONTRACT_SOURCE_DIR}/contract.ts`;\n }\n return `${DEFAULT_CONTRACT_SOURCE_DIR}/contract.prisma`;\n}\n\nexport function starterSchema(target: TargetId, authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return target === 'mongo' ? starterSchemaTsMongo() : starterSchemaTsPostgres();\n }\n return target === 'mongo' ? starterSchemaPslMongo() : starterSchemaPslPostgres();\n}\n\n/**\n * Renders a short authoring-appropriate schema sample (FR5.1) for embedding\n * in `prisma-next.md`. Returns a complete fenced markdown code block.\n *\n * The sample intentionally shows just one model: it's illustrative, not\n * a substitute for the full scaffolded contract file. The TS samples use\n * the same outer shape as `starterSchemaTs*` (FR5.3) so a user reading\n * the doc and the file side-by-side sees the same structure.\n */\nexport function schemaSample(target: TargetId, authoring: AuthoringId): string {\n if (authoring === 'typescript') {\n return target === 'mongo' ? schemaSampleTsMongo() : schemaSampleTsPostgres();\n }\n return target === 'mongo' ? schemaSamplePslMongo() : schemaSamplePslPostgres();\n}\n\nfunction schemaSamplePslPostgres(): string {\n return `\\`\\`\\`prisma\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n username String?\n name String?\n}\n\\`\\`\\``;\n}\n\nfunction schemaSamplePslMongo(): string {\n return `\\`\\`\\`prisma\nmodel User {\n id ObjectId @id @map(\"_id\")\n email String @unique\n username String?\n name String?\n @@map(\"users\")\n}\n\\`\\`\\``;\n}\n\nfunction schemaSampleTsPostgres(): string {\n return `\\`\\`\\`typescript\nimport { defineContract } from '@prisma-next/postgres/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model }) => ({\n models: {\n User: model('User', {\n fields: {\n id: field.id.uuidv7(),\n email: field.text().unique(),\n username: field.text().optional(),\n name: field.text().optional(),\n },\n }),\n },\n }),\n);\n\\`\\`\\``;\n}\n\nfunction schemaSampleTsMongo(): string {\n return `\\`\\`\\`typescript\nimport { defineContract } from '@prisma-next/mongo/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model }) => ({\n models: {\n User: model('User', {\n collection: 'users',\n fields: {\n _id: field.objectId(),\n email: field.string(),\n username: field.string().optional(),\n name: field.string().optional(),\n },\n }),\n },\n }),\n);\n\\`\\`\\``;\n}\n\nfunction starterSchemaPslPostgres(): string {\n return `// use prisma-next\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n username String?\n name String?\n posts Post[]\n createdAt DateTime @default(now())\n updatedAt temporal.updatedAt()\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n content String?\n author User @relation(fields: [authorId], references: [id])\n authorId Int\n createdAt DateTime @default(now())\n updatedAt temporal.updatedAt()\n}\n`;\n}\n\nfunction starterSchemaPslMongo(): string {\n return `// use prisma-next\n\nmodel User {\n id ObjectId @id @map(\"_id\")\n email String @unique\n username String?\n name String?\n posts Post[]\n @@map(\"users\")\n}\n\nmodel Post {\n id ObjectId @id @map(\"_id\")\n title String\n content String?\n author User @relation(fields: [authorId], references: [id])\n authorId ObjectId\n @@map(\"posts\")\n}\n`;\n}\n\nfunction starterSchemaTsPostgres(): string {\n return `import { defineContract } from '@prisma-next/postgres/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model, rel }) => ({\n models: {\n User: model('User', {\n fields: {\n id: field.id.uuidv7(),\n email: field.text().unique(),\n username: field.text().optional(),\n name: field.text().optional(),\n createdAt: field.temporal.createdAt(),\n updatedAt: field.temporal.updatedAt(),\n },\n relations: {\n posts: rel.hasMany('Post', { by: 'authorId' }),\n },\n }),\n\n Post: model('Post', {\n fields: {\n id: field.id.uuidv7(),\n title: field.text(),\n content: field.text().optional(),\n authorId: field.uuid(),\n createdAt: field.temporal.createdAt(),\n updatedAt: field.temporal.updatedAt(),\n },\n relations: {\n author: rel.belongsTo('User', { from: 'authorId', to: 'id' }),\n },\n }),\n },\n }),\n);\n`;\n}\n\nfunction starterSchemaTsMongo(): string {\n return `import { defineContract } from '@prisma-next/mongo/contract-builder';\n\nexport const contract = defineContract(\n {},\n ({ field, model, rel }) => ({\n models: {\n User: model('User', {\n collection: 'users',\n fields: {\n _id: field.objectId(),\n email: field.string(),\n username: field.string().optional(),\n name: field.string().optional(),\n },\n relations: {\n posts: rel.hasMany('Post', { from: '_id', to: 'authorId' }),\n },\n }),\n\n Post: model('Post', {\n collection: 'posts',\n fields: {\n _id: field.objectId(),\n title: field.string(),\n content: field.string().optional(),\n authorId: field.objectId(),\n },\n relations: {\n author: rel.belongsTo('User', { from: 'authorId', to: '_id' }),\n },\n }),\n },\n }),\n);\n`;\n}\n\nexport function configFile(target: TargetId, contractPath: string): string {\n const pkg = targetPackageName(target);\n return `import 'dotenv/config';\nimport { defineConfig } from '${pkg}/config';\n\nexport default defineConfig({\n contract: ${JSON.stringify(contractPath)},\n db: {\n connection: process.env['DATABASE_URL']!,\n },\n});\n`;\n}\n\nexport function dbFile(target: TargetId): string {\n if (target === 'postgres') {\n return `import postgres from '@prisma-next/postgres/runtime';\nimport type { Contract } from './contract.d';\nimport contractJson from './contract.json' with { type: 'json' };\n\nexport const db = postgres<Contract>({\n contractJson,\n url: process.env['DATABASE_URL']!,\n});\n`;\n }\n\n return `import mongo from '@prisma-next/mongo/runtime';\nimport type { Contract } from './contract.d';\nimport contractJson from './contract.json' with { type: 'json' };\n\nexport const db = mongo<Contract>({\n contractJson,\n url: process.env['DATABASE_URL']!,\n});\n`;\n}\n","import { Command } from 'commander';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../../utils/command-helpers';\nimport { type CommonCommandOptions, parseGlobalFlagsOrExit } from '../../utils/global-flags';\nimport { fireTelemetryAfterInitConsent } from '../../utils/telemetry';\nimport {\n INIT_EXIT_EMIT_FAILED,\n INIT_EXIT_INSTALL_FAILED,\n INIT_EXIT_INTERNAL_ERROR,\n INIT_EXIT_OK,\n INIT_EXIT_PRECONDITION,\n INIT_EXIT_SKILL_INSTALL_FAILED,\n INIT_EXIT_USER_ABORTED,\n} from './exit-codes';\nimport { defaultSchemaPath } from './templates/code-templates';\n\n/**\n * Commander.js parsed options for `init`. The init-specific options live\n * alongside the inherited `CommonCommandOptions` global flags.\n *\n * `target` and `authoring` are typed as plain `string` here because\n * Commander.js does not enforce enums at parse time — the validation /\n * normalisation happens in `inputs.ts::resolveInitInputs`, which can\n * raise a structured `errorInitInvalidFlagValue` with the full set of\n * allowed values.\n */\ninterface InitCommandOptions extends CommonCommandOptions {\n readonly target?: string;\n readonly authoring?: string;\n readonly schemaPath?: string;\n readonly force?: boolean;\n readonly writeEnv?: boolean;\n readonly probeDb?: boolean;\n readonly strictProbe?: boolean;\n readonly install?: boolean;\n readonly skill?: boolean;\n}\n\nexport function createInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Initialize a new Prisma Next project',\n 'Scaffolds config, schema, and runtime files, installs dependencies,\\n' +\n 'and emits the contract. Gets you from zero to typed queries in one step.\\n' +\n '\\n' +\n 'Run interactively for a guided experience, or supply --target / --authoring\\n' +\n 'and --yes for a fully scriptable run (CI, AI coding agents, automation).\\n' +\n '\\n' +\n 'Exit codes (see CLI Style Guide § Exit Codes):\\n' +\n ` ${INIT_EXIT_OK} OK Init succeeded.\\n` +\n ` ${INIT_EXIT_INTERNAL_ERROR} INTERNAL_ERROR Unexpected bug in prisma-next (please report).\\n` +\n ` ${INIT_EXIT_PRECONDITION} PRECONDITION Bad flags / missing prerequisite (e.g. no package.json).\\n` +\n ` ${INIT_EXIT_USER_ABORTED} USER_ABORTED User cancelled an interactive prompt.\\n` +\n ` ${INIT_EXIT_INSTALL_FAILED} INSTALL_FAILED Dependency installation failed (init-specific).\\n` +\n ` ${INIT_EXIT_EMIT_FAILED} EMIT_FAILED \\`contract emit\\` failed after install (init-specific).\\n` +\n ` ${INIT_EXIT_SKILL_INSTALL_FAILED} SKILL_INSTALL_FAILED Agent-skill install failed (re-run with --no-skill to skip).`,\n );\n setCommandExamples(command, [\n 'prisma-next init',\n 'prisma-next init --yes --target postgres --authoring psl',\n 'prisma-next init --yes --target mongodb --authoring typescript --json',\n 'prisma-next init --yes --force --target postgres --authoring psl # overwrite an existing scaffold',\n 'prisma-next init --no-install # skip pnpm/npm install + emit',\n 'prisma-next init --no-skill # skip the skills install (air-gapped / restricted env)',\n ]);\n\n return addGlobalOptions(command)\n .option('--target <db>', 'Database target: postgres or mongodb')\n .option('--authoring <style>', 'Schema authoring style: psl or typescript')\n .option(\n '--schema-path <path>',\n `Where to write the starter schema (default: ${defaultSchemaPath('psl')})`,\n )\n .option('--force', 'Overwrite an existing scaffold without prompting')\n .option(\n '--write-env',\n 'Write a .env file from .env.example (gitignored; default: only .env.example)',\n )\n .option(\n '--probe-db',\n 'Connect to DATABASE_URL once and check the server version against the target minimum (opt-in; off by default)',\n )\n .option(\n '--strict-probe',\n 'Treat a failed --probe-db as fatal (no-op without --probe-db; init is offline-by-default)',\n )\n .option('--no-install', 'Skip dependency installation and contract emission')\n .option(\n '--no-skill',\n 'Skip Prisma Next skills install (air-gapped CI, restricted registries, etc.)',\n )\n .action(async (options: InitCommandOptions, actionCommand: Command) => {\n const { runInit } = await import('./init');\n const flags = parseGlobalFlagsOrExit(options);\n const canPrompt = deriveCanPrompt({\n flagsInteractive: flags.interactive,\n optionInteractive: options.interactive,\n stdinIsTTY: Boolean(process.stdin.isTTY),\n });\n const exitCode = await runInit(process.cwd(), {\n options,\n flags,\n canPrompt,\n afterFirstTelemetryConsent: (inputs) => {\n fireTelemetryAfterInitConsent(actionCommand, { databaseTarget: inputs.target });\n },\n });\n process.exit(exitCode);\n });\n}\n\n/**\n * Bridges the action handler's two TTY checks (stdout via `flags`, stdin\n * via `process.stdin.isTTY`) into the `canPrompt` boolean `runInit`\n * consumes.\n *\n * Per the [Style Guide § Interactivity](../../../../../../../docs/CLI%20Style%20Guide.md#interactivity):\n *\n * - `flags.interactive` governs *decoration* (TerminalUI, intro/outro,\n * spinners) and is derived from stdout-TTY by `parseGlobalFlags`,\n * honouring `--interactive` / `--no-interactive`.\n * - Prompting additionally requires a stdin TTY — closing stdin is a\n * common signal in CI / agent environments even when stdout stays\n * attached.\n * - `--interactive` is the explicit override: when the user passes it,\n * we honour it (e.g. testing flows where stdin is stubbed).\n *\n * Exported so callers and tests can derive the same value without\n * touching `process` globals.\n */\nexport function deriveCanPrompt(opts: {\n readonly flagsInteractive: boolean | undefined;\n readonly optionInteractive: boolean | undefined;\n readonly stdinIsTTY: boolean;\n}): boolean {\n if (opts.optionInteractive === true) return true;\n if (opts.flagsInteractive === false) return false;\n return opts.stdinIsTTY;\n}\n","import { distance } from 'closest-match';\n\n/**\n * Suggests similar command names for a mistyped input.\n *\n * Uses Levenshtein distance to find close matches. Only suggests commands\n * within a reasonable distance threshold (40% of the input length, minimum 2).\n * Returns up to 3 suggestions in case of ties.\n *\n * @returns Array of suggested command names (empty if nothing is close enough).\n */\nexport function suggestCommands(input: string, candidates: readonly string[]): string[] {\n if (candidates.length === 0) return [];\n\n // Threshold: at most 40% of the input length (min 2) to avoid absurd suggestions\n const maxDistance = Math.max(2, Math.ceil(input.length * 0.4));\n\n const scored = candidates\n .map((name) => ({ name, dist: distance(input, name) }))\n .filter((entry) => entry.dist <= maxDistance)\n .sort((a, b) => a.dist - b.dist);\n\n if (scored.length === 0) return [];\n\n // Take the best distance, then include ties (up to 3)\n const bestDist = scored[0]!.dist;\n return scored\n .filter((entry) => entry.dist === bestDist)\n .slice(0, 3)\n .map((entry) => entry.name);\n}\n","import { Command } from 'commander';\nimport packageJson from '../package.json' with { type: 'json' };\nimport { createContractEmitCommand } from './commands/contract-emit';\nimport { createContractInferCommand } from './commands/contract-infer';\nimport { createInitCommand } from './commands/init';\nimport { installShutdownHandlers } from './utils/shutdown';\n\n// Install SIGINT/SIGTERM handlers before anything else\ninstallShutdownHandlers();\n\nimport { createDbInitCommand } from './commands/db-init';\nimport { createDbSchemaCommand } from './commands/db-schema';\nimport { createDbSignCommand } from './commands/db-sign';\nimport { createDbUpdateCommand } from './commands/db-update';\nimport { createDbVerifyCommand } from './commands/db-verify';\nimport { createMigrateCommand } from './commands/migrate';\nimport { createMigrationCheckCommand } from './commands/migration-check';\nimport { createMigrationGraphCommand } from './commands/migration-graph';\nimport { createMigrationListCommand } from './commands/migration-list';\nimport { createMigrationLogCommand } from './commands/migration-log';\nimport { createMigrationNewCommand } from './commands/migration-new';\nimport { createMigrationPlanCommand } from './commands/migration-plan';\nimport { createMigrationShowCommand } from './commands/migration-show';\nimport { createMigrationStatusCommand } from './commands/migration-status';\nimport { createRefCommand } from './commands/ref';\nimport { setCommandDescriptions } from './utils/command-helpers';\nimport { formatCommandHelp, formatRootHelp } from './utils/formatters/help';\nimport { parseGlobalFlags } from './utils/global-flags';\nimport { suggestCommands } from './utils/suggest-command';\nimport { fireTelemetryFromPreAction } from './utils/telemetry';\n\n/**\n * Lookup table mapping removed subcommands to their replacement verbs.\n * Keyed by `<parent>:<subcommand>` (e.g. `migration:apply`).\n * The handler consults this before falling back to the fuzzy suggest engine.\n */\nconst removedVerbRedirects: Record<string, string> = {\n 'migration:apply': 'Use `prisma-next migrate --to <contract>` instead.',\n 'migration:ref': 'Use `prisma-next ref set|list|delete` instead.',\n};\n\n/**\n * Removed flags on specific subcommands. Keyed by `<parent>:<sub>:<flag>`.\n * Checked during the pre-parse argv scan before commander sees the flags.\n */\nconst removedFlagRedirects: Record<string, string> = {\n 'migration:status:graph': 'Use `prisma-next migration graph` to view the migration graph.',\n 'migration:status:all':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:limit':\n 'Use `prisma-next migration log --db <url>` to view the full execution history.',\n 'migration:status:ref': 'Use `--to <contract>` instead of `--ref`.',\n};\n\n/**\n * Formats the \"Did you mean ...?\" hint for an unknown command.\n */\nfunction formatSuggestion(input: string, candidates: readonly string[]): string {\n const suggestions = suggestCommands(\n input,\n candidates.map((c) => c),\n );\n if (suggestions.length === 0) return '';\n if (suggestions.length === 1) return `\\nDid you mean ${suggestions[0]}?\\n`;\n return `\\nDid you mean one of these?\\n${suggestions.map((s) => ` ${s}`).join('\\n')}\\n`;\n}\n\nconst program = new Command();\n\nprogram.name('prisma-next').description('Prisma Next CLI').version(packageJson.version);\n\n// Telemetry hook — fires at command start, before the action body\n// runs. Synchronous by construction: `fireTelemetryFromPreAction`\n// resolves gates (cheap), then `fork()`s the detached sender. The\n// fork is enqueued before the action body runs at all, so the child\n// survives even when the action throws synchronously. The try/catch\n// is defence-in-depth — `runTelemetry` already swallows every failure\n// mode internally and returns an outcome instead of throwing.\nprogram.hook('preAction', (_thisCommand, actionCommand) => {\n try {\n fireTelemetryFromPreAction(actionCommand);\n } catch {\n // defence-in-depth — runTelemetry already swallows internally.\n }\n});\n\n// Override version option description to match capitalization style\nconst versionOption = program.options.find((opt) => opt.flags.includes('--version'));\nif (versionOption) {\n versionOption.description = 'Output the version number';\n}\n\nprogram.configureOutput({\n writeErr: () => {\n // Suppress all default error output - we handle errors in exitOverride\n },\n writeOut: (str) => {\n // Commander routes explicitly-requested `--help` (success-path help)\n // through writeOut; per the Style Guide § Output Conventions rule 8,\n // user-requested help is data and goes to stdout. Error-path help\n // (e.g. usage shown after an unknown command) goes through writeErr,\n // which stays suppressed because we render that ourselves with the\n // matching error envelope.\n //\n // Explicit `--version` is short-circuited before `program.parse()`\n // (see the argv pre-scan at the bottom of this file), so it does not\n // reach this writer.\n process.stdout.write(str);\n },\n});\n\n// Customize root help output to use our styled format\nconst rootHelpFormatter = (cmd: Command) => {\n const flags = parseGlobalFlags({});\n return formatRootHelp({ program: cmd, flags });\n};\n\nprogram.configureHelp({\n formatHelp: rootHelpFormatter,\n subcommandDescription: () => '',\n});\n\n// Override exit to handle unhandled errors (fail fast cases)\n// Commands handle structured errors themselves via process.exit()\nprogram.exitOverride((err) => {\n if (err) {\n const errorCode = (err as { code?: string }).code;\n const errorMessage = String(err.message ?? '');\n const errorName = err.name ?? '';\n\n // Unknown command/argument → exit 2 (CLI usage error)\n const isUnknownCommandError =\n errorCode === 'commander.unknownCommand' ||\n errorCode === 'commander.unknownArgument' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('unknown command') || errorMessage.includes('unknown argument')));\n if (isUnknownCommandError) {\n const flags = parseGlobalFlags({});\n const match = errorMessage.match(/unknown command ['\"]([^'\"]+)['\"]/);\n const commandName = match ? match[1] : process.argv[3] || process.argv[2] || 'unknown';\n\n const firstArg = process.argv[2];\n const parentCommand = firstArg\n ? program.commands.find((cmd) => cmd.name() === firstArg)\n : undefined;\n\n if (parentCommand && commandName !== firstArg) {\n const subNames = parentCommand.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, subNames)}\\n`,\n );\n const helpText = formatCommandHelp({ command: parentCommand, flags });\n process.stderr.write(`${helpText}\\n`);\n } else {\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n }\n process.exit(2);\n return;\n }\n\n // Help requests → exit 0\n const isHelpError =\n errorCode === 'commander.help' ||\n errorCode === 'commander.helpDisplayed' ||\n errorCode === 'outputHelp' ||\n errorMessage === '(outputHelp)' ||\n errorMessage.includes('outputHelp') ||\n (errorName === 'CommanderError' && errorMessage.includes('outputHelp'));\n if (isHelpError) {\n process.exit(0);\n return;\n }\n\n // Missing required arguments → exit 2 (CLI usage error)\n const isMissingArgumentError =\n errorCode === 'commander.missingArgument' ||\n errorCode === 'commander.missingMandatoryOptionValue' ||\n (errorName === 'CommanderError' &&\n (errorMessage.includes('missing') || errorMessage.includes('required')));\n if (isMissingArgumentError) {\n process.exit(2);\n return;\n }\n\n // Unhandled error → exit 1\n process.stderr.write(`Unhandled error: ${err.message}\\n`);\n if (err.stack) {\n process.stderr.write(`${err.stack}\\n`);\n }\n process.exit(1);\n }\n process.exit(0);\n});\n\n// Register contract subcommand\nconst contractCommand = new Command('contract');\nsetCommandDescriptions(\n contractCommand,\n 'Contract management commands',\n 'Define and emit your application data contract. The contract describes your schema as a\\n' +\n 'declarative data structure that can be signed and verified against your database.',\n);\ncontractCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add emit subcommand to contract\nconst contractEmitCommand = createContractEmitCommand();\ncontractCommand.addCommand(contractEmitCommand);\n\n// Add infer subcommand to contract\nconst contractInferCommand = createContractInferCommand();\ncontractCommand.addCommand(contractInferCommand);\n\n// Register db subcommand\nconst dbCommand = new Command('db');\nsetCommandDescriptions(\n dbCommand,\n 'Database management commands',\n 'Verify and sign your database with your contract. Ensure your database schema matches\\n' +\n 'your contract, and sign it to record the contract hash for future verification.',\n);\ndbCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\n// Add verify subcommand to db\nconst dbVerifyCommand = createDbVerifyCommand();\ndbCommand.addCommand(dbVerifyCommand);\n\n// Add init subcommand to db\nconst dbInitCommand = createDbInitCommand();\ndbCommand.addCommand(dbInitCommand);\n\n// Add update subcommand to db\nconst dbUpdateCommand = createDbUpdateCommand();\ndbCommand.addCommand(dbUpdateCommand);\n\n// Add schema subcommand to db\nconst dbSchemaCommand = createDbSchemaCommand();\ndbCommand.addCommand(dbSchemaCommand);\n\n// Add sign subcommand to db\nconst dbSignCommand = createDbSignCommand();\ndbCommand.addCommand(dbSignCommand);\n\n// Register migration subcommand\nconst migrationCommand = new Command('migration');\nsetCommandDescriptions(\n migrationCommand,\n 'On-disk migration management commands',\n 'Plan, apply, and scaffold on-disk migration packages. Migrations are\\n' +\n 'contract-to-contract edges stored as versioned directories under migrations/.',\n);\nmigrationCommand.configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n subcommandDescription: () => '',\n});\n\nconst migrationPlanCommand = createMigrationPlanCommand();\nmigrationCommand.addCommand(migrationPlanCommand);\n\nconst migrationNewCommand = createMigrationNewCommand();\nmigrationCommand.addCommand(migrationNewCommand);\n\nconst migrationShowCommand = createMigrationShowCommand();\nmigrationCommand.addCommand(migrationShowCommand);\n\nconst migrationStatusCommand = createMigrationStatusCommand();\nmigrationCommand.addCommand(migrationStatusCommand);\n\nconst migrationLogCommand = createMigrationLogCommand();\nmigrationCommand.addCommand(migrationLogCommand);\n\nconst migrationListCommand = createMigrationListCommand();\nmigrationCommand.addCommand(migrationListCommand);\n\nconst migrationGraphCommand = createMigrationGraphCommand();\nmigrationCommand.addCommand(migrationGraphCommand);\n\nconst migrationCheckCommand = createMigrationCheckCommand();\nmigrationCommand.addCommand(migrationCheckCommand);\n\n// Top-level migrate command\nconst migrateCommand = createMigrateCommand();\n\n// Top-level ref command (replaces `migration ref`)\nconst refCommand = createRefCommand();\n\n// Top-level init command\nconst initCommand = createInitCommand();\n\n// Register top-level commands in the order the spec's intended-surface\n// diagram lists them: verbs (init, migrate) first, then subject\n// namespaces (contract, db, migration, ref). The order shows up in\n// `prisma-next --help` and is the first thing a new user sees, so it\n// matches the order spec.md uses to introduce the surface.\nprogram.addCommand(initCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(contractCommand);\nprogram.addCommand(dbCommand);\nprogram.addCommand(migrationCommand);\nprogram.addCommand(refCommand);\n\n// Test-only hidden command used by `cli-telemetry`'s `cli-e2e.test.ts`\n// to verify that telemetry still lands when a CLI command crashes\n// mid-execution. The preAction hook is synchronous and `fork()`s the\n// detached sender before this action body runs; the small sleep\n// gives the IPC `child.send()` a tick to flush before the throw\n// triggers commander's `exitOverride` and `process.exit(1)`. Hidden\n// from help; underscore prefix marks it as internal. Doesn't depend\n// on any project state, so it runs in any tempdir.\n//\n// Gated behind `PRISMA_NEXT_ENABLE_TEST_COMMANDS=1` so the command is\n// not even registered (and therefore not invocable) in shipped\n// binaries. `hidden: true` only filters the help output; without this\n// env gate the command would still be callable from production. The\n// e2e suite sets the env var when it spawns the CLI.\nconst TELEMETRY_CRASH_TEST_SLEEP_MS = 200;\nif (process.env['PRISMA_NEXT_ENABLE_TEST_COMMANDS'] === '1') {\n const telemetryCrashTestCommand = new Command('__telemetry-crash-test')\n .description('Internal: deliberately throw for the telemetry e2e suite.')\n .action(async () => {\n await new Promise((settle) => setTimeout(settle, TELEMETRY_CRASH_TEST_SLEEP_MS));\n throw new Error('__telemetry-crash-test: intentional crash for e2e coverage');\n });\n telemetryCrashTestCommand.configureHelp({ visibleCommands: () => [] });\n program.addCommand(telemetryCrashTestCommand, { hidden: true });\n}\n\n// Create help command\nconst helpCommand = new Command('help')\n .description('Show usage instructions')\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n // The `help` command was invoked explicitly: help is the data the\n // caller asked for. Per Style Guide § Output Conventions rule 8,\n // explicit help goes to stdout with exit code 0.\n process.stdout.write(`${helpText}\\n`);\n process.exit(0);\n });\n\nprogram.addCommand(helpCommand);\n\n// Set help as the default action when no command is provided. The user\n// did not invoke `--help`; we are voluntarily showing usage to help them\n// recover from an underspecified invocation, so the help text is\n// decoration around an implicit \"what did you want me to do?\" and goes\n// to stderr (Style Guide § Output Conventions rule 8).\n//\n// FOLLOW-UP: the exit code here is 0 today, but a no-arg invocation is\n// arguably a usage error (PRECONDITION → exit 2) for consistency with\n// the unknown-command path. Out of scope for the explicit-help routing\n// work; revisit when tightening exit-code semantics across the CLI.\nprogram.action(() => {\n const flags = parseGlobalFlags({});\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n});\n\n// Check if a command was invoked with no arguments (just the command name)\n// or if an unrecognized command was provided\nconst args = process.argv.slice(2);\nif (args.length > 0) {\n const commandName = args[0];\n // Handle version option explicitly since we suppress default output\n if (commandName === '--version' || commandName === '-V') {\n // Version is data → stdout\n process.stdout.write(`${program.version()}\\n`);\n process.exit(0);\n }\n // Skip command check for global options like --help, -h\n const isGlobalOption = commandName === '--help' || commandName === '-h';\n if (!isGlobalOption) {\n // Check if this is a recognized command\n const command = program.commands.find((cmd) => cmd.name() === commandName);\n\n if (!command) {\n // Unrecognized command → exit 2 (CLI usage error)\n const flags = parseGlobalFlags({});\n const topNames = program.commands.map((c) => c.name());\n process.stderr.write(\n `Unknown command: ${commandName}${formatSuggestion(commandName!, topNames)}\\n`,\n );\n const helpText = formatRootHelp({ program, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(2);\n } else if (command.commands.length > 0 && args.length >= 2) {\n const subcommandName = args[1];\n const redirectKey = `${commandName}:${subcommandName}`;\n const redirect = removedVerbRedirects[redirectKey];\n if (redirect) {\n process.stderr.write(`Unknown command: ${subcommandName}\\n${redirect}\\n`);\n process.exit(2);\n }\n for (let i = 2; i < args.length; i++) {\n const arg = args[i]!;\n if (!arg.startsWith('--')) continue;\n const flagName = arg.slice(2);\n const flagKey = `${commandName}:${subcommandName}:${flagName}`;\n const flagRedirect = removedFlagRedirects[flagKey];\n if (flagRedirect) {\n process.stderr.write(`Unknown option: ${arg}\\n${flagRedirect}\\n`);\n process.exit(2);\n }\n }\n }\n\n if (command.commands.length > 0 && args.length === 1) {\n // Parent command called with no subcommand. Same shape as the\n // no-args case above: the user did not request help, we are\n // voluntarily rendering it as decoration around an underspecified\n // invocation, so it goes to stderr per Style Guide § Output\n // Conventions rule 8. Exit code 0 today; the FOLLOW-UP note on\n // `program.action` applies here too (arguably should be 2).\n const flags = parseGlobalFlags({});\n const helpText = formatCommandHelp({ command, flags });\n process.stderr.write(`${helpText}\\n`);\n process.exit(0);\n }\n }\n}\n\nprogram.parse();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACyBA,SAAS,eAAe,eAAkC;CACxD,MAAM,OAAiB,EAAE;CACzB,IAAI,SAAyB;CAC7B,OAAO,WAAW,MAAM;EACtB,KAAK,QAAQ,OAAO,MAAM,CAAC;EAC3B,SAAS,OAAO;;CAElB,OAAO;;AAGT,SAAS,yBAAyB,eAAgD;CAChF,OAAO,cAAc,QAAQ,KAAK,WAAW;EAC3C,MAAM,gBAAgB,OAAO,eAAe;EAC5C,OAAO;GACL;GACA,UAAU,OAAO,QAAQ;GACzB,QAAQ,cAAc,qBAAqB,cAAc,IAAI;GAC9D;GACD;;;;;;AAOJ,SAAgB,8BAA8B,eAA8C;CAC1F,OAAO;EACL,aAAa,eAAe,cAAc;EAC1C,gBAAgB,cAAc;EA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AAC,IAAI,WAAW,KAAK,EAAE;IAG3B,MAAM,eAAe,qBAAqB,GADvB,YAAY,GAAG,eAAe,GADhC,IAAI,MAAM,EACiC;IAE5D,IAAI,cAAc;KAChB,QAAQ,OAAO,MAAM,mBAAmB,IAAI,IAAI,aAAa,IAAI;KACjE,QAAQ,KAAK,EAAE;;;;EAKrB,IAAI,QAAQ,SAAS,SAAS,KAAK,KAAK,WAAW,GAAG;GAQpD,MAAM,WAAW,kBAAkB;IAAE;IAAS,OADhC,iBAAiB,EAAE,CACkB;IAAE,CAAC;GACtD,QAAQ,OAAO,MAAM,GAAG,SAAS,IAAI;GACrC,QAAQ,KAAK,EAAE;;;;AAKrB,QAAQ,OAAO"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as assertFrameworkComponentsCompatible } from "./framework-components-
|
|
1
|
+
import { h as errorRunnerFailed, t as CliStructuredError } from "./cli-errors-Djtz98Vm.mjs";
|
|
2
|
+
import { t as assertFrameworkComponentsCompatible } from "./framework-components-65gOHkHB.mjs";
|
|
3
3
|
import { t as enrichContract } from "./contract-enrichment-Dani0mMW.mjs";
|
|
4
|
-
import { t as buildContractSpaceAggregate } from "./contract-space-aggregate-loader-
|
|
4
|
+
import { t as buildContractSpaceAggregate } from "./contract-space-aggregate-loader-BmNQwlws.mjs";
|
|
5
5
|
import { emit } from "@prisma-next/emitter";
|
|
6
6
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
7
7
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -78,7 +78,8 @@ async function applyAggregate(inputs) {
|
|
|
78
78
|
...ifDefined("why", runnerResult.failure.why),
|
|
79
79
|
meta: {
|
|
80
80
|
...runnerResult.failure.meta ?? {},
|
|
81
|
-
failingSpace: runnerResult.failure.failingSpace
|
|
81
|
+
failingSpace: runnerResult.failure.failingSpace,
|
|
82
|
+
runnerErrorCode: runnerResult.failure.code
|
|
82
83
|
}
|
|
83
84
|
});
|
|
84
85
|
}
|
|
@@ -1480,4 +1481,4 @@ var ControlClientImpl = class {
|
|
|
1480
1481
|
//#endregion
|
|
1481
1482
|
export { ContractValidationError as a, executeDbInit as i, executeDbVerify as n, executeDbUpdate as r, createControlClient as t };
|
|
1482
1483
|
|
|
1483
|
-
//# sourceMappingURL=client-
|
|
1484
|
+
//# sourceMappingURL=client-oXO2WCPD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-oXO2WCPD.mjs","names":["SPAN_IDS","emitContractArtifacts"],"sources":["../src/control-api/errors.ts","../src/control-api/operations/apply-aggregate.ts","../src/control-api/operations/migration-helpers.ts","../src/control-api/operations/db-apply-aggregate.ts","../src/control-api/operations/db-init.ts","../src/control-api/operations/db-update.ts","../src/control-api/operations/db-verify.ts","../src/control-api/operations/migration-apply.ts","../src/control-api/client.ts"],"sourcesContent":["export class ContractValidationError extends Error {\n override readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'ContractValidationError';\n this.cause = cause;\n }\n}\n","import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlFamilyInstance,\n MigrationOperationPolicy,\n MultiSpaceCapableRunner,\n MultiSpaceRunnerPerSpaceOptions,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { hasMultiSpaceRunner } from '@prisma-next/framework-components/control';\nimport type {\n AggregatePerSpacePlan,\n ContractSpaceAggregate,\n} from '@prisma-next/migration-tools/aggregate';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { errorRunnerFailed } from '../../utils/cli-errors';\nimport type { AggregatePerSpaceExecutionEntry, OnControlProgress } from '../types';\n\n/**\n * Span id emitted via `onProgress` for the apply phase. Stable\n * identifier consumed by the structured-output renderer and by tests.\n */\nconst APPLY_SPAN_ID = 'apply' as const;\n\n/**\n * Action that originated this apply call. Threaded into `OnControlProgress`\n * events so the parent CLI command can attribute the span correctly,\n * and used to compose action-specific summary phrasing.\n */\nexport type AggregateApplyAction = 'dbInit' | 'dbUpdate' | 'migrationApply';\n\n/**\n * Failure variant emitted by {@link applyAggregate} when the multi-space\n * runner itself rejects the apply. Mirrors the failure shape callers\n * already wrap into their own action-specific failure envelopes\n * (`DbInitFailure`, `DbUpdateFailure`, `MigrationApplyFailure`) so each\n * caller keeps owning its own discriminated failure code.\n */\nexport interface AggregateApplyRunnerFailure {\n readonly summary: string;\n readonly why?: string;\n readonly meta: Record<string, unknown>;\n}\n\nexport interface ApplyAggregateInputs<TFamilyId extends string, TTargetId extends string> {\n readonly aggregate: ContractSpaceAggregate;\n /**\n * Per-space plans, keyed by `spaceId`. Produced by either the full\n * {@link planAggregate} pipeline (`db init` / `db update` — synth\n * for the app, graph-walk for extensions) or by direct\n * {@link graphWalkStrategy} calls (`migrate` — graph-walk\n * for every member). Either way, the runner consumes the same shape.\n */\n readonly perSpacePlans: ReadonlyMap<string, AggregatePerSpacePlan>;\n /**\n * Canonical schedule order — extensions alphabetically by `spaceId`,\n * then app. Mirrors {@link import('@prisma-next/migration-tools/concatenate-space-apply-inputs').concatenateSpaceApplyInputs}'s\n * convention so `MultiSpaceRunnerFailure.failingSpace` attribution\n * stays byte-for-byte stable across callers.\n */\n readonly applyOrder: readonly string[];\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly policy: MigrationOperationPolicy;\n readonly action: AggregateApplyAction;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Resolved per-space plan in canonical schedule order. Surfaced from\n * {@link applyAggregate} to callers so each one can build its own\n * action-specific success envelope (e.g. `DbInitSuccess` vs\n * `MigrationApplySuccess`) without re-deriving the ordering.\n */\nexport interface OrderedResolution {\n readonly spaceId: string;\n readonly entry: AggregatePerSpacePlan;\n}\n\nexport interface ApplyAggregateValue {\n readonly orderedResolutions: readonly OrderedResolution[];\n readonly totalOpsPlanned: number;\n readonly totalOpsExecuted: number;\n /**\n * Per-space breakdown ready to thread into action-specific success\n * envelopes. Each entry carries the post-apply marker (live storage hash\n * plus invariants) so callers can render it directly without re-reading.\n */\n readonly perSpace: readonly AggregatePerSpaceExecutionEntry[];\n}\n\nexport type ApplyAggregateResult = Result<ApplyAggregateValue, AggregateApplyRunnerFailure>;\n\n/**\n * Runner-driving tail shared by every aggregate apply caller — `db init`,\n * `db update`, and `migrate`. Consumes already-resolved per-space\n * plans (the planner-vs-replay distinction is owned by the caller) and\n * dispatches them to the multi-space runner in canonical order.\n *\n * Marker advancement is part of the runner's per-space transaction\n * (the SQL family runner writes the marker as the last step of each\n * space's transaction), so this primitive does not advance markers\n * separately — by the time `executeAcrossSpaces` returns ok, every\n * space's marker has been advanced to its plan's destination.\n *\n * Span emission (`spanStart 'apply'` / `spanEnd 'apply'`) is owned here\n * so callers don't have to duplicate it; the `action` field on each\n * progress event is taken from the caller's `action` argument.\n */\nexport async function applyAggregate<TFamilyId extends string, TTargetId extends string>(\n inputs: ApplyAggregateInputs<TFamilyId, TTargetId>,\n): Promise<ApplyAggregateResult> {\n const {\n aggregate,\n perSpacePlans,\n applyOrder,\n driver,\n familyInstance,\n migrations,\n frameworkComponents,\n policy,\n action,\n onProgress,\n } = inputs;\n\n const orderedResolutions = collectOrdered(applyOrder, perSpacePlans);\n\n const runner = migrations.createRunner(familyInstance);\n if (!hasMultiSpaceRunner(runner)) {\n throw errorRunnerFailed(\n `Runner for target \"${aggregate.targetId}\" does not implement \\`executeAcrossSpaces\\``,\n {\n why: `${labelForAction(action)} requires multi-space-capable runners (today: every SQL family runner).`,\n },\n );\n }\n\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: APPLY_SPAN_ID,\n label: progressLabelForAction(action),\n });\n\n const perSpaceOptions: MultiSpaceRunnerPerSpaceOptions<TFamilyId, TTargetId>[] =\n orderedResolutions.map((r) => ({\n space: r.spaceId,\n plan: r.entry.plan,\n driver,\n destinationContract: r.entry.destinationContract,\n policy,\n frameworkComponents,\n // Per-space post-apply schema verification is non-strict: each\n // space's `destinationContract` describes only its own slice; a\n // strict verifier would treat every other space's tables as\n // `extras`. Tolerant mode still catches missing tables / columns.\n // SQL family runners read `strictVerification` via structural\n // typing.\n strictVerification: false,\n })) as MultiSpaceRunnerPerSpaceOptions<TFamilyId, TTargetId>[];\n\n const runnerResult = await (\n runner as MultiSpaceCapableRunner<TFamilyId, TTargetId>\n ).executeAcrossSpaces({ driver, perSpaceOptions });\n\n if (!runnerResult.ok) {\n onProgress?.({ action, kind: 'spanEnd', spanId: APPLY_SPAN_ID, outcome: 'error' });\n return notOk({\n summary: runnerResult.failure.summary,\n ...ifDefined('why', runnerResult.failure.why),\n meta: {\n ...(runnerResult.failure.meta ?? {}),\n failingSpace: runnerResult.failure.failingSpace,\n runnerErrorCode: runnerResult.failure.code,\n },\n });\n }\n onProgress?.({ action, kind: 'spanEnd', spanId: APPLY_SPAN_ID, outcome: 'ok' });\n\n const totalOpsPlanned = runnerResult.value.perSpaceResults.reduce(\n (sum, r) => sum + r.value.operationsPlanned,\n 0,\n );\n const totalOpsExecuted = runnerResult.value.perSpaceResults.reduce(\n (sum, r) => sum + r.value.operationsExecuted,\n 0,\n );\n\n const perSpace = buildPerSpaceBreakdown(orderedResolutions, aggregate.app.spaceId, {\n includeMarkers: true,\n });\n\n return ok({\n orderedResolutions,\n totalOpsPlanned,\n totalOpsExecuted,\n perSpace,\n });\n}\n\n/**\n * Project the planner's per-space resolutions into the\n * `AggregatePerSpaceExecutionEntry[]` shape the CLI surfaces.\n *\n * `includeMarkers` is `true` for apply-mode (each space's marker is\n * the `destination.storageHash` of its plan, which the runner\n * advances as the last step of each space's transaction) and `false`\n * for plan-mode (no marker has been written yet).\n *\n * Exported alongside {@link applyAggregate} so plan-mode callers can\n * assemble the same per-space block without going through the runner.\n */\nexport function buildPerSpaceBreakdown(\n orderedResolutions: readonly OrderedResolution[],\n appSpaceId: string,\n options: { readonly includeMarkers: boolean },\n): readonly AggregatePerSpaceExecutionEntry[] {\n return orderedResolutions.map((r) => {\n const operations = r.entry.displayOps.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n }));\n const base: AggregatePerSpaceExecutionEntry = {\n spaceId: r.spaceId,\n kind: r.spaceId === appSpaceId ? 'app' : 'extension',\n operations,\n };\n if (!options.includeMarkers) return base;\n return {\n ...base,\n marker: { storageHash: r.entry.plan.destination.storageHash },\n };\n });\n}\n\n/**\n * Materialise the `applyOrder` ordering into resolved per-space\n * entries. Throws if the planner output is missing a member listed\n * in `applyOrder` — a wiring bug that should never reach runtime.\n *\n * Exported so callers building their own success envelopes after a\n * plan-mode dispatch can replay the same ordering.\n */\nexport function collectOrdered(\n applyOrder: readonly string[],\n perSpace: ReadonlyMap<string, AggregatePerSpacePlan>,\n): readonly OrderedResolution[] {\n return applyOrder.map((spaceId) => {\n const entry = perSpace.get(spaceId);\n if (!entry) {\n throw new Error(`Aggregate planner output missing per-space plan for \"${spaceId}\"`);\n }\n return { spaceId, entry };\n });\n}\n\n/**\n * Action-appropriate label for the `spanStart` event the apply\n * primitive emits. `applyAggregate` is shared by `db init`, `db update`,\n * and `migrate`; the span label tracks the user-visible action\n * so structured-progress output reads naturally for each surface.\n */\nexport function progressLabelForAction(action: AggregateApplyAction): string {\n switch (action) {\n case 'dbInit':\n return 'Initialising database across spaces';\n case 'dbUpdate':\n return 'Updating database across spaces';\n case 'migrationApply':\n return 'Applying migration plan across spaces';\n }\n}\n\nfunction labelForAction(action: AggregateApplyAction): string {\n switch (action) {\n case 'dbInit':\n return 'db init';\n case 'dbUpdate':\n return 'db update';\n case 'migrationApply':\n return 'migrate';\n }\n}\n","import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';\nimport type { ControlActionName, OnControlProgress } from '../types';\n\n/**\n * Strips operation objects to their public shape (id, label, operationClass).\n * Used at the API boundary to avoid leaking internal fields (precheck, execute, postcheck, etc.).\n */\nexport function stripOperations(\n operations: readonly MigrationPlanOperation[],\n): ReadonlyArray<{ readonly id: string; readonly label: string; readonly operationClass: string }> {\n return operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n }));\n}\n\n/**\n * Creates per-operation progress callbacks for the runner.\n * Returns undefined when no onProgress callback is provided.\n */\nexport function createOperationCallbacks(\n onProgress: OnControlProgress | undefined,\n action: ControlActionName,\n parentSpanId: string,\n) {\n if (!onProgress) {\n return undefined;\n }\n return {\n onOperationStart: (op: MigrationPlanOperation) => {\n onProgress({\n action,\n kind: 'spanStart',\n spanId: `operation:${op.id}`,\n parentSpanId,\n label: op.label,\n });\n },\n onOperationComplete: (op: MigrationPlanOperation) => {\n onProgress({\n action,\n kind: 'spanEnd',\n spanId: `operation:${op.id}`,\n outcome: 'ok',\n });\n },\n };\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n MigrationOperationPolicy,\n MigrationPlanOperation,\n OperationPreview,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { hasOperationPreview } from '@prisma-next/framework-components/control';\nimport {\n type AggregatePlannerError,\n type ContractSpaceAggregate,\n planAggregate,\n} from '@prisma-next/migration-tools/aggregate';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { CliStructuredError } from '../../utils/cli-errors';\nimport {\n type BuildAggregateInputs,\n buildContractSpaceAggregate,\n} from '../../utils/contract-space-aggregate-loader';\nimport type {\n AggregatePerSpaceExecutionEntry,\n DbInitFailure,\n DbInitResult,\n DbInitSuccess,\n DbUpdateFailure,\n DbUpdateResult,\n DbUpdateSuccess,\n OnControlProgress,\n} from '../types';\nimport { applyAggregate, buildPerSpaceBreakdown, collectOrdered } from './apply-aggregate';\nimport { stripOperations } from './migration-helpers';\n\n/**\n * Span IDs emitted via `onProgress` during the aggregate apply flow.\n * Stable identifiers consumed by the structured-output renderer and by\n * tests asserting on span ids. The `apply` span itself is owned by\n * the {@link applyAggregate} primitive — only the introspect / plan\n * spans are emitted directly here.\n */\nconst SPAN_IDS = {\n introspect: 'introspect',\n plan: 'plan',\n} as const;\n\n/**\n * Inputs shared by `db init` and `db update` aggregate apply flows.\n *\n * Accepts the already-validated app contract + descriptor list — the\n * loader gathers the rest from disk + descriptors. The CLI is the\n * descriptor-import boundary; everything downstream is descriptor-free.\n */\nexport interface ExecuteAggregateApplyOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly mode: 'plan' | 'apply';\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly migrationsDir: string;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly targetId: TTargetId;\n readonly policy: MigrationOperationPolicy;\n readonly action: 'dbInit' | 'dbUpdate';\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Loader → planner → runner pipeline shared by `db init` and `db update`.\n *\n * The pipeline:\n *\n * 1. **Load**: build a {@link ContractSpaceAggregate} from the descriptor\n * set + on-disk on-disk artefacts. Any layout / drift / disjointness /\n * integrity violation short-circuits with a structured error.\n * 2. **Read DB state**: marker rows (`familyInstance.readAllMarkers`)\n * + introspected schema (`familyInstance.introspect`).\n * 3. **Plan**: {@link planAggregate} chooses graph-walk vs synth per\n * member according to `callerPolicy.ignoreGraphFor`. The app member\n * is forced through synth (today's daily-driver behaviour); every\n * extension member walks its on-disk graph.\n * 4. **Apply** (when `mode === 'apply'`): every per-space `MigrationPlan`\n * feeds into the runner's `executeAcrossSpaces` — one outer\n * transaction across every space; failure on any space rolls back\n * every space's writes.\n */\nexport async function executeAggregateApply<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteAggregateApplyOptions<TFamilyId, TTargetId>,\n): Promise<DbInitResult | DbUpdateResult> {\n const {\n driver,\n familyInstance,\n contract,\n mode,\n migrations,\n frameworkComponents,\n migrationsDir,\n extensionPacks,\n targetId,\n policy,\n action,\n onProgress,\n } = options;\n\n // 1. Load aggregate from descriptors + on-disk state.\n const loadInputs: BuildAggregateInputs<TFamilyId, TTargetId> = {\n targetId,\n migrationsDir,\n appContract: contract,\n extensionPacks,\n deserializeContract: (json) => familyInstance.deserializeContract(json),\n };\n const loaded = await buildContractSpaceAggregate(loadInputs);\n if (!loaded.ok) {\n throw loaded.failure;\n }\n const aggregate = loaded.value;\n\n // 2. Read live DB state (markers + schema).\n const markerRows = await familyInstance.readAllMarkers({ driver });\n\n // 2a. Orphan-marker pre-flight: refuse to *apply* when a marker row\n // exists for a space that is not declared in the aggregate. Plan mode\n // (`db init/update --dry-run`) must still be able to introspect the\n // aggregate plan in this state — a retired extension whose marker\n // happens to linger should not block the user from inspecting what a\n // run would do. Apply mode tells the user to clean up the orphan\n // before silently advancing the app's marker.\n if (mode === 'apply') {\n const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows);\n if (orphanMarkerError !== null) {\n throw orphanMarkerError;\n }\n }\n\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: SPAN_IDS.introspect,\n label: 'Introspecting database schema',\n });\n const schemaIR = await familyInstance.introspect({ driver });\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.introspect, outcome: 'ok' });\n\n // 3. Plan via aggregate planner. App is forced through synth (today's\n // `db init` / `db update` daily-driver behaviour); extensions walk\n // their on-disk migration graphs.\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: SPAN_IDS.plan,\n label: 'Planning migration',\n });\n const planResult = await planAggregate<TFamilyId, TTargetId>({\n aggregate,\n currentDBState: { markersBySpaceId: markerRows, schemaIntrospection: schemaIR },\n familyInstance,\n migrations,\n frameworkComponents,\n callerPolicy: { ignoreGraphFor: new Set([aggregate.app.spaceId]) },\n operationPolicy: policy,\n });\n if (!planResult.ok) {\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.plan, outcome: 'error' });\n return mapPlannerError(planResult.failure);\n }\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.plan, outcome: 'ok' });\n\n const orderedResolutions = collectOrdered(planResult.value.applyOrder, planResult.value.perSpace);\n\n // The destination's structural shape comes from the app's plan — its\n // `destination` is the storage hash users see in CLI output.\n const appResolution = orderedResolutions.find((r) => r.spaceId === aggregate.app.spaceId);\n if (!appResolution) {\n throw new Error(\n 'Aggregate planner returned no plan for the app member — the planner is supposed to always emit one.',\n );\n }\n const appPlan = appResolution.entry.plan;\n\n // 4. Plan-mode: surface aggregate operations without applying.\n if (mode === 'plan') {\n const aggregateOps = orderedResolutions.flatMap((r) => r.entry.displayOps);\n const preview = hasOperationPreview(familyInstance)\n ? familyInstance.toOperationPreview(aggregateOps)\n : undefined;\n const perSpace = buildPerSpaceBreakdown(orderedResolutions, aggregate.app.spaceId, {\n includeMarkers: false,\n });\n const summary = `Planned ${aggregateOps.length} operation(s) across ${orderedResolutions.length} space(s)`;\n return wrapPlanResult({\n operations: aggregateOps,\n destination: appPlan.destination,\n preview,\n perSpace,\n summary,\n });\n }\n\n // 5. Apply mode: hand off to the shared `applyAggregate` primitive.\n // The runner-driving tail is identical for `db init` / `db update` /\n // `migrate` — only how each caller produces `perSpacePlans`\n // differs (synth + graph-walk via planAggregate here; graph-walk\n // only for migrate). Each caller produces perSpacePlans differently;\n // this helper handles the shared apply tail.\n const applied = await applyAggregate({\n aggregate,\n perSpacePlans: planResult.value.perSpace,\n applyOrder: planResult.value.applyOrder,\n driver,\n familyInstance,\n migrations,\n frameworkComponents,\n policy,\n action,\n ...ifDefined('onProgress', onProgress),\n });\n if (!applied.ok) {\n return buildRunnerFailure({\n summary: applied.failure.summary,\n ...ifDefined('why', applied.failure.why),\n meta: applied.failure.meta,\n });\n }\n\n const aggregateOps = applied.value.orderedResolutions.flatMap((r) => r.entry.displayOps);\n const summary =\n action === 'dbInit'\n ? `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), database signed`\n : applied.value.totalOpsExecuted === 0\n ? `Database already matches contract across ${applied.value.orderedResolutions.length} space(s), signature updated`\n : `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), signature updated`;\n\n return wrapApplyResult({\n operations: aggregateOps,\n destination: appPlan.destination,\n operationsPlanned: applied.value.totalOpsPlanned,\n operationsExecuted: applied.value.totalOpsExecuted,\n perSpace: applied.value.perSpace,\n summary,\n });\n}\n\n/**\n * Compare the live `_prisma_marker` rows against the aggregate's\n * declared members. Any marker row whose `space` is not a member of\n * the aggregate is an \"orphan\" — typically a marker left behind by\n * an extension that was removed from `extensionPacks` without first\n * cleaning up its on-disk migrations / database tables.\n *\n * Returns a {@link CliStructuredError} envelope (code `5002`,\n * `kind: 'orphanMarker'`) for the first orphan it finds, or `null`\n * when every marker row maps to a declared member. Mirrors the M2\n * `runContractSpaceVerifierMarkerCheck` envelope so downstream\n * tooling (integration tests, JSON consumers) keeps asserting on the\n * same shape.\n */\nfunction detectOrphanMarkers(\n aggregate: ContractSpaceAggregate,\n markerRows: ReadonlyMap<string, unknown>,\n): CliStructuredError | null {\n const memberSpaceIds = new Set<string>([\n aggregate.app.spaceId,\n ...aggregate.extensions.map((m) => m.spaceId),\n ]);\n const orphans: string[] = [];\n for (const [spaceId, row] of markerRows) {\n if (row !== null && row !== undefined && !memberSpaceIds.has(spaceId)) {\n orphans.push(spaceId);\n }\n }\n if (orphans.length === 0) return null;\n orphans.sort((a, b) => a.localeCompare(b));\n const summary =\n orphans.length === 1\n ? `Orphan contract-space marker detected for \"${orphans[0]}\"`\n : `Orphan contract-space markers detected for ${orphans.length} spaces`;\n return new CliStructuredError('5002', summary, {\n domain: 'MIG',\n why: `The database has \\`_prisma_marker\\` rows for spaces (${orphans\n .map((s) => `\"${s}\"`)\n .join(\n ', ',\n )}) that are not declared in the project's \\`extensionPacks\\`. The aggregate pipeline refuses to advance markers it cannot account for.`,\n fix: 'Either re-declare the missing extension(s) in `extensionPacks` (so the aggregate owns them again), or remove the orphan marker row(s) from `_prisma_marker` once you have confirmed the corresponding tables can be safely retired.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: {\n violations: orphans.map((spaceId) => ({ kind: 'orphanMarker', spaceId })),\n },\n });\n}\n\nfunction mapPlannerError(error: AggregatePlannerError): DbInitResult | DbUpdateResult {\n if (error.kind === 'appSynthFailure') {\n const failure: DbInitFailure | DbUpdateFailure = {\n code: 'PLANNING_FAILED',\n summary: 'Migration planning failed due to conflicts',\n conflicts: error.conflicts,\n why: undefined,\n meta: undefined,\n };\n return notOk(failure) as DbInitResult | DbUpdateResult;\n }\n if (error.kind === 'extensionPathUnreachable') {\n return buildRunnerFailure({\n summary: `Cannot resolve apply path for extension space \"${error.spaceId}\"`,\n why: `No path in the on-disk migration graph for extension space \"${error.spaceId}\" reaches the on-disk head ref hash \"${error.target}\".`,\n meta: { spaceId: error.spaceId, target: error.target },\n });\n }\n if (error.kind === 'extensionPathUnsatisfiable') {\n return buildRunnerFailure({\n summary: `Cannot resolve apply path for extension space \"${error.spaceId}\"`,\n why: `On-disk migration graph for extension space \"${error.spaceId}\" reaches the on-disk head ref but does not cover required invariants: ${error.missingInvariants.join(', ')}.`,\n meta: { spaceId: error.spaceId, missingInvariants: error.missingInvariants },\n });\n }\n // policyConflict — surfaces as a runner-style failure naming the\n // space; conceptually a configuration bug, but mapping it onto the\n // existing failure surface keeps callers untouched.\n return buildRunnerFailure({\n summary: `Aggregate planner policy conflict for space \"${error.spaceId}\"`,\n why: error.detail,\n meta: { spaceId: error.spaceId },\n });\n}\n\nfunction wrapPlanResult(args: {\n readonly operations: readonly MigrationPlanOperation[];\n readonly destination: { readonly storageHash: string; readonly profileHash?: string };\n readonly preview: OperationPreview | undefined;\n readonly perSpace: readonly AggregatePerSpaceExecutionEntry[];\n readonly summary: string;\n}): DbInitResult | DbUpdateResult {\n const success: DbInitSuccess | DbUpdateSuccess = {\n mode: 'plan',\n plan: {\n operations: stripOperations(args.operations),\n ...ifDefined('preview', args.preview),\n },\n destination: {\n storageHash: args.destination.storageHash,\n ...ifDefined('profileHash', args.destination.profileHash),\n },\n perSpace: args.perSpace,\n summary: args.summary,\n };\n return ok(success);\n}\n\nfunction wrapApplyResult(args: {\n readonly operations: readonly MigrationPlanOperation[];\n readonly destination: { readonly storageHash: string; readonly profileHash?: string };\n readonly operationsPlanned: number;\n readonly operationsExecuted: number;\n readonly perSpace: readonly AggregatePerSpaceExecutionEntry[];\n readonly summary: string;\n}): DbInitResult | DbUpdateResult {\n const success: DbInitSuccess | DbUpdateSuccess = {\n mode: 'apply',\n plan: { operations: stripOperations(args.operations) },\n destination: {\n storageHash: args.destination.storageHash,\n ...ifDefined('profileHash', args.destination.profileHash),\n },\n execution: {\n operationsPlanned: args.operationsPlanned,\n operationsExecuted: args.operationsExecuted,\n },\n marker: args.destination.profileHash\n ? { storageHash: args.destination.storageHash, profileHash: args.destination.profileHash }\n : { storageHash: args.destination.storageHash },\n perSpace: args.perSpace,\n summary: args.summary,\n };\n return ok(success);\n}\n\nfunction buildRunnerFailure(args: {\n readonly summary: string;\n readonly why?: string;\n readonly meta: Record<string, unknown>;\n}): DbInitResult | DbUpdateResult {\n const failure: DbInitFailure | DbUpdateFailure = {\n code: 'RUNNER_FAILED',\n summary: args.summary,\n why: args.why,\n meta: args.meta,\n conflicts: undefined,\n };\n return notOk(failure) as DbInitResult | DbUpdateResult;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { DbInitResult, OnControlProgress } from '../types';\nimport { executeAggregateApply } from './db-apply-aggregate';\n\n/**\n * Options for executing the `db init` operation.\n *\n * `db init` runs the loader → planner → runner pipeline:\n *\n * 1. {@link executeAggregateApply} loads a `ContractSpaceAggregate` via\n * {@link import('@prisma-next/migration-tools/aggregate').loadContractSpaceAggregate}\n * from the supplied descriptor set + on-disk on-disk artefacts.\n * 2. The aggregate planner runs with `callerPolicy.ignoreGraphFor`\n * locked to the app member — synth strategy for the app, graph-walk\n * for every extension.\n * 3. The runner's `executeAcrossSpaces` applies the per-space plans\n * inside one outer transaction.\n *\n * `extensionPacks` mirrors `Config.extensionPacks` (descriptor list).\n * The loader (sub-spec § Loader) is the sole descriptor-import boundary.\n */\nexport interface ExecuteDbInitOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly mode: 'plan' | 'apply';\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n /**\n * On-disk migrations directory the aggregate loader reads on-disk\n * artefacts from. Required.\n */\n readonly migrationsDir: string;\n /**\n * Resolved adapter target id. Threaded through to the loader for\n * target-consistency checks across descriptors and the app contract.\n */\n readonly targetId: TTargetId;\n /**\n * Declared extension descriptors. Defaults to an empty list, which\n * routes through the same loader → planner → runner pipeline with no\n * extension members in the aggregate.\n */\n readonly extensionPacks?: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n /** Optional progress callback for observing operation progress */\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Execute `db init` against the configured contract.\n *\n * Routes through the loader → planner → runner pipeline (sub-spec\n * \"Commit-by-commit § Commit 4\"). Always additive-only; destructive\n * changes belong to `db update`.\n */\nexport async function executeDbInit<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbInitOptions<TFamilyId, TTargetId>,\n): Promise<DbInitResult> {\n const result = await executeAggregateApply<TFamilyId, TTargetId>({\n driver: options.driver,\n familyInstance: options.familyInstance,\n contract: options.contract,\n mode: options.mode,\n migrations: options.migrations,\n frameworkComponents: options.frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: options.targetId,\n extensionPacks: options.extensionPacks ?? [],\n policy: { allowedOperationClasses: ['additive'] },\n action: 'dbInit',\n ...ifDefined('onProgress', options.onProgress),\n });\n return result as DbInitResult;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk } from '@prisma-next/utils/result';\nimport type { DbUpdateResult, OnControlProgress } from '../types';\nimport { executeAggregateApply } from './db-apply-aggregate';\n\nconst DB_UPDATE_POLICY = {\n allowedOperationClasses: ['additive', 'widening', 'destructive'] as const,\n} as const;\n\n/**\n * Options for the `db update` operation.\n *\n * Same loader → planner → runner pipeline as `db init`, but with the\n * widened operation policy (additive + widening + destructive). The\n * destructive-change confirmation gate runs at this layer: when\n * `mode === 'apply'` and `acceptDataLoss` is `false`, the operation\n * pre-plans, surfaces destructive ops to the caller, and aborts.\n */\nexport interface ExecuteDbUpdateOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly mode: 'plan' | 'apply';\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly acceptDataLoss?: boolean;\n readonly migrationsDir: string;\n readonly targetId: TTargetId;\n readonly extensionPacks?: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Execute `db update` against the configured contract.\n *\n * Routes through the loader → planner → runner pipeline. Destructive\n * operations require either `acceptDataLoss: true` or a prior\n * `mode: 'plan'` invocation that surfaces the destructive ops; the\n * confirmation gate is implemented here so the lower-level applier\n * remains policy-agnostic.\n */\nexport async function executeDbUpdate<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbUpdateOptions<TFamilyId, TTargetId>,\n): Promise<DbUpdateResult> {\n const sharedInputs = {\n driver: options.driver,\n familyInstance: options.familyInstance,\n contract: options.contract,\n migrations: options.migrations,\n frameworkComponents: options.frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: options.targetId,\n extensionPacks: options.extensionPacks ?? [],\n policy: DB_UPDATE_POLICY,\n action: 'dbUpdate' as const,\n ...ifDefined('onProgress', options.onProgress),\n };\n if (options.mode === 'apply' && !options.acceptDataLoss) {\n const gate = await guardDestructiveChanges<TFamilyId, TTargetId>(sharedInputs);\n if (gate !== null) return gate;\n }\n return (await executeAggregateApply<TFamilyId, TTargetId>({\n ...sharedInputs,\n mode: options.mode,\n })) as DbUpdateResult;\n}\n\n/**\n * Pre-plan once when running `db update apply` without `acceptDataLoss`.\n * Surfaces destructive operations across every space; if any are\n * planned, returns a `DESTRUCTIVE_CHANGES` failure that the CLI shows\n * as a confirmation prompt. Returns `null` when the apply is safe to\n * run.\n */\nasync function guardDestructiveChanges<TFamilyId extends string, TTargetId extends string>(\n sharedInputs: Omit<Parameters<typeof executeAggregateApply<TFamilyId, TTargetId>>[0], 'mode'>,\n): Promise<DbUpdateResult | null> {\n const planResult = (await executeAggregateApply<TFamilyId, TTargetId>({\n ...sharedInputs,\n mode: 'plan',\n })) as DbUpdateResult;\n if (!planResult.ok) return planResult;\n const destructiveOps = planResult.value.plan.operations\n .filter((op) => op.operationClass === 'destructive')\n .map((op) => ({ id: op.id, label: op.label }));\n if (destructiveOps.length === 0) return null;\n return notOk({\n code: 'DESTRUCTIVE_CHANGES',\n summary: `Planned ${destructiveOps.length} destructive operation(s) that require confirmation`,\n why: 'Destructive operations require confirmation — re-run with -y to accept',\n conflicts: undefined,\n meta: { destructiveOperations: destructiveOps },\n });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport {\n type AggregateVerifierOutput,\n type ContractSpaceMember,\n verifyAggregate,\n} from '@prisma-next/migration-tools/aggregate';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { CliStructuredError } from '../../utils/cli-errors';\nimport {\n type BuildAggregateInputs,\n buildContractSpaceAggregate,\n} from '../../utils/contract-space-aggregate-loader';\nimport type { OnControlProgress } from '../types';\n\n/**\n * Span IDs emitted via `onProgress` during the aggregate verify flow.\n * Mirrors the span identifiers used by the legacy precheck / marker-check\n * helpers so structured-output renderers and progress tests keep working.\n */\nconst SPAN_IDS = {\n introspect: 'introspect',\n verify: 'verify',\n} as const;\n\n/**\n * Inputs for the aggregate `db verify` operation.\n *\n * Loader → verifier pipeline. The loader (sole descriptor-import\n * boundary) builds a {@link import('@prisma-next/migration-tools/aggregate').ContractSpaceAggregate};\n * the aggregate verifier bundles `markerCheck` + per-space pre-projected\n * `schemaCheck`. `mode: 'strict' | 'lenient'` maps directly to the user\n * facing `--strict` flag.\n */\nexport interface ExecuteDbVerifyOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly migrationsDir: string;\n readonly targetId: TTargetId;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly mode: 'strict' | 'lenient';\n readonly skipSchema: boolean;\n readonly skipMarker: boolean;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Result of the aggregate verify operation.\n *\n * Marker-check failures are surfaced as a {@link CliStructuredError}\n * (same envelope code `5002` the legacy `runContractSpaceVerifierMarkerCheck`\n * emitted, so downstream tooling and integration tests assert on the\n * same shape).\n *\n * On success, the per-space schema results are returned for the CLI to\n * render. When `skipSchema` is true (`--marker-only`), the schema map\n * is empty.\n */\nexport interface ExecuteDbVerifySuccess {\n readonly schemaResults: ReadonlyMap<string, VerifyDatabaseSchemaResult>;\n readonly memberOrder: readonly string[];\n readonly appSpaceId: string;\n}\n\nexport type ExecuteDbVerifyResult = Result<ExecuteDbVerifySuccess, CliStructuredError>;\n\n/**\n * Loader → verifier pipeline shared by `db verify` modes (`full`,\n * `marker-only`, `schema-only`).\n *\n * 1. **Load**: build a {@link import('@prisma-next/migration-tools/aggregate').ContractSpaceAggregate}\n * from descriptors + on-disk on-disk artefacts. Layout / drift /\n * integrity / disjointness violations short-circuit with a\n * structured CLI error.\n * 2. **Read DB state**: marker rows + (when `skipSchema` is `false`)\n * schema introspection.\n * 3. **Verify**: {@link verifyAggregate} returns per-space\n * `markerCheck` + per-space pre-projected `schemaCheck` (closes F23).\n * Marker mismatches map to `CliStructuredError` (code `5002`) so\n * callers (CLI command) can render and exit. Schema results are\n * returned to the caller verbatim.\n */\nexport async function executeDbVerify<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbVerifyOptions<TFamilyId, TTargetId>,\n): Promise<ExecuteDbVerifyResult> {\n const { driver, familyInstance, onProgress, skipSchema, skipMarker } = options;\n const loaded = await buildContractSpaceAggregate(buildLoadInputs(options));\n if (!loaded.ok) return notOk(loaded.failure);\n const aggregate = loaded.value;\n\n const markersBySpaceId = await familyInstance.readAllMarkers({ driver });\n const schemaIntrospection = skipSchema\n ? null\n : await runIntrospection({ driver, familyInstance, onProgress });\n\n emitVerifySpan(onProgress, 'spanStart');\n const verifyResult = verifyAggregate({\n aggregate,\n markersBySpaceId,\n schemaIntrospection,\n mode: options.mode,\n verifySchemaForMember: createPerMemberVerifier(options),\n });\n return finaliseVerifyResult({ verifyResult, aggregate, skipMarker, onProgress });\n}\n\nfunction buildLoadInputs<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbVerifyOptions<TFamilyId, TTargetId>,\n): BuildAggregateInputs<TFamilyId, TTargetId> {\n return {\n targetId: options.targetId,\n migrationsDir: options.migrationsDir,\n appContract: options.contract,\n extensionPacks: options.extensionPacks,\n deserializeContract: (json) => options.familyInstance.deserializeContract(json),\n };\n}\n\nasync function runIntrospection<TFamilyId extends string, TTargetId extends string>(args: {\n driver: ControlDriverInstance<TFamilyId, TTargetId>;\n familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n onProgress: OnControlProgress | undefined;\n}): Promise<unknown> {\n const { driver, familyInstance, onProgress } = args;\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanStart',\n spanId: SPAN_IDS.introspect,\n label: 'Introspecting database schema',\n });\n try {\n const result = await familyInstance.introspect({ driver });\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanEnd',\n spanId: SPAN_IDS.introspect,\n outcome: 'ok',\n });\n return result;\n } catch (error) {\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanEnd',\n spanId: SPAN_IDS.introspect,\n outcome: 'error',\n });\n throw error;\n }\n}\n\n/**\n * Build the per-member schema callback handed to the aggregate verifier.\n * When `skipSchema` is true the callback short-circuits with a synthetic\n * `ok` result so the verifier still runs the (cheap) schemaCheck loop\n * without invoking the family's verification path.\n */\nfunction createPerMemberVerifier<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbVerifyOptions<TFamilyId, TTargetId>,\n): (\n projectedSchema: unknown,\n member: ContractSpaceMember,\n verifyMode: 'strict' | 'lenient',\n) => VerifyDatabaseSchemaResult {\n const { skipSchema, familyInstance, frameworkComponents } = options;\n return (projectedSchema, member, verifyMode) => {\n if (skipSchema) return buildSkippedSchemaResult(member);\n return familyInstance.verifySchema({\n contract: member.contract,\n // The family's `TSchemaIR` is opaque to migration-tools; the\n // aggregate verifier passes through whatever we hand it. The\n // family expects its own IR shape on the way back.\n schema: projectedSchema as never,\n strict: verifyMode === 'strict',\n frameworkComponents,\n });\n };\n}\n\nfunction emitVerifySpan(\n onProgress: OnControlProgress | undefined,\n kind: 'spanStart' | 'spanEndOk' | 'spanEndError',\n): void {\n if (kind === 'spanStart') {\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanStart',\n spanId: SPAN_IDS.verify,\n label: 'Verifying contract spaces',\n });\n return;\n }\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanEnd',\n spanId: SPAN_IDS.verify,\n outcome: kind === 'spanEndOk' ? 'ok' : 'error',\n });\n}\n\n/**\n * Map an {@link AggregateVerifierOutput} to the operation's\n * {@link ExecuteDbVerifyResult}, applying the `skipMarker` policy used\n * by the CLI's `--schema-only` mode.\n */\nfunction finaliseVerifyResult(args: {\n verifyResult: AggregateVerifierOutput<VerifyDatabaseSchemaResult>;\n aggregate: {\n readonly app: { readonly spaceId: string };\n readonly extensions: ReadonlyArray<{ readonly spaceId: string }>;\n };\n skipMarker: boolean;\n onProgress: OnControlProgress | undefined;\n}): ExecuteDbVerifyResult {\n const { verifyResult, aggregate, skipMarker, onProgress } = args;\n if (!verifyResult.ok) {\n emitVerifySpan(onProgress, 'spanEndError');\n return notOk(\n new CliStructuredError('5002', 'Aggregate verifier introspection failed', {\n domain: 'MIG',\n why: verifyResult.failure.detail,\n fix: 'Check database connectivity and the introspection tooling.',\n docsUrl: 'https://pris.ly/contract-spaces',\n }),\n );\n }\n const markerError = skipMarker\n ? null\n : mapMarkerCheckFailures(aggregate.app.spaceId, verifyResult.value.markerCheck);\n if (markerError !== null) {\n emitVerifySpan(onProgress, 'spanEndError');\n return notOk(markerError);\n }\n emitVerifySpan(onProgress, 'spanEndOk');\n return ok({\n schemaResults: verifyResult.value.schemaCheck.perSpace,\n memberOrder: [aggregate.app.spaceId, ...aggregate.extensions.map((e) => e.spaceId)],\n appSpaceId: aggregate.app.spaceId,\n });\n}\n\nfunction buildSkippedSchemaResult(member: ContractSpaceMember): VerifyDatabaseSchemaResult {\n const profileHash = (member.contract as { profileHash?: string }).profileHash;\n return {\n ok: true,\n summary: 'Schema verification skipped',\n contract: {\n storageHash: member.headRef.hash,\n ...(profileHash ? { profileHash } : {}),\n },\n target: { expected: member.contract.target },\n schema: {\n issues: [],\n root: {\n status: 'pass',\n kind: 'skipped',\n name: member.spaceId,\n contractPath: '',\n code: 'SKIPPED',\n message: 'Schema verification skipped',\n expected: undefined,\n actual: undefined,\n children: [],\n },\n counts: { pass: 0, warn: 0, fail: 0, totalNodes: 0 },\n },\n timings: { total: 0 },\n };\n}\n\n/**\n * Translate per-space marker check failures and orphan markers into a\n * single CLI structured error envelope. Preserves the legacy code\n * `5002` (was emitted by `runContractSpaceVerifierMarkerCheck`).\n */\nfunction mapMarkerCheckFailures(\n appSpaceId: string,\n section: {\n readonly perSpace: ReadonlyMap<\n string,\n | { readonly kind: 'ok' }\n | { readonly kind: 'absent' }\n | { readonly kind: 'hashMismatch'; readonly markerHash: string; readonly expected: string }\n | { readonly kind: 'missingInvariants'; readonly missing: readonly string[] }\n >;\n readonly orphanMarkers: readonly { readonly spaceId: string; readonly row: unknown }[];\n },\n): CliStructuredError | null {\n const violations: Array<{\n kind: string;\n spaceId: string;\n remediation: string;\n }> = [];\n for (const [spaceId, result] of section.perSpace) {\n if (result.kind === 'ok' || result.kind === 'absent') continue;\n if (result.kind === 'hashMismatch') {\n violations.push({\n kind: 'hashMismatch',\n spaceId,\n remediation:\n spaceId === appSpaceId\n ? 'Run `prisma-next db update` to advance the marker, or roll the database back to the recorded hash.'\n : `Apply on-disk migrations under \\`migrations/${spaceId}/\\` to advance the marker, or remove the conflicting marker row.`,\n });\n continue;\n }\n if (result.kind === 'missingInvariants') {\n violations.push({\n kind: 'invariantsMismatch',\n spaceId,\n remediation: `Re-apply the migrations under \\`migrations/${spaceId}/\\` so the marker carries invariants: ${result.missing.join(', ')}.`,\n });\n }\n }\n for (const orphan of section.orphanMarkers) {\n violations.push({\n kind: 'orphanMarker',\n spaceId: orphan.spaceId,\n remediation: `Add the corresponding extension to \\`extensionPacks\\` in \\`prisma-next.config.ts\\`, or delete the orphan marker row for \"${orphan.spaceId}\".`,\n });\n }\n if (violations.length === 0) return null;\n const lines = violations.map((v) => `- [${v.kind}] ${v.spaceId}: ${v.remediation}`);\n const summary =\n violations.length === 1\n ? 'Contract-space verifier found a violation'\n : `Contract-space verifier found violations (${violations.length})`;\n return new CliStructuredError('5002', summary, {\n domain: 'MIG',\n why: `The on-disk \\`migrations/\\` directory, the \\`extensionPacks\\` declaration, and the live database marker rows are not in agreement.\\n${lines.join('\\n')}`,\n fix: violations[0]?.remediation ?? 'Review and reconcile the violations listed above.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: { violations },\n });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport {\n type AggregatePerSpacePlan,\n type ContractMarkerRecordLike,\n type ContractSpaceAggregate,\n type ContractSpaceMember,\n graphWalkStrategy,\n} from '@prisma-next/migration-tools/aggregate';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { errorNoInvariantPath } from '@prisma-next/migration-tools/errors';\nimport { findPathWithDecision } from '@prisma-next/migration-tools/migration-graph';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport {\n type BuildAggregateInputs,\n buildContractSpaceAggregate,\n} from '../../utils/contract-space-aggregate-loader';\nimport type {\n AggregatePerSpaceExecutionEntry,\n MigrationApplyFailure,\n MigrationApplyPathDecision,\n MigrationApplyResult,\n MigrationApplySuccess,\n OnControlProgress,\n} from '../types';\nimport { applyAggregate, buildPerSpaceBreakdown } from './apply-aggregate';\n\n/**\n * Inputs for the aggregate-walking `migrate` control-api\n * operation.\n *\n * The CLI command resolves the descriptor surface (config, refs,\n * contract envelope) and hands a flat input through. The operation\n * is the single descriptor-free seam between the CLI and the\n * aggregate runtime.\n */\nexport interface ExecuteMigrationApplyOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n /** Already-validated app contract (the canonical \"where we are heading\" hash). */\n readonly contract: Contract;\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly migrationsDir: string;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly targetId: TTargetId;\n /**\n * Already-loaded app-space migration packages. The CLI command\n * loads these via `loadMigrationPackages(appMigrationsDir)`; the\n * operation hydrates the app member's graph with them. Required\n * because the framework-neutral aggregate loader doesn't know how\n * to read the user's `migrations/` directory layout (it's family-\n * aware: ops.json shape, manifest keys, etc.).\n */\n readonly appMigrationPackages: ReadonlyArray<OnDiskMigrationPackage>;\n /**\n * Optional app-space ref override. When provided, the app member's\n * graph-walk targets this hash instead of `member.headRef.hash`.\n * Extensions are unaffected — they always walk to their own head.\n *\n * Sub-spec § `--ref <hash>` semantics under multi-space.\n */\n readonly refHash?: string;\n /**\n * Required invariants attached to the user-supplied app-space ref.\n * Threaded into the graph-walk's `required` calculation so the\n * planner picks an invariant-bearing path and surfaces the\n * required/satisfied set on the success envelope. When `refHash`\n * is absent the file's `member.headRef.invariants` are used.\n */\n readonly refInvariants?: readonly string[];\n /**\n * Resolved name of the user-supplied app-space ref. Surfaces in\n * `pathDecision.refName` and in `MIGRATION.NO_INVARIANT_PATH`\n * error envelopes so diagnostics name what the user actually\n * passed (`--ref prod`) instead of a synthetic placeholder.\n * Ignored when `refHash` is absent.\n */\n readonly refName?: string;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Apply pending migrations across every contract space (app +\n * extensions). Replay-only: graph-walk against the on-disk graph for\n * every member; no synth, no introspection.\n *\n * Pipeline:\n *\n * 1. Load aggregate from disk (loader hydrates extension graphs;\n * caller provides app-space packages).\n * 2. Read live marker rows per space (`familyInstance.readAllMarkers`).\n * 3. Per member: `graphWalkStrategy` plots the path from the live\n * marker to `member.headRef.hash` (or `refHash` for the app\n * member when provided). Empty-graph members fail loudly — a\n * \"never planned\" space is a user-error condition for replay.\n * 4. Hand off to {@link applyAggregate} (the runner-driving tail\n * shared with `db init` / `db update`). Marker advancement is\n * inside the per-space transaction.\n *\n * Encodes the replay-only contract: every contract space must have an\n * authored migration graph on disk before this operation can advance it.\n */\nexport async function executeMigrationApply<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteMigrationApplyOptions<TFamilyId, TTargetId>,\n): Promise<MigrationApplyResult> {\n const {\n driver,\n familyInstance,\n contract,\n migrations,\n frameworkComponents,\n migrationsDir,\n extensionPacks,\n targetId,\n appMigrationPackages,\n refHash,\n refInvariants,\n refName,\n onProgress,\n } = options;\n\n const loadInputs: BuildAggregateInputs<TFamilyId, TTargetId> = {\n targetId,\n migrationsDir,\n appContract: contract,\n extensionPacks,\n deserializeContract: (json) => familyInstance.deserializeContract(json),\n appMigrationPackages,\n };\n const loaded = await buildContractSpaceAggregate(loadInputs);\n if (!loaded.ok) {\n throw loaded.failure;\n }\n const aggregate = loaded.value;\n\n const markerRows = await familyInstance.readAllMarkers({ driver });\n\n // Plan every member via graph-walk. App member targets `refHash`\n // when provided, otherwise its own head; extensions always walk\n // to their own head ref.\n const allMembers: ReadonlyArray<ContractSpaceMember> = [aggregate.app, ...aggregate.extensions];\n const perSpacePlans = new Map<string, AggregatePerSpacePlan>();\n // Already-at-head empty-graph members (typically extensions whose\n // head ref is the empty sentinel, or whose live marker already\n // matches the target). Kept out of the runner schedule so we don't\n // write spurious markers for greenfield extensions, but merged back\n // into the success envelope so every loaded member is represented.\n const atHeadResolutions = new Map<string, AggregatePerSpacePlan>();\n for (const member of allMembers) {\n const isAppMember = member.spaceId === aggregate.app.spaceId;\n const targetHash = isAppMember && refHash !== undefined ? refHash : member.headRef.hash;\n const liveMarker = markerRows.get(member.spaceId) ?? null;\n\n // Empty-graph members fail loudly: replay needs an on-disk path\n // and an empty graph means the user has never planned this space.\n if (member.migrations.graph.nodes.size === 0) {\n // Edge case: target == EMPTY (greenfield, nothing to do) or\n // the live marker already matches the target. Loader integrity\n // allows this for extensions whose head ref is the empty\n // sentinel. Record a zero-op resolution so the aggregate result\n // still surfaces the member in `perSpace[]` as already-at-head;\n // the runner is not invoked for these members because they have\n // no authored ops and (for greenfield extensions) no marker to\n // advance.\n const liveHash = liveMarker?.storageHash;\n if (\n targetHash === liveHash ||\n (liveHash === undefined && targetHash === EMPTY_CONTRACT_HASH)\n ) {\n atHeadResolutions.set(\n member.spaceId,\n buildAtHeadResolution({\n aggregateTargetId: aggregate.targetId,\n member,\n targetHash,\n liveMarker,\n }),\n );\n continue;\n }\n return notOk(buildNeverPlannedFailure(member.spaceId, targetHash));\n }\n\n const targetInvariants =\n isAppMember && refHash !== undefined && refInvariants !== undefined\n ? refInvariants\n : member.headRef.invariants;\n const targetMember: ContractSpaceMember =\n targetHash === member.headRef.hash && targetInvariants === member.headRef.invariants\n ? member\n : { ...member, headRef: { hash: targetHash, invariants: targetInvariants } };\n\n const walked = graphWalkStrategy({\n aggregateTargetId: aggregate.targetId,\n member: targetMember,\n currentMarker: liveMarker,\n ...(isAppMember && refName !== undefined ? { refName } : {}),\n });\n if (walked.kind === 'unreachable') {\n return notOk(buildPathNotFoundFailure(member.spaceId, liveMarker, targetHash));\n }\n if (walked.kind === 'unsatisfiable') {\n // Surface the canonical MIGRATION.NO_INVARIANT_PATH envelope\n // (the error rendering pipeline maps it to meta.code +\n // meta.required + meta.missing + meta.structuralPath that the\n // cli-journeys invariant suite asserts on).\n // Greenfield runs (no marker yet) use the canonical empty-hash\n // sentinel so the structural path stays attached to the\n // `MIGRATION.NO_INVARIANT_PATH` error envelope. Using an empty\n // string here would leave the structural lookup with a hash that\n // is never a graph node, producing an empty `structuralPath` and\n // a less actionable diagnostic.\n const fromHash = liveMarker?.storageHash ?? EMPTY_CONTRACT_HASH;\n const structural = findPathWithDecision(targetMember.migrations.graph, fromHash, targetHash, {\n required: new Set<string>(),\n });\n const structuralPath =\n structural.kind === 'ok'\n ? structural.decision.selectedPath.map((edge) => ({\n dirName: edge.dirName,\n migrationHash: edge.migrationHash,\n from: edge.from,\n to: edge.to,\n invariants: edge.invariants,\n }))\n : [];\n throw errorNoInvariantPath({\n ...(isAppMember && refName !== undefined ? { refName } : {}),\n required: targetInvariants,\n missing: walked.missing,\n structuralPath,\n });\n }\n\n perSpacePlans.set(member.spaceId, walked.result);\n }\n\n const canonicalOrder = [...aggregate.extensions.map((m) => m.spaceId), aggregate.app.spaceId];\n const applyOrder = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId));\n\n // Short-circuit: nothing pending across any space (no runner-bound\n // plans). Surfaces every loaded member — including at-head empty-\n // graph extensions — in `perSpace[]` so the result reflects the\n // full aggregate, not just the spaces the runner would have touched.\n const totalPlannedOps = sumPlannedOps(applyOrder, perSpacePlans);\n if (totalPlannedOps === 0) {\n const ordered = canonicalOrder\n .filter((spaceId) => perSpacePlans.has(spaceId) || atHeadResolutions.has(spaceId))\n .map((spaceId) => {\n const entry = perSpacePlans.get(spaceId) ?? atHeadResolutions.get(spaceId);\n if (entry === undefined) {\n throw new Error(`Unreachable: missing per-space plan for \"${spaceId}\"`);\n }\n return { spaceId, entry };\n });\n const perSpace = buildPerSpaceBreakdown(ordered, aggregate.app.spaceId, {\n includeMarkers: true,\n });\n const totalSpaces = ordered.length;\n return ok(\n buildSuccess({\n aggregate,\n orderedResolutions: ordered,\n perSpace,\n totalOpsExecuted: 0,\n summary:\n totalSpaces === 0\n ? 'Already up to date — no contract spaces are loaded'\n : totalSpaces === 1\n ? 'Already up to date'\n : `Already up to date across ${totalSpaces} space(s)`,\n }),\n );\n }\n\n const applied = await applyAggregate({\n aggregate,\n perSpacePlans,\n applyOrder,\n driver,\n familyInstance,\n migrations,\n frameworkComponents,\n policy: { allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'] },\n action: 'migrationApply',\n ...ifDefined('onProgress', onProgress),\n });\n\n if (!applied.ok) {\n const failure: MigrationApplyFailure = {\n code: 'RUNNER_FAILED',\n summary: applied.failure.summary,\n why: applied.failure.why,\n meta: applied.failure.meta,\n };\n return notOk(failure);\n }\n\n // Merge at-head zero-op resolutions back into the canonical order\n // so the success envelope surfaces every loaded member, not just\n // those the runner executed.\n const orderedAll = canonicalOrder\n .filter((spaceId) => perSpacePlans.has(spaceId) || atHeadResolutions.has(spaceId))\n .map((spaceId) => {\n if (perSpacePlans.has(spaceId)) {\n const fromRunner = applied.value.orderedResolutions.find((r) => r.spaceId === spaceId);\n if (fromRunner !== undefined) return fromRunner;\n }\n const entry = atHeadResolutions.get(spaceId);\n if (entry === undefined) {\n throw new Error(`Unreachable: missing per-space plan for \"${spaceId}\"`);\n }\n return { spaceId, entry };\n });\n const perSpaceAll = buildPerSpaceBreakdown(orderedAll, aggregate.app.spaceId, {\n includeMarkers: true,\n });\n const totalMigrationsApplied = applied.value.orderedResolutions.reduce(\n (sum, r) => sum + (r.entry.migrationEdges?.length ?? 0),\n 0,\n );\n const summary = `Applied ${totalMigrationsApplied} migration(s) (${applied.value.totalOpsExecuted} operation(s)) across ${orderedAll.length} contract space(s)`;\n\n return ok(\n buildSuccess({\n aggregate,\n orderedResolutions: orderedAll,\n perSpace: perSpaceAll,\n totalOpsExecuted: applied.value.totalOpsExecuted,\n summary,\n }),\n );\n}\n\n/**\n * Build a zero-op {@link AggregatePerSpacePlan} for an empty-graph\n * member whose live marker already matches the target. Lets the apply\n * pipeline thread the member through `perSpacePlans` -> `applyOrder`\n * -> the success envelope's `perSpace[]` block so the result reflects\n * every loaded space, even when there is nothing to execute.\n */\nfunction buildAtHeadResolution(args: {\n readonly aggregateTargetId: string;\n readonly member: ContractSpaceMember;\n readonly targetHash: string;\n readonly liveMarker: ContractMarkerRecordLike | null;\n}): AggregatePerSpacePlan {\n const { aggregateTargetId, member, targetHash, liveMarker } = args;\n return {\n plan: {\n targetId: aggregateTargetId,\n spaceId: member.spaceId,\n origin: liveMarker === null ? null : { storageHash: liveMarker.storageHash },\n destination: { storageHash: targetHash },\n operations: [],\n providedInvariants: [],\n },\n displayOps: [],\n destinationContract: member.contract,\n strategy: 'graph-walk',\n migrationEdges: [],\n };\n}\n\nfunction sumPlannedOps(\n applyOrder: readonly string[],\n perSpacePlans: ReadonlyMap<string, AggregatePerSpacePlan>,\n): number {\n let total = 0;\n for (const spaceId of applyOrder) {\n const entry = perSpacePlans.get(spaceId);\n if (!entry) continue;\n total += entry.plan.operations.length;\n }\n return total;\n}\n\ninterface BuildSuccessArgs {\n readonly aggregate: ContractSpaceAggregate;\n readonly orderedResolutions: ReadonlyArray<{\n readonly spaceId: string;\n readonly entry: AggregatePerSpacePlan;\n }>;\n readonly perSpace: ReadonlyArray<AggregatePerSpaceExecutionEntry>;\n readonly totalOpsExecuted: number;\n readonly summary: string;\n}\n\nfunction buildSuccess(args: BuildSuccessArgs): MigrationApplySuccess {\n // The marker hash surfaced at the top level is the **app member's**\n // post-apply marker (today's single-space `markerHash` field).\n // Per-space markers live on `perSpace[].marker.storageHash`.\n const appResolution = args.orderedResolutions.find(\n (r) => r.spaceId === args.aggregate.app.spaceId,\n );\n const appMarkerHash =\n appResolution?.entry.plan.destination.storageHash ?? args.aggregate.app.headRef.hash;\n\n // Per-migration entries (one per authored edge) preserve the\n // single-space `migrationsApplied` count semantics for back-compat\n // with existing JSON-shape consumers (e.g. `parsed.applied.length`\n // in integration tests). The aggregate per-space breakdown lives on\n // `perSpace[]`.\n const applied = args.orderedResolutions.flatMap((r) => {\n const edges = r.entry.migrationEdges ?? [];\n return edges.map((edge) => ({\n spaceId: r.spaceId,\n dirName: edge.dirName,\n migrationHash: edge.migrationHash,\n from: edge.from,\n to: edge.to,\n operationsExecuted: edge.operationCount,\n }));\n });\n\n const appPlan = appResolution?.entry;\n const pathDecision: MigrationApplyPathDecision | undefined = appPlan?.pathDecision\n ? {\n fromHash: appPlan.pathDecision.fromHash,\n toHash: appPlan.pathDecision.toHash,\n alternativeCount: appPlan.pathDecision.alternativeCount,\n tieBreakReasons: appPlan.pathDecision.tieBreakReasons,\n ...(appPlan.pathDecision.refName !== undefined\n ? { refName: appPlan.pathDecision.refName }\n : {}),\n requiredInvariants: appPlan.pathDecision.requiredInvariants ?? [],\n satisfiedInvariants: appPlan.pathDecision.satisfiedInvariants ?? [],\n selectedPath: appPlan.pathDecision.selectedPath.map((entry) => ({\n dirName: entry.dirName,\n migrationHash: entry.migrationHash,\n from: entry.from,\n to: entry.to,\n invariants: entry.invariants,\n })),\n }\n : undefined;\n\n return {\n migrationsApplied: applied.length,\n markerHash: appMarkerHash,\n applied,\n summary: args.summary,\n perSpace: args.perSpace,\n ...(pathDecision !== undefined ? { pathDecision } : {}),\n };\n}\n\nfunction buildNeverPlannedFailure(spaceId: string, targetHash: string): MigrationApplyFailure {\n return {\n code: 'MIGRATION_PATH_NOT_FOUND',\n summary: `No on-disk migrations for contract space \"${spaceId}\"`,\n why: `migrate is replay-only: every contract space must have an authored migration graph on disk. Space \"${spaceId}\" has no migrations under \\`migrations/${spaceId}/\\` but its head ref targets \"${targetHash}\". Run \\`prisma-next migration plan\\` first to materialise the path.`,\n meta: { spaceId, target: targetHash, kind: 'neverPlanned' },\n };\n}\n\nfunction buildPathNotFoundFailure(\n spaceId: string,\n marker: ContractMarkerRecordLike | null,\n targetHash: string,\n): MigrationApplyFailure {\n const fromHash = marker?.storageHash ?? '<empty>';\n // The single-space-degenerate phrasing names the user-visible\n // condition (a contract has been emitted that no on-disk\n // migration reaches) so the error reads naturally for the\n // single-space app case. Multi-space callers see the same\n // condition expressed against the offending space.\n const summary =\n spaceId === 'app'\n ? 'Current contract has no planned migration path'\n : `Current contract has no planned migration path for contract space \"${spaceId}\"`;\n return {\n code: 'MIGRATION_PATH_NOT_FOUND',\n summary,\n why: `Cannot reach target \"${targetHash}\" from current marker \"${fromHash}\" in space \"${spaceId}\". The on-disk migration graph for this space does not connect the two states. Run \\`prisma-next migration plan\\` to materialise the path.`,\n meta: { spaceId, fromHash, targetHash, kind: 'pathUnreachable' },\n };\n}\n","import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { emit as emitContractArtifacts } from '@prisma-next/emitter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlFamilyInstance,\n ControlStack,\n CoreSchemaView,\n MigrationPlanOperation,\n OperationPreview,\n SignDatabaseResult,\n VerifyDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport {\n APP_SPACE_ID,\n createControlStack,\n hasMigrations,\n hasOperationPreview,\n hasPslContractInfer,\n hasSchemaView,\n} from '@prisma-next/framework-components/control';\nimport type { PslDocumentAst } from '@prisma-next/framework-components/psl-ast';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { assertFrameworkComponentsCompatible } from '../utils/framework-components';\nimport { enrichContract } from './contract-enrichment';\nimport { ContractValidationError } from './errors';\nimport { executeDbInit } from './operations/db-init';\nimport { executeDbUpdate } from './operations/db-update';\nimport { type ExecuteDbVerifyResult, executeDbVerify } from './operations/db-verify';\nimport { executeMigrationApply } from './operations/migration-apply';\n\nimport type {\n ControlActionName,\n ControlClient,\n ControlClientOptions,\n DbInitOptions,\n DbInitResult,\n DbUpdateOptions,\n DbUpdateResult,\n DbVerifyOptions,\n EmitOptions,\n EmitResult,\n IntrospectOptions,\n MigrationApplyOptions,\n MigrationApplyResult,\n OnControlProgress,\n SchemaVerifyOptions,\n SignOptions,\n VerifyOptions,\n} from './types';\n\n/**\n * Creates a programmatic control client for Prisma Next operations.\n *\n * The client accepts framework component descriptors at creation time,\n * manages driver lifecycle via connect()/close(), and exposes domain\n * operations that delegate to the existing family instance methods.\n *\n * @see {@link ControlClient} for the client interface\n * @see README.md \"Programmatic Control API\" section for usage examples\n */\nexport function createControlClient(options: ControlClientOptions): ControlClient {\n return new ControlClientImpl(options);\n}\n\n/**\n * Implementation of ControlClient.\n * Manages initialization and connection state, delegates operations to family instance.\n */\nclass ControlClientImpl implements ControlClient {\n private readonly options: ControlClientOptions;\n private stack: ControlStack | null = null;\n private driver: ControlDriverInstance<string, string> | null = null;\n private familyInstance: ControlFamilyInstance<string, unknown> | null = null;\n private frameworkComponents: ReadonlyArray<\n TargetBoundComponentDescriptor<string, string>\n > | null = null;\n private initialized = false;\n private readonly defaultConnection: unknown;\n\n constructor(options: ControlClientOptions) {\n this.options = options;\n this.defaultConnection = options.connection;\n }\n\n init(): void {\n if (this.initialized) {\n return; // Idempotent\n }\n\n this.stack = createControlStack({\n family: this.options.family,\n target: this.options.target,\n adapter: this.options.adapter,\n driver: this.options.driver,\n extensionPacks: this.options.extensionPacks,\n });\n\n this.familyInstance = this.options.family.create(this.stack);\n\n // Validate and type-narrow framework components\n const rawComponents = [\n this.options.target,\n this.options.adapter,\n ...(this.options.extensionPacks ?? []),\n ];\n this.frameworkComponents = assertFrameworkComponentsCompatible(\n this.options.family.familyId,\n this.options.target.targetId,\n rawComponents,\n );\n\n this.initialized = true;\n }\n\n async connect(connection?: unknown): Promise<void> {\n // Auto-init if needed\n this.init();\n\n if (this.driver) {\n throw new Error('Already connected. Call close() before reconnecting.');\n }\n\n // Resolve connection: argument > default from options\n const resolvedConnection = connection ?? this.defaultConnection;\n if (resolvedConnection === undefined) {\n throw new Error(\n 'No connection provided. Pass a connection to connect() or provide a default connection when creating the client.',\n );\n }\n\n // Check for driver descriptor\n if (!this.stack?.driver) {\n throw new Error(\n 'Driver is not configured. Pass a driver descriptor when creating the control client to enable database operations.',\n );\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: required for runtime connection type flexibility\n this.driver = await this.stack.driver.create(resolvedConnection as any);\n }\n\n async close(): Promise<void> {\n if (this.driver) {\n await this.driver.close();\n this.driver = null;\n }\n }\n\n private async ensureConnected(): Promise<{\n driver: ControlDriverInstance<string, string>;\n familyInstance: ControlFamilyInstance<string, unknown>;\n frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<string, string>>;\n }> {\n // Auto-init if needed\n this.init();\n\n // Auto-connect if not connected and default connection is available\n if (!this.driver && this.defaultConnection !== undefined) {\n await this.connect(this.defaultConnection);\n }\n\n if (!this.driver || !this.familyInstance || !this.frameworkComponents) {\n throw new Error('Not connected. Call connect(connection) first.');\n }\n return {\n driver: this.driver,\n familyInstance: this.familyInstance,\n frameworkComponents: this.frameworkComponents,\n };\n }\n\n private async connectWithProgress(\n connection: unknown | undefined,\n action: ControlActionName,\n onProgress?: OnControlProgress,\n ): Promise<void> {\n if (connection === undefined) return;\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: 'connect',\n label: 'Connecting to database...',\n });\n try {\n await this.connect(connection);\n onProgress?.({ action, kind: 'spanEnd', spanId: 'connect', outcome: 'ok' });\n } catch (error) {\n onProgress?.({ action, kind: 'spanEnd', spanId: 'connect', outcome: 'error' });\n throw error;\n }\n }\n\n async verify(options: VerifyOptions): Promise<VerifyDatabaseResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'verify', onProgress);\n const { driver, familyInstance } = await this.ensureConnected();\n\n // Validate contract using family instance\n let contract: Contract;\n try {\n contract = familyInstance.deserializeContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n // Emit verify span\n onProgress?.({\n action: 'verify',\n kind: 'spanStart',\n spanId: 'verify',\n label: 'Verifying database marker...',\n });\n\n try {\n // Delegate to family instance verify method\n // Note: We pass empty strings for contractPath/configPath since the programmatic\n // API doesn't deal with file paths. The family instance accepts these as optional\n // metadata for error reporting.\n const result = await familyInstance.verify({\n driver,\n contract,\n expectedTargetId: this.options.target.targetId,\n contractPath: '',\n });\n\n onProgress?.({\n action: 'verify',\n kind: 'spanEnd',\n spanId: 'verify',\n outcome: result.ok ? 'ok' : 'error',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'verify',\n kind: 'spanEnd',\n spanId: 'verify',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n async schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'schemaVerify', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n // Validate contract using family instance\n let contract: Contract;\n try {\n contract = familyInstance.deserializeContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n // Emit schemaVerify span\n onProgress?.({\n action: 'schemaVerify',\n kind: 'spanStart',\n spanId: 'schemaVerify',\n label: 'Verifying database schema...',\n });\n\n try {\n // Introspect the live schema, then verify the contract against\n // it. Composing the two primitives here keeps the family\n // interface a single synchronous verifier and gives callers\n // (and tests) explicit control over the introspected schema.\n const schema = await familyInstance.introspect({ driver, contract });\n const result = familyInstance.verifySchema({\n contract,\n schema,\n strict: options.strict ?? false,\n frameworkComponents,\n });\n\n onProgress?.({\n action: 'schemaVerify',\n kind: 'spanEnd',\n spanId: 'schemaVerify',\n outcome: result.ok ? 'ok' : 'error',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'schemaVerify',\n kind: 'spanEnd',\n spanId: 'schemaVerify',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n async sign(options: SignOptions): Promise<SignDatabaseResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'sign', onProgress);\n const { driver, familyInstance } = await this.ensureConnected();\n\n // Validate contract using family instance\n let contract: Contract;\n try {\n contract = familyInstance.deserializeContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n // Emit sign span\n onProgress?.({\n action: 'sign',\n kind: 'spanStart',\n spanId: 'sign',\n label: 'Signing database...',\n });\n\n try {\n // Delegate to family instance sign method\n const result = await familyInstance.sign({\n driver,\n contract,\n contractPath: options.contractPath ?? '',\n ...ifDefined('configPath', options.configPath),\n });\n\n onProgress?.({\n action: 'sign',\n kind: 'spanEnd',\n spanId: 'sign',\n outcome: 'ok',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'sign',\n kind: 'spanEnd',\n spanId: 'sign',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n async dbInit(options: DbInitOptions): Promise<DbInitResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'dbInit', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n if (!hasMigrations(this.options.target)) {\n throw new Error(`Target \"${this.options.target.targetId}\" does not support migrations`);\n }\n\n let contract: Contract;\n try {\n contract = familyInstance.deserializeContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n return executeDbInit({\n driver,\n familyInstance,\n contract,\n mode: options.mode,\n migrations: this.options.target.migrations,\n frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: this.options.target.targetId,\n extensionPacks: this.options.extensionPacks ?? [],\n ...ifDefined('onProgress', onProgress),\n });\n }\n\n async dbUpdate(options: DbUpdateOptions): Promise<DbUpdateResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'dbUpdate', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n if (!hasMigrations(this.options.target)) {\n throw new Error(`Target \"${this.options.target.targetId}\" does not support migrations`);\n }\n\n let contract: Contract;\n try {\n contract = familyInstance.deserializeContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n return executeDbUpdate({\n driver,\n familyInstance,\n contract,\n mode: options.mode,\n migrations: this.options.target.migrations,\n frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: this.options.target.targetId,\n extensionPacks: this.options.extensionPacks ?? [],\n ...ifDefined('acceptDataLoss', options.acceptDataLoss),\n ...ifDefined('onProgress', onProgress),\n });\n }\n\n async dbVerify(options: DbVerifyOptions): Promise<ExecuteDbVerifyResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'dbVerify', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n return executeDbVerify({\n driver,\n familyInstance,\n contract: options.contract,\n migrationsDir: options.migrationsDir,\n targetId: this.options.target.targetId,\n extensionPacks: this.options.extensionPacks ?? [],\n frameworkComponents,\n mode: options.strict ? 'strict' : 'lenient',\n skipSchema: options.skipSchema,\n skipMarker: options.skipMarker,\n ...ifDefined('onProgress', onProgress),\n });\n }\n\n async readMarker(): Promise<ContractMarkerRecord | null> {\n const { driver, familyInstance } = await this.ensureConnected();\n // The CLI client's readMarker reads the app's marker. Per-extension\n // readers go through the orchestrator's per-space planner / runner\n // boundary, which threads the extension's space id through the\n // family interface explicitly.\n return familyInstance.readMarker({ driver, space: APP_SPACE_ID });\n }\n\n async readAllMarkers(): Promise<ReadonlyMap<string, ContractMarkerRecord>> {\n const { driver, familyInstance } = await this.ensureConnected();\n return familyInstance.readAllMarkers({ driver });\n }\n\n async migrationApply(options: MigrationApplyOptions): Promise<MigrationApplyResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'migrationApply', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n if (!hasMigrations(this.options.target)) {\n throw new Error(`Target \"${this.options.target.targetId}\" does not support migrations`);\n }\n\n let contract: Contract;\n try {\n contract = familyInstance.deserializeContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n return executeMigrationApply({\n driver,\n familyInstance,\n contract,\n migrations: this.options.target.migrations,\n frameworkComponents,\n migrationsDir: options.migrationsDir,\n extensionPacks: this.options.extensionPacks ?? [],\n targetId: this.options.target.targetId,\n appMigrationPackages: options.appMigrationPackages,\n ...ifDefined('refHash', options.refHash),\n ...ifDefined('refInvariants', options.refInvariants),\n ...ifDefined('refName', options.refName),\n ...ifDefined('onProgress', onProgress),\n });\n }\n\n async introspect(options?: IntrospectOptions): Promise<unknown> {\n const onProgress = options?.onProgress;\n await this.connectWithProgress(options?.connection, 'introspect', onProgress);\n const { driver, familyInstance } = await this.ensureConnected();\n\n // TODO: Pass schema option to familyInstance.introspect when schema filtering is implemented\n const _schema = options?.schema;\n void _schema;\n\n // Emit introspect span\n onProgress?.({\n action: 'introspect',\n kind: 'spanStart',\n spanId: 'introspect',\n label: 'Introspecting database schema...',\n });\n\n try {\n const result = await familyInstance.introspect({ driver });\n\n onProgress?.({\n action: 'introspect',\n kind: 'spanEnd',\n spanId: 'introspect',\n outcome: 'ok',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'introspect',\n kind: 'spanEnd',\n spanId: 'introspect',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n toSchemaView(schemaIR: unknown): CoreSchemaView | undefined {\n this.init();\n if (this.familyInstance && hasSchemaView(this.familyInstance)) {\n return this.familyInstance.toSchemaView(schemaIR);\n }\n return undefined;\n }\n\n inferPslContract(schemaIR: unknown): PslDocumentAst | undefined {\n this.init();\n if (this.familyInstance && hasPslContractInfer(this.familyInstance)) {\n return this.familyInstance.inferPslContract(schemaIR);\n }\n return undefined;\n }\n\n toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview | undefined {\n this.init();\n if (this.familyInstance && hasOperationPreview(this.familyInstance)) {\n return this.familyInstance.toOperationPreview(operations);\n }\n return undefined;\n }\n\n async emit(options: EmitOptions): Promise<EmitResult> {\n const { onProgress, contractConfig } = options;\n\n // Ensure initialized (creates stack and family instance)\n // emit() does NOT require a database connection\n this.init();\n\n if (!this.familyInstance) {\n throw new Error('Family instance was not initialized. This is a bug.');\n }\n\n let contractRaw: unknown;\n onProgress?.({\n action: 'emit',\n kind: 'spanStart',\n spanId: 'resolveSource',\n label: 'Resolving contract source...',\n });\n\n try {\n const stack = this.stack!;\n const sourceContext = {\n composedExtensionPacks: stack.extensionPacks.map((p) => p.id),\n scalarTypeDescriptors: stack.scalarTypeDescriptors,\n authoringContributions: stack.authoringContributions,\n codecLookup: stack.codecLookup,\n controlMutationDefaults: stack.controlMutationDefaults,\n resolvedInputs: contractConfig.source.inputs ?? [],\n };\n const providerResult = await contractConfig.source.load(sourceContext);\n if (!providerResult.ok) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'resolveSource',\n outcome: 'error',\n });\n\n return notOk({\n code: 'CONTRACT_SOURCE_INVALID',\n summary: providerResult.failure.summary,\n why: providerResult.failure.summary,\n meta: providerResult.failure.meta,\n diagnostics: providerResult.failure,\n });\n }\n contractRaw = providerResult.value;\n\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'resolveSource',\n outcome: 'ok',\n });\n } catch (error) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'resolveSource',\n outcome: 'error',\n });\n\n const message = error instanceof Error ? error.message : String(error);\n return notOk({\n code: 'CONTRACT_SOURCE_INVALID',\n summary: 'Failed to resolve contract source',\n why: message,\n diagnostics: {\n summary: 'Contract source provider threw an exception',\n diagnostics: [\n {\n code: 'PROVIDER_THROW',\n message,\n },\n ],\n },\n meta: undefined,\n });\n }\n\n // Emit contract\n onProgress?.({\n action: 'emit',\n kind: 'spanStart',\n spanId: 'emit',\n label: 'Emitting contract...',\n });\n\n try {\n // Blind cast: `contractRaw` is the unverified provider\n // payload — `enrichContract` only adds capability + extension\n // metadata onto whatever shape it receives. The structural\n // check happens immediately afterwards via\n // `familyInstance.deserializeContract(enrichedIR)`, which is\n // the seam-of-record and the only thing that may surface\n // structural errors to the caller.\n const enrichedIR = enrichContract(\n contractRaw as unknown as Contract,\n this.frameworkComponents ?? [],\n );\n\n try {\n this.familyInstance.deserializeContract(enrichedIR);\n } catch (error) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'emit',\n outcome: 'error',\n });\n const message = error instanceof Error ? error.message : String(error);\n return notOk({\n code: 'CONTRACT_VALIDATION_FAILED',\n summary: 'Contract validation failed',\n why: message,\n meta: undefined,\n });\n }\n\n const result = await emitContractArtifacts(\n enrichedIR,\n this.stack!,\n this.options.family.emission,\n {\n serializeContract: (contract) =>\n this.options.target.contractSerializer.serializeContract(contract),\n },\n );\n\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'emit',\n outcome: 'ok',\n });\n\n return ok({\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n profileHash: result.profileHash,\n contractJson: result.contractJson,\n contractDts: result.contractDts,\n });\n } catch (error) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'emit',\n outcome: 'error',\n });\n\n return notOk({\n code: 'EMIT_FAILED',\n summary: 'Failed to emit contract',\n why: error instanceof Error ? error.message : String(error),\n meta: undefined,\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAa,0BAAb,cAA6C,MAAM;CACjD;CAEA,YAAY,SAAiB,OAAiB;EAC5C,MAAM,QAAQ;EACd,KAAK,OAAO;EACZ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