prisma-next 0.5.0-dev.9 → 0.6.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/cli-errors-B9OBbled.d.mts +3 -0
  2. package/dist/cli-errors-D3_sMh2K.mjs +33 -0
  3. package/dist/cli-errors-D3_sMh2K.mjs.map +1 -0
  4. package/dist/cli.mjs +16 -78
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/client-qVH-rEgd.mjs +1595 -0
  7. package/dist/client-qVH-rEgd.mjs.map +1 -0
  8. package/dist/{result-handler-Ba3zWQsI.mjs → command-helpers-BeZHkxV8.mjs} +70 -47
  9. package/dist/command-helpers-BeZHkxV8.mjs.map +1 -0
  10. package/dist/commands/contract-emit.d.mts.map +1 -1
  11. package/dist/commands/contract-emit.mjs +2 -4
  12. package/dist/commands/contract-infer.d.mts.map +1 -1
  13. package/dist/commands/contract-infer.mjs +2 -4
  14. package/dist/commands/db-init.d.mts.map +1 -1
  15. package/dist/commands/db-init.mjs +16 -13
  16. package/dist/commands/db-init.mjs.map +1 -1
  17. package/dist/commands/db-schema.d.mts.map +1 -1
  18. package/dist/commands/db-schema.mjs +6 -7
  19. package/dist/commands/db-schema.mjs.map +1 -1
  20. package/dist/commands/db-sign.d.mts.map +1 -1
  21. package/dist/commands/db-sign.mjs +9 -9
  22. package/dist/commands/db-sign.mjs.map +1 -1
  23. package/dist/commands/db-update.d.mts.map +1 -1
  24. package/dist/commands/db-update.mjs +15 -13
  25. package/dist/commands/db-update.mjs.map +1 -1
  26. package/dist/commands/db-verify.d.mts.map +1 -1
  27. package/dist/commands/db-verify.mjs +1 -321
  28. package/dist/commands/migration-apply.d.mts +28 -13
  29. package/dist/commands/migration-apply.d.mts.map +1 -1
  30. package/dist/commands/migration-apply.mjs +55 -151
  31. package/dist/commands/migration-apply.mjs.map +1 -1
  32. package/dist/commands/migration-new.d.mts +0 -1
  33. package/dist/commands/migration-new.d.mts.map +1 -1
  34. package/dist/commands/migration-new.mjs +34 -40
  35. package/dist/commands/migration-new.mjs.map +1 -1
  36. package/dist/commands/migration-plan.d.mts +33 -6
  37. package/dist/commands/migration-plan.d.mts.map +1 -1
  38. package/dist/commands/migration-plan.mjs +2 -348
  39. package/dist/commands/migration-ref.d.mts +1 -1
  40. package/dist/commands/migration-ref.d.mts.map +1 -1
  41. package/dist/commands/migration-ref.mjs +8 -12
  42. package/dist/commands/migration-ref.mjs.map +1 -1
  43. package/dist/commands/migration-show.d.mts +13 -7
  44. package/dist/commands/migration-show.d.mts.map +1 -1
  45. package/dist/commands/migration-show.mjs +35 -36
  46. package/dist/commands/migration-show.mjs.map +1 -1
  47. package/dist/commands/migration-status.d.mts +126 -5
  48. package/dist/commands/migration-status.d.mts.map +1 -1
  49. package/dist/commands/migration-status.mjs +2 -4
  50. package/dist/{config-loader-C25b63rJ.mjs → config-loader-B6sJjXTv.mjs} +3 -5
  51. package/dist/config-loader-B6sJjXTv.mjs.map +1 -0
  52. package/dist/config-loader.d.mts +0 -1
  53. package/dist/config-loader.d.mts.map +1 -1
  54. package/dist/config-loader.mjs +2 -3
  55. package/dist/contract-emit-9DBda5Ou.mjs +150 -0
  56. package/dist/contract-emit-9DBda5Ou.mjs.map +1 -0
  57. package/dist/contract-emit-B77TsJqf.mjs +327 -0
  58. package/dist/contract-emit-B77TsJqf.mjs.map +1 -0
  59. package/dist/{contract-enrichment-CAOELa-H.mjs → contract-enrichment-Dani0mMW.mjs} +4 -6
  60. package/dist/contract-enrichment-Dani0mMW.mjs.map +1 -0
  61. package/dist/{contract-infer-D9cC3rJm.mjs → contract-infer-BK9YFGEG.mjs} +13 -22
  62. package/dist/contract-infer-BK9YFGEG.mjs.map +1 -0
  63. package/dist/db-verify-C0y1PCO2.mjs +404 -0
  64. package/dist/db-verify-C0y1PCO2.mjs.map +1 -0
  65. package/dist/exports/config-types.mjs +1 -2
  66. package/dist/exports/control-api.d.mts +101 -586
  67. package/dist/exports/control-api.d.mts.map +1 -1
  68. package/dist/exports/control-api.mjs +4 -6
  69. package/dist/exports/index.d.mts.map +1 -1
  70. package/dist/exports/index.mjs +28 -30
  71. package/dist/exports/index.mjs.map +1 -1
  72. package/dist/exports/init-output.d.mts +2 -4
  73. package/dist/exports/init-output.d.mts.map +1 -1
  74. package/dist/exports/init-output.mjs +2 -3
  75. package/dist/extension-pack-inputs-C7xgE-vv.mjs +74 -0
  76. package/dist/extension-pack-inputs-C7xgE-vv.mjs.map +1 -0
  77. package/dist/{framework-components-Cr--XBKy.mjs → framework-components-ChqVUxR-.mjs} +3 -4
  78. package/dist/{framework-components-Cr--XBKy.mjs.map → framework-components-ChqVUxR-.mjs.map} +1 -1
  79. package/dist/global-flags-Icqpxk23.d.mts +12 -0
  80. package/dist/global-flags-Icqpxk23.d.mts.map +1 -0
  81. package/dist/helpers-eqdN8tH6.mjs +25 -0
  82. package/dist/helpers-eqdN8tH6.mjs.map +1 -0
  83. package/dist/{init-C5220SY9.mjs → init-DETSgw3h.mjs} +40 -49
  84. package/dist/init-DETSgw3h.mjs.map +1 -0
  85. package/dist/{inspect-live-schema-yrHAvG71.mjs → inspect-live-schema-CWYxGKlb.mjs} +10 -11
  86. package/dist/inspect-live-schema-CWYxGKlb.mjs.map +1 -0
  87. package/dist/migration-cli.d.mts +41 -12
  88. package/dist/migration-cli.d.mts.map +1 -1
  89. package/dist/migration-cli.mjs +309 -86
  90. package/dist/migration-cli.mjs.map +1 -1
  91. package/dist/{migration-command-scaffold-B3B09et6.mjs → migration-command-scaffold-B5dORFEv.mjs} +8 -9
  92. package/dist/migration-command-scaffold-B5dORFEv.mjs.map +1 -0
  93. package/dist/migration-plan-C6lVaHsO.mjs +554 -0
  94. package/dist/migration-plan-C6lVaHsO.mjs.map +1 -0
  95. package/dist/{migration-status-DUMiH8_G.mjs → migration-status-CZ-D5k7k.mjs} +272 -65
  96. package/dist/migration-status-CZ-D5k7k.mjs.map +1 -0
  97. package/dist/migrations-D_UJnpuW.mjs +216 -0
  98. package/dist/migrations-D_UJnpuW.mjs.map +1 -0
  99. package/dist/{output-BpcQrnnq.mjs → output-B16Kefzx.mjs} +9 -3
  100. package/dist/output-B16Kefzx.mjs.map +1 -0
  101. package/dist/{progress-adapter-DvQWB1nK.mjs → progress-adapter-DFfvZcYL.mjs} +2 -2
  102. package/dist/{progress-adapter-DvQWB1nK.mjs.map → progress-adapter-DFfvZcYL.mjs.map} +1 -1
  103. package/dist/result-handler-rmPVKIP2.mjs +25 -0
  104. package/dist/result-handler-rmPVKIP2.mjs.map +1 -0
  105. package/dist/rolldown-runtime-twds-ZHy.mjs +14 -0
  106. package/dist/{terminal-ui-C3ZLwQxK.mjs → terminal-ui-C_hFNbAn.mjs} +4 -28
  107. package/dist/terminal-ui-C_hFNbAn.mjs.map +1 -0
  108. package/dist/types-D7x-IFLO.d.mts +858 -0
  109. package/dist/types-D7x-IFLO.d.mts.map +1 -0
  110. package/dist/{verify-Bkycc-Tf.mjs → verify-CiwNWM9N.mjs} +3 -4
  111. package/dist/verify-CiwNWM9N.mjs.map +1 -0
  112. package/package.json +19 -17
  113. package/dist/cli-errors-BFYgBH3L.d.mts +0 -4
  114. package/dist/cli-errors-Cd79vmTH.mjs +0 -5
  115. package/dist/client-CrsnY58k.mjs +0 -997
  116. package/dist/client-CrsnY58k.mjs.map +0 -1
  117. package/dist/commands/db-verify.mjs.map +0 -1
  118. package/dist/commands/migration-plan.mjs.map +0 -1
  119. package/dist/config-loader-C25b63rJ.mjs.map +0 -1
  120. package/dist/contract-emit--feXyNd7.mjs +0 -4
  121. package/dist/contract-emit-NJ01hiiv.mjs +0 -195
  122. package/dist/contract-emit-NJ01hiiv.mjs.map +0 -1
  123. package/dist/contract-emit-V5SSitUT.mjs +0 -122
  124. package/dist/contract-emit-V5SSitUT.mjs.map +0 -1
  125. package/dist/contract-enrichment-CAOELa-H.mjs.map +0 -1
  126. package/dist/contract-infer-D9cC3rJm.mjs.map +0 -1
  127. package/dist/extract-operation-statements-DsFfxXVZ.mjs +0 -13
  128. package/dist/extract-operation-statements-DsFfxXVZ.mjs.map +0 -1
  129. package/dist/extract-sql-ddl-D9UbZDyz.mjs +0 -26
  130. package/dist/extract-sql-ddl-D9UbZDyz.mjs.map +0 -1
  131. package/dist/init-C5220SY9.mjs.map +0 -1
  132. package/dist/inspect-live-schema-yrHAvG71.mjs.map +0 -1
  133. package/dist/migration-command-scaffold-B3B09et6.mjs.map +0 -1
  134. package/dist/migration-status-DUMiH8_G.mjs.map +0 -1
  135. package/dist/migrations-Bo5WtTla.mjs +0 -153
  136. package/dist/migrations-Bo5WtTla.mjs.map +0 -1
  137. package/dist/output-BpcQrnnq.mjs.map +0 -1
  138. package/dist/result-handler-Ba3zWQsI.mjs.map +0 -1
  139. package/dist/terminal-ui-C3ZLwQxK.mjs.map +0 -1
  140. package/dist/validate-contract-deps-B_Cs29TL.mjs +0 -37
  141. package/dist/validate-contract-deps-B_Cs29TL.mjs.map +0 -1
  142. package/dist/verify-Bkycc-Tf.mjs.map +0 -1
@@ -0,0 +1,1595 @@
1
+ import { p as errorRunnerFailed, t as CliStructuredError } from "./cli-errors-D3_sMh2K.mjs";
2
+ import { t as assertFrameworkComponentsCompatible } from "./framework-components-ChqVUxR-.mjs";
3
+ import { t as enrichContract } from "./contract-enrichment-Dani0mMW.mjs";
4
+ import { n as toExtensionInputs, t as toDeclaredExtensions } from "./extension-pack-inputs-C7xgE-vv.mjs";
5
+ import { emit } from "@prisma-next/emitter";
6
+ import { ifDefined } from "@prisma-next/utils/defined";
7
+ import { notOk, ok } from "@prisma-next/utils/result";
8
+ import { APP_SPACE_ID, createControlStack, hasMigrations, hasMultiSpaceRunner, hasOperationPreview, hasPslContractInfer, hasSchemaView } from "@prisma-next/framework-components/control";
9
+ import { findPathWithDecision } from "@prisma-next/migration-tools/migration-graph";
10
+ import { graphWalkStrategy, loadContractSpaceAggregate, planAggregate, verifyAggregate } from "@prisma-next/migration-tools/aggregate";
11
+ import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
12
+ import { errorNoInvariantPath } from "@prisma-next/migration-tools/errors";
13
+ //#region src/control-api/errors.ts
14
+ var ContractValidationError = class extends Error {
15
+ cause;
16
+ constructor(message, cause) {
17
+ super(message);
18
+ this.name = "ContractValidationError";
19
+ this.cause = cause;
20
+ }
21
+ };
22
+ //#endregion
23
+ //#region src/utils/contract-space-aggregate-loader.ts
24
+ /**
25
+ * Render a {@link LoadAggregateError} into a CLI structured-error
26
+ * envelope. Preserves error codes `5001` (layout) and `5002` (marker /
27
+ * drift / disjointness / etc.) so existing integration tests and
28
+ * downstream tooling continue to assert on the same `meta.violations[]`
29
+ * shape they did under the old precheck/marker-check helpers.
30
+ */
31
+ function mapLoadAggregateError(error) {
32
+ if (error.kind === "layoutViolation") {
33
+ const lines = error.violations.map((v) => `- [${v.kind}] ${v.spaceId}`);
34
+ return new CliStructuredError("5001", error.violations.length === 1 ? "Contract-space layout violation detected" : `Contract-space layout violations detected (${error.violations.length})`, {
35
+ domain: "MIG",
36
+ why: `The on-disk \`migrations/\` directory and your \`extensionPacks\` declaration are not in agreement.\n${lines.join("\n")}`,
37
+ fix: "Run `prisma-next migrate` to materialise on-disk artefacts for declared extensions, or remove the orphan directory.",
38
+ docsUrl: "https://pris.ly/contract-spaces",
39
+ meta: { violations: error.violations.map((v) => ({
40
+ kind: v.kind,
41
+ spaceId: v.spaceId
42
+ })) }
43
+ });
44
+ }
45
+ if (error.kind === "driftViolation") return new CliStructuredError("5002", `Contract-space drift detected for "${error.spaceId}"`, {
46
+ domain: "MIG",
47
+ why: `The on-disk contract for space "${error.spaceId}" (hash ${error.priorHeadHash}) does not match the live extension descriptor (hash ${error.liveHash}).`,
48
+ fix: "Run `prisma-next migrate` to refresh the on-disk artefacts to match the live descriptor.",
49
+ docsUrl: "https://pris.ly/contract-spaces",
50
+ meta: { violations: [{
51
+ kind: "drift",
52
+ spaceId: error.spaceId,
53
+ priorHeadHash: error.priorHeadHash,
54
+ liveHash: error.liveHash
55
+ }] }
56
+ });
57
+ if (error.kind === "disjointnessViolation") return new CliStructuredError("5002", `Contract-space disjointness violation: storage element "${error.element}" claimed by multiple spaces`, {
58
+ domain: "MIG",
59
+ why: `Spaces ${error.claimedBy.map((s) => `"${s}"`).join(", ")} all claim the storage element "${error.element}". Each storage element must be owned by exactly one contract space.`,
60
+ fix: "Update the conflicting contracts so each storage element is claimed by exactly one space.",
61
+ docsUrl: "https://pris.ly/contract-spaces",
62
+ meta: { violations: [{
63
+ kind: "disjointness",
64
+ spaceId: error.claimedBy.join(","),
65
+ element: error.element,
66
+ claimedBy: error.claimedBy
67
+ }] }
68
+ });
69
+ if (error.kind === "integrityFailure") return new CliStructuredError("5002", `Contract-space integrity failure for "${error.spaceId}"`, {
70
+ domain: "MIG",
71
+ why: error.detail,
72
+ fix: "Run `prisma-next migrate` to refresh on-disk artefacts, or restore the on-disk `migrations/` directory from version control.",
73
+ docsUrl: "https://pris.ly/contract-spaces",
74
+ meta: { violations: [{
75
+ kind: "integrity",
76
+ spaceId: error.spaceId,
77
+ detail: error.detail
78
+ }] }
79
+ });
80
+ if (error.kind === "validationFailure") return new CliStructuredError("5002", `Contract-space contract validation failed for "${error.spaceId}"`, {
81
+ domain: "MIG",
82
+ why: error.detail,
83
+ fix: "Run `prisma-next migrate` to refresh on-disk artefacts, or fix the extension descriptor producing the invalid contract.",
84
+ meta: { violations: [{
85
+ kind: "validation",
86
+ spaceId: error.spaceId,
87
+ detail: error.detail
88
+ }] }
89
+ });
90
+ return new CliStructuredError("5002", `Contract-space target mismatch for "${error.spaceId}"`, {
91
+ domain: "MIG",
92
+ why: `Space "${error.spaceId}" targets "${error.actual}" but the project's adapter targets "${error.expected}".`,
93
+ fix: "Update the extension descriptor to target the configured database, or change the project adapter.",
94
+ meta: { violations: [{
95
+ kind: "targetMismatch",
96
+ spaceId: error.spaceId,
97
+ expected: error.expected,
98
+ actual: error.actual
99
+ }] }
100
+ });
101
+ }
102
+ /**
103
+ * Run the aggregate loader at the CLI surface, mapping any
104
+ * {@link LoadAggregateError} into a {@link CliStructuredError} envelope.
105
+ *
106
+ * App-side migration packages flow through `inputs.appMigrationPackages`
107
+ * (defaulting to `[]`). `db init` / `db update` leave it empty: the
108
+ * planner's `synth` strategy is used for the app member (driven by
109
+ * `callerPolicy.ignoreGraphFor`), so the app's authored `migrations/`
110
+ * graph does not need to be walked. `migration apply` threads the
111
+ * already-loaded app-space packages through so the graph-walk strategy
112
+ * can plot a path through them — replay forbids synth.
113
+ *
114
+ * @see specs/contract-space-aggregate-spec.md § Loader.
115
+ */
116
+ async function buildContractSpaceAggregate(inputs) {
117
+ const { entries, hashByContractJson } = toDeclaredExtensions(toExtensionInputs(inputs.extensionPacks));
118
+ const result = await loadContractSpaceAggregate({
119
+ targetId: inputs.targetId,
120
+ migrationsDir: inputs.migrationsDir,
121
+ appContract: inputs.appContract,
122
+ declaredExtensions: entries,
123
+ validateContract: inputs.validateContract,
124
+ hashContract: (contractJson) => {
125
+ const precomputed = hashByContractJson.get(contractJson);
126
+ if (precomputed === void 0) throw new Error("CLI aggregate loader: encountered an extension contract without a pre-computed descriptor hash. This is a wiring bug.");
127
+ return precomputed;
128
+ },
129
+ appMigrationPackages: inputs.appMigrationPackages ?? []
130
+ });
131
+ if (!result.ok) return notOk(mapLoadAggregateError(result.failure));
132
+ return ok(result.value.aggregate);
133
+ }
134
+ //#endregion
135
+ //#region src/control-api/operations/apply-aggregate.ts
136
+ /**
137
+ * Span id emitted via `onProgress` for the apply phase. Stable
138
+ * identifier consumed by the structured-output renderer and by tests.
139
+ */
140
+ const APPLY_SPAN_ID = "apply";
141
+ /**
142
+ * Runner-driving tail shared by every aggregate apply caller — `db init`,
143
+ * `db update`, and `migration apply`. Consumes already-resolved per-space
144
+ * plans (the planner-vs-replay distinction is owned by the caller) and
145
+ * dispatches them to the multi-space runner in canonical order.
146
+ *
147
+ * Marker advancement is part of the runner's per-space transaction
148
+ * (the SQL family runner writes the marker as the last step of each
149
+ * space's transaction), so this primitive does not advance markers
150
+ * separately — by the time `executeAcrossSpaces` returns ok, every
151
+ * space's marker has been advanced to its plan's destination.
152
+ *
153
+ * Span emission (`spanStart 'apply'` / `spanEnd 'apply'`) is owned here
154
+ * so callers don't have to duplicate it; the `action` field on each
155
+ * progress event is taken from the caller's `action` argument.
156
+ */
157
+ async function applyAggregate(inputs) {
158
+ const { aggregate, perSpacePlans, applyOrder, driver, familyInstance, migrations, frameworkComponents, policy, action, onProgress } = inputs;
159
+ const orderedResolutions = collectOrdered(applyOrder, perSpacePlans);
160
+ const runner = migrations.createRunner(familyInstance);
161
+ if (!hasMultiSpaceRunner(runner)) throw errorRunnerFailed(`Runner for target "${aggregate.targetId}" does not implement \`executeAcrossSpaces\``, { why: `${labelForAction(action)} requires multi-space-capable runners (today: every SQL family runner).` });
162
+ onProgress?.({
163
+ action,
164
+ kind: "spanStart",
165
+ spanId: APPLY_SPAN_ID,
166
+ label: progressLabelForAction(action)
167
+ });
168
+ const perSpaceOptions = orderedResolutions.map((r) => ({
169
+ space: r.spaceId,
170
+ plan: r.entry.plan,
171
+ driver,
172
+ destinationContract: r.entry.destinationContract,
173
+ policy,
174
+ frameworkComponents,
175
+ strictVerification: false
176
+ }));
177
+ const runnerResult = await runner.executeAcrossSpaces({
178
+ driver,
179
+ perSpaceOptions
180
+ });
181
+ if (!runnerResult.ok) {
182
+ onProgress?.({
183
+ action,
184
+ kind: "spanEnd",
185
+ spanId: APPLY_SPAN_ID,
186
+ outcome: "error"
187
+ });
188
+ return notOk({
189
+ summary: runnerResult.failure.summary,
190
+ ...ifDefined("why", runnerResult.failure.why),
191
+ meta: {
192
+ ...runnerResult.failure.meta ?? {},
193
+ failingSpace: runnerResult.failure.failingSpace
194
+ }
195
+ });
196
+ }
197
+ onProgress?.({
198
+ action,
199
+ kind: "spanEnd",
200
+ spanId: APPLY_SPAN_ID,
201
+ outcome: "ok"
202
+ });
203
+ return ok({
204
+ orderedResolutions,
205
+ totalOpsPlanned: runnerResult.value.perSpaceResults.reduce((sum, r) => sum + r.value.operationsPlanned, 0),
206
+ totalOpsExecuted: runnerResult.value.perSpaceResults.reduce((sum, r) => sum + r.value.operationsExecuted, 0),
207
+ perSpace: buildPerSpaceBreakdown(orderedResolutions, aggregate.app.spaceId, { includeMarkers: true })
208
+ });
209
+ }
210
+ /**
211
+ * Project the planner's per-space resolutions into the
212
+ * `AggregatePerSpaceExecutionEntry[]` shape the CLI surfaces.
213
+ *
214
+ * `includeMarkers` is `true` for apply-mode (each space's marker is
215
+ * the `destination.storageHash` of its plan, which the runner
216
+ * advances as the last step of each space's transaction) and `false`
217
+ * for plan-mode (no marker has been written yet).
218
+ *
219
+ * Exported alongside {@link applyAggregate} so plan-mode callers can
220
+ * assemble the same per-space block without going through the runner.
221
+ */
222
+ function buildPerSpaceBreakdown(orderedResolutions, appSpaceId, options) {
223
+ return orderedResolutions.map((r) => {
224
+ const operations = r.entry.displayOps.map((op) => ({
225
+ id: op.id,
226
+ label: op.label,
227
+ operationClass: op.operationClass
228
+ }));
229
+ const base = {
230
+ spaceId: r.spaceId,
231
+ kind: r.spaceId === appSpaceId ? "app" : "extension",
232
+ operations
233
+ };
234
+ if (!options.includeMarkers) return base;
235
+ return {
236
+ ...base,
237
+ marker: { storageHash: r.entry.plan.destination.storageHash }
238
+ };
239
+ });
240
+ }
241
+ /**
242
+ * Materialise the `applyOrder` ordering into resolved per-space
243
+ * entries. Throws if the planner output is missing a member listed
244
+ * in `applyOrder` — a wiring bug that should never reach runtime.
245
+ *
246
+ * Exported so callers building their own success envelopes after a
247
+ * plan-mode dispatch can replay the same ordering.
248
+ */
249
+ function collectOrdered(applyOrder, perSpace) {
250
+ return applyOrder.map((spaceId) => {
251
+ const entry = perSpace.get(spaceId);
252
+ if (!entry) throw new Error(`Aggregate planner output missing per-space plan for "${spaceId}"`);
253
+ return {
254
+ spaceId,
255
+ entry
256
+ };
257
+ });
258
+ }
259
+ /**
260
+ * Action-appropriate label for the `spanStart` event the apply
261
+ * primitive emits. `applyAggregate` is shared by `db init`, `db update`,
262
+ * and `migration apply`; the span label tracks the user-visible action
263
+ * so structured-progress output reads naturally for each surface.
264
+ */
265
+ function progressLabelForAction(action) {
266
+ switch (action) {
267
+ case "dbInit": return "Initialising database across spaces";
268
+ case "dbUpdate": return "Updating database across spaces";
269
+ case "migrationApply": return "Applying migration plan across spaces";
270
+ }
271
+ }
272
+ function labelForAction(action) {
273
+ switch (action) {
274
+ case "dbInit": return "db init";
275
+ case "dbUpdate": return "db update";
276
+ case "migrationApply": return "migration apply";
277
+ }
278
+ }
279
+ //#endregion
280
+ //#region src/control-api/operations/migration-helpers.ts
281
+ /**
282
+ * Strips operation objects to their public shape (id, label, operationClass).
283
+ * Used at the API boundary to avoid leaking internal fields (precheck, execute, postcheck, etc.).
284
+ */
285
+ function stripOperations(operations) {
286
+ return operations.map((op) => ({
287
+ id: op.id,
288
+ label: op.label,
289
+ operationClass: op.operationClass
290
+ }));
291
+ }
292
+ //#endregion
293
+ //#region src/control-api/operations/db-apply-aggregate.ts
294
+ /**
295
+ * Span IDs emitted via `onProgress` during the aggregate apply flow.
296
+ * Stable identifiers consumed by the structured-output renderer and by
297
+ * tests asserting on span ids. The `apply` span itself is owned by
298
+ * the {@link applyAggregate} primitive — only the introspect / plan
299
+ * spans are emitted directly here.
300
+ */
301
+ const SPAN_IDS$1 = {
302
+ introspect: "introspect",
303
+ plan: "plan"
304
+ };
305
+ /**
306
+ * Loader → planner → runner pipeline shared by `db init` and `db update`.
307
+ *
308
+ * The pipeline:
309
+ *
310
+ * 1. **Load**: build a {@link ContractSpaceAggregate} from the descriptor
311
+ * set + on-disk on-disk artefacts. Any layout / drift / disjointness /
312
+ * integrity violation short-circuits with a structured error.
313
+ * 2. **Read DB state**: marker rows (`familyInstance.readAllMarkers`)
314
+ * + introspected schema (`familyInstance.introspect`).
315
+ * 3. **Plan**: {@link planAggregate} chooses graph-walk vs synth per
316
+ * member according to `callerPolicy.ignoreGraphFor`. The app member
317
+ * is forced through synth (today's daily-driver behaviour); every
318
+ * extension member walks its on-disk graph.
319
+ * 4. **Apply** (when `mode === 'apply'`): every per-space `MigrationPlan`
320
+ * feeds into the runner's `executeAcrossSpaces` — one outer
321
+ * transaction across every space; failure on any space rolls back
322
+ * every space's writes.
323
+ */
324
+ async function executeAggregateApply(options) {
325
+ const { driver, familyInstance, contract, mode, migrations, frameworkComponents, migrationsDir, extensionPacks, targetId, policy, action, onProgress } = options;
326
+ const loaded = await buildContractSpaceAggregate({
327
+ targetId,
328
+ migrationsDir,
329
+ appContract: contract,
330
+ extensionPacks,
331
+ validateContract: (json) => familyInstance.validateContract(json)
332
+ });
333
+ if (!loaded.ok) throw loaded.failure;
334
+ const aggregate = loaded.value;
335
+ const markerRows = await familyInstance.readAllMarkers({ driver });
336
+ const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows);
337
+ if (orphanMarkerError !== null) throw orphanMarkerError;
338
+ onProgress?.({
339
+ action,
340
+ kind: "spanStart",
341
+ spanId: SPAN_IDS$1.introspect,
342
+ label: "Introspecting database schema"
343
+ });
344
+ const schemaIR = await familyInstance.introspect({ driver });
345
+ onProgress?.({
346
+ action,
347
+ kind: "spanEnd",
348
+ spanId: SPAN_IDS$1.introspect,
349
+ outcome: "ok"
350
+ });
351
+ onProgress?.({
352
+ action,
353
+ kind: "spanStart",
354
+ spanId: SPAN_IDS$1.plan,
355
+ label: "Planning migration"
356
+ });
357
+ const planResult = await planAggregate({
358
+ aggregate,
359
+ currentDBState: {
360
+ markersBySpaceId: markerRows,
361
+ schemaIntrospection: schemaIR
362
+ },
363
+ familyInstance,
364
+ migrations,
365
+ frameworkComponents,
366
+ callerPolicy: { ignoreGraphFor: new Set([aggregate.app.spaceId]) },
367
+ operationPolicy: policy
368
+ });
369
+ if (!planResult.ok) {
370
+ onProgress?.({
371
+ action,
372
+ kind: "spanEnd",
373
+ spanId: SPAN_IDS$1.plan,
374
+ outcome: "error"
375
+ });
376
+ return mapPlannerError(planResult.failure);
377
+ }
378
+ onProgress?.({
379
+ action,
380
+ kind: "spanEnd",
381
+ spanId: SPAN_IDS$1.plan,
382
+ outcome: "ok"
383
+ });
384
+ const orderedResolutions = collectOrdered(planResult.value.applyOrder, planResult.value.perSpace);
385
+ const appResolution = orderedResolutions.find((r) => r.spaceId === aggregate.app.spaceId);
386
+ if (!appResolution) throw new Error("Aggregate planner returned no plan for the app member — the planner is supposed to always emit one.");
387
+ const appPlan = appResolution.entry.plan;
388
+ if (mode === "plan") {
389
+ const aggregateOps = orderedResolutions.flatMap((r) => r.entry.displayOps);
390
+ const preview = hasOperationPreview(familyInstance) ? familyInstance.toOperationPreview(aggregateOps) : void 0;
391
+ const perSpace = buildPerSpaceBreakdown(orderedResolutions, aggregate.app.spaceId, { includeMarkers: false });
392
+ const summary = `Planned ${aggregateOps.length} operation(s) across ${orderedResolutions.length} space(s)`;
393
+ return wrapPlanResult({
394
+ operations: aggregateOps,
395
+ destination: appPlan.destination,
396
+ preview,
397
+ perSpace,
398
+ summary
399
+ });
400
+ }
401
+ const applied = await applyAggregate({
402
+ aggregate,
403
+ perSpacePlans: planResult.value.perSpace,
404
+ applyOrder: planResult.value.applyOrder,
405
+ driver,
406
+ familyInstance,
407
+ migrations,
408
+ frameworkComponents,
409
+ policy,
410
+ action,
411
+ ...ifDefined("onProgress", onProgress)
412
+ });
413
+ if (!applied.ok) return buildRunnerFailure({
414
+ summary: applied.failure.summary,
415
+ ...ifDefined("why", applied.failure.why),
416
+ meta: applied.failure.meta
417
+ });
418
+ const aggregateOps = applied.value.orderedResolutions.flatMap((r) => r.entry.displayOps);
419
+ const summary = action === "dbInit" ? `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), database signed` : applied.value.totalOpsExecuted === 0 ? `Database already matches contract across ${applied.value.orderedResolutions.length} space(s), signature updated` : `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), signature updated`;
420
+ return wrapApplyResult({
421
+ operations: aggregateOps,
422
+ destination: appPlan.destination,
423
+ operationsPlanned: applied.value.totalOpsPlanned,
424
+ operationsExecuted: applied.value.totalOpsExecuted,
425
+ perSpace: applied.value.perSpace,
426
+ summary
427
+ });
428
+ }
429
+ /**
430
+ * Compare the live `_prisma_marker` rows against the aggregate's
431
+ * declared members. Any marker row whose `space` is not a member of
432
+ * the aggregate is an "orphan" — typically a marker left behind by
433
+ * an extension that was removed from `extensionPacks` without first
434
+ * cleaning up its on-disk migrations / database tables.
435
+ *
436
+ * Returns a {@link CliStructuredError} envelope (code `5002`,
437
+ * `kind: 'orphanMarker'`) for the first orphan it finds, or `null`
438
+ * when every marker row maps to a declared member. Mirrors the M2
439
+ * `runContractSpaceVerifierMarkerCheck` envelope so downstream
440
+ * tooling (integration tests, JSON consumers) keeps asserting on the
441
+ * same shape.
442
+ */
443
+ function detectOrphanMarkers(aggregate, markerRows) {
444
+ const memberSpaceIds = new Set([aggregate.app.spaceId, ...aggregate.extensions.map((m) => m.spaceId)]);
445
+ const orphans = [];
446
+ for (const [spaceId, row] of markerRows) if (row !== null && row !== void 0 && !memberSpaceIds.has(spaceId)) orphans.push(spaceId);
447
+ if (orphans.length === 0) return null;
448
+ orphans.sort((a, b) => a.localeCompare(b));
449
+ return new CliStructuredError("5002", orphans.length === 1 ? `Orphan contract-space marker detected for "${orphans[0]}"` : `Orphan contract-space markers detected for ${orphans.length} spaces`, {
450
+ domain: "MIG",
451
+ why: `The database has \`_prisma_marker\` rows for spaces (${orphans.map((s) => `"${s}"`).join(", ")}) that are not declared in the project's \`extensionPacks\`. The aggregate pipeline refuses to advance markers it cannot account for.`,
452
+ 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.",
453
+ docsUrl: "https://pris.ly/contract-spaces",
454
+ meta: { violations: orphans.map((spaceId) => ({
455
+ kind: "orphanMarker",
456
+ spaceId
457
+ })) }
458
+ });
459
+ }
460
+ function mapPlannerError(error) {
461
+ if (error.kind === "appSynthFailure") return notOk({
462
+ code: "PLANNING_FAILED",
463
+ summary: "Migration planning failed due to conflicts",
464
+ conflicts: error.conflicts,
465
+ why: void 0,
466
+ meta: void 0
467
+ });
468
+ if (error.kind === "extensionPathUnreachable") return buildRunnerFailure({
469
+ summary: `Cannot resolve apply path for extension space "${error.spaceId}"`,
470
+ why: `No path in the on-disk migration graph for extension space "${error.spaceId}" reaches the on-disk head ref hash "${error.target}".`,
471
+ meta: {
472
+ spaceId: error.spaceId,
473
+ target: error.target
474
+ }
475
+ });
476
+ if (error.kind === "extensionPathUnsatisfiable") return buildRunnerFailure({
477
+ summary: `Cannot resolve apply path for extension space "${error.spaceId}"`,
478
+ 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(", ")}.`,
479
+ meta: {
480
+ spaceId: error.spaceId,
481
+ missingInvariants: error.missingInvariants
482
+ }
483
+ });
484
+ return buildRunnerFailure({
485
+ summary: `Aggregate planner policy conflict for space "${error.spaceId}"`,
486
+ why: error.detail,
487
+ meta: { spaceId: error.spaceId }
488
+ });
489
+ }
490
+ function wrapPlanResult(args) {
491
+ return ok({
492
+ mode: "plan",
493
+ plan: {
494
+ operations: stripOperations(args.operations),
495
+ ...ifDefined("preview", args.preview)
496
+ },
497
+ destination: {
498
+ storageHash: args.destination.storageHash,
499
+ ...ifDefined("profileHash", args.destination.profileHash)
500
+ },
501
+ perSpace: args.perSpace,
502
+ summary: args.summary
503
+ });
504
+ }
505
+ function wrapApplyResult(args) {
506
+ return ok({
507
+ mode: "apply",
508
+ plan: { operations: stripOperations(args.operations) },
509
+ destination: {
510
+ storageHash: args.destination.storageHash,
511
+ ...ifDefined("profileHash", args.destination.profileHash)
512
+ },
513
+ execution: {
514
+ operationsPlanned: args.operationsPlanned,
515
+ operationsExecuted: args.operationsExecuted
516
+ },
517
+ marker: args.destination.profileHash ? {
518
+ storageHash: args.destination.storageHash,
519
+ profileHash: args.destination.profileHash
520
+ } : { storageHash: args.destination.storageHash },
521
+ perSpace: args.perSpace,
522
+ summary: args.summary
523
+ });
524
+ }
525
+ function buildRunnerFailure(args) {
526
+ return notOk({
527
+ code: "RUNNER_FAILED",
528
+ summary: args.summary,
529
+ why: args.why,
530
+ meta: args.meta,
531
+ conflicts: void 0
532
+ });
533
+ }
534
+ //#endregion
535
+ //#region src/control-api/operations/db-init.ts
536
+ /**
537
+ * Execute `db init` against the configured contract.
538
+ *
539
+ * Routes through the loader → planner → runner pipeline (sub-spec
540
+ * "Commit-by-commit § Commit 4"). Always additive-only; destructive
541
+ * changes belong to `db update`.
542
+ */
543
+ async function executeDbInit(options) {
544
+ return await executeAggregateApply({
545
+ driver: options.driver,
546
+ familyInstance: options.familyInstance,
547
+ contract: options.contract,
548
+ mode: options.mode,
549
+ migrations: options.migrations,
550
+ frameworkComponents: options.frameworkComponents,
551
+ migrationsDir: options.migrationsDir,
552
+ targetId: options.targetId,
553
+ extensionPacks: options.extensionPacks ?? [],
554
+ policy: { allowedOperationClasses: ["additive"] },
555
+ action: "dbInit",
556
+ ...ifDefined("onProgress", options.onProgress)
557
+ });
558
+ }
559
+ //#endregion
560
+ //#region src/control-api/operations/db-update.ts
561
+ const DB_UPDATE_POLICY = { allowedOperationClasses: [
562
+ "additive",
563
+ "widening",
564
+ "destructive"
565
+ ] };
566
+ /**
567
+ * Execute `db update` against the configured contract.
568
+ *
569
+ * Routes through the loader → planner → runner pipeline. Destructive
570
+ * operations require either `acceptDataLoss: true` or a prior
571
+ * `mode: 'plan'` invocation that surfaces the destructive ops; the
572
+ * confirmation gate is implemented here so the lower-level applier
573
+ * remains policy-agnostic.
574
+ */
575
+ async function executeDbUpdate(options) {
576
+ const sharedInputs = {
577
+ driver: options.driver,
578
+ familyInstance: options.familyInstance,
579
+ contract: options.contract,
580
+ migrations: options.migrations,
581
+ frameworkComponents: options.frameworkComponents,
582
+ migrationsDir: options.migrationsDir,
583
+ targetId: options.targetId,
584
+ extensionPacks: options.extensionPacks ?? [],
585
+ policy: DB_UPDATE_POLICY,
586
+ action: "dbUpdate",
587
+ ...ifDefined("onProgress", options.onProgress)
588
+ };
589
+ if (options.mode === "apply" && !options.acceptDataLoss) {
590
+ const gate = await guardDestructiveChanges(sharedInputs);
591
+ if (gate !== null) return gate;
592
+ }
593
+ return await executeAggregateApply({
594
+ ...sharedInputs,
595
+ mode: options.mode
596
+ });
597
+ }
598
+ /**
599
+ * Pre-plan once when running `db update apply` without `acceptDataLoss`.
600
+ * Surfaces destructive operations across every space; if any are
601
+ * planned, returns a `DESTRUCTIVE_CHANGES` failure that the CLI shows
602
+ * as a confirmation prompt. Returns `null` when the apply is safe to
603
+ * run.
604
+ */
605
+ async function guardDestructiveChanges(sharedInputs) {
606
+ const planResult = await executeAggregateApply({
607
+ ...sharedInputs,
608
+ mode: "plan"
609
+ });
610
+ if (!planResult.ok) return planResult;
611
+ const destructiveOps = planResult.value.plan.operations.filter((op) => op.operationClass === "destructive").map((op) => ({
612
+ id: op.id,
613
+ label: op.label
614
+ }));
615
+ if (destructiveOps.length === 0) return null;
616
+ return notOk({
617
+ code: "DESTRUCTIVE_CHANGES",
618
+ summary: `Planned ${destructiveOps.length} destructive operation(s) that require confirmation`,
619
+ why: "Destructive operations require confirmation — re-run with -y to accept",
620
+ conflicts: void 0,
621
+ meta: { destructiveOperations: destructiveOps }
622
+ });
623
+ }
624
+ //#endregion
625
+ //#region src/control-api/operations/db-verify.ts
626
+ /**
627
+ * Span IDs emitted via `onProgress` during the aggregate verify flow.
628
+ * Mirrors the span identifiers used by the legacy precheck / marker-check
629
+ * helpers so structured-output renderers and progress tests keep working.
630
+ */
631
+ const SPAN_IDS = {
632
+ introspect: "introspect",
633
+ verify: "verify"
634
+ };
635
+ /**
636
+ * Loader → verifier pipeline shared by `db verify` modes (`full`,
637
+ * `marker-only`, `schema-only`).
638
+ *
639
+ * 1. **Load**: build a {@link import('@prisma-next/migration-tools/aggregate').ContractSpaceAggregate}
640
+ * from descriptors + on-disk on-disk artefacts. Layout / drift /
641
+ * integrity / disjointness violations short-circuit with a
642
+ * structured CLI error.
643
+ * 2. **Read DB state**: marker rows + (when `skipSchema` is `false`)
644
+ * schema introspection.
645
+ * 3. **Verify**: {@link verifyAggregate} returns per-space
646
+ * `markerCheck` + per-space pre-projected `schemaCheck` (closes F23).
647
+ * Marker mismatches map to `CliStructuredError` (code `5002`) so
648
+ * callers (CLI command) can render and exit. Schema results are
649
+ * returned to the caller verbatim.
650
+ */
651
+ async function executeDbVerify(options) {
652
+ const { driver, familyInstance, onProgress, skipSchema, skipMarker } = options;
653
+ const loaded = await buildContractSpaceAggregate(buildLoadInputs(options));
654
+ if (!loaded.ok) return notOk(loaded.failure);
655
+ const aggregate = loaded.value;
656
+ const markersBySpaceId = await familyInstance.readAllMarkers({ driver });
657
+ const schemaIntrospection = skipSchema ? null : await runIntrospection({
658
+ driver,
659
+ familyInstance,
660
+ onProgress
661
+ });
662
+ emitVerifySpan(onProgress, "spanStart");
663
+ return finaliseVerifyResult({
664
+ verifyResult: verifyAggregate({
665
+ aggregate,
666
+ markersBySpaceId,
667
+ schemaIntrospection,
668
+ mode: options.mode,
669
+ verifySchemaForMember: createPerMemberVerifier(options)
670
+ }),
671
+ aggregate,
672
+ skipMarker,
673
+ onProgress
674
+ });
675
+ }
676
+ function buildLoadInputs(options) {
677
+ return {
678
+ targetId: options.targetId,
679
+ migrationsDir: options.migrationsDir,
680
+ appContract: options.contract,
681
+ extensionPacks: options.extensionPacks,
682
+ validateContract: (json) => options.familyInstance.validateContract(json)
683
+ };
684
+ }
685
+ async function runIntrospection(args) {
686
+ const { driver, familyInstance, onProgress } = args;
687
+ onProgress?.({
688
+ action: "dbVerify",
689
+ kind: "spanStart",
690
+ spanId: SPAN_IDS.introspect,
691
+ label: "Introspecting database schema"
692
+ });
693
+ try {
694
+ const result = await familyInstance.introspect({ driver });
695
+ onProgress?.({
696
+ action: "dbVerify",
697
+ kind: "spanEnd",
698
+ spanId: SPAN_IDS.introspect,
699
+ outcome: "ok"
700
+ });
701
+ return result;
702
+ } catch (error) {
703
+ onProgress?.({
704
+ action: "dbVerify",
705
+ kind: "spanEnd",
706
+ spanId: SPAN_IDS.introspect,
707
+ outcome: "error"
708
+ });
709
+ throw error;
710
+ }
711
+ }
712
+ /**
713
+ * Build the per-member schema callback handed to the aggregate verifier.
714
+ * When `skipSchema` is true the callback short-circuits with a synthetic
715
+ * `ok` result so the verifier still runs the (cheap) schemaCheck loop
716
+ * without invoking the family's verification path.
717
+ */
718
+ function createPerMemberVerifier(options) {
719
+ const { skipSchema, familyInstance, frameworkComponents } = options;
720
+ return (projectedSchema, member, verifyMode) => {
721
+ if (skipSchema) return buildSkippedSchemaResult(member);
722
+ return familyInstance.schemaVerifyAgainstSchema({
723
+ contract: member.contract,
724
+ schema: projectedSchema,
725
+ strict: verifyMode === "strict",
726
+ frameworkComponents
727
+ });
728
+ };
729
+ }
730
+ function emitVerifySpan(onProgress, kind) {
731
+ if (kind === "spanStart") {
732
+ onProgress?.({
733
+ action: "dbVerify",
734
+ kind: "spanStart",
735
+ spanId: SPAN_IDS.verify,
736
+ label: "Verifying contract spaces"
737
+ });
738
+ return;
739
+ }
740
+ onProgress?.({
741
+ action: "dbVerify",
742
+ kind: "spanEnd",
743
+ spanId: SPAN_IDS.verify,
744
+ outcome: kind === "spanEndOk" ? "ok" : "error"
745
+ });
746
+ }
747
+ /**
748
+ * Map an {@link AggregateVerifierOutput} to the operation's
749
+ * {@link ExecuteDbVerifyResult}, applying the `skipMarker` policy used
750
+ * by the CLI's `--schema-only` mode.
751
+ */
752
+ function finaliseVerifyResult(args) {
753
+ const { verifyResult, aggregate, skipMarker, onProgress } = args;
754
+ if (!verifyResult.ok) {
755
+ emitVerifySpan(onProgress, "spanEndError");
756
+ return notOk(new CliStructuredError("5002", "Aggregate verifier introspection failed", {
757
+ domain: "MIG",
758
+ why: verifyResult.failure.detail,
759
+ fix: "Check database connectivity and the introspection tooling.",
760
+ docsUrl: "https://pris.ly/contract-spaces"
761
+ }));
762
+ }
763
+ const markerError = skipMarker ? null : mapMarkerCheckFailures(aggregate.app.spaceId, verifyResult.value.markerCheck);
764
+ if (markerError !== null) {
765
+ emitVerifySpan(onProgress, "spanEndError");
766
+ return notOk(markerError);
767
+ }
768
+ emitVerifySpan(onProgress, "spanEndOk");
769
+ return ok({
770
+ schemaResults: verifyResult.value.schemaCheck.perSpace,
771
+ memberOrder: [aggregate.app.spaceId, ...aggregate.extensions.map((e) => e.spaceId)],
772
+ appSpaceId: aggregate.app.spaceId
773
+ });
774
+ }
775
+ function buildSkippedSchemaResult(member) {
776
+ const profileHash = member.contract.profileHash;
777
+ return {
778
+ ok: true,
779
+ summary: "Schema verification skipped",
780
+ contract: {
781
+ storageHash: member.headRef.hash,
782
+ ...profileHash ? { profileHash } : {}
783
+ },
784
+ target: { expected: member.contract.target },
785
+ schema: {
786
+ issues: [],
787
+ root: {
788
+ status: "pass",
789
+ kind: "skipped",
790
+ name: member.spaceId,
791
+ contractPath: "",
792
+ code: "SKIPPED",
793
+ message: "Schema verification skipped",
794
+ expected: void 0,
795
+ actual: void 0,
796
+ children: []
797
+ },
798
+ counts: {
799
+ pass: 0,
800
+ warn: 0,
801
+ fail: 0,
802
+ totalNodes: 0
803
+ }
804
+ },
805
+ timings: { total: 0 }
806
+ };
807
+ }
808
+ /**
809
+ * Translate per-space marker check failures and orphan markers into a
810
+ * single CLI structured error envelope. Preserves the legacy code
811
+ * `5002` (was emitted by `runContractSpaceVerifierMarkerCheck`).
812
+ */
813
+ function mapMarkerCheckFailures(appSpaceId, section) {
814
+ const violations = [];
815
+ for (const [spaceId, result] of section.perSpace) {
816
+ if (result.kind === "ok" || result.kind === "absent") continue;
817
+ if (result.kind === "hashMismatch") {
818
+ violations.push({
819
+ kind: "hashMismatch",
820
+ spaceId,
821
+ remediation: spaceId === appSpaceId ? "Run `prisma-next db update` to advance the marker, or roll the database back to the recorded hash." : `Apply on-disk migrations under \`migrations/${spaceId}/\` to advance the marker, or remove the conflicting marker row.`
822
+ });
823
+ continue;
824
+ }
825
+ if (result.kind === "missingInvariants") violations.push({
826
+ kind: "invariantsMismatch",
827
+ spaceId,
828
+ remediation: `Re-apply the migrations under \`migrations/${spaceId}/\` so the marker carries invariants: ${result.missing.join(", ")}.`
829
+ });
830
+ }
831
+ for (const orphan of section.orphanMarkers) violations.push({
832
+ kind: "orphanMarker",
833
+ spaceId: orphan.spaceId,
834
+ remediation: `Add the corresponding extension to \`extensionPacks\` in \`prisma-next.config.ts\`, or delete the orphan marker row for "${orphan.spaceId}".`
835
+ });
836
+ if (violations.length === 0) return null;
837
+ const lines = violations.map((v) => `- [${v.kind}] ${v.spaceId}: ${v.remediation}`);
838
+ return new CliStructuredError("5002", violations.length === 1 ? "Contract-space verifier found a violation" : `Contract-space verifier found violations (${violations.length})`, {
839
+ domain: "MIG",
840
+ why: `The on-disk \`migrations/\` directory, the \`extensionPacks\` declaration, and the live database marker rows are not in agreement.\n${lines.join("\n")}`,
841
+ fix: violations[0]?.remediation ?? "Review and reconcile the violations listed above.",
842
+ docsUrl: "https://pris.ly/contract-spaces",
843
+ meta: { violations }
844
+ });
845
+ }
846
+ //#endregion
847
+ //#region src/control-api/operations/migration-apply.ts
848
+ /**
849
+ * Apply pending migrations across every contract space (app +
850
+ * extensions). Replay-only: graph-walk against the on-disk graph for
851
+ * every member; no synth, no introspection.
852
+ *
853
+ * Pipeline:
854
+ *
855
+ * 1. Load aggregate from disk (loader hydrates extension graphs;
856
+ * caller provides app-space packages).
857
+ * 2. Read live marker rows per space (`familyInstance.readAllMarkers`).
858
+ * 3. Per member: `graphWalkStrategy` plots the path from the live
859
+ * marker to `member.headRef.hash` (or `refHash` for the app
860
+ * member when provided). Empty-graph members fail loudly — a
861
+ * "never planned" space is a user-error condition for replay.
862
+ * 4. Hand off to {@link applyAggregate} (the runner-driving tail
863
+ * shared with `db init` / `db update`). Marker advancement is
864
+ * inside the per-space transaction.
865
+ *
866
+ * Sub-spec § `migration apply` semantics + § Required changes 1.
867
+ */
868
+ async function executeMigrationApply(options) {
869
+ const { driver, familyInstance, contract, migrations, frameworkComponents, migrationsDir, extensionPacks, targetId, appMigrationPackages, refHash, refInvariants, refName, onProgress } = options;
870
+ const loaded = await buildContractSpaceAggregate({
871
+ targetId,
872
+ migrationsDir,
873
+ appContract: contract,
874
+ extensionPacks,
875
+ validateContract: (json) => familyInstance.validateContract(json),
876
+ appMigrationPackages
877
+ });
878
+ if (!loaded.ok) throw loaded.failure;
879
+ const aggregate = loaded.value;
880
+ const markerRows = await familyInstance.readAllMarkers({ driver });
881
+ const allMembers = [aggregate.app, ...aggregate.extensions];
882
+ const perSpacePlans = /* @__PURE__ */ new Map();
883
+ const atHeadResolutions = /* @__PURE__ */ new Map();
884
+ for (const member of allMembers) {
885
+ const isAppMember = member.spaceId === aggregate.app.spaceId;
886
+ const targetHash = isAppMember && refHash !== void 0 ? refHash : member.headRef.hash;
887
+ const liveMarker = markerRows.get(member.spaceId) ?? null;
888
+ if (member.migrations.graph.nodes.size === 0) {
889
+ const liveHash = liveMarker?.storageHash;
890
+ if (targetHash === liveHash || liveHash === void 0 && targetHash === EMPTY_CONTRACT_HASH) {
891
+ atHeadResolutions.set(member.spaceId, buildAtHeadResolution({
892
+ aggregateTargetId: aggregate.targetId,
893
+ member,
894
+ targetHash,
895
+ liveMarker
896
+ }));
897
+ continue;
898
+ }
899
+ return notOk(buildNeverPlannedFailure(member.spaceId, targetHash));
900
+ }
901
+ const targetInvariants = isAppMember && refHash !== void 0 && refInvariants !== void 0 ? refInvariants : member.headRef.invariants;
902
+ const targetMember = targetHash === member.headRef.hash && targetInvariants === member.headRef.invariants ? member : {
903
+ ...member,
904
+ headRef: {
905
+ hash: targetHash,
906
+ invariants: targetInvariants
907
+ }
908
+ };
909
+ const walked = graphWalkStrategy({
910
+ aggregateTargetId: aggregate.targetId,
911
+ member: targetMember,
912
+ currentMarker: liveMarker,
913
+ ...isAppMember && refName !== void 0 ? { refName } : {}
914
+ });
915
+ if (walked.kind === "unreachable") return notOk(buildPathNotFoundFailure(member.spaceId, liveMarker, targetHash));
916
+ if (walked.kind === "unsatisfiable") {
917
+ const fromHash = liveMarker?.storageHash ?? "";
918
+ const structural = findPathWithDecision(targetMember.migrations.graph, fromHash, targetHash, { required: /* @__PURE__ */ new Set() });
919
+ const structuralPath = structural.kind === "ok" ? structural.decision.selectedPath.map((edge) => ({
920
+ dirName: edge.dirName,
921
+ migrationHash: edge.migrationHash,
922
+ from: edge.from,
923
+ to: edge.to,
924
+ invariants: edge.invariants
925
+ })) : [];
926
+ throw errorNoInvariantPath({
927
+ ...isAppMember && refName !== void 0 ? { refName } : {},
928
+ required: targetInvariants,
929
+ missing: walked.missing,
930
+ structuralPath
931
+ });
932
+ }
933
+ perSpacePlans.set(member.spaceId, walked.result);
934
+ }
935
+ const canonicalOrder = [...aggregate.extensions.map((m) => m.spaceId), aggregate.app.spaceId];
936
+ const applyOrder = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId));
937
+ if (sumPlannedOps(applyOrder, perSpacePlans) === 0) {
938
+ const ordered = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId) || atHeadResolutions.has(spaceId)).map((spaceId) => {
939
+ const entry = perSpacePlans.get(spaceId) ?? atHeadResolutions.get(spaceId);
940
+ if (entry === void 0) throw new Error(`Unreachable: missing per-space plan for "${spaceId}"`);
941
+ return {
942
+ spaceId,
943
+ entry
944
+ };
945
+ });
946
+ const perSpace = buildPerSpaceBreakdown(ordered, aggregate.app.spaceId, { includeMarkers: true });
947
+ const totalSpaces = ordered.length;
948
+ return ok(buildSuccess({
949
+ aggregate,
950
+ orderedResolutions: ordered,
951
+ perSpace,
952
+ totalOpsExecuted: 0,
953
+ summary: totalSpaces === 0 ? "Already up to date — no contract spaces are loaded" : totalSpaces === 1 ? "Already up to date" : `Already up to date across ${totalSpaces} space(s)`
954
+ }));
955
+ }
956
+ const applied = await applyAggregate({
957
+ aggregate,
958
+ perSpacePlans,
959
+ applyOrder,
960
+ driver,
961
+ familyInstance,
962
+ migrations,
963
+ frameworkComponents,
964
+ policy: { allowedOperationClasses: [
965
+ "additive",
966
+ "widening",
967
+ "destructive",
968
+ "data"
969
+ ] },
970
+ action: "migrationApply",
971
+ ...ifDefined("onProgress", onProgress)
972
+ });
973
+ if (!applied.ok) return notOk({
974
+ code: "RUNNER_FAILED",
975
+ summary: applied.failure.summary,
976
+ why: applied.failure.why,
977
+ meta: applied.failure.meta
978
+ });
979
+ const orderedAll = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId) || atHeadResolutions.has(spaceId)).map((spaceId) => {
980
+ if (perSpacePlans.has(spaceId)) {
981
+ const fromRunner = applied.value.orderedResolutions.find((r) => r.spaceId === spaceId);
982
+ if (fromRunner !== void 0) return fromRunner;
983
+ }
984
+ const entry = atHeadResolutions.get(spaceId);
985
+ if (entry === void 0) throw new Error(`Unreachable: missing per-space plan for "${spaceId}"`);
986
+ return {
987
+ spaceId,
988
+ entry
989
+ };
990
+ });
991
+ const perSpaceAll = buildPerSpaceBreakdown(orderedAll, aggregate.app.spaceId, { includeMarkers: true });
992
+ const summary = `Applied ${applied.value.orderedResolutions.reduce((sum, r) => sum + (r.entry.migrationEdges?.length ?? 0), 0)} migration(s) (${applied.value.totalOpsExecuted} operation(s)) across ${orderedAll.length} contract space(s)`;
993
+ return ok(buildSuccess({
994
+ aggregate,
995
+ orderedResolutions: orderedAll,
996
+ perSpace: perSpaceAll,
997
+ totalOpsExecuted: applied.value.totalOpsExecuted,
998
+ summary
999
+ }));
1000
+ }
1001
+ /**
1002
+ * Build a zero-op {@link AggregatePerSpacePlan} for an empty-graph
1003
+ * member whose live marker already matches the target. Lets the apply
1004
+ * pipeline thread the member through `perSpacePlans` -> `applyOrder`
1005
+ * -> the success envelope's `perSpace[]` block so the result reflects
1006
+ * every loaded space, even when there is nothing to execute.
1007
+ */
1008
+ function buildAtHeadResolution(args) {
1009
+ const { aggregateTargetId, member, targetHash, liveMarker } = args;
1010
+ return {
1011
+ plan: {
1012
+ targetId: aggregateTargetId,
1013
+ spaceId: member.spaceId,
1014
+ origin: liveMarker === null ? null : { storageHash: liveMarker.storageHash },
1015
+ destination: { storageHash: targetHash },
1016
+ operations: [],
1017
+ providedInvariants: []
1018
+ },
1019
+ displayOps: [],
1020
+ destinationContract: member.contract,
1021
+ strategy: "graph-walk",
1022
+ migrationEdges: []
1023
+ };
1024
+ }
1025
+ function sumPlannedOps(applyOrder, perSpacePlans) {
1026
+ let total = 0;
1027
+ for (const spaceId of applyOrder) {
1028
+ const entry = perSpacePlans.get(spaceId);
1029
+ if (!entry) continue;
1030
+ total += entry.plan.operations.length;
1031
+ }
1032
+ return total;
1033
+ }
1034
+ function buildSuccess(args) {
1035
+ const appResolution = args.orderedResolutions.find((r) => r.spaceId === args.aggregate.app.spaceId);
1036
+ const appMarkerHash = appResolution?.entry.plan.destination.storageHash ?? args.aggregate.app.headRef.hash;
1037
+ const applied = args.orderedResolutions.flatMap((r) => {
1038
+ return (r.entry.migrationEdges ?? []).map((edge) => ({
1039
+ spaceId: r.spaceId,
1040
+ dirName: edge.dirName,
1041
+ migrationHash: edge.migrationHash,
1042
+ from: edge.from,
1043
+ to: edge.to,
1044
+ operationsExecuted: edge.operationCount
1045
+ }));
1046
+ });
1047
+ const appPlan = appResolution?.entry;
1048
+ const pathDecision = appPlan?.pathDecision ? {
1049
+ fromHash: appPlan.pathDecision.fromHash,
1050
+ toHash: appPlan.pathDecision.toHash,
1051
+ alternativeCount: appPlan.pathDecision.alternativeCount,
1052
+ tieBreakReasons: appPlan.pathDecision.tieBreakReasons,
1053
+ ...appPlan.pathDecision.refName !== void 0 ? { refName: appPlan.pathDecision.refName } : {},
1054
+ requiredInvariants: appPlan.pathDecision.requiredInvariants ?? [],
1055
+ satisfiedInvariants: appPlan.pathDecision.satisfiedInvariants ?? [],
1056
+ selectedPath: appPlan.pathDecision.selectedPath.map((entry) => ({
1057
+ dirName: entry.dirName,
1058
+ migrationHash: entry.migrationHash,
1059
+ from: entry.from,
1060
+ to: entry.to,
1061
+ invariants: entry.invariants
1062
+ }))
1063
+ } : void 0;
1064
+ return {
1065
+ migrationsApplied: applied.length,
1066
+ markerHash: appMarkerHash,
1067
+ applied,
1068
+ summary: args.summary,
1069
+ perSpace: args.perSpace,
1070
+ ...pathDecision !== void 0 ? { pathDecision } : {}
1071
+ };
1072
+ }
1073
+ function buildNeverPlannedFailure(spaceId, targetHash) {
1074
+ return {
1075
+ code: "MIGRATION_PATH_NOT_FOUND",
1076
+ summary: `No on-disk migrations for contract space "${spaceId}"`,
1077
+ why: `migration apply is replay-only: every contract space must have an authored migration graph on disk. Space "${spaceId}" has no migrations under \`migrations/${spaceId}/\` but its head ref targets "${targetHash}". Run \`prisma-next migration plan\` first to materialise the path.`,
1078
+ meta: {
1079
+ spaceId,
1080
+ target: targetHash,
1081
+ kind: "neverPlanned"
1082
+ }
1083
+ };
1084
+ }
1085
+ function buildPathNotFoundFailure(spaceId, marker, targetHash) {
1086
+ const fromHash = marker?.storageHash ?? "<empty>";
1087
+ return {
1088
+ code: "MIGRATION_PATH_NOT_FOUND",
1089
+ summary: spaceId === "app" ? "Current contract has no planned migration path" : `Current contract has no planned migration path for contract space "${spaceId}"`,
1090
+ why: `Cannot reach target "${targetHash}" from current marker "${fromHash}" in space "${spaceId}". The on-disk migration graph for this space does not connect the two states. Run \`prisma-next migration plan\` to materialise the path.`,
1091
+ meta: {
1092
+ spaceId,
1093
+ fromHash,
1094
+ targetHash,
1095
+ kind: "pathUnreachable"
1096
+ }
1097
+ };
1098
+ }
1099
+ //#endregion
1100
+ //#region src/control-api/client.ts
1101
+ /**
1102
+ * Creates a programmatic control client for Prisma Next operations.
1103
+ *
1104
+ * The client accepts framework component descriptors at creation time,
1105
+ * manages driver lifecycle via connect()/close(), and exposes domain
1106
+ * operations that delegate to the existing family instance methods.
1107
+ *
1108
+ * @see {@link ControlClient} for the client interface
1109
+ * @see README.md "Programmatic Control API" section for usage examples
1110
+ */
1111
+ function createControlClient(options) {
1112
+ return new ControlClientImpl(options);
1113
+ }
1114
+ /**
1115
+ * Implementation of ControlClient.
1116
+ * Manages initialization and connection state, delegates operations to family instance.
1117
+ */
1118
+ var ControlClientImpl = class {
1119
+ options;
1120
+ stack = null;
1121
+ driver = null;
1122
+ familyInstance = null;
1123
+ frameworkComponents = null;
1124
+ initialized = false;
1125
+ defaultConnection;
1126
+ constructor(options) {
1127
+ this.options = options;
1128
+ this.defaultConnection = options.connection;
1129
+ }
1130
+ init() {
1131
+ if (this.initialized) return;
1132
+ this.stack = createControlStack({
1133
+ family: this.options.family,
1134
+ target: this.options.target,
1135
+ adapter: this.options.adapter,
1136
+ driver: this.options.driver,
1137
+ extensionPacks: this.options.extensionPacks
1138
+ });
1139
+ this.familyInstance = this.options.family.create(this.stack);
1140
+ const rawComponents = [
1141
+ this.options.target,
1142
+ this.options.adapter,
1143
+ ...this.options.extensionPacks ?? []
1144
+ ];
1145
+ this.frameworkComponents = assertFrameworkComponentsCompatible(this.options.family.familyId, this.options.target.targetId, rawComponents);
1146
+ this.initialized = true;
1147
+ }
1148
+ async connect(connection) {
1149
+ this.init();
1150
+ if (this.driver) throw new Error("Already connected. Call close() before reconnecting.");
1151
+ const resolvedConnection = connection ?? this.defaultConnection;
1152
+ if (resolvedConnection === void 0) throw new Error("No connection provided. Pass a connection to connect() or provide a default connection when creating the client.");
1153
+ if (!this.stack?.driver) throw new Error("Driver is not configured. Pass a driver descriptor when creating the control client to enable database operations.");
1154
+ this.driver = await this.stack.driver.create(resolvedConnection);
1155
+ }
1156
+ async close() {
1157
+ if (this.driver) {
1158
+ await this.driver.close();
1159
+ this.driver = null;
1160
+ }
1161
+ }
1162
+ async ensureConnected() {
1163
+ this.init();
1164
+ if (!this.driver && this.defaultConnection !== void 0) await this.connect(this.defaultConnection);
1165
+ if (!this.driver || !this.familyInstance || !this.frameworkComponents) throw new Error("Not connected. Call connect(connection) first.");
1166
+ return {
1167
+ driver: this.driver,
1168
+ familyInstance: this.familyInstance,
1169
+ frameworkComponents: this.frameworkComponents
1170
+ };
1171
+ }
1172
+ async connectWithProgress(connection, action, onProgress) {
1173
+ if (connection === void 0) return;
1174
+ onProgress?.({
1175
+ action,
1176
+ kind: "spanStart",
1177
+ spanId: "connect",
1178
+ label: "Connecting to database..."
1179
+ });
1180
+ try {
1181
+ await this.connect(connection);
1182
+ onProgress?.({
1183
+ action,
1184
+ kind: "spanEnd",
1185
+ spanId: "connect",
1186
+ outcome: "ok"
1187
+ });
1188
+ } catch (error) {
1189
+ onProgress?.({
1190
+ action,
1191
+ kind: "spanEnd",
1192
+ spanId: "connect",
1193
+ outcome: "error"
1194
+ });
1195
+ throw error;
1196
+ }
1197
+ }
1198
+ async verify(options) {
1199
+ const { onProgress } = options;
1200
+ await this.connectWithProgress(options.connection, "verify", onProgress);
1201
+ const { driver, familyInstance } = await this.ensureConnected();
1202
+ let contract;
1203
+ try {
1204
+ contract = familyInstance.validateContract(options.contract);
1205
+ } catch (error) {
1206
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), error);
1207
+ }
1208
+ onProgress?.({
1209
+ action: "verify",
1210
+ kind: "spanStart",
1211
+ spanId: "verify",
1212
+ label: "Verifying database marker..."
1213
+ });
1214
+ try {
1215
+ const result = await familyInstance.verify({
1216
+ driver,
1217
+ contract,
1218
+ expectedTargetId: this.options.target.targetId,
1219
+ contractPath: ""
1220
+ });
1221
+ onProgress?.({
1222
+ action: "verify",
1223
+ kind: "spanEnd",
1224
+ spanId: "verify",
1225
+ outcome: result.ok ? "ok" : "error"
1226
+ });
1227
+ return result;
1228
+ } catch (error) {
1229
+ onProgress?.({
1230
+ action: "verify",
1231
+ kind: "spanEnd",
1232
+ spanId: "verify",
1233
+ outcome: "error"
1234
+ });
1235
+ throw error;
1236
+ }
1237
+ }
1238
+ async schemaVerify(options) {
1239
+ const { onProgress } = options;
1240
+ await this.connectWithProgress(options.connection, "schemaVerify", onProgress);
1241
+ const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
1242
+ let contract;
1243
+ try {
1244
+ contract = familyInstance.validateContract(options.contract);
1245
+ } catch (error) {
1246
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), error);
1247
+ }
1248
+ onProgress?.({
1249
+ action: "schemaVerify",
1250
+ kind: "spanStart",
1251
+ spanId: "schemaVerify",
1252
+ label: "Verifying database schema..."
1253
+ });
1254
+ try {
1255
+ const result = await familyInstance.schemaVerify({
1256
+ driver,
1257
+ contract,
1258
+ strict: options.strict ?? false,
1259
+ contractPath: "",
1260
+ frameworkComponents
1261
+ });
1262
+ onProgress?.({
1263
+ action: "schemaVerify",
1264
+ kind: "spanEnd",
1265
+ spanId: "schemaVerify",
1266
+ outcome: result.ok ? "ok" : "error"
1267
+ });
1268
+ return result;
1269
+ } catch (error) {
1270
+ onProgress?.({
1271
+ action: "schemaVerify",
1272
+ kind: "spanEnd",
1273
+ spanId: "schemaVerify",
1274
+ outcome: "error"
1275
+ });
1276
+ throw error;
1277
+ }
1278
+ }
1279
+ async sign(options) {
1280
+ const { onProgress } = options;
1281
+ await this.connectWithProgress(options.connection, "sign", onProgress);
1282
+ const { driver, familyInstance } = await this.ensureConnected();
1283
+ let contract;
1284
+ try {
1285
+ contract = familyInstance.validateContract(options.contract);
1286
+ } catch (error) {
1287
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), error);
1288
+ }
1289
+ onProgress?.({
1290
+ action: "sign",
1291
+ kind: "spanStart",
1292
+ spanId: "sign",
1293
+ label: "Signing database..."
1294
+ });
1295
+ try {
1296
+ const result = await familyInstance.sign({
1297
+ driver,
1298
+ contract,
1299
+ contractPath: options.contractPath ?? "",
1300
+ ...ifDefined("configPath", options.configPath)
1301
+ });
1302
+ onProgress?.({
1303
+ action: "sign",
1304
+ kind: "spanEnd",
1305
+ spanId: "sign",
1306
+ outcome: "ok"
1307
+ });
1308
+ return result;
1309
+ } catch (error) {
1310
+ onProgress?.({
1311
+ action: "sign",
1312
+ kind: "spanEnd",
1313
+ spanId: "sign",
1314
+ outcome: "error"
1315
+ });
1316
+ throw error;
1317
+ }
1318
+ }
1319
+ async dbInit(options) {
1320
+ const { onProgress } = options;
1321
+ await this.connectWithProgress(options.connection, "dbInit", onProgress);
1322
+ const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
1323
+ if (!hasMigrations(this.options.target)) throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
1324
+ let contract;
1325
+ try {
1326
+ contract = familyInstance.validateContract(options.contract);
1327
+ } catch (error) {
1328
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), error);
1329
+ }
1330
+ return executeDbInit({
1331
+ driver,
1332
+ familyInstance,
1333
+ contract,
1334
+ mode: options.mode,
1335
+ migrations: this.options.target.migrations,
1336
+ frameworkComponents,
1337
+ migrationsDir: options.migrationsDir,
1338
+ targetId: this.options.target.targetId,
1339
+ extensionPacks: this.options.extensionPacks ?? [],
1340
+ ...ifDefined("onProgress", onProgress)
1341
+ });
1342
+ }
1343
+ async dbUpdate(options) {
1344
+ const { onProgress } = options;
1345
+ await this.connectWithProgress(options.connection, "dbUpdate", onProgress);
1346
+ const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
1347
+ if (!hasMigrations(this.options.target)) throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
1348
+ let contract;
1349
+ try {
1350
+ contract = familyInstance.validateContract(options.contract);
1351
+ } catch (error) {
1352
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), error);
1353
+ }
1354
+ return executeDbUpdate({
1355
+ driver,
1356
+ familyInstance,
1357
+ contract,
1358
+ mode: options.mode,
1359
+ migrations: this.options.target.migrations,
1360
+ frameworkComponents,
1361
+ migrationsDir: options.migrationsDir,
1362
+ targetId: this.options.target.targetId,
1363
+ extensionPacks: this.options.extensionPacks ?? [],
1364
+ ...ifDefined("acceptDataLoss", options.acceptDataLoss),
1365
+ ...ifDefined("onProgress", onProgress)
1366
+ });
1367
+ }
1368
+ async dbVerify(options) {
1369
+ const { onProgress } = options;
1370
+ await this.connectWithProgress(options.connection, "dbVerify", onProgress);
1371
+ const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
1372
+ let contract;
1373
+ try {
1374
+ contract = familyInstance.validateContract(options.contract);
1375
+ } catch (error) {
1376
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), error);
1377
+ }
1378
+ return executeDbVerify({
1379
+ driver,
1380
+ familyInstance,
1381
+ contract,
1382
+ migrationsDir: options.migrationsDir,
1383
+ targetId: this.options.target.targetId,
1384
+ extensionPacks: this.options.extensionPacks ?? [],
1385
+ frameworkComponents,
1386
+ mode: options.strict ? "strict" : "lenient",
1387
+ skipSchema: options.skipSchema,
1388
+ skipMarker: options.skipMarker,
1389
+ ...ifDefined("onProgress", onProgress)
1390
+ });
1391
+ }
1392
+ async readMarker() {
1393
+ const { driver, familyInstance } = await this.ensureConnected();
1394
+ return familyInstance.readMarker({
1395
+ driver,
1396
+ space: APP_SPACE_ID
1397
+ });
1398
+ }
1399
+ async readAllMarkers() {
1400
+ const { driver, familyInstance } = await this.ensureConnected();
1401
+ return familyInstance.readAllMarkers({ driver });
1402
+ }
1403
+ async migrationApply(options) {
1404
+ const { onProgress } = options;
1405
+ await this.connectWithProgress(options.connection, "migrationApply", onProgress);
1406
+ const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
1407
+ if (!hasMigrations(this.options.target)) throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
1408
+ let contract;
1409
+ try {
1410
+ contract = familyInstance.validateContract(options.contract);
1411
+ } catch (error) {
1412
+ throw new ContractValidationError(error instanceof Error ? error.message : String(error), error);
1413
+ }
1414
+ return executeMigrationApply({
1415
+ driver,
1416
+ familyInstance,
1417
+ contract,
1418
+ migrations: this.options.target.migrations,
1419
+ frameworkComponents,
1420
+ migrationsDir: options.migrationsDir,
1421
+ extensionPacks: this.options.extensionPacks ?? [],
1422
+ targetId: this.options.target.targetId,
1423
+ appMigrationPackages: options.appMigrationPackages,
1424
+ ...ifDefined("refHash", options.refHash),
1425
+ ...ifDefined("refInvariants", options.refInvariants),
1426
+ ...ifDefined("refName", options.refName),
1427
+ ...ifDefined("onProgress", onProgress)
1428
+ });
1429
+ }
1430
+ async introspect(options) {
1431
+ const onProgress = options?.onProgress;
1432
+ await this.connectWithProgress(options?.connection, "introspect", onProgress);
1433
+ const { driver, familyInstance } = await this.ensureConnected();
1434
+ options?.schema;
1435
+ onProgress?.({
1436
+ action: "introspect",
1437
+ kind: "spanStart",
1438
+ spanId: "introspect",
1439
+ label: "Introspecting database schema..."
1440
+ });
1441
+ try {
1442
+ const result = await familyInstance.introspect({ driver });
1443
+ onProgress?.({
1444
+ action: "introspect",
1445
+ kind: "spanEnd",
1446
+ spanId: "introspect",
1447
+ outcome: "ok"
1448
+ });
1449
+ return result;
1450
+ } catch (error) {
1451
+ onProgress?.({
1452
+ action: "introspect",
1453
+ kind: "spanEnd",
1454
+ spanId: "introspect",
1455
+ outcome: "error"
1456
+ });
1457
+ throw error;
1458
+ }
1459
+ }
1460
+ toSchemaView(schemaIR) {
1461
+ this.init();
1462
+ if (this.familyInstance && hasSchemaView(this.familyInstance)) return this.familyInstance.toSchemaView(schemaIR);
1463
+ }
1464
+ inferPslContract(schemaIR) {
1465
+ this.init();
1466
+ if (this.familyInstance && hasPslContractInfer(this.familyInstance)) return this.familyInstance.inferPslContract(schemaIR);
1467
+ }
1468
+ toOperationPreview(operations) {
1469
+ this.init();
1470
+ if (this.familyInstance && hasOperationPreview(this.familyInstance)) return this.familyInstance.toOperationPreview(operations);
1471
+ }
1472
+ async emit(options) {
1473
+ const { onProgress, contractConfig } = options;
1474
+ this.init();
1475
+ if (!this.familyInstance) throw new Error("Family instance was not initialized. This is a bug.");
1476
+ let contractRaw;
1477
+ onProgress?.({
1478
+ action: "emit",
1479
+ kind: "spanStart",
1480
+ spanId: "resolveSource",
1481
+ label: "Resolving contract source..."
1482
+ });
1483
+ try {
1484
+ const stack = this.stack;
1485
+ const sourceContext = {
1486
+ composedExtensionPacks: stack.extensionPacks.map((p) => p.id),
1487
+ scalarTypeDescriptors: stack.scalarTypeDescriptors,
1488
+ authoringContributions: stack.authoringContributions,
1489
+ codecLookup: stack.codecLookup,
1490
+ controlMutationDefaults: stack.controlMutationDefaults,
1491
+ resolvedInputs: contractConfig.source.inputs ?? []
1492
+ };
1493
+ const providerResult = await contractConfig.source.load(sourceContext);
1494
+ if (!providerResult.ok) {
1495
+ onProgress?.({
1496
+ action: "emit",
1497
+ kind: "spanEnd",
1498
+ spanId: "resolveSource",
1499
+ outcome: "error"
1500
+ });
1501
+ return notOk({
1502
+ code: "CONTRACT_SOURCE_INVALID",
1503
+ summary: providerResult.failure.summary,
1504
+ why: providerResult.failure.summary,
1505
+ meta: providerResult.failure.meta,
1506
+ diagnostics: providerResult.failure
1507
+ });
1508
+ }
1509
+ contractRaw = providerResult.value;
1510
+ onProgress?.({
1511
+ action: "emit",
1512
+ kind: "spanEnd",
1513
+ spanId: "resolveSource",
1514
+ outcome: "ok"
1515
+ });
1516
+ } catch (error) {
1517
+ onProgress?.({
1518
+ action: "emit",
1519
+ kind: "spanEnd",
1520
+ spanId: "resolveSource",
1521
+ outcome: "error"
1522
+ });
1523
+ const message = error instanceof Error ? error.message : String(error);
1524
+ return notOk({
1525
+ code: "CONTRACT_SOURCE_INVALID",
1526
+ summary: "Failed to resolve contract source",
1527
+ why: message,
1528
+ diagnostics: {
1529
+ summary: "Contract source provider threw an exception",
1530
+ diagnostics: [{
1531
+ code: "PROVIDER_THROW",
1532
+ message
1533
+ }]
1534
+ },
1535
+ meta: void 0
1536
+ });
1537
+ }
1538
+ onProgress?.({
1539
+ action: "emit",
1540
+ kind: "spanStart",
1541
+ spanId: "emit",
1542
+ label: "Emitting contract..."
1543
+ });
1544
+ try {
1545
+ const enrichedIR = enrichContract(contractRaw, this.frameworkComponents ?? []);
1546
+ try {
1547
+ this.familyInstance.validateContract(enrichedIR);
1548
+ } catch (error) {
1549
+ onProgress?.({
1550
+ action: "emit",
1551
+ kind: "spanEnd",
1552
+ spanId: "emit",
1553
+ outcome: "error"
1554
+ });
1555
+ return notOk({
1556
+ code: "CONTRACT_VALIDATION_FAILED",
1557
+ summary: "Contract validation failed",
1558
+ why: error instanceof Error ? error.message : String(error),
1559
+ meta: void 0
1560
+ });
1561
+ }
1562
+ const result = await emit(enrichedIR, this.stack, this.options.family.emission);
1563
+ onProgress?.({
1564
+ action: "emit",
1565
+ kind: "spanEnd",
1566
+ spanId: "emit",
1567
+ outcome: "ok"
1568
+ });
1569
+ return ok({
1570
+ storageHash: result.storageHash,
1571
+ ...ifDefined("executionHash", result.executionHash),
1572
+ profileHash: result.profileHash,
1573
+ contractJson: result.contractJson,
1574
+ contractDts: result.contractDts
1575
+ });
1576
+ } catch (error) {
1577
+ onProgress?.({
1578
+ action: "emit",
1579
+ kind: "spanEnd",
1580
+ spanId: "emit",
1581
+ outcome: "error"
1582
+ });
1583
+ return notOk({
1584
+ code: "EMIT_FAILED",
1585
+ summary: "Failed to emit contract",
1586
+ why: error instanceof Error ? error.message : String(error),
1587
+ meta: void 0
1588
+ });
1589
+ }
1590
+ }
1591
+ };
1592
+ //#endregion
1593
+ export { buildContractSpaceAggregate as a, executeDbInit as i, executeDbVerify as n, ContractValidationError as o, executeDbUpdate as r, createControlClient as t };
1594
+
1595
+ //# sourceMappingURL=client-qVH-rEgd.mjs.map