@prisma-next/cli 0.14.0-dev.3 → 0.14.0-dev.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.mjs +29 -12
  3. package/dist/cli.mjs.map +1 -1
  4. package/dist/{client-CJzuo5wX.mjs → client-Ri4Tnfhw.mjs} +7 -5
  5. package/dist/client-Ri4Tnfhw.mjs.map +1 -0
  6. package/dist/{command-helpers-DGMvGBeX.mjs → command-helpers-6cNJZ863.mjs} +3 -3
  7. package/dist/{command-helpers-DGMvGBeX.mjs.map → command-helpers-6cNJZ863.mjs.map} +1 -1
  8. package/dist/commands/contract-emit.mjs +1 -1
  9. package/dist/commands/contract-infer.mjs +1 -1
  10. package/dist/commands/db-init.mjs +3 -3
  11. package/dist/commands/db-schema.mjs +3 -3
  12. package/dist/commands/db-sign.mjs +5 -5
  13. package/dist/commands/db-sign.mjs.map +1 -1
  14. package/dist/commands/db-update.mjs +4 -4
  15. package/dist/commands/db-verify.mjs +1 -1
  16. package/dist/commands/migrate.d.mts +1 -1
  17. package/dist/commands/migrate.mjs +6 -6
  18. package/dist/commands/migrate.mjs.map +1 -1
  19. package/dist/commands/migration-check.d.mts +1 -1
  20. package/dist/commands/migration-check.mjs +1 -1
  21. package/dist/commands/migration-graph.d.mts +1 -1
  22. package/dist/commands/migration-graph.mjs +4 -4
  23. package/dist/commands/migration-graph.mjs.map +1 -1
  24. package/dist/commands/migration-list.d.mts +1 -1
  25. package/dist/commands/migration-list.mjs +1 -1
  26. package/dist/commands/migration-log.d.mts +1 -1
  27. package/dist/commands/migration-log.mjs +1 -1
  28. package/dist/commands/migration-new.mjs +4 -4
  29. package/dist/commands/migration-new.mjs.map +1 -1
  30. package/dist/commands/migration-plan.mjs +1 -1
  31. package/dist/commands/migration-show.mjs +4 -4
  32. package/dist/commands/migration-show.mjs.map +1 -1
  33. package/dist/commands/migration-status.d.mts +1 -1
  34. package/dist/commands/migration-status.mjs +1 -1
  35. package/dist/commands/ref.d.mts +1 -1
  36. package/dist/commands/ref.mjs +3 -3
  37. package/dist/commands/ref.mjs.map +1 -1
  38. package/dist/commands/telemetry/index.mjs +1 -1
  39. package/dist/{contract-at-errors-CFXsstzm.mjs → contract-at-errors-DdxWRjMc.mjs} +2 -2
  40. package/dist/{contract-at-errors-CFXsstzm.mjs.map → contract-at-errors-DdxWRjMc.mjs.map} +1 -1
  41. package/dist/{contract-emit-B_qriF8B.mjs → contract-emit-C4i_rUXA.mjs} +6 -6
  42. package/dist/contract-emit-C4i_rUXA.mjs.map +1 -0
  43. package/dist/{contract-emit-C8HmtboH.mjs → contract-emit-CwnzLGfH.mjs} +6 -5
  44. package/dist/contract-emit-CwnzLGfH.mjs.map +1 -0
  45. package/dist/{contract-infer-BYT_ra_U.mjs → contract-infer-C5MVYYOB.mjs} +3 -3
  46. package/dist/{contract-infer-BYT_ra_U.mjs.map → contract-infer-C5MVYYOB.mjs.map} +1 -1
  47. package/dist/{contract-space-aggregate-loader-ClI1KN6d.mjs → contract-space-aggregate-loader-Bu2fjSWV.mjs} +2 -2
  48. package/dist/{contract-space-aggregate-loader-ClI1KN6d.mjs.map → contract-space-aggregate-loader-Bu2fjSWV.mjs.map} +1 -1
  49. package/dist/{db-verify-C24FKhb7.mjs → db-verify-CHyzYwsM.mjs} +8 -5
  50. package/dist/db-verify-CHyzYwsM.mjs.map +1 -0
  51. package/dist/exports/control-api.d.mts +1 -1
  52. package/dist/exports/control-api.mjs +2 -2
  53. package/dist/exports/index.d.mts +5 -1
  54. package/dist/exports/index.d.mts.map +1 -1
  55. package/dist/exports/index.mjs +4 -3
  56. package/dist/exports/index.mjs.map +1 -1
  57. package/dist/format-C3XdaDuA.mjs +102 -0
  58. package/dist/format-C3XdaDuA.mjs.map +1 -0
  59. package/dist/{framework-components-YVQHhPH7.mjs → framework-components-5RljWT7Q.mjs} +2 -2
  60. package/dist/{framework-components-YVQHhPH7.mjs.map → framework-components-5RljWT7Q.mjs.map} +1 -1
  61. package/dist/{init-0HwB-Vh8.mjs → init-DCBYcJXZ.mjs} +12 -8
  62. package/dist/init-DCBYcJXZ.mjs.map +1 -0
  63. package/dist/{inspect-live-schema-DF6IwcDl.mjs → inspect-live-schema-DraXO0SQ.mjs} +4 -4
  64. package/dist/inspect-live-schema-DraXO0SQ.mjs.map +1 -0
  65. package/dist/{migration-check-soB5uZEQ.mjs → migration-check-CTcJfCC4.mjs} +5 -5
  66. package/dist/migration-check-CTcJfCC4.mjs.map +1 -0
  67. package/dist/migration-cli.mjs +1 -1
  68. package/dist/migration-cli.mjs.map +1 -1
  69. package/dist/{migration-command-scaffold-DA-Lhx6o.mjs → migration-command-scaffold-BZIOhPQO.mjs} +4 -4
  70. package/dist/migration-command-scaffold-BZIOhPQO.mjs.map +1 -0
  71. package/dist/{migration-list-DlJJ_38Z.mjs → migration-list-DVHVmMrf.mjs} +4 -4
  72. package/dist/migration-list-DVHVmMrf.mjs.map +1 -0
  73. package/dist/{migration-log-CG0qQAFm.mjs → migration-log-EkG_DZSn.mjs} +4 -4
  74. package/dist/migration-log-EkG_DZSn.mjs.map +1 -0
  75. package/dist/{migration-path-target-Ce6OZImp.mjs → migration-path-target-zK6RG6JY.mjs} +2 -2
  76. package/dist/{migration-path-target-Ce6OZImp.mjs.map → migration-path-target-zK6RG6JY.mjs.map} +1 -1
  77. package/dist/{migration-plan-W_E8FQOk.mjs → migration-plan-o2aqjnfd.mjs} +6 -6
  78. package/dist/migration-plan-o2aqjnfd.mjs.map +1 -0
  79. package/dist/{migration-status-CgWSoI_g.mjs → migration-status-Dlhn-_Cu.mjs} +6 -6
  80. package/dist/migration-status-Dlhn-_Cu.mjs.map +1 -0
  81. package/dist/{telemetry-BIM4beEO.mjs → telemetry-BckOSUWG.mjs} +2 -2
  82. package/dist/{telemetry-BIM4beEO.mjs.map → telemetry-BckOSUWG.mjs.map} +1 -1
  83. package/dist/{types-C_tYiJYx.d.mts → types-qETCCNbe.d.mts} +2 -2
  84. package/dist/{types-C_tYiJYx.d.mts.map → types-qETCCNbe.d.mts.map} +1 -1
  85. package/dist/{verify-DcOYZ1tH.mjs → verify-CLw3YRbl.mjs} +7 -2
  86. package/dist/{verify-DcOYZ1tH.mjs.map → verify-CLw3YRbl.mjs.map} +1 -1
  87. package/package.json +21 -23
  88. package/src/cli.ts +7 -0
  89. package/src/commands/contract-emit.ts +1 -1
  90. package/src/commands/db-sign.ts +1 -1
  91. package/src/commands/db-verify.ts +1 -1
  92. package/src/commands/format.ts +75 -0
  93. package/src/commands/init/detect-package-manager.ts +8 -4
  94. package/src/commands/init/hygiene-package-scripts.ts +16 -3
  95. package/src/commands/inspect-live-schema.ts +1 -1
  96. package/src/commands/lsp.ts +32 -0
  97. package/src/commands/migrate.ts +1 -1
  98. package/src/commands/migration-check.ts +1 -1
  99. package/src/commands/migration-graph.ts +1 -1
  100. package/src/commands/migration-list.ts +1 -1
  101. package/src/commands/migration-log.ts +1 -1
  102. package/src/commands/migration-new.ts +1 -1
  103. package/src/commands/migration-plan.ts +1 -1
  104. package/src/commands/migration-show.ts +1 -1
  105. package/src/commands/migration-status.ts +1 -1
  106. package/src/commands/ref.ts +1 -1
  107. package/src/control-api/client.ts +4 -3
  108. package/src/control-api/operations/contract-emit.ts +7 -7
  109. package/src/control-api/operations/db-verify.ts +1 -0
  110. package/src/control-api/operations/format.ts +98 -0
  111. package/src/exports/index.ts +1 -0
  112. package/src/migration-cli.ts +1 -1
  113. package/src/utils/combine-schema-results.ts +3 -0
  114. package/src/utils/formatters/verify.ts +8 -0
  115. package/src/utils/migration-command-scaffold.ts +1 -1
  116. package/dist/client-CJzuo5wX.mjs.map +0 -1
  117. package/dist/config-loader-p9JMrekQ.mjs +0 -88
  118. package/dist/config-loader-p9JMrekQ.mjs.map +0 -1
  119. package/dist/config-loader.d.mts +0 -16
  120. package/dist/config-loader.d.mts.map +0 -1
  121. package/dist/config-loader.mjs +0 -2
  122. package/dist/contract-emit-B_qriF8B.mjs.map +0 -1
  123. package/dist/contract-emit-C8HmtboH.mjs.map +0 -1
  124. package/dist/db-verify-C24FKhb7.mjs.map +0 -1
  125. package/dist/init-0HwB-Vh8.mjs.map +0 -1
  126. package/dist/inspect-live-schema-DF6IwcDl.mjs.map +0 -1
  127. package/dist/migration-check-soB5uZEQ.mjs.map +0 -1
  128. package/dist/migration-command-scaffold-DA-Lhx6o.mjs.map +0 -1
  129. package/dist/migration-list-DlJJ_38Z.mjs.map +0 -1
  130. package/dist/migration-log-CG0qQAFm.mjs.map +0 -1
  131. package/dist/migration-plan-W_E8FQOk.mjs.map +0 -1
  132. package/dist/migration-status-CgWSoI_g.mjs.map +0 -1
  133. package/src/config-loader.ts +0 -92
  134. package/src/config-path-validation.ts +0 -74
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-CJzuo5wX.mjs","names":["SPAN_IDS","emitContractArtifacts"],"sources":["../src/control-api/errors.ts","../src/control-api/operations/migration-helpers.ts","../src/control-api/operations/run-migration.ts","../src/control-api/operations/db-run.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/migrate.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 { 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","/**\n * Shared runner tail (`runMigration` + `buildPerSpaceBreakdown`/`collectOrdered`).\n * Backs no command directly; consumed by db-run and migrate.\n */\n\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlFamilyInstance,\n MigrationOperationPolicy,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport type { ContractSpaceAggregate, PerSpacePlan } from '@prisma-next/migration-tools/aggregate';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport type { OnControlProgress, PerSpaceExecutionEntry } from '../types';\n\n/**\n * Span id emitted via `onProgress` for the run phase. Stable\n * identifier consumed by the structured-output renderer and by tests.\n */\nconst RUN_SPAN_ID = 'apply' as const;\n\n/**\n * Action that originated this run 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 RunAction = 'dbInit' | 'dbUpdate' | 'migrate';\n\n/**\n * Failure variant emitted by {@link runMigration} when the runner\n * itself rejects the run. Mirrors the failure shape callers\n * already wrap into their own action-specific failure envelopes\n * (`DbInitFailure`, `DbUpdateFailure`, `MigrateFailure`) so each\n * caller keeps owning its own discriminated failure code.\n */\nexport interface RunnerFailure {\n readonly summary: string;\n readonly why?: string;\n readonly meta: Record<string, unknown>;\n}\n\nexport interface RunMigrationInputs<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 planMigration} 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, PerSpacePlan>;\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 `MigrationRunnerFailure.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: RunAction;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Resolved per-space plan in canonical schedule order. Surfaced from\n * {@link runMigration} to callers so each one can build its own\n * action-specific success envelope (e.g. `DbInitSuccess` vs\n * `MigrateSuccess`) without re-deriving the ordering.\n */\nexport interface OrderedResolution {\n readonly spaceId: string;\n readonly entry: PerSpacePlan;\n}\n\nexport interface RunMigrationValue {\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 PerSpaceExecutionEntry[];\n}\n\nexport type RunMigrationResult = Result<RunMigrationValue, RunnerFailure>;\n\n/**\n * Runner-driving tail shared by every run 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 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 `execute` 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 runMigration<TFamilyId extends string, TTargetId extends string>(\n inputs: RunMigrationInputs<TFamilyId, TTargetId>,\n): Promise<RunMigrationResult> {\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\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: RUN_SPAN_ID,\n label: progressLabelForAction(action),\n });\n\n const perSpaceOptions = orderedResolutions.map((r) => ({\n space: r.spaceId,\n plan: r.entry.plan,\n driver,\n destinationContract: r.entry.destinationContract,\n policy,\n frameworkComponents,\n migrationEdges: r.entry.migrationEdges,\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 strictVerification: false,\n }));\n\n const runnerResult = await runner.execute({ driver, perSpaceOptions });\n\n if (!runnerResult.ok) {\n onProgress?.({ action, kind: 'spanEnd', spanId: RUN_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: RUN_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 * `PerSpaceExecutionEntry[]` 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 runMigration} 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 PerSpaceExecutionEntry[] {\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: PerSpaceExecutionEntry = {\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, PerSpacePlan>,\n): readonly OrderedResolution[] {\n return applyOrder.map((spaceId) => {\n const entry = perSpace.get(spaceId);\n if (!entry) {\n throw new Error(`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 run\n * primitive emits. `runMigration` 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: RunAction): string {\n switch (action) {\n case 'dbInit':\n return 'Initialising database across spaces';\n case 'dbUpdate':\n return 'Updating database across spaces';\n case 'migrate':\n return 'Running migration plan across spaces';\n }\n}\n","/**\n * Backs `db init` / `db update`. Strategy: introspect → planMigration; synth-for-app + graph-walk-extensions; plan-mode + orphan-marker preflight.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlAdapterInstance,\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n MigrationOperationPolicy,\n MigrationPlannerConflict,\n MigrationPlanOperation,\n OperationPreview,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { hasOperationPreview } from '@prisma-next/framework-components/control';\nimport {\n type ContractSpaceAggregate,\n collectAggregateNamespaces,\n type PlannerError,\n planMigration,\n} from '@prisma-next/migration-tools/aggregate';\nimport { blindCast } from '@prisma-next/utils/casts';\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 DbInitFailure,\n DbInitResult,\n DbInitSuccess,\n DbUpdateFailure,\n DbUpdateResult,\n DbUpdateSuccess,\n OnControlProgress,\n PerSpaceExecutionEntry,\n} from '../types';\nimport { stripOperations } from './migration-helpers';\nimport {\n buildPerSpaceBreakdown,\n collectOrdered,\n type OrderedResolution,\n runMigration,\n} from './run-migration';\n\n/**\n * Span IDs emitted via `onProgress` during the run 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 runMigration} 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` run 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 ExecuteRunOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly adapter: ControlAdapterInstance<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 planMigration} 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 `execute` — one outer\n * transaction across every space; failure on any space rolls back\n * every space's writes.\n */\nexport async function executeRun<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteRunOptions<TFamilyId, TTargetId>,\n): Promise<DbInitResult | DbUpdateResult> {\n const {\n driver,\n adapter,\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({\n driver,\n contract: collectAggregateNamespaces(aggregate),\n });\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 planMigration<TFamilyId, TTargetId>({\n aggregate,\n currentDBState: { markersBySpaceId: markerRows, schemaIntrospection: schemaIR },\n adapter,\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 const plannerWarnings = aggregatePlannerWarnings(orderedResolutions);\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 ...ifDefined('warnings', plannerWarnings),\n });\n }\n\n // 5. Run mode: hand off to the shared `runMigration` 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 planMigration here; graph-walk\n // only for migrate). Each caller produces perSpacePlans differently;\n // this helper handles the shared run tail.\n const applied = await runMigration({\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 ...ifDefined('warnings', plannerWarnings),\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 ...ifDefined('warnings', plannerWarnings),\n });\n}\n\nfunction aggregatePlannerWarnings(\n orderedResolutions: readonly OrderedResolution[],\n): readonly MigrationPlannerConflict[] | undefined {\n const warnings = orderedResolutions.flatMap((r) => r.entry.warnings ?? []);\n return warnings.length > 0 ? warnings : undefined;\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: PlannerError): 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 blindCast<\n DbInitResult | DbUpdateResult,\n 'notOk(failure) is shape-compatible with both DbInitResult and DbUpdateResult; the union is the return type of the surrounding function'\n >(notOk(failure));\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 PerSpaceExecutionEntry[];\n readonly summary: string;\n readonly warnings?: readonly MigrationPlannerConflict[];\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 ...ifDefined('warnings', args.warnings),\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 PerSpaceExecutionEntry[];\n readonly summary: string;\n readonly warnings?: readonly MigrationPlannerConflict[];\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 ...ifDefined('warnings', args.warnings),\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 readonly warnings?: readonly MigrationPlannerConflict[];\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 ...ifDefined('warnings', args.warnings),\n };\n return blindCast<\n DbInitResult | DbUpdateResult,\n 'notOk(failure) is shape-compatible with both DbInitResult and DbUpdateResult; the union is the return type of the surrounding function'\n >(notOk(failure));\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlAdapterInstance,\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 { executeRun } from './db-run';\n\n/**\n * Options for executing the `db init` operation.\n *\n * `db init` runs the loader → planner → runner pipeline:\n *\n * 1. {@link executeRun} 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 `execute` 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 adapter: ControlAdapterInstance<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 executeRun<TFamilyId, TTargetId>({\n driver: options.driver,\n adapter: options.adapter,\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 ControlAdapterInstance,\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 { executeRun } from './db-run';\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 adapter: ControlAdapterInstance<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 adapter: options.adapter,\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 executeRun<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 executeRun<TFamilyId, TTargetId>>[0], 'mode'>,\n): Promise<DbUpdateResult | null> {\n const planResult = (await executeRun<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 ContractSpaceMember,\n collectAggregateNamespaces,\n requireHeadRef,\n type VerifierOutput,\n verifyMigration,\n} from '@prisma-next/migration-tools/aggregate';\nimport { blindCast, castAs } from '@prisma-next/utils/casts';\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 verifyMigration} 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({\n driver,\n familyInstance,\n onProgress,\n contract: collectAggregateNamespaces(aggregate),\n });\n\n emitVerifySpan(onProgress, 'spanStart');\n const verifyResult = verifyMigration({\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 contract: unknown;\n}): Promise<unknown> {\n const { driver, familyInstance, onProgress, contract } = 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, contract });\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 */\nexport function 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: blindCast<\n never,\n 'family TSchemaIR is opaque to migration-tools; projectedSchema is passed straight through'\n >(projectedSchema),\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 VerifierOutput} 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: VerifierOutput<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 contract = member.contract();\n const headRef = requireHeadRef(member);\n const profileHash = castAs<{ profileHash?: string }>(contract).profileHash;\n return {\n ok: true,\n summary: 'Schema verification skipped',\n contract: {\n storageHash: headRef.hash,\n ...(profileHash ? { profileHash } : {}),\n },\n target: { expected: 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","/**\n * Backs the `migrate` command. Strategy: graph-walk-all-members, replay-only (no introspect/synth/planner).\n */\n\nimport 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 buildSynthMigrationEdge,\n type ContractMarkerRecordLike,\n type ContractSpaceAggregate,\n type ContractSpaceMember,\n graphWalkStrategy,\n type PerSpacePlan,\n requireHeadRef,\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 { 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 MigrateFailure,\n MigratePathDecision,\n MigrateResult,\n MigrateSuccess,\n OnControlProgress,\n PerSpaceExecutionEntry,\n} from '../types';\nimport { buildPerSpaceBreakdown, runMigration } from './run-migration';\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 ExecuteMigrateOptions<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 * 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 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 runMigration} (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 executeMigrate<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteMigrateOptions<TFamilyId, TTargetId>,\n): Promise<MigrateResult> {\n const {\n driver,\n familyInstance,\n contract,\n migrations,\n frameworkComponents,\n migrationsDir,\n extensionPacks,\n targetId,\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 };\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, PerSpacePlan>();\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, PerSpacePlan>();\n for (const member of allMembers) {\n const isAppMember = member.spaceId === aggregate.app.spaceId;\n // The aggregate passed the integrity gate, so every member's head ref\n // is resolved (the app's is synthesised from the live contract).\n const headRef = requireHeadRef(member);\n const memberTargetHash = isAppMember && refHash !== undefined ? refHash : headRef.hash;\n const memberRefInvariants = isAppMember && refHash !== undefined ? refInvariants : undefined;\n const liveMarker = markerRows.get(member.spaceId) ?? null;\n\n const outcome = planMemberPath({\n member,\n aggregate,\n targetHash: memberTargetHash,\n refInvariants: memberRefInvariants,\n liveMarker,\n ...(isAppMember ? { refName } : {}),\n });\n\n if (outcome.kind === 'at-head') {\n // Empty-graph member whose live marker already matches the target.\n // Kept out of the runner schedule so we don't write spurious markers\n // for greenfield extensions, but merged back into the success envelope\n // so every loaded member is represented.\n atHeadResolutions.set(member.spaceId, outcome.plan);\n continue;\n }\n if (outcome.kind === 'never-planned') {\n return notOk(buildNeverPlannedFailure(outcome.spaceId, outcome.targetHash));\n }\n if (outcome.kind === 'unreachable') {\n return notOk(\n buildPathNotFoundFailure(outcome.spaceId, outcome.liveMarker, outcome.targetHash),\n );\n }\n if (outcome.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 structural = findPathWithDecision(\n outcome.targetMember.graph(),\n outcome.liveHash,\n memberTargetHash,\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 ...(outcome.refName !== undefined ? { refName: outcome.refName } : {}),\n required: outcome.targetInvariants,\n missing: outcome.missing,\n structuralPath,\n });\n }\n\n perSpacePlans.set(member.spaceId, outcome.plan);\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 runMigration({\n aggregate,\n perSpacePlans,\n applyOrder,\n driver,\n familyInstance,\n migrations,\n frameworkComponents,\n policy: { allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'] },\n action: 'migrate',\n ...ifDefined('onProgress', onProgress),\n });\n\n if (!applied.ok) {\n const failure: MigrateFailure = {\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,\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 * Outcome variants for one member's path computation.\n *\n * Callers switch on `kind` and map to their own error representation:\n * `executeMigrate` throws / returns `notOk`; `executeMigrateShowCommand`\n * returns a CLI structured error. The shared discriminant guarantees both\n * paths feed `graphWalkStrategy` the same inputs.\n *\n * @internal Exported for `executeMigrateShowCommand` to call.\n */\nexport type MemberPathOutcome =\n | { readonly kind: 'ok'; readonly plan: PerSpacePlan }\n | { readonly kind: 'at-head'; readonly plan: PerSpacePlan }\n | { readonly kind: 'never-planned'; readonly spaceId: string; readonly targetHash: string }\n | {\n readonly kind: 'unreachable';\n readonly spaceId: string;\n readonly liveMarker: ContractMarkerRecordLike | null;\n readonly targetHash: string;\n }\n | {\n readonly kind: 'unsatisfiable';\n readonly spaceId: string;\n readonly isAppMember: boolean;\n readonly missing: readonly string[];\n readonly targetInvariants: readonly string[];\n readonly targetMember: ContractSpaceMember;\n readonly liveHash: string;\n readonly refName: string | undefined;\n };\n\n/**\n * Compute the graph-walk path for one contract-space member.\n *\n * Encapsulates the invariant-correct input assembly that both\n * `executeMigrate` and `executeMigrateShowCommand` must use:\n * - `currentMarker` carries the full live marker including `invariants`\n * (not a stripped `{ storageHash, invariants: [] }` shell).\n * - `targetInvariants` uses the caller-supplied `refInvariants` when a\n * `--to` ref was resolved (not always the file head ref's invariants).\n *\n * Both callers map the returned `MemberPathOutcome` to their own error\n * representation; the path-compute logic is shared and identical.\n *\n * @internal Exported for `executeMigrateShowCommand`.\n */\nexport function planMemberPath({\n member,\n aggregate,\n targetHash,\n refInvariants,\n liveMarker,\n refName,\n}: {\n readonly member: ContractSpaceMember;\n readonly aggregate: Pick<ContractSpaceAggregate, 'targetId' | 'app'>;\n readonly targetHash: string;\n readonly refInvariants: readonly string[] | undefined;\n readonly liveMarker: ContractMarkerRecordLike | null;\n readonly refName?: string;\n}): MemberPathOutcome {\n const isAppMember = member.spaceId === aggregate.app.spaceId;\n const headRef = requireHeadRef(member);\n\n if (member.graph().nodes.size === 0) {\n const liveHash = liveMarker?.storageHash;\n if (targetHash === liveHash || (liveHash === undefined && targetHash === EMPTY_CONTRACT_HASH)) {\n return {\n kind: 'at-head',\n plan: buildAtHeadResolution({\n aggregateTargetId: aggregate.targetId,\n member,\n targetHash,\n liveMarker,\n }),\n };\n }\n return { kind: 'never-planned', spaceId: member.spaceId, targetHash };\n }\n\n const targetInvariants =\n isAppMember && refInvariants !== undefined ? refInvariants : headRef.invariants;\n const targetMember: ContractSpaceMember =\n targetHash === headRef.hash && targetInvariants === 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\n if (walked.kind === 'unreachable') {\n return { kind: 'unreachable', spaceId: member.spaceId, liveMarker, targetHash };\n }\n if (walked.kind === 'unsatisfiable') {\n const liveHash = liveMarker?.storageHash ?? EMPTY_CONTRACT_HASH;\n return {\n kind: 'unsatisfiable',\n spaceId: member.spaceId,\n isAppMember,\n missing: walked.missing,\n targetInvariants,\n targetMember,\n liveHash,\n refName,\n };\n }\n return { kind: 'ok', plan: walked.result };\n}\n\n/**\n * Build a zero-op {@link PerSpacePlan} 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}): PerSpacePlan {\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 buildSynthMigrationEdge({\n currentMarkerStorageHash: liveMarker?.storageHash,\n destinationStorageHash: targetHash,\n operationCount: 0,\n }),\n ],\n };\n}\n\nfunction sumPlannedOps(\n applyOrder: readonly string[],\n perSpacePlans: ReadonlyMap<string, PerSpacePlan>,\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: PerSpacePlan;\n }>;\n readonly perSpace: ReadonlyArray<PerSpaceExecutionEntry>;\n readonly totalOpsExecuted: number;\n readonly summary: string;\n}\n\nfunction buildSuccess(args: BuildSuccessArgs): MigrateSuccess {\n // The marker hash surfaced at the top level is the **app member's**\n // post-migrate marker (the top-level `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 ?? requireHeadRef(args.aggregate.app).hash;\n\n // Per-migration entries (one per authored edge) preserve the\n // `migrationsApplied` count semantics for back-compat with existing\n // JSON-shape consumers (e.g. `parsed.applied.length` in integration\n // tests). The aggregate per-space breakdown lives on `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: MigratePathDecision | 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\n/**\n * Build the `neverPlanned` failure raised when a contract space has no on-disk\n * migration graph but migrate was asked to reach a target hash. The `why`\n * states only the condition; the recovery sequence is composed by\n * `errorPathUnreachable`'s `fix`.\n *\n * @internal Exported for testing only.\n */\nexport function buildNeverPlannedFailure(spaceId: string, targetHash: string): MigrateFailure {\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}\".`,\n meta: { spaceId, target: targetHash, kind: 'neverPlanned' },\n };\n}\n\n/**\n * Build the `pathUnreachable` failure raised when an emitted contract has no\n * on-disk migration edge from the current marker to the target. The `why`\n * states only the condition (no edge between the two named states, and migrate\n * replays edges rather than inventing them); the recovery sequence — plan the\n * edge, then re-apply — is composed by `errorPathUnreachable`'s `fix`, so the\n * two read as one non-redundant plan-then-apply story.\n *\n * @internal Exported for testing only.\n */\nexport function buildPathNotFoundFailure(\n spaceId: string,\n marker: ContractMarkerRecordLike | null,\n targetHash: string,\n): MigrateFailure {\n const fromHash = marker?.storageHash ?? '<empty>';\n // The app-case phrasing names the user-visible condition (a\n // contract has been emitted that no on-disk migration reaches) so\n // the error reads naturally for the app member. Extension spaces\n // see the same 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: `No migration edge connects the current state \"${fromHash}\" to the target \"${targetHash}\" in contract space \"${spaceId}\". The on-disk migration graph does not join the two, and migrate replays existing edges — it never invents one.`,\n meta: { spaceId, fromHash, targetHash, kind: 'pathUnreachable' },\n };\n}\n","import type {\n Contract,\n ContractMarkerRecord,\n LedgerEntryRecord,\n} from '@prisma-next/contract/types';\nimport { emit as emitContractArtifacts } from '@prisma-next/emitter';\nimport type { AuthoringPslBlockDescriptorNamespace } from '@prisma-next/framework-components/authoring';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlAdapterInstance,\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 { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { toExtensionInputs } from '../utils/extension-pack-inputs';\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 { executeMigrate } from './operations/migrate';\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 MigrateOptions,\n MigrateResult,\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 /**\n * Construct the control adapter once for a migration operation and return\n * it, mirroring how the runtime plane builds the execution adapter once in\n * `createExecutionStack`. Only `dbInit` / `dbUpdate` need it (it lowers the\n * planner's DDL); read-only operations never build it. The descriptor is\n * optional on the stack — targets without migrations omit it.\n */\n private buildControlAdapter(): ControlAdapterInstance<string, string> {\n this.init();\n if (!this.stack?.adapter) {\n throw new Error(\n `Target \"${this.options.target.targetId}\" requires an adapter for migrations`,\n );\n }\n return this.stack.adapter.create(this.stack);\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 const adapter = this.buildControlAdapter();\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 adapter,\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 const adapter = this.buildControlAdapter();\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 adapter,\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 /** Reads the per-migration journal; omit `space` to return every space. */\n async readLedger(space?: string): Promise<readonly LedgerEntryRecord[]> {\n const { driver, familyInstance } = await this.ensureConnected();\n return familyInstance.readLedger({ driver, ...ifDefined('space', space) });\n }\n\n async migrate(options: MigrateOptions): Promise<MigrateResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'migrate', 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 executeMigrate({\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 ...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 getPslBlockDescriptors(): AuthoringPslBlockDescriptorNamespace {\n this.init();\n return this.stack!.authoringContributions.pslBlockDescriptors;\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 extensionInputs = toExtensionInputs(\n blindCast<\n readonly unknown[],\n 'toExtensionInputs accepts readonly unknown[] per its documented structural cast boundary'\n >(stack.extensionPacks),\n );\n const composedExtensionContracts = new Map<string, Contract>(\n extensionInputs\n .filter((p) => p.contractSpace !== undefined)\n .map((p) => [\n p.id,\n blindCast<\n Contract,\n 'contractSpace.contractJson is the typed contract for this extension space'\n >(p.contractSpace!.contractJson),\n ]),\n );\n const sourceContext = {\n composedExtensionPacks: stack.extensionPacks.map((p) => p.id),\n composedExtensionContracts,\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 let deserializedContract: Contract;\n try {\n deserializedContract = 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 deserializedContract,\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,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;;;;;ACDA,SAAgB,gBACd,YACiG;CACjG,OAAO,WAAW,KAAK,QAAQ;EAC7B,IAAI,GAAG;EACP,OAAO,GAAG;EACV,gBAAgB,GAAG;CACrB,EAAE;AACJ;;;;;;;ACMA,MAAM,cAAc;;;;;;;;;;;;;;;;;AA6FpB,eAAsB,aACpB,QAC6B;CAC7B,MAAM,EACJ,WACA,eACA,YACA,QACA,gBACA,YACA,qBACA,QACA,QACA,eACE;CAEJ,MAAM,qBAAqB,eAAe,YAAY,aAAa;CAEnE,MAAM,SAAS,WA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AQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,MAAM;IACX,MAAM;IACN,SAAS;IACT,KAAK;IACL,aAAa;KACX,SAAS;KACT,aAAa,CACX;MACE,MAAM;MACN;KACF,CACF;IACF;IACA,MAAM,KAAA;GACR,CAAC;EACH;EAGA,aAAa;GACX,QAAQ;GACR,MAAM;GACN,QAAQ;GACR,OAAO;EACT,CAAC;EAED,IAAI;GAQF,MAAM,aAAa,eACjB,aACA,KAAK,uBAAuB,CAAC,CAC/B;GAEA,IAAI;GACJ,IAAI;IACF,uBAAuB,KAAK,eAAe,oBAAoB,UAAU;GAC3E,SAAS,OAAO;IACd,aAAa;KACX,QAAQ;KACR,MAAM;KACN,QAAQ;KACR,SAAS;IACX,CAAC;IAED,OAAO,MAAM;KACX,MAAM;KACN,SAAS;KACT,KAJc,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;KAKnE,MAAM,KAAA;IACR,CAAC;GACH;GAEA,MAAM,SAAS,MAAMC,KACnB,sBACA,KAAK,OACL,KAAK,QAAQ,OAAO,UACpB,EACE,oBAAoB,aAClB,KAAK,QAAQ,OAAO,mBAAmB,kBAAkB,QAAQ,EACrE,CACF;GAEA,aAAa;IACX,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;GACX,CAAC;GAED,OAAO,GAAG;IACR,aAAa,OAAO;IACpB,GAAG,UAAU,iBAAiB,OAAO,aAAa;IAClD,aAAa,OAAO;IACpB,cAAc,OAAO;IACrB,aAAa,OAAO;GACtB,CAAC;EACH,SAAS,OAAO;GACd,aAAa;IACX,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;GACX,CAAC;GAED,OAAO,MAAM;IACX,MAAM;IACN,SAAS;IACT,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC1D,MAAM,KAAA;GACR,CAAC;EACH;CACF;AACF"}
@@ -1,88 +0,0 @@
1
- import { getEmittedArtifactPaths } from "@prisma-next/emitter";
2
- import { errorConfigFileNotFound, errorConfigValidation, errorUnexpected } from "@prisma-next/errors/control";
3
- import { ifDefined } from "@prisma-next/utils/defined";
4
- import { dirname, resolve } from "pathe";
5
- import { ConfigValidationError, validateConfig } from "@prisma-next/config/config-validation";
6
- import { loadConfig } from "c12";
7
- import { normalizeContractConfig } from "@prisma-next/config/config-types";
8
- //#region src/config-path-validation.ts
9
- function throwValidation(field, why) {
10
- throw new ConfigValidationError(field, why);
11
- }
12
- function finalizeContractSource(source, configDir) {
13
- const resolvedInputs = source.inputs?.map((input) => resolve(configDir, input));
14
- if (resolvedInputs === void 0) return source;
15
- return {
16
- ...source,
17
- inputs: resolvedInputs
18
- };
19
- }
20
- function validateNoOutputsAreInputs(inputs, output) {
21
- if (inputs === void 0 || output === void 0) return;
22
- let emittedArtifactPaths;
23
- try {
24
- emittedArtifactPaths = getEmittedArtifactPaths(output);
25
- } catch (error) {
26
- throwValidation("contract.output", error instanceof Error ? error.message : String(error));
27
- }
28
- const emittedPaths = new Set([emittedArtifactPaths.jsonPath, emittedArtifactPaths.dtsPath]);
29
- for (const input of inputs) if (emittedPaths.has(input)) throwValidation("contract.source.inputs[]", "Config.contract.source.inputs must not include emitted artifact paths derived from contract.output");
30
- }
31
- function finalizeConfig(config, configDir) {
32
- if (!config.contract) return config;
33
- const contract = normalizeContractConfig(config.contract);
34
- const source = finalizeContractSource(contract.source, configDir);
35
- const output = resolve(configDir, contract.output);
36
- validateNoOutputsAreInputs(source.inputs, output);
37
- return {
38
- ...config,
39
- contract: {
40
- ...contract,
41
- source,
42
- output
43
- }
44
- };
45
- }
46
- //#endregion
47
- //#region src/config-loader.ts
48
- async function loadValidatedConfig(configPath) {
49
- const cwd = process.cwd();
50
- const resolvedConfigPath = configPath ? resolve(cwd, configPath) : void 0;
51
- const configCwd = resolvedConfigPath ? dirname(resolvedConfigPath) : cwd;
52
- const result = await loadConfig({
53
- name: "prisma-next",
54
- ...ifDefined("configFile", resolvedConfigPath),
55
- cwd: configCwd
56
- });
57
- if (resolvedConfigPath && result.configFile !== resolvedConfigPath) throw errorConfigFileNotFound(resolvedConfigPath);
58
- if (!result.config || Object.keys(result.config).length === 0) throw errorConfigFileNotFound(result.configFile || resolvedConfigPath || configPath);
59
- validateConfig(result.config);
60
- const loadedConfigDir = result.configFile ? dirname(result.configFile) : configCwd;
61
- return finalizeConfig(result.config, loadedConfigDir);
62
- }
63
- /**
64
- * Loads the Prisma Next config from a TypeScript file.
65
- * Supports both default export and named export.
66
- * Uses c12 to automatically handle TypeScript compilation and config file discovery.
67
- *
68
- * @param configPath - Optional path to config file. Defaults to `./prisma-next.config.ts` in current directory.
69
- * @returns The loaded config object.
70
- * @throws Error if config file doesn't exist or is invalid.
71
- */
72
- async function loadConfig$1(configPath) {
73
- try {
74
- return await loadValidatedConfig(configPath);
75
- } catch (error) {
76
- if (error instanceof ConfigValidationError) throw errorConfigValidation(error.field, { why: error.why });
77
- if (error instanceof Error && "code" in error && typeof error.code === "string") throw error;
78
- if (error instanceof Error) {
79
- if (error.message.includes("not found") || error.message.includes("Cannot find") || error.message.includes("ENOENT")) throw errorConfigFileNotFound(configPath ? resolve(process.cwd(), configPath) : void 0, { why: error.message });
80
- throw errorUnexpected(error.message, { why: `Failed to load config: ${error.message}` });
81
- }
82
- throw errorUnexpected(String(error));
83
- }
84
- }
85
- //#endregion
86
- export { loadConfig$1 as t };
87
-
88
- //# sourceMappingURL=config-loader-p9JMrekQ.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-loader-p9JMrekQ.mjs","names":["loadConfigC12","loadConfig"],"sources":["../src/config-path-validation.ts","../src/config-loader.ts"],"sourcesContent":["import {\n type ContractSourceProvider,\n normalizeContractConfig,\n type PrismaNextConfig,\n} from '@prisma-next/config/config-types';\nimport { ConfigValidationError } from '@prisma-next/config/config-validation';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { resolve } from 'pathe';\n\nfunction throwValidation(field: string, why: string): never {\n throw new ConfigValidationError(field, why);\n}\n\nfunction finalizeContractSource(\n source: ContractSourceProvider,\n configDir: string,\n): ContractSourceProvider {\n const resolvedInputs = source.inputs?.map((input) => resolve(configDir, input));\n if (resolvedInputs === undefined) {\n return source;\n }\n\n return {\n ...source,\n inputs: resolvedInputs,\n };\n}\n\nfunction validateNoOutputsAreInputs(\n inputs: readonly string[] | undefined,\n output: string | undefined,\n): void {\n if (inputs === undefined || output === undefined) {\n return;\n }\n\n let emittedArtifactPaths: ReturnType<typeof getEmittedArtifactPaths>;\n try {\n emittedArtifactPaths = getEmittedArtifactPaths(output);\n } catch (error) {\n throwValidation('contract.output', error instanceof Error ? error.message : String(error));\n }\n\n const emittedPaths = new Set([emittedArtifactPaths.jsonPath, emittedArtifactPaths.dtsPath]);\n\n for (const input of inputs) {\n if (emittedPaths.has(input)) {\n throwValidation(\n 'contract.source.inputs[]',\n 'Config.contract.source.inputs must not include emitted artifact paths derived from contract.output',\n );\n }\n }\n}\n\nexport function finalizeConfig(config: PrismaNextConfig, configDir: string): PrismaNextConfig {\n if (!config.contract) {\n return config;\n }\n const contract = normalizeContractConfig(config.contract);\n const source = finalizeContractSource(contract.source, configDir);\n const output = resolve(configDir, contract.output);\n\n validateNoOutputsAreInputs(source.inputs, output);\n\n return {\n ...config,\n contract: {\n ...contract,\n source,\n output,\n },\n };\n}\n","import type { PrismaNextConfig } from '@prisma-next/config/config-types';\nimport { ConfigValidationError, validateConfig } from '@prisma-next/config/config-validation';\nimport {\n errorConfigFileNotFound,\n errorConfigValidation,\n errorUnexpected,\n} from '@prisma-next/errors/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { loadConfig as loadConfigC12 } from 'c12';\nimport { dirname, resolve } from 'pathe';\nimport { finalizeConfig } from './config-path-validation';\n\nasync function loadValidatedConfig(configPath?: string): Promise<PrismaNextConfig> {\n const cwd = process.cwd();\n const resolvedConfigPath = configPath ? resolve(cwd, configPath) : undefined;\n const configCwd = resolvedConfigPath ? dirname(resolvedConfigPath) : cwd;\n\n const result = await loadConfigC12<PrismaNextConfig>({\n name: 'prisma-next',\n ...ifDefined('configFile', resolvedConfigPath),\n cwd: configCwd,\n });\n\n // When a specific config file was requested, verify it was actually loaded\n // (c12 falls back to searching by name if the specified file doesn't exist)\n if (resolvedConfigPath && result.configFile !== resolvedConfigPath) {\n throw errorConfigFileNotFound(resolvedConfigPath);\n }\n\n // Check if config is missing or empty (c12 may return empty object when file doesn't exist)\n if (!result.config || Object.keys(result.config).length === 0) {\n // Use c12's configFile if available, otherwise use explicit configPath, otherwise omit path\n const displayPath = result.configFile || resolvedConfigPath || configPath;\n throw errorConfigFileNotFound(displayPath);\n }\n\n // Validate config structure\n validateConfig(result.config);\n\n const loadedConfigDir = result.configFile ? dirname(result.configFile) : configCwd;\n return finalizeConfig(result.config, loadedConfigDir);\n}\n\n/**\n * Loads the Prisma Next config from a TypeScript file.\n * Supports both default export and named export.\n * Uses c12 to automatically handle TypeScript compilation and config file discovery.\n *\n * @param configPath - Optional path to config file. Defaults to `./prisma-next.config.ts` in current directory.\n * @returns The loaded config object.\n * @throws Error if config file doesn't exist or is invalid.\n */\nexport async function loadConfig(configPath?: string): Promise<PrismaNextConfig> {\n try {\n return await loadValidatedConfig(configPath);\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw errorConfigValidation(error.field, {\n why: error.why,\n });\n }\n\n // Re-throw structured errors as-is\n if (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code: string }).code === 'string'\n ) {\n throw error;\n }\n\n if (error instanceof Error) {\n // Check for file not found errors\n if (\n error.message.includes('not found') ||\n error.message.includes('Cannot find') ||\n error.message.includes('ENOENT')\n ) {\n // Use resolved path if available, otherwise use original configPath\n const displayPath = configPath ? resolve(process.cwd(), configPath) : undefined;\n throw errorConfigFileNotFound(displayPath, {\n why: error.message,\n });\n }\n // For other errors, wrap in unexpected error\n throw errorUnexpected(error.message, {\n why: `Failed to load config: ${error.message}`,\n });\n }\n throw errorUnexpected(String(error));\n }\n}\n"],"mappings":";;;;;;;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AO,eAAe,oBAC9C,MAAM,wBAAwB,kBAAkB;CAIlD,IAAI,CAAC,OAAO,UAAU,OAAO,KAAK,OAAO,MAAM,CAAC,CAAC,WAAW,GAG1D,MAAM,wBADc,OAAO,cAAc,sBAAsB,UACtB;CAI3C,eAAe,OAAO,MAAM;CAE5B,MAAM,kBAAkB,OAAO,aAAa,QAAQ,OAAO,UAAU,IAAI;CACzE,OAAO,eAAe,OAAO,QAAQ,eAAe;AACtD;;;;;;;;;;AAWA,eAAsBC,aAAW,YAAgD;CAC/E,IAAI;EACF,OAAO,MAAM,oBAAoB,UAAU;CAC7C,SAAS,OAAO;EACd,IAAI,iBAAiB,uBACnB,MAAM,sBAAsB,MAAM,OAAO,EACvC,KAAK,MAAM,IACb,CAAC;EAIH,IACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA2B,SAAS,UAE5C,MAAM;EAGR,IAAI,iBAAiB,OAAO;GAE1B,IACE,MAAM,QAAQ,SAAS,WAAW,KAClC,MAAM,QAAQ,SAAS,aAAa,KACpC,MAAM,QAAQ,SAAS,QAAQ,GAI/B,MAAM,wBADc,aAAa,QAAQ,QAAQ,IAAI,GAAG,UAAU,IAAI,KAAA,GAC3B,EACzC,KAAK,MAAM,QACb,CAAC;GAGH,MAAM,gBAAgB,MAAM,SAAS,EACnC,KAAK,0BAA0B,MAAM,UACvC,CAAC;EACH;EACA,MAAM,gBAAgB,OAAO,KAAK,CAAC;CACrC;AACF"}
@@ -1,16 +0,0 @@
1
- import { PrismaNextConfig } from "@prisma-next/config/config-types";
2
-
3
- //#region src/config-loader.d.ts
4
- /**
5
- * Loads the Prisma Next config from a TypeScript file.
6
- * Supports both default export and named export.
7
- * Uses c12 to automatically handle TypeScript compilation and config file discovery.
8
- *
9
- * @param configPath - Optional path to config file. Defaults to `./prisma-next.config.ts` in current directory.
10
- * @returns The loaded config object.
11
- * @throws Error if config file doesn't exist or is invalid.
12
- */
13
- declare function loadConfig(configPath?: string): Promise<PrismaNextConfig>;
14
- //#endregion
15
- export { loadConfig };
16
- //# sourceMappingURL=config-loader.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-loader.d.mts","names":[],"sources":["../src/config-loader.ts"],"mappings":";;;;;AAoDA;;;;;;;iBAAsB,UAAA,CAAW,UAAA,YAAsB,OAAO,CAAC,gBAAA"}
@@ -1,2 +0,0 @@
1
- import { t as loadConfig } from "./config-loader-p9JMrekQ.mjs";
2
- export { loadConfig };
@@ -1 +0,0 @@
1
- {"version":3,"file":"contract-emit-B_qriF8B.mjs","names":["CliStructuredError","errorUnexpected"],"sources":["../src/utils/formatters/emit.ts","../src/commands/contract-emit.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { relative } from 'pathe';\n\nimport type { GlobalFlags } from '../global-flags';\nimport { isVerbose } from './helpers';\n\n// EmitContractResult type for CLI output formatting (includes file paths)\nexport interface EmitContractResult {\n readonly storageHash: string;\n readonly executionHash?: string;\n readonly profileHash: string;\n readonly outDir: string;\n readonly files: {\n readonly json: string;\n readonly dts: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * Formats human-readable output for contract emit.\n */\nexport function formatEmitOutput(result: EmitContractResult, flags: GlobalFlags): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n // Convert absolute paths to relative paths from cwd\n const jsonPath = relative(process.cwd(), result.files.json);\n const dtsPath = relative(process.cwd(), result.files.dts);\n\n lines.push(`✔ Emitted contract.json → ${jsonPath}`);\n lines.push(`✔ Emitted contract.d.ts → ${dtsPath}`);\n lines.push(` storageHash: ${result.storageHash}`);\n if (result.executionHash) {\n lines.push(` executionHash: ${result.executionHash}`);\n }\n if (result.profileHash) {\n lines.push(` profileHash: ${result.profileHash}`);\n }\n if (isVerbose(flags, 1)) {\n lines.push(` Total time: ${result.timings.total}ms`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for contract emit.\n */\nexport function formatEmitJson(result: EmitContractResult): string {\n const output = {\n ok: true,\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n ...(result.profileHash ? { profileHash: result.profileHash } : {}),\n outDir: result.outDir,\n files: result.files,\n timings: result.timings,\n };\n\n return JSON.stringify(output, null, 2);\n}\n","import { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { errorContractConfigMissing } from '@prisma-next/errors/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, join, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { executeContractEmit } from '../control-api/operations/contract-emit';\nimport type { ContractEmitResult } from '../control-api/types';\nimport { CliStructuredError, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n type EmitContractResult,\n formatEmitJson,\n formatEmitOutput,\n} from '../utils/formatters/emit';\nimport { formatStyledHeader, formatSuccessMessage } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface ContractEmitOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly outputPath?: string;\n}\n\ninterface HeaderPaths {\n readonly displayConfigPath: string;\n readonly outputJsonPath: string;\n readonly outputDtsPath: string;\n}\n\n/**\n * Pre-load the config just to compute display paths for the styled header. The\n * actual emit work goes through `executeContractEmit`, which loads the config\n * itself; the redundant load here is bounded and lets the header render before\n * the emit spans start.\n */\nasync function resolveHeaderPaths(\n configOption: string | undefined,\n outputPath: string | undefined,\n): Promise<Result<HeaderPaths, CliStructuredError>> {\n const displayConfigPath = configOption\n ? relative(process.cwd(), resolve(configOption))\n : 'prisma-next.config.ts';\n\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = await loadConfig(configOption);\n } catch (error) {\n if (error instanceof CliStructuredError) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: 'Failed to load config',\n }),\n );\n }\n\n const effectiveJsonPath =\n outputPath !== undefined ? join(outputPath, 'contract.json') : config.contract?.output;\n\n if (!effectiveJsonPath) {\n return notOk(\n errorContractConfigMissing({\n why: 'Config.contract.output is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n }),\n );\n }\n\n try {\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } =\n getEmittedArtifactPaths(effectiveJsonPath);\n return ok({ displayConfigPath, outputJsonPath, outputDtsPath });\n } catch (error) {\n return notOk(\n errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n}\n\nasync function executeContractEmitCommand(\n options: ContractEmitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<EmitContractResult, CliStructuredError>> {\n const outputPath = options.outputPath !== undefined ? resolve(options.outputPath) : undefined;\n\n const headerPathsResult = await resolveHeaderPaths(options.config, outputPath);\n if (!headerPathsResult.ok) {\n return headerPathsResult;\n }\n const { displayConfigPath, outputJsonPath, outputDtsPath } = headerPathsResult.value;\n\n if (!flags.json && !flags.quiet) {\n ui.stderr(\n formatStyledHeader({\n command: 'contract emit',\n description: 'Emit your contract artifacts',\n url: 'https://pris.ly/contract-emit',\n details: [\n { label: 'config', value: displayConfigPath },\n { label: 'contract', value: relative(process.cwd(), outputJsonPath) },\n { label: 'types', value: relative(process.cwd(), outputDtsPath) },\n ],\n flags,\n }),\n );\n }\n\n const onProgress = createProgressAdapter({ ui, flags });\n const configPath = options.config ? resolve(options.config) : 'prisma-next.config.ts';\n\n let result: ContractEmitResult;\n try {\n result = await executeContractEmit({\n configPath,\n onProgress,\n ...ifDefined('outputPath', outputPath),\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected('Unexpected error during contract emit', {\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n\n if (result.validationWarning) {\n ui.warn(result.validationWarning);\n }\n\n return ok({\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n profileHash: result.profileHash,\n outDir: dirname(result.files.json),\n files: result.files,\n timings: { total: Date.now() - startTime },\n });\n}\n\nexport function createContractEmitCommand(): Command {\n const command = new Command('emit');\n setCommandDescriptions(\n command,\n 'Emit your contract artifacts',\n 'Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\\n' +\n 'contract.d.ts. The contract.json contains the canonical contract structure, and\\n' +\n 'contract.d.ts provides TypeScript types for type-safe query building.',\n );\n setCommandExamples(command, [\n 'prisma-next contract emit',\n 'prisma-next contract emit --config ./custom-config.ts',\n 'prisma-next contract emit --output-path ./generated',\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--output-path <dir>', 'Directory to write contract.json and contract.d.ts into')\n .action(async (options: ContractEmitOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const startTime = Date.now();\n\n const result = await executeContractEmitCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (emitResult) => {\n if (flags.json) {\n ui.output(formatEmitJson(emitResult));\n } else {\n const output = formatEmitOutput(emitResult, flags);\n if (output) {\n ui.log(output);\n }\n if (!flags.quiet) {\n ui.success(formatSuccessMessage(flags));\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,QAA4B,OAA4B;CACvF,IAAI,MAAM,OACR,OAAO;CAGT,MAAM,QAAkB,CAAC;CAGzB,MAAM,WAAW,SAAS,QAAQ,IAAI,GAAG,OAAO,MAAM,IAAI;CAC1D,MAAM,UAAU,SAAS,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG;CAExD,MAAM,KAAK,6BA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,OAAO,MAAM,IAAI;EACjC,OAAO,OAAO;EACd,SAAS,EAAE,OAAO,KAAK,IAAI,IAAI,UAAU;CAC3C,CAAC;AACH;AAEA,SAAgB,4BAAqC;CACnD,MAAM,UAAU,IAAI,QAAQ,MAAM;CAClC,uBACE,SACA,gCACA,8OAGF;CACA,mBAAmB,SAAS;EAC1B;EACA;EACA;CACF,CAAC;CACD,iBAAiB,OAAO,CAAC,CACtB,OAAO,mBAAmB,+BAA+B,CAAC,CAC1D,OAAO,uBAAuB,yDAAyD,CAAC,CACxF,OAAO,OAAO,YAAiC;EAC9C,MAAM,QAAQ,uBAAuB,OAAO;EAC5C,MAAM,KAAK,iBAAiB,KAAK;EAKjC,MAAM,WAAW,aAAa,MAFT,2BAA2B,SAAS,OAAO,IAF9C,KAAK,IAEqD,CAAC,GAEvC,OAAO,KAAK,eAAe;GAC/D,IAAI,MAAM,MACR,GAAG,OAAO,eAAe,UAAU,CAAC;QAC/B;IACL,MAAM,SAAS,iBAAiB,YAAY,KAAK;IACjD,IAAI,QACF,GAAG,IAAI,MAAM;IAEf,IAAI,CAAC,MAAM,OACT,GAAG,QAAQ,qBAAqB,KAAK,CAAC;GAE1C;EACF,CAAC;EACD,QAAQ,KAAK,QAAQ;CACvB,CAAC;CAEH,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"contract-emit-C8HmtboH.mjs","names":["isRecord"],"sources":["../src/utils/emit-queue.ts","../src/utils/publish-contract-artifact-pair.ts","../src/utils/validate-contract-deps.ts","../src/control-api/operations/contract-emit.ts"],"sourcesContent":["/**\n * Per-output FIFO queue for `executeContractEmit`.\n *\n * Ensures that at most one emit (load → resolve source → emit bytes → publish)\n * runs per output JSON path at a time. Concurrent calls for the same path\n * line up behind the in-flight one and run in submission order; the user-visible\n * outcome is \"last submission wins on disk\" without any supersession bookkeeping.\n *\n * Long-lived hosts (Vite dev server, watch CLIs) must call `disposeEmitQueue`\n * when they stop publishing to a path, otherwise the module-global `Map`\n * accumulates one entry per unique output path for the lifetime of the process.\n */\nconst emitQueues = new Map<string, Promise<unknown>>();\n\nexport function queueEmitByOutput<T>(outputJsonPath: string, action: () => Promise<T>): Promise<T> {\n const previous = emitQueues.get(outputJsonPath) ?? Promise.resolve();\n // Continue regardless of the previous task's outcome — a failed emit must not\n // block subsequent ones. The current task's outcome propagates via `next`.\n const next = previous.then(action, action);\n emitQueues.set(outputJsonPath, next);\n return next;\n}\n\nexport function disposeEmitQueue(outputJsonPath: string): void {\n emitQueues.delete(outputJsonPath);\n}\n","import { readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'pathe';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction createTempArtifactPath(path: string, publicationToken: string, phase: string): string {\n return join(dirname(path), `.${basename(path)}.${process.pid}.${publicationToken}.${phase}.tmp`);\n}\n\ntype PreviousArtifact = { readonly content: string } | 'remove';\n\nasync function readExistingArtifact(path: string): Promise<PreviousArtifact> {\n try {\n return { content: await readFile(path, 'utf-8') };\n } catch (error) {\n if (isRecord(error) && error['code'] === 'ENOENT') {\n return 'remove';\n }\n throw error;\n }\n}\n\nasync function restoreArtifact(\n path: string,\n previous: PreviousArtifact,\n publicationToken: string,\n): Promise<void> {\n if (previous === 'remove') {\n await rm(path, { force: true });\n return;\n }\n\n const restorePath = createTempArtifactPath(path, publicationToken, 'rollback');\n await writeFile(restorePath, previous.content, 'utf-8');\n try {\n await rename(restorePath, path);\n } finally {\n await rm(restorePath, { force: true });\n }\n}\n\ninterface PublishEntry {\n readonly tempPath: string;\n readonly outputPath: string;\n readonly previous: PreviousArtifact;\n}\n\nfunction withRollbackFailureCause(error: unknown, rollbackFailures: readonly unknown[]): Error {\n const rollbackCause = new AggregateError(\n rollbackFailures,\n 'Failed to restore published artifacts',\n );\n\n if (error instanceof Error) {\n Object.defineProperty(error, 'cause', {\n value: rollbackCause,\n configurable: true,\n writable: true,\n });\n return error;\n }\n\n return new Error(String(error), { cause: rollbackCause });\n}\n\nasync function publishPairWithRollback(\n entries: readonly PublishEntry[],\n publicationToken: string,\n): Promise<void> {\n const replaced: PublishEntry[] = [];\n try {\n for (const entry of entries) {\n await rename(entry.tempPath, entry.outputPath);\n replaced.push(entry);\n }\n } catch (error) {\n const rollbackResults = await Promise.allSettled(\n replaced.map((entry) => restoreArtifact(entry.outputPath, entry.previous, publicationToken)),\n );\n const rollbackFailures = rollbackResults.flatMap((result) =>\n result.status === 'rejected' ? [result.reason] : [],\n );\n\n if (rollbackFailures.length > 0) {\n throw withRollbackFailureCause(error, rollbackFailures);\n }\n\n throw error;\n }\n}\n\nexport async function publishContractArtifactPair({\n outputJsonPath,\n outputDtsPath,\n contractJson,\n contractDts,\n publicationToken,\n beforePublish,\n}: {\n readonly outputJsonPath: string;\n readonly outputDtsPath: string;\n readonly contractJson: string;\n readonly contractDts: string;\n readonly publicationToken: string;\n readonly beforePublish?: () => Promise<boolean> | boolean;\n}): Promise<boolean> {\n const tempJsonPath = createTempArtifactPath(outputJsonPath, publicationToken, 'next');\n const tempDtsPath = createTempArtifactPath(outputDtsPath, publicationToken, 'next');\n\n try {\n await writeFile(tempJsonPath, contractJson, 'utf-8');\n await writeFile(tempDtsPath, contractDts, 'utf-8');\n\n if ((await beforePublish?.()) === false) {\n return false;\n }\n\n const previousJson = await readExistingArtifact(outputJsonPath);\n const previousDts = await readExistingArtifact(outputDtsPath);\n\n await publishPairWithRollback(\n [\n { tempPath: tempDtsPath, outputPath: outputDtsPath, previous: previousDts },\n { tempPath: tempJsonPath, outputPath: outputJsonPath, previous: previousJson },\n ],\n publicationToken,\n );\n return true;\n } finally {\n await Promise.allSettled([rm(tempJsonPath, { force: true }), rm(tempDtsPath, { force: true })]);\n }\n}\n","import { createRequire } from 'node:module';\n\nconst IMPORT_PATTERN = /import\\s+type\\s+.*?\\s+from\\s+['\"](@[^/]+\\/[^/'\"]+)/g;\n\nexport function extractPackageSpecifiers(dtsContent: string): string[] {\n const packages = new Set<string>();\n for (const match of dtsContent.matchAll(IMPORT_PATTERN)) {\n const pkg = match[1];\n if (pkg) packages.add(pkg);\n }\n return [...packages];\n}\n\nexport interface ContractDepsValidation {\n readonly missing: readonly string[];\n readonly warning?: string;\n}\n\nexport function validateContractDeps(\n dtsContent: string,\n projectRoot: string,\n): ContractDepsValidation {\n const packages = extractPackageSpecifiers(dtsContent);\n const resolve = createRequire(`${projectRoot}/package.json`);\n\n const missing: string[] = [];\n for (const pkg of packages) {\n try {\n resolve.resolve(`${pkg}/package.json`);\n } catch {\n missing.push(pkg);\n }\n }\n\n if (missing.length === 0) {\n return { missing };\n }\n\n const list = missing.map((p) => ` - ${p}`).join('\\n');\n const warning = [\n 'contract.d.ts imports types from packages that are not installed:',\n list,\n '',\n 'Install them with your package manager:',\n ...missing.map((p) => ` ${p}`),\n ].join('\\n');\n\n return { missing, warning };\n}\n","import { mkdir } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { emit, getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { abortable } from '@prisma-next/utils/abortable';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport { dirname, join } from 'pathe';\nimport { loadConfig } from '../../config-loader';\nimport { errorContractConfigMissing, errorRuntime } from '../../utils/cli-errors';\nimport { queueEmitByOutput } from '../../utils/emit-queue';\nimport { toExtensionInputs } from '../../utils/extension-pack-inputs';\nimport { assertFrameworkComponentsCompatible } from '../../utils/framework-components';\nimport { publishContractArtifactPair } from '../../utils/publish-contract-artifact-pair';\nimport { validateContractDeps } from '../../utils/validate-contract-deps';\nimport { enrichContract } from '../contract-enrichment';\nimport type {\n ContractEmitOptions,\n ContractEmitResult,\n ControlActionName,\n OnControlProgress,\n} from '../types';\n\nconst EMIT_ACTION: ControlActionName = 'emit';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction startSpan(onProgress: OnControlProgress | undefined, spanId: string, label: string): void {\n onProgress?.({ action: EMIT_ACTION, kind: 'spanStart', spanId, label });\n}\n\nfunction endSpan(\n onProgress: OnControlProgress | undefined,\n spanId: string,\n outcome: 'ok' | 'error',\n): void {\n onProgress?.({ action: EMIT_ACTION, kind: 'spanEnd', spanId, outcome });\n}\n\nfunction failedToResolveContractSource(why: string, fix: string, meta?: Record<string, unknown>) {\n return errorRuntime('Failed to resolve contract source', {\n why,\n fix,\n ...ifDefined('meta', meta),\n });\n}\n\ntype ValidatedProviderResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: ReturnType<typeof errorRuntime> };\n\nfunction diagnosticLocationSuffix(diagnostic: Record<string, unknown>): string {\n const sourceId = typeof diagnostic['sourceId'] === 'string' ? diagnostic['sourceId'] : undefined;\n const span = isRecord(diagnostic['span']) ? diagnostic['span'] : undefined;\n const start = span && isRecord(span['start']) ? span['start'] : undefined;\n const line = start && typeof start['line'] === 'number' ? start['line'] : undefined;\n const column = start && typeof start['column'] === 'number' ? start['column'] : undefined;\n if (sourceId && line !== undefined && column !== undefined) {\n return ` (${sourceId}:${line}:${column})`;\n }\n if (sourceId) {\n return ` (${sourceId})`;\n }\n return '';\n}\n\nfunction mapDiagnosticsToIssues(\n diagnostics: readonly unknown[],\n): ReadonlyArray<{ readonly kind: string; readonly message: string }> {\n const issues: { readonly kind: string; readonly message: string }[] = [];\n for (const raw of diagnostics) {\n if (!isRecord(raw)) continue;\n const code = typeof raw['code'] === 'string' ? raw['code'] : 'diagnostic';\n const message = typeof raw['message'] === 'string' ? raw['message'] : '';\n issues.push({ kind: code, message: `${message}${diagnosticLocationSuffix(raw)}` });\n }\n return issues;\n}\n\nfunction validateProviderResult(providerResult: unknown): ValidatedProviderResult {\n if (!isRecord(providerResult) || typeof providerResult['ok'] !== 'boolean') {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed result shape.',\n 'Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics }).',\n ),\n };\n }\n\n if (providerResult['ok']) {\n if (!('value' in providerResult)) {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed success result: missing value.',\n 'Ensure contract.source.load success payload is ok(Contract).',\n ),\n };\n }\n return { ok: true, value: providerResult['value'] };\n }\n\n const failure = providerResult['failure'];\n if (\n !isRecord(failure) ||\n typeof failure['summary'] !== 'string' ||\n !Array.isArray(failure['diagnostics'])\n ) {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed failure result: expected summary and diagnostics.',\n 'Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? }).',\n ),\n };\n }\n return {\n ok: false,\n error: failedToResolveContractSource(\n String(failure['summary']),\n 'Fix contract source diagnostics and return ok(Contract).',\n {\n diagnostics: failure['diagnostics'],\n issues: mapDiagnosticsToIssues(failure['diagnostics']),\n ...ifDefined('providerMeta', failure['meta']),\n },\n ),\n };\n}\n\n/**\n * Canonical contract emit operation.\n *\n * This is the SINGLE publication path used by both the CLI command\n * (`prisma-next contract emit`) and the Vite plugin\n * (`@prisma-next/vite-plugin-contract-emit`). New callers must go through this\n * function rather than re-implementing load → emit → publish.\n *\n * The whole flow (load config → resolve source → emit bytes → atomic publish)\n * is serialized per output JSON path via `queueEmitByOutput`. Concurrent calls\n * for the same output line up FIFO; the user-visible outcome is \"last\n * submission wins on disk\" without any supersession bookkeeping. Within a\n * single emit, `publishContractArtifactPair` stages temp files, renames\n * `contract.d.ts` before `contract.json`, and attempts to restore the previous\n * pair if either rename fails — so type-only consumers never observe a\n * mismatched pair.\n *\n * @throws {CliStructuredError} on config/source/validation problems\n * @throws {DOMException} `AbortError` if cancelled via `signal`\n */\nexport async function executeContractEmit(\n options: ContractEmitOptions,\n): Promise<ContractEmitResult> {\n const { configPath, outputPath, signal = new AbortController().signal, onProgress } = options;\n const unlessAborted = abortable(signal);\n\n const config = await unlessAborted(loadConfig(configPath));\n\n if (!config.contract) {\n throw errorContractConfigMissing({\n why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n });\n }\n\n const contractConfig = config.contract;\n\n const effectiveOutput =\n outputPath !== undefined ? join(outputPath, 'contract.json') : contractConfig.output;\n\n if (!effectiveOutput) {\n throw errorContractConfigMissing({\n why: 'Contract config must have output path. This should not happen if defineConfig() was used.',\n });\n }\n\n if (typeof contractConfig.source?.load !== 'function') {\n throw errorContractConfigMissing({\n why: 'Contract config must include a valid source provider object',\n });\n }\n\n let outputPaths: ReturnType<typeof getEmittedArtifactPaths>;\n try {\n outputPaths = getEmittedArtifactPaths(effectiveOutput);\n } catch (error) {\n throw errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n });\n }\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;\n\n return queueEmitByOutput(outputJsonPath, async () => {\n const stack = createControlStack(config);\n\n const extensionInputs = toExtensionInputs(\n blindCast<\n readonly unknown[],\n 'toExtensionInputs accepts readonly unknown[] per its documented structural cast boundary'\n >(stack.extensionPacks),\n );\n const composedExtensionContracts = new Map<string, Contract>(\n extensionInputs\n .filter((p) => p.contractSpace !== undefined)\n .map((p) => [\n p.id,\n blindCast<\n Contract,\n 'contractSpace.contractJson is the typed contract for this extension space'\n >(p.contractSpace!.contractJson),\n ]),\n );\n const sourceContext = {\n composedExtensionPacks: stack.extensionPacks.map((p) => p.id),\n composedExtensionContracts,\n scalarTypeDescriptors: stack.scalarTypeDescriptors,\n authoringContributions: stack.authoringContributions,\n codecLookup: stack.codecLookup,\n controlMutationDefaults: stack.controlMutationDefaults,\n resolvedInputs: contractConfig.source.inputs ?? [],\n };\n\n startSpan(onProgress, 'resolveSource', 'Resolving contract source...');\n let providerResult: Awaited<ReturnType<typeof contractConfig.source.load>>;\n try {\n providerResult = await unlessAborted(contractConfig.source.load(sourceContext));\n } catch (error) {\n endSpan(onProgress, 'resolveSource', 'error');\n if (signal.aborted || (isRecord(error) && error['name'] === 'AbortError')) {\n throw error;\n }\n throw failedToResolveContractSource(\n error instanceof Error ? error.message : String(error),\n 'Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.',\n );\n }\n\n const validatedContract = validateProviderResult(providerResult);\n if (!validatedContract.ok) {\n endSpan(onProgress, 'resolveSource', 'error');\n throw validatedContract.error;\n }\n endSpan(onProgress, 'resolveSource', 'ok');\n\n startSpan(onProgress, 'emit', 'Emitting contract...');\n let emitResult: Awaited<ReturnType<typeof emit>>;\n try {\n const familyInstance = config.family.create(stack);\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n // Blind cast: `validateProviderResult` upstream has already\n // pinned `validatedContract.value` to the provider's loose\n // `Contract` envelope, but the local `Contract` type at this\n // call site is the precise structural interface. Re-narrowing\n // the envelope into the precise type is exactly what the\n // `familyInstance.deserializeContract(enrichedIR)` call on the\n // next line does — the cast just defers the structural check\n // by one statement so `enrichContract` can decorate first.\n const enrichedIR = enrichContract(\n validatedContract.value as unknown as Contract,\n frameworkComponents,\n );\n const deserializedContract = familyInstance.deserializeContract(enrichedIR);\n // Each target's descriptor ships a `contractSerializer` SPI; the\n // framework canonicalizer threads its `serializeContract` so the\n // on-disk JSON envelope is constructed by target-owned code\n // rather than by walking the in-memory contract with\n // `Object.entries` (which would leak runtime-only class API\n // fields into the persisted shape). The optional `shouldPreserveEmpty`\n // and `sortStorage` hooks let the family contribute storage-specific\n // canonicalization rules without the framework importing family code.\n const { contractSerializer } = config.target;\n const serializeContract = (c: Contract): JsonObject =>\n contractSerializer.serializeContract(c);\n emitResult = await unlessAborted(\n emit(deserializedContract, stack, config.family.emission, {\n outputJsonPath,\n serializeContract,\n ...ifDefined('shouldPreserveEmpty', contractSerializer.shouldPreserveEmpty),\n ...ifDefined('sortStorage', contractSerializer.sortStorage),\n }),\n );\n } catch (error) {\n endSpan(onProgress, 'emit', 'error');\n throw error;\n }\n endSpan(onProgress, 'emit', 'ok');\n\n await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));\n await publishContractArtifactPair({\n outputJsonPath,\n outputDtsPath,\n contractJson: emitResult.contractJson,\n contractDts: emitResult.contractDts,\n publicationToken: String(process.hrtime.bigint()),\n });\n\n const validationWarning = validateContractDeps(\n emitResult.contractDts,\n dirname(outputDtsPath),\n ).warning;\n\n return {\n storageHash: emitResult.storageHash,\n ...ifDefined('executionHash', emitResult.executionHash),\n profileHash: emitResult.profileHash,\n files: {\n json: outputJsonPath,\n dts: outputDtsPath,\n },\n ...ifDefined('validationWarning', validationWarning),\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAM,6BAAa,IAAI,IAA8B;AAErD,SAAgB,kBAAqB,gBAAwB,QAAsC;CAIjG,MAAM,QAHW,WAAW,IAAI,cAAc,KAAK,QAAQ,QAAQ,EAAA,CAG7C,KAAK,QAAQ,MAAM;CACzC,WAAW,IAAI,gBAAgB,IAAI;CACnC,OAAO;AACT;AAEA,SAAgB,iBAAiB,gBAA8B;CAC7D,WAAW,OAAO,cAAc;AAClC;;;ACtBA,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,uBAAuB,MAAc,kBAA0B,OAAuB;CAC7F,OAAO,KAAK,QAAQ,IAAI,GAAG,IAAI,SAAS,IAAI,EAAE,GAAG,QAAQ,IAAI,GAAG,iBAAiB,GAAG,MAAM,KAAK;AACjG;AAIA,eAAe,qBAAqB,MAAyC;CAC3E,IAAI;EACF,OAAO,EAAE,SAAS,MAAM,SAAS,MAAM,OAAO,EAAE;CAClD,SAAS,OAAO;EACd,IAAIA,WAAS,KAAK,KAAK,MAAM,YAAY,UACvC,OAAO;EAET,MAAM;CACR;AACF;AAEA,eAAe,gBACb,MACA,UACA,kBACe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