@prisma/orm-toolchain 8.0.0-rc.16-dev.6 → 8.0.0-rc.16-dev.8

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 (65) hide show
  1. package/dist/{aggregate-DLptsx8n.d.mts → aggregate-C23h_Ybm.d.mts} +47 -22
  2. package/dist/{aggregate-DLptsx8n.d.mts.map → aggregate-C23h_Ybm.d.mts.map} +1 -1
  3. package/dist/{aggregate-C7IHVcsV.mjs → aggregate-DlfOyErc.mjs} +40 -8
  4. package/dist/aggregate-DlfOyErc.mjs.map +1 -0
  5. package/dist/{caught-errors-N266GMql-B7p73Xyj.mjs → caught-errors-HFQjjQVE-b_GDV-6J.mjs} +125 -9
  6. package/dist/caught-errors-HFQjjQVE-b_GDV-6J.mjs.map +1 -0
  7. package/dist/cli-telemetry.mjs +1 -1
  8. package/dist/cli.mjs +187 -114
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/cli__control-api.d.mts +73 -43
  11. package/dist/cli__control-api.d.mts.map +1 -1
  12. package/dist/cli__control-api.mjs +3 -3
  13. package/dist/cli__control-api__testing.d.mts +1 -1
  14. package/dist/cli__control-api__testing.mjs +3 -0
  15. package/dist/cli__control-api__testing.mjs.map +1 -1
  16. package/dist/cli__migration-cli.d.mts +1 -1
  17. package/dist/cli__migration-cli.mjs +3 -3
  18. package/dist/cli__migration-cli.mjs.map +1 -1
  19. package/dist/config-loader.mjs +1 -1
  20. package/dist/{contract-snapshot-store-1S_6vaGt-CQPNFWho.mjs → contract-snapshot-store-1S_6vaGt-HJIMKsVd.mjs} +2 -2
  21. package/dist/{contract-snapshot-store-1S_6vaGt-CQPNFWho.mjs.map → contract-snapshot-store-1S_6vaGt-HJIMKsVd.mjs.map} +1 -1
  22. package/dist/{db-sign-BxYV7wMQ-CNy01Yj7.d.mts → db-sign-BPf9SzzX-CwOFPxoZ.d.mts} +100 -53
  23. package/dist/db-sign-BPf9SzzX-CwOFPxoZ.d.mts.map +1 -0
  24. package/dist/{exports-CBfiI5mf.mjs → exports-Bd3uWDtm.mjs} +2 -2
  25. package/dist/{exports-CBfiI5mf.mjs.map → exports-Bd3uWDtm.mjs.map} +1 -1
  26. package/dist/{exports-Czq5v0Dn.mjs → exports-C7GzkPEc.mjs} +2 -2
  27. package/dist/{exports-Czq5v0Dn.mjs.map → exports-C7GzkPEc.mjs.map} +1 -1
  28. package/dist/{io-xKnQrxIC-BPHEfarH.mjs → io-xKnQrxIC-CEXpCgE_.mjs} +3 -3
  29. package/dist/{io-xKnQrxIC-BPHEfarH.mjs.map → io-xKnQrxIC-CEXpCgE_.mjs.map} +1 -1
  30. package/dist/{migration-B2ljMJim.d.mts → migration-Bjz05034.d.mts} +12 -5
  31. package/dist/migration-Bjz05034.d.mts.map +1 -0
  32. package/dist/{migration-DaFjTC8t.mjs → migration-oIynqb-J.mjs} +14 -2
  33. package/dist/migration-oIynqb-J.mjs.map +1 -0
  34. package/dist/migration-tools.d.mts +3 -3
  35. package/dist/migration-tools.mjs +9 -9
  36. package/dist/migration-tools__aggregate.d.mts +2 -2
  37. package/dist/migration-tools__aggregate.mjs +1 -1
  38. package/dist/migration-tools__contract-snapshot-store.mjs +1 -1
  39. package/dist/migration-tools__io.mjs +1 -1
  40. package/dist/migration-tools__migration-ts.mjs +1 -1
  41. package/dist/migration-tools__migration.d.mts +1 -1
  42. package/dist/migration-tools__migration.mjs +1 -1
  43. package/dist/migration-tools__ref-resolution.mjs +1 -1
  44. package/dist/migration-tools__refs.mjs +1 -1
  45. package/dist/migration-tools__spaces.mjs +2 -2
  46. package/dist/{migration-ts-BQuIba9e.mjs → migration-ts-FyF55c4M.mjs} +2 -2
  47. package/dist/{migration-ts-BQuIba9e.mjs.map → migration-ts-FyF55c4M.mjs.map} +1 -1
  48. package/dist/{ref-BCEAH4F9-Bgr9vmL7.mjs → ref-Cc_CTagE-C070Ym7p.mjs} +1206 -202
  49. package/dist/ref-Cc_CTagE-C070Ym7p.mjs.map +1 -0
  50. package/dist/{ref-resolution-d7rcmU6F.mjs → ref-resolution-Be_zewf7.mjs} +2 -2
  51. package/dist/{ref-resolution-d7rcmU6F.mjs.map → ref-resolution-Be_zewf7.mjs.map} +1 -1
  52. package/dist/{refs-qwvw4_dV-X8sR92eT.mjs → refs-qwvw4_dV-DNg_7WTD.mjs} +2 -2
  53. package/dist/{refs-qwvw4_dV-X8sR92eT.mjs.map → refs-qwvw4_dV-DNg_7WTD.mjs.map} +1 -1
  54. package/dist/{spaces-CzLQQYa9.mjs → spaces-DGu96Hkk.mjs} +5 -5
  55. package/dist/{spaces-CzLQQYa9.mjs.map → spaces-DGu96Hkk.mjs.map} +1 -1
  56. package/dist/{verify-contract-spaces-CYjc343k-FXABEJZE.mjs → verify-contract-spaces-CYjc343k-ClHHEkJF.mjs} +3 -3
  57. package/dist/{verify-contract-spaces-CYjc343k-FXABEJZE.mjs.map → verify-contract-spaces-CYjc343k-ClHHEkJF.mjs.map} +1 -1
  58. package/dist/vite-plugin-contract-emit.mjs +2 -2
  59. package/package.json +13 -13
  60. package/dist/aggregate-C7IHVcsV.mjs.map +0 -1
  61. package/dist/caught-errors-N266GMql-B7p73Xyj.mjs.map +0 -1
  62. package/dist/db-sign-BxYV7wMQ-CNy01Yj7.d.mts.map +0 -1
  63. package/dist/migration-B2ljMJim.d.mts.map +0 -1
  64. package/dist/migration-DaFjTC8t.mjs.map +0 -1
  65. package/dist/ref-BCEAH4F9-Bgr9vmL7.mjs.map +0 -1
@@ -1,39 +1,39 @@
1
- import { i as expandContractInputs } from "./exports-Czq5v0Dn.mjs";
1
+ import { i as expandContractInputs } from "./exports-C7GzkPEc.mjs";
2
2
  import { D as errorNoInvariantPath, M as errorUnknownInvariant, b as errorInvalidRefName, r as errorContractDeserializationFailed, t as MigrationToolsError } from "./errors-DD6iLGXk-6I9PqjpZ.mjs";
3
3
  import { r as verifyMigrationHash, t as computeMigrationHash } from "./hash-BAZVWU4a-BQovI7hF.mjs";
4
- import { a as snapshotsImportPathFrom, n as createSnapshotContentVerifier, o as writeContractSnapshot, r as readContractSnapshotJson, t as contractSnapshotDir } from "./contract-snapshot-store-1S_6vaGt-CQPNFWho.mjs";
4
+ import { a as snapshotsImportPathFrom, n as createSnapshotContentVerifier, o as writeContractSnapshot, r as readContractSnapshotJson, t as contractSnapshotDir } from "./contract-snapshot-store-1S_6vaGt-HJIMKsVd.mjs";
5
5
  import { t as deriveProvidedInvariants } from "./invariants-C0lpc60l-CMUCvk4O.mjs";
6
- import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-xKnQrxIC-BPHEfarH.mjs";
6
+ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-xKnQrxIC-CEXpCgE_.mjs";
7
7
  import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
8
8
  import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
9
- import { a as isValidSpaceId, c as spaceMigrationDirectory, l as spaceRefsDirectory, o as listContractSpaceDirectories, s as readContractSpaceHeadRef, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-CYjc343k-FXABEJZE.mjs";
10
- import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-CzLQQYa9.mjs";
11
- import { A as errorPlanProducedNoOperations, D as errorPathUnreachable, F as errorRuntime, G as readContractEnvelope, H as getTargetMigrations, J as resolveContractPath, L as errorSnapshotMissing, M as errorRefSetEmptySentinel, N as errorRefSetHashNotInGraph, O as errorPlanForgotTheFlag, Q as toStructuralEdge, R as errorSpaceNotFound, S as errorMarkerMismatch, T as errorMigrationPlanningFailed, U as mapRefResolutionError, V as errorUnexpected, X as runCommandAction, Y as resolveMigrationPaths, _ as errorFileNotFound, a as closeQuietly, b as errorInvalidSpaceId, c as errorAmbiguousMigrationRef, f as errorContractConfigMissing, h as errorDestructiveChanges, i as chooseAction, j as errorRefSetBundleNotFound, k as errorPlanOriginUnknown, l as errorConfigValidation$1, n as CliStructuredError$1, o as collectDeclaredInvariants, p as errorContractValidationFailed, q as requireLiveDatabase, u as errorConsentPlanMismatch, v as errorFromCaught, z as errorTargetMigrationNotSupported } from "./caught-errors-N266GMql-B7p73Xyj.mjs";
9
+ import { a as isValidSpaceId, c as spaceMigrationDirectory, l as spaceRefsDirectory, o as listContractSpaceDirectories, s as readContractSpaceHeadRef, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-CYjc343k-ClHHEkJF.mjs";
10
+ import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-DGu96Hkk.mjs";
11
+ import { $ as runCommandAction, A as errorRefSetEmptySentinel, B as errorStatementOriginUnknown, C as errorMigrationPlanningFailed, D as errorPlanOriginUnknown, E as errorPlanForgotTheFlag, F as errorSnapshotMissing, G as getTargetMigrations, H as errorTargetMigrationNotSupported, I as errorSpaceNotFound, J as readContractEnvelope, K as mapRefResolutionError, L as errorStatementAnswersNoQuestion, N as errorRuntime, O as errorPlanProducedNoOperations, Q as resolveMigrationPaths, R as errorStatementDidNotResolveLoss, T as errorPathUnreachable, V as errorStatementUnresolved, W as errorUnexpected, X as requireLiveDatabase, Z as resolveContractPath, a as closeQuietly, b as errorMarkerMismatch, c as errorAmbiguousMigrationRef, d as errorContractConfigMissing, f as errorContractValidationFailed, g as errorFromCaught, h as errorFileNotFound, i as chooseAction, j as errorRefSetHashNotInGraph, k as errorRefSetBundleNotFound, l as errorConfigValidation$1, n as CliStructuredError$1, o as collectDeclaredInvariants, r as STORE_ORIGIN_SNAPSHOT_STEPS, tt as toStructuralEdge, v as errorInvalidSpaceId, z as errorStatementInvalid } from "./caught-errors-HFQjjQVE-b_GDV-6J.mjs";
12
12
  import { r as getEmittedArtifactPaths, t as emit } from "./exports-DaDckULH-JNQeM6Nn.mjs";
13
13
  import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-C_ZO26nT-B7C4CJsh.mjs";
14
- import { d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, t as HEAD_REF_NAME, u as validateRefValue } from "./refs-qwvw4_dV-X8sR92eT.mjs";
15
- import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-C7IHVcsV.mjs";
14
+ import { d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, t as HEAD_REF_NAME, u as validateRefValue } from "./refs-qwvw4_dV-DNg_7WTD.mjs";
15
+ import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-DlfOyErc.mjs";
16
16
  import { c as internalImportRoot, o as importRootForDependencies, r as createImportSpecifierResolver, t as ImportRootError } from "./import-roots-BeAYfehL.mjs";
17
- import { c as parseContractRef, l as parseMigrationRef, o as isLiveMarkerRef, r as RESERVED_CONTRACT_REFS, s as isReservedContractRef, t as EMPTY_CONTRACT_REF } from "./ref-resolution-d7rcmU6F.mjs";
18
- import { i as writeMigrationTs } from "./migration-ts-BQuIba9e.mjs";
17
+ import { c as parseContractRef, l as parseMigrationRef, o as isLiveMarkerRef, r as RESERVED_CONTRACT_REFS, s as isReservedContractRef, t as EMPTY_CONTRACT_REF } from "./ref-resolution-Be_zewf7.mjs";
18
+ import { i as writeMigrationTs } from "./migration-ts-FyF55c4M.mjs";
19
19
  import { createRequire } from "node:module";
20
20
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
21
21
  import { CliStructuredError } from "@prisma/orm-framework/errors/control";
22
- import { APP_SPACE_ID, createControlStack, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView } from "@prisma/orm-framework/components/control";
22
+ import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, planOriginOf } from "@prisma/orm-framework/components/control";
23
23
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
24
24
  import { isStructuredErrorCode, structuredError } from "@prisma/orm-framework/utils/structured-error";
25
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
26
25
  import { basename, dirname, isAbsolute, join, relative, resolve } from "pathe";
27
- import { createHash } from "node:crypto";
28
- import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
26
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
29
27
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
30
28
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
31
29
  import { keepInternalSpecifiers } from "@prisma/orm-framework/components/emission";
30
+ import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
32
31
  import { notOk, ok } from "@prisma/orm-framework/utils/result";
33
32
  import { mergeCapabilityMatrices } from "@prisma/orm-framework/components/components";
33
+ import { asNamespaceId } from "@prisma/orm-framework/contract/types";
34
34
  import { abortable } from "@prisma/orm-framework/utils/abortable";
35
35
  import { resolve as resolve$1 } from "node:path";
36
- //#region ../../../1-framework/3-tooling/cli/dist/ref-BCEAH4F9.mjs
36
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-Cc_CTagE.mjs
37
37
  /**
38
38
  * Asserts that all framework components are compatible with the expected family and target.
39
39
  *
@@ -166,6 +166,760 @@ function enrichContract(ir, components) {
166
166
  extensions: sortDeepTyped(extensions)
167
167
  };
168
168
  }
169
+ function formsFix(verb) {
170
+ return verb === "delete" ? "Write the statement as --delete <name>, where the name is Model, namespace.Model, Model.field or namespace.Model.field, or the storage name the refusal gave, for example --delete Legacy or --delete User.nickname." : "Write the statement as --allow <name>, where the name is the model the refusal gave, for example --allow User.";
171
+ }
172
+ /**
173
+ * Checks the text of one delete or allow statement. The text stays unresolved: it names what a
174
+ * plan would do to a subject, so it is matched by equality against the plan's subjects, not
175
+ * resolved against the contracts. Any name a subject can have is accepted, since a storage name
176
+ * may contain any character a quoted identifier can.
177
+ */
178
+ function parseConsentStatement(statement) {
179
+ if (statement.text.trim() === "") return notOk(errorStatementInvalid(statement, "The statement names nothing.", formsFix(statement.verb)));
180
+ return ok({
181
+ verb: statement.verb,
182
+ text: statement.text
183
+ });
184
+ }
185
+ const MAX_SEGMENTS = 3;
186
+ /** The forms a statement takes, with an example of each. */
187
+ function statementFormsFix(verb) {
188
+ return `Write the statement as --${verb} <old>:<new>, where each side is Model, namespace.Model, Model.field or namespace.Model.field, for example --${verb} Profile:User for a model or --${verb} User.name:User.fullName for a field.`;
189
+ }
190
+ /**
191
+ * The two statements a user who named a model on one side and a field on the other may have
192
+ * meant, written with their names.
193
+ */
194
+ function mixedSidesFix(verb, from, to) {
195
+ const modelIsOld = from.length < to.length;
196
+ const field = modelIsOld ? to : from;
197
+ const model = (modelIsOld ? from : to).join(".");
198
+ const fieldModel = field.slice(0, -1).join(".");
199
+ const fieldName = field[field.length - 1];
200
+ const [modelStatement, fieldStatement] = modelIsOld ? [`${model}:${fieldModel}`, `${fieldModel}.<old field>:${field.join(".")}`] : [`${fieldModel}:${model}`, `${model}.${fieldName}:${model}.<new field>`];
201
+ return `To rename the model, write --${verb} ${modelStatement}. To rename a field, write --${verb} ${fieldStatement}, naming the field's model as the new contract names it.`;
202
+ }
203
+ function invalid(statement, why) {
204
+ return errorStatementInvalid(statement, why, statementFormsFix(statement.verb));
205
+ }
206
+ function parseSide(statement, side) {
207
+ const segments = side.split(".");
208
+ if (segments.some((segment) => segment === "")) return notOk(invalid(statement, `"${side}" has an empty name.`));
209
+ const [first, second, third] = segments;
210
+ if (first === void 0 || segments.length > MAX_SEGMENTS) return notOk(invalid(statement, `"${side}" has ${segments.length} names; at most three are allowed.`));
211
+ if (second === void 0) return ok([first]);
212
+ if (third === void 0) return ok([first, second]);
213
+ return ok([
214
+ first,
215
+ second,
216
+ third
217
+ ]);
218
+ }
219
+ function namesModelAndField(from, to) {
220
+ const lengths = [from.length, to.length];
221
+ return lengths.includes(1) && lengths.includes(MAX_SEGMENTS);
222
+ }
223
+ /** Parses the text of one rename statement, `<old>:<new>`. */
224
+ function parseRenameStatement(statement) {
225
+ const sides = statement.text.split(":");
226
+ const [oldSide, newSide] = sides;
227
+ if (oldSide === void 0 || newSide === void 0) return notOk(invalid(statement, "The statement has no \":\" between the old and new name."));
228
+ if (sides.length > 2) return notOk(invalid(statement, "The statement has more than one \":\"."));
229
+ const from = parseSide(statement, oldSide);
230
+ if (!from.ok) return from;
231
+ const to = parseSide(statement, newSide);
232
+ if (!to.ok) return to;
233
+ if (namesModelAndField(from.value, to.value)) return notOk(errorStatementInvalid(statement, "The statement names a model on one side and a field on the other.", mixedSidesFix(statement.verb, from.value, to.value)));
234
+ return ok({
235
+ verb: "rename",
236
+ text: statement.text,
237
+ from: from.value,
238
+ to: to.value
239
+ });
240
+ }
241
+ const MODEL_RENAMES = "model";
242
+ const FIELD_RENAMES = "field";
243
+ const LISTED_LIMIT = 20;
244
+ const CHECK_NAMES_FIX = "The old name must exist in the origin contract and not in the destination contract, and the new name the other way round. Names match exactly, including case.";
245
+ const STORED_NAME_ONLY = "If only the stored name changed (@map or @@map), a statement cannot state that in this release, and a plan without it drops and creates what the model or field is stored in, with its data. With migration plan, edit the planned migration.ts to rename the stored name instead of dropping and creating it. With db update, rename it in the database yourself first, then run db update, which then finds nothing that loses data.";
246
+ const VALUE_OBJECT_FIX = "Leave value objects and their fields out of the statements.";
247
+ const REPEATED_NAME_FIX = "Give each model or field at most one statement, and each new name to one model or field only.";
248
+ function qualifiedModel(coordinate) {
249
+ return modelDisplayName(coordinate);
250
+ }
251
+ function displayName(namespaceId, name) {
252
+ return modelDisplayName({
253
+ namespaceId: asNamespaceId(namespaceId),
254
+ model: name
255
+ });
256
+ }
257
+ function qualifiedField(coordinate) {
258
+ return `${qualifiedModel(coordinate)}.${coordinate.field}`;
259
+ }
260
+ function listed(names) {
261
+ if (names.length === 0) return "(none)";
262
+ const sorted = [...names].sort();
263
+ const shown = sorted.slice(0, LISTED_LIMIT).join(", ");
264
+ return sorted.length > LISTED_LIMIT ? `${shown} and ${sorted.length - LISTED_LIMIT} more` : shown;
265
+ }
266
+ function sentence(reason) {
267
+ return `${reason.charAt(0).toUpperCase()}${reason.slice(1)}.`;
268
+ }
269
+ function unresolved(statement, refusal) {
270
+ return errorStatementUnresolved(statement, sentence(refusal.reason), refusal.fix);
271
+ }
272
+ function modelIn(namespace, name) {
273
+ return Object.hasOwn(namespace.models, name) ? namespace.models[name] : void 0;
274
+ }
275
+ function hasValueObject(namespace, name) {
276
+ return namespace.valueObjects !== void 0 && Object.hasOwn(namespace.valueObjects, name);
277
+ }
278
+ function modelAt(contract, coordinate) {
279
+ const namespaces = contract.domain.namespaces;
280
+ const namespace = Object.hasOwn(namespaces, coordinate.namespaceId) ? namespaces[coordinate.namespaceId] : void 0;
281
+ return namespace === void 0 ? void 0 : modelIn(namespace, coordinate.model);
282
+ }
283
+ function fieldNames(model) {
284
+ return [...Object.keys(model.fields), ...Object.keys(model.relations)];
285
+ }
286
+ function hasField(model, field) {
287
+ return Object.hasOwn(model.fields, field) || Object.hasOwn(model.relations, field);
288
+ }
289
+ function missing(reason) {
290
+ return {
291
+ reason,
292
+ fix: CHECK_NAMES_FIX
293
+ };
294
+ }
295
+ function valueObjectRefusal(name) {
296
+ return {
297
+ reason: `"${name}" is a value object, and value object renames are not supported in this release`,
298
+ fix: VALUE_OBJECT_FIX
299
+ };
300
+ }
301
+ function lookupModelInNamespace(contract, namespaceId, namespace, name) {
302
+ const model = modelIn(namespace, name);
303
+ if (model !== void 0) return {
304
+ kind: "found",
305
+ coordinate: {
306
+ namespaceId: asNamespaceId(namespaceId),
307
+ model: name
308
+ },
309
+ model
310
+ };
311
+ if (hasValueObject(namespace, name)) return {
312
+ kind: "refused",
313
+ ...valueObjectRefusal(displayName(namespaceId, name))
314
+ };
315
+ return {
316
+ kind: "missing",
317
+ ...missing(`the ${contract.name} contract has no model "${name}" in namespace "${namespaceId}" (models there: ${listed(Object.keys(namespace.models))})`)
318
+ };
319
+ }
320
+ function lookupModel(contract, namespaceId, name) {
321
+ const namespaces = contract.contract.domain.namespaces;
322
+ if (namespaceId !== void 0) {
323
+ const namespace = Object.hasOwn(namespaces, namespaceId) ? namespaces[namespaceId] : void 0;
324
+ if (namespace === void 0) {
325
+ const named = Object.keys(namespaces).filter((id) => id !== UNBOUND_NAMESPACE_ID);
326
+ return {
327
+ kind: "missing",
328
+ ...missing(named.length === 0 ? `the ${contract.name} contract has no namespaces` : `the ${contract.name} contract has no namespace "${namespaceId}" (namespaces: ${listed(named)})`)
329
+ };
330
+ }
331
+ return lookupModelInNamespace(contract, namespaceId, namespace, name);
332
+ }
333
+ const declaring = Object.entries(namespaces).filter(([, namespace]) => modelIn(namespace, name) !== void 0);
334
+ const [only] = declaring;
335
+ if (only !== void 0 && declaring.length === 1) return lookupModelInNamespace(contract, only[0], only[1], name);
336
+ if (declaring.length > 1) {
337
+ const candidates = declaring.map(([id]) => `${id}.${name}`).sort();
338
+ return {
339
+ kind: "refused",
340
+ reason: `"${name}" is a model in more than one namespace of the ${contract.name} contract (${listed(candidates)})`,
341
+ fix: `Name the model with its namespace, for example ${candidates[0]}.`
342
+ };
343
+ }
344
+ if (Object.values(namespaces).some((namespace) => hasValueObject(namespace, name))) return {
345
+ kind: "refused",
346
+ ...valueObjectRefusal(name)
347
+ };
348
+ const models = Object.entries(namespaces).flatMap(([id, namespace]) => Object.keys(namespace.models).map((model) => displayName(id, model)));
349
+ return {
350
+ kind: "missing",
351
+ ...missing(`the ${contract.name} contract has no model "${name}" (models: ${listed(models)})`)
352
+ };
353
+ }
354
+ function readModel(state, side, namespaceId, name) {
355
+ const lookup = lookupModel(side === "old" ? state.origin : state.destination, namespaceId, name);
356
+ if (lookup.kind !== "found") return notOk(lookup);
357
+ return ok({
358
+ entity: "model",
359
+ coordinate: lookup.coordinate,
360
+ model: lookup.model
361
+ });
362
+ }
363
+ function readFieldOf(contract, found, field, destinationModel) {
364
+ if (!hasField(found.model, field)) return notOk(missing(`the ${contract.name} model "${qualifiedModel(found.coordinate)}" has no field "${field}" (fields: ${listed(fieldNames(found.model))})`));
365
+ return ok({
366
+ entity: "field",
367
+ coordinate: {
368
+ ...found.coordinate,
369
+ field
370
+ },
371
+ model: found.model,
372
+ destinationModel
373
+ });
374
+ }
375
+ function originCounterpart(state, destinationModel) {
376
+ const coordinate = state.originOfRenamedModel.get(qualifiedModel(destinationModel)) ?? destinationModel;
377
+ const model = modelAt(state.origin.contract, coordinate);
378
+ return model === void 0 ? void 0 : {
379
+ coordinate,
380
+ model
381
+ };
382
+ }
383
+ /**
384
+ * The old side of a field rename names the model as the destination spells
385
+ * it, and the field as the origin counterpart of that model has it. When the
386
+ * model is not in the destination but the origin has it with that field, the
387
+ * reading still resolves so the caller can say the field would move between
388
+ * models.
389
+ */
390
+ function readOldField(state, namespaceId, modelName, field) {
391
+ const destination = lookupModel(state.destination, namespaceId, modelName);
392
+ if (destination.kind === "found") {
393
+ const counterpart = originCounterpart(state, destination.coordinate);
394
+ if (counterpart === void 0) {
395
+ const name = qualifiedModel(destination.coordinate);
396
+ return notOk({
397
+ reason: `the destination model "${name}" has no counterpart in the origin contract: the origin has no model "${name}" and no earlier statement renames a model to it`,
398
+ fix: `Rename the origin model to "${name}" with its own --rename statement before this one, or check the names.`,
399
+ modelWithoutCounterpart: name
400
+ });
401
+ }
402
+ return readFieldOf(state.origin, counterpart, field, destination.coordinate);
403
+ }
404
+ if (destination.kind === "refused") return notOk(destination);
405
+ const origin = lookupModel(state.origin, namespaceId, modelName);
406
+ if (origin.kind === "found" && hasField(origin.model, field)) return readFieldOf(state.origin, origin, field, void 0);
407
+ return notOk(destination);
408
+ }
409
+ function readNewField(state, namespaceId, modelName, field) {
410
+ const destination = lookupModel(state.destination, namespaceId, modelName);
411
+ if (destination.kind !== "found") return notOk(destination);
412
+ return readFieldOf(state.destination, destination, field, destination.coordinate);
413
+ }
414
+ function readField(state, side, namespaceId, modelName, field) {
415
+ return side === "old" ? readOldField(state, namespaceId, modelName, field) : readNewField(state, namespaceId, modelName, field);
416
+ }
417
+ function readSide(state, side, segments) {
418
+ if (segments.length === 1) return readModel(state, side, void 0, segments[0]);
419
+ if (segments.length === 3) return readField(state, side, ...segments);
420
+ const [first, second] = segments;
421
+ const asModel = readModel(state, side, first, second);
422
+ const asField = readField(state, side, void 0, first, second);
423
+ if (asModel.ok && asField.ok) return notOk({
424
+ reason: `"${first}.${second}" resolves both as namespace "${first}" model "${second}" and as model "${first}" field "${second}"`,
425
+ fix: "Write the field as namespace.Model.field if you mean the field."
426
+ });
427
+ if (asModel.ok) return asModel;
428
+ if (asField.ok) return asField;
429
+ const contract = side === "old" ? state.origin : state.destination;
430
+ if (!Object.keys(contract.contract.domain.namespaces).some((id) => id !== UNBOUND_NAMESPACE_ID)) return asField;
431
+ return notOk({
432
+ ...missing(`"${first}.${second}" resolves neither as namespace.Model (${asModel.failure.reason}) nor as Model.field (${asField.failure.reason})`),
433
+ ...ifDefined("modelWithoutCounterpart", asField.failure.modelWithoutCounterpart)
434
+ });
435
+ }
436
+ function resolveModelRename(state, statement, from, to) {
437
+ const fromKey = `${MODEL_RENAMES}:${qualifiedModel(from)}`;
438
+ const toKey = `${MODEL_RENAMES}:${qualifiedModel(to)}`;
439
+ if (state.renamedFrom.has(fromKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames "${qualifiedModel(from)}".`, REPEATED_NAME_FIX));
440
+ if (state.renamedTo.has(toKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames a model to "${qualifiedModel(to)}".`, REPEATED_NAME_FIX));
441
+ if (qualifiedModel(from) === qualifiedModel(to)) return notOk(errorStatementInvalid(statement, `The statement renames model "${qualifiedModel(from)}" to itself.`, `Leave out --${statement.verb} ${statement.text}. ${STORED_NAME_ONLY}`));
442
+ if (modelAt(state.origin.contract, to) !== void 0 && modelAt(state.destination.contract, from) !== void 0) return notOk(swapRefusal(statement, "model", qualifiedModel(from), qualifiedModel(to)));
443
+ if (modelAt(state.origin.contract, to) !== void 0) return notOk(errorStatementUnresolved(statement, `"${qualifiedModel(to)}" already exists in the origin contract, so it cannot be the new name of a model.`, CHECK_NAMES_FIX));
444
+ if (modelAt(state.destination.contract, from) !== void 0) return notOk(errorStatementUnresolved(statement, `"${qualifiedModel(from)}" still exists in the destination contract, so it was not renamed.`, CHECK_NAMES_FIX));
445
+ state.renamedFrom.add(fromKey);
446
+ state.renamedTo.add(toKey);
447
+ state.originOfRenamedModel.set(qualifiedModel(to), from);
448
+ return ok({
449
+ kind: "rename",
450
+ entity: "model",
451
+ from,
452
+ to
453
+ });
454
+ }
455
+ function modelPart(side) {
456
+ return side.slice(0, -1).join(".");
457
+ }
458
+ /**
459
+ * The old side names a model the destination contract does not have. The
460
+ * user most likely named the field's model by its old name, so the error
461
+ * writes the statement with the model named as the destination names it.
462
+ */
463
+ function oldModelNotInDestination(state, statement, from, toModel) {
464
+ const oldModel = modelPart(statement.from);
465
+ const newModel = modelPart(statement.to);
466
+ const corrected = `${newModel}.${from.coordinate.field}:${statement.to.join(".")}`;
467
+ const renamedEarlier = state.originOfRenamedModel.get(toModel);
468
+ const modelRenamed = renamedEarlier !== void 0 && qualifiedModel(renamedEarlier) === qualifiedModel(from.coordinate);
469
+ const modelStatement = `${oldModel}:${newModel}`;
470
+ return errorStatementInvalid(statement, [
471
+ `"${qualifiedModel(from.coordinate)}" is not a model of the destination contract, and a field cannot move between models.`,
472
+ `Name a field's model as the destination contract names it: --${statement.verb} ${corrected}.`,
473
+ ...modelRenamed ? [] : [`The model also needs its own statement, --rename ${modelStatement}, before it.`]
474
+ ].join(" "), modelRenamed ? `Write the statement as --${statement.verb} ${corrected}.` : `Write the statements as --rename ${modelStatement} --${statement.verb} ${corrected}.`);
475
+ }
476
+ function fieldMovesBetweenModels(statement, fromModel, toModel) {
477
+ return errorStatementInvalid(statement, `The old name is a field of "${fromModel}" and the new name a field of "${toModel}"; a field cannot move between models.`, "Rename a field within one model, and name that model as the destination contract names it.");
478
+ }
479
+ /**
480
+ * True when the old side most likely names the new side's model by its old
481
+ * name: no earlier statement renamed the old model to some other model or
482
+ * some other model to the new model, and the origin does not have the new
483
+ * model.
484
+ */
485
+ function oldSideNamesNewModel(state, from, to) {
486
+ const oldModel = qualifiedModel(from.coordinate);
487
+ const renamedTo = [...state.originOfRenamedModel.entries()].find(([, origin]) => qualifiedModel(origin) === oldModel)?.[0];
488
+ if (renamedTo !== void 0) return renamedTo === qualifiedModel(to.coordinate);
489
+ if (state.originOfRenamedModel.has(qualifiedModel(to.coordinate))) return false;
490
+ return modelAt(state.origin.contract, to.coordinate) === void 0;
491
+ }
492
+ function resolveFieldRename(state, statement, from, to) {
493
+ const toModel = qualifiedModel(to.coordinate);
494
+ if (from.destinationModel === void 0) return notOk(oldSideNamesNewModel(state, from, to) ? oldModelNotInDestination(state, statement, from, toModel) : fieldMovesBetweenModels(statement, qualifiedModel(from.coordinate), toModel));
495
+ if (qualifiedModel(from.destinationModel) !== toModel) return notOk(fieldMovesBetweenModels(statement, qualifiedModel(from.destinationModel), toModel));
496
+ const fromKey = `${FIELD_RENAMES}:${qualifiedField(from.coordinate)}`;
497
+ const toKey = `${FIELD_RENAMES}:${qualifiedField(to.coordinate)}`;
498
+ if (state.renamedFrom.has(fromKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames "${qualifiedField(from.coordinate)}".`, REPEATED_NAME_FIX));
499
+ if (state.renamedTo.has(toKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames a field to "${qualifiedField(to.coordinate)}".`, REPEATED_NAME_FIX));
500
+ if (from.coordinate.field === to.coordinate.field) return notOk(errorStatementInvalid(statement, `The statement renames field "${toModel}.${to.coordinate.field}" to itself.`, `Leave out --${statement.verb} ${statement.text}. ${STORED_NAME_ONLY}`));
501
+ if (hasField(from.model, to.coordinate.field) && hasField(to.model, from.coordinate.field)) return notOk(swapRefusal(statement, "field", `${toModel}.${from.coordinate.field}`, `${toModel}.${to.coordinate.field}`));
502
+ if (hasField(from.model, to.coordinate.field)) return notOk(errorStatementUnresolved(statement, `The field "${to.coordinate.field}" already exists on the origin model "${qualifiedModel(from.coordinate)}", so it cannot be the new name of a field.`, CHECK_NAMES_FIX));
503
+ if (hasField(to.model, from.coordinate.field)) return notOk(errorStatementUnresolved(statement, `The field "${from.coordinate.field}" still exists on the destination model "${toModel}", so it was not renamed.`, CHECK_NAMES_FIX));
504
+ state.renamedFrom.add(fromKey);
505
+ state.renamedTo.add(toKey);
506
+ return ok({
507
+ kind: "rename",
508
+ entity: "field",
509
+ from: from.coordinate,
510
+ to: to.coordinate
511
+ });
512
+ }
513
+ /**
514
+ * Two names that trade places: each is an old name and a new name, which one plan cannot do.
515
+ * Statements resolve against contracts, so the swap takes three plans through a temporary name.
516
+ */
517
+ function swapRefusal(statement, entity, first, second) {
518
+ const verb = statement.verb;
519
+ const oldName = statement.from.join(".");
520
+ const newName = statement.to.join(".");
521
+ const temporary = entity === "field" ? `${statement.to.slice(0, -1).join(".")}.<temporary name>` : "<temporary name>";
522
+ return errorStatementInvalid(statement, `"${first}" and "${second}" swap names: each is both an old name and a new name, and statements cannot swap names in one plan.`, `Make the swap in three plans. First change the contract so that "${first}" has a temporary name, and plan it with --${verb} ${oldName}:${temporary}. Then give "${second}" the name "${first}", and plan it with --${verb} ${newName}:${oldName}. Then give the temporary name the name "${second}", and plan it with --${verb} ${temporary}:${newName}.`);
523
+ }
524
+ /**
525
+ * The old side does not resolve. Says so in terms of what the user can do next when the statement
526
+ * is the wrong way round, when the rename has already happened, or when a later statement renames
527
+ * the field's model.
528
+ */
529
+ function oldSideRefusal(state, statement, later, refusal) {
530
+ const oldText = statement.from.join(".");
531
+ const newText = statement.to.join(".");
532
+ const newIsInOrigin = readSide(state, "old", statement.to).ok;
533
+ const newIsInDestination = readSide(state, "new", statement.to).ok;
534
+ const oldIsInDestination = readSide(state, "new", statement.from).ok;
535
+ if (newIsInOrigin && oldIsInDestination && !newIsInDestination) return errorStatementUnresolved(statement, `The statement is the wrong way round: "${newText}" is the old name, in the origin contract, and "${oldText}" the new name, in the destination contract.`, `Write the old name first: --${statement.verb} ${newText}:${oldText}.`);
536
+ if (newIsInOrigin && newIsInDestination && !oldIsInDestination) return errorStatementUnresolved(statement, `The origin contract already has "${newText}" and has no "${oldText}", so this rename has already happened. For db update, the database is already at the new name.`, `Leave out --${statement.verb} ${statement.text}.`);
537
+ const model = refusal.modelWithoutCounterpart;
538
+ const renamesModel = model === void 0 ? void 0 : later.find((candidate) => candidate.to.length < 3 && readSide(state, "new", candidate.to).ok && [model, model.split(".").pop()].includes(candidate.to.join(".")));
539
+ if (renamesModel !== void 0) return errorStatementUnresolved(statement, `${sentence(refusal.reason)} A later statement, --${renamesModel.verb} ${renamesModel.text}, renames it, and statements apply in the order given.`, `Put --${renamesModel.verb} ${renamesModel.text} before --${statement.verb} ${statement.text}.`);
540
+ return unresolved(statement, refusal);
541
+ }
542
+ function resolveStatement(state, statement, later) {
543
+ const from = readSide(state, "old", statement.from);
544
+ if (!from.ok) return notOk(oldSideRefusal(state, statement, later, from.failure));
545
+ const to = readSide(state, "new", statement.to);
546
+ if (!to.ok) return notOk(unresolved(statement, to.failure));
547
+ if (from.value.entity === "model" && to.value.entity === "model") return resolveModelRename(state, statement, from.value.coordinate, to.value.coordinate);
548
+ if (from.value.entity === "field" && to.value.entity === "field") return resolveFieldRename(state, statement, from.value, to.value);
549
+ return notOk(errorStatementInvalid(statement, "The statement names a model on one side and a field on the other.", mixedSidesFix(statement.verb, statement.from, statement.to)));
550
+ }
551
+ /**
552
+ * Resolves the rename statements a user gave, in order, against the origin and
553
+ * destination contracts. Each resolved statement names its old and new entity
554
+ * by namespace, model and field. A delete or allow statement is checked and
555
+ * left out: it names what a plan would do to a subject, so it is matched against
556
+ * the plan, and it needs no origin contract.
557
+ */
558
+ function resolveStatements(input) {
559
+ const parsed = [];
560
+ for (const entry of input.statements) {
561
+ if (entry.verb === "delete" || entry.verb === "allow") {
562
+ const statement = parseConsentStatement({
563
+ ...entry,
564
+ verb: entry.verb
565
+ });
566
+ if (!statement.ok) return statement;
567
+ continue;
568
+ }
569
+ if (input.origin.kind === "missing") return notOk(errorStatementOriginUnknown(input.origin));
570
+ const statement = parseRenameStatement({
571
+ ...entry,
572
+ verb: entry.verb
573
+ });
574
+ if (!statement.ok) return statement;
575
+ parsed.push(statement.value);
576
+ }
577
+ if (parsed.length === 0 || input.origin.kind === "missing") return ok([]);
578
+ const state = {
579
+ origin: {
580
+ name: "origin",
581
+ contract: input.origin.contract
582
+ },
583
+ destination: {
584
+ name: "destination",
585
+ contract: input.destination
586
+ },
587
+ originOfRenamedModel: /* @__PURE__ */ new Map(),
588
+ renamedFrom: /* @__PURE__ */ new Set(),
589
+ renamedTo: /* @__PURE__ */ new Set()
590
+ };
591
+ const resolved = [];
592
+ for (const [index, statement] of parsed.entries()) {
593
+ const result = resolveStatement(state, statement, parsed.slice(index + 1));
594
+ if (!result.ok) return result;
595
+ resolved.push(result.value);
596
+ }
597
+ return ok(resolved);
598
+ }
599
+ function modelText(contract, coordinate) {
600
+ return Object.keys(contract.domain.namespaces).length > 1 ? modelDisplayName(coordinate) : coordinate.model;
601
+ }
602
+ /** The model a rename statement of `contracts` gives `coordinate` in the destination, if any. */
603
+ function renamedModel(coordinate, contracts) {
604
+ if (contracts.destination === void 0 || contracts.renames.length === 0) return void 0;
605
+ const resolved = resolveStatements({
606
+ statements: contracts.renames,
607
+ origin: {
608
+ kind: "contract",
609
+ contract: contracts.origin
610
+ },
611
+ destination: contracts.destination
612
+ });
613
+ if (!resolved.ok) return void 0;
614
+ return resolved.value.find((statement) => statement.entity === "model" && statement.from.namespaceId === coordinate.namespaceId && statement.from.model === coordinate.model)?.to;
615
+ }
616
+ /**
617
+ * The subject as a statement names it: `Model` or `Model.field`, with the namespace when its
618
+ * contract has several, or the storage name when no model stores what the operation is about. A
619
+ * field of a model the plan renames is named through the model's new name, as a rename of the
620
+ * field is written.
621
+ */
622
+ function subjectText(subject, contracts) {
623
+ switch (subject.kind) {
624
+ case "model": return modelText(contracts.origin, subject);
625
+ case "field": {
626
+ const renamed = renamedModel(subject, contracts);
627
+ return `${renamed === void 0 || contracts.destination === void 0 ? modelText(contracts.origin, subject) : modelText(contracts.destination, renamed)}.${subject.field}`;
628
+ }
629
+ case "storage": return subject.name;
630
+ }
631
+ }
632
+ /** The statement's description, written as its question names the subject: `delete field "User.nickname"`. */
633
+ function consentDescription(verb, subject, text) {
634
+ return `${verb} ${subject.kind} "${text}"`;
635
+ }
636
+ function lossText(subject, text, originKnown) {
637
+ switch (subject.kind) {
638
+ case "model": return `would lose the data of model "${text}"`;
639
+ case "field": return `would lose the values of field "${text}"`;
640
+ case "storage": return originKnown ? `would lose the data in "${text}", which no model of the origin contract stores` : `would lose the data in "${text}", named by its storage name because the origin contract is unknown; --delete loses its rows`;
641
+ }
642
+ }
643
+ /**
644
+ * How to keep the rows of a storage subject that was renamed, when the origin contract is unknown:
645
+ * store the snapshot of the contract the database is at, as `MIGRATION.STATEMENT_ORIGIN_UNKNOWN`
646
+ * advises, then answer with a rename. The refusal gives it once, on its first storage question. The
647
+ * engine does not put the CLI's name in a question's text, so the steps name `prisma`.
648
+ */
649
+ const ORIGIN_SNAPSHOT_RECOVERY = ["If it was renamed, keep its data instead: store the snapshot of the contract the database is at, then run this command again and answer with --rename.", ...STORE_ORIGIN_SNAPSHOT_STEPS.map((step) => step.replaceAll("{bin}", "prisma"))].join(" ");
650
+ function sameCoordinate(statement, subject) {
651
+ if (subject.kind === "storage") return false;
652
+ const { from } = statement;
653
+ if (from.namespaceId !== subject.namespaceId || from.model !== subject.model) return false;
654
+ return subject.kind === "field" ? statement.entity === "field" && statement.from.field === subject.field : statement.entity === "model";
655
+ }
656
+ function namesSubject(verb, subject) {
657
+ return (text) => text === subject ? void 0 : `${verb} names "${subject}": --${verb} ${subject}.`;
658
+ }
659
+ /**
660
+ * How the target says to keep a subject's data by hand when its planner carries out no rename, or
661
+ * `undefined` when it carries them out.
662
+ */
663
+ function keepDataByHandFor(migrations, origin) {
664
+ const refused = migrations.renameStatements;
665
+ return refused === void 0 ? void 0 : (subject) => refused.keepDataByHand(subject, origin);
666
+ }
667
+ /** A rename as a statement is written: a field's new name keeps the model, `User.nickname:User.<new name>`. */
668
+ function renameForm(subject, text) {
669
+ return subject.kind === "field" ? `${text}:${text.slice(0, text.lastIndexOf("."))}.<new name>` : `${text}:<new name>`;
670
+ }
671
+ /** Whether a rename statement of the plan already gives the subject a new name. */
672
+ function renamedByPlan(subject, contracts) {
673
+ if (subject.kind === "storage" || contracts.renames.length === 0) return false;
674
+ const resolved = resolveStatements({
675
+ statements: contracts.renames,
676
+ origin: {
677
+ kind: "contract",
678
+ contract: contracts.origin
679
+ },
680
+ destination: contracts.destination
681
+ });
682
+ return resolved.ok && resolved.value.some((statement) => sameCoordinate(statement, subject));
683
+ }
684
+ /** Whether the destination still has the subject's model or field, under the name a rename gives it. */
685
+ function inDestination(subject, contracts) {
686
+ if (subject.kind === "storage") return false;
687
+ const model = renamedModel(subject, contracts) ?? subject;
688
+ const destinationModel = contracts.destination.domain.namespaces[model.namespaceId]?.models[model.model];
689
+ if (destinationModel === void 0) return false;
690
+ return subject.kind === "model" || Object.hasOwn(destinationModel.fields, subject.field);
691
+ }
692
+ /**
693
+ * The question for one operation that would lose data. A model or field the destination no longer
694
+ * has, and no rename of the plan renamed, may be renamed instead of deleted; a rename is resolved
695
+ * against the two contracts after the plan's other renames, and its old name must be the subject.
696
+ * A subject the destination keeps, such as a field whose type changes, and data no model stores,
697
+ * can only be deleted. Where the target's planner carries out no rename, `keepDataByHand` says how
698
+ * to keep the data instead.
699
+ */
700
+ function dataLossQuestion(loss, contracts) {
701
+ const subject = subjectText(loss.subject, contracts);
702
+ const renamable = contracts.keepDataByHand === void 0 && loss.subject.kind !== "storage" && !inDestination(loss.subject, contracts) && !renamedByPlan(loss.subject, contracts);
703
+ const deleteNames = namesSubject("delete", subject);
704
+ return {
705
+ question: [`${loss.label} ${lossText(loss.subject, subject, contracts.originKnown)}.`, ...contracts.keepDataByHand === void 0 ? [] : [contracts.keepDataByHand(loss.subject)]].join(" "),
706
+ subject,
707
+ verbs: renamable ? ["rename", "delete"] : ["delete"],
708
+ forms: renamable ? { rename: renameForm(loss.subject, subject) } : {},
709
+ validate: (verb, text) => {
710
+ if (verb !== "rename") return deleteNames(text);
711
+ const resolved = resolveStatements({
712
+ statements: [...contracts.renames, {
713
+ verb: "rename",
714
+ text
715
+ }],
716
+ origin: {
717
+ kind: "contract",
718
+ contract: contracts.origin
719
+ },
720
+ destination: contracts.destination
721
+ });
722
+ if (!resolved.ok) return `${resolved.failure.message}. ${resolved.failure.why ?? ""}`.trim();
723
+ const statement = resolved.value.at(-1);
724
+ return statement !== void 0 && sameCoordinate(statement, loss.subject) ? void 0 : `The rename's old name is not "${subject}". Write it as ${renameForm(loss.subject, subject)}.`;
725
+ }
726
+ };
727
+ }
728
+ /**
729
+ * The question for one operation that changes who can read or write its subject's rows: it widens
730
+ * access, as disabling row-level security does, or changes it either way, as dropping a policy
731
+ * does. Each such operation is its own question, answered by its own `allow`.
732
+ */
733
+ function accessWideningQuestion(widening, contracts) {
734
+ const subject = subjectText(widening.subject, contracts);
735
+ return {
736
+ question: `${widening.label} would ${widening.widens ? "widen" : "change"} who can read and write its rows.`,
737
+ subject,
738
+ verbs: ["allow"],
739
+ forms: {},
740
+ validate: (_verb, text) => namesSubject("allow", subject)(text)
741
+ };
742
+ }
743
+ const keyOf = (planned) => migrationSubjectKey(planned.subject);
744
+ /**
745
+ * The pre-answers that answer a question about `text`: every `delete` of the subject, or the
746
+ * first `allow` of it no earlier question took, since an `allow` answers one operation.
747
+ */
748
+ function givenFor(verb, text, preAnswers, taken) {
749
+ const matching = preAnswers.filter((statement) => statement.verb === verb && statement.text === text);
750
+ if (verb === "delete") return matching;
751
+ const first = matching.find((statement) => !taken.has(statement));
752
+ return first === void 0 ? [] : [first];
753
+ }
754
+ /**
755
+ * A `delete` answers for its subject; an `allow` for its one operation, known by its label and
756
+ * subject, since a re-plan moves every operation's position.
757
+ */
758
+ function questionKey(verb, entry) {
759
+ return verb === "allow" ? `allow:${entry.label}:${keyOf(entry)}` : `delete:${keyOf(entry)}`;
760
+ }
761
+ function checkAnswers(questions, answers) {
762
+ if (answers.length !== questions.length) {
763
+ const noun = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
764
+ throw new InternalError(`answerQuestions gave ${noun(answers.length, "answer")} for ${noun(questions.length, "question")}; answer each question in order, or throw to refuse.`, { cause: {
765
+ questions: questions.map(({ subject }) => subject),
766
+ answers
767
+ } });
768
+ }
769
+ questions.forEach((question, index) => {
770
+ const answer = answers[index];
771
+ if (answer === void 0) return;
772
+ const cause = { cause: {
773
+ question: question.subject,
774
+ verbs: question.verbs,
775
+ answer
776
+ } };
777
+ if (!question.verbs.includes(answer.verb)) throw new InternalError(`answerQuestions answered "${question.question}" with ${answer.verb}, which it does not accept; it accepts ${question.verbs.join(" or ")}.`, cause);
778
+ const rejected = question.validate(answer.verb, answer.text);
779
+ if (rejected !== void 0) throw new InternalError(`answerQuestions answered "${question.question}" wrongly: ${rejected}`, cause);
780
+ });
781
+ }
782
+ function withRecoveryOnFirstStorageQuestion(asked, recoveryApplies) {
783
+ const first = recoveryApplies ? asked.findIndex(({ loss }) => loss.subject.kind === "storage") : -1;
784
+ return asked.map(({ question }, index) => index === first ? {
785
+ ...question,
786
+ question: `${question.question} ${ORIGIN_SNAPSHOT_RECOVERY}`
787
+ } : question);
788
+ }
789
+ /**
790
+ * Asks about every operation of a plan that would lose data and, when `askAccess`, every one that
791
+ * would widen access, until each is answered. A `delete` or `allow` text in `preAnswers`, or
792
+ * `consentAll` for its verb, answers its question without asking. A rename typed at the prompt is a statement
793
+ * the plan did not have, so the plan is made again with it, and the operation it answered must be
794
+ * gone; a loss the new plan has on the same subject, such as a type change on the renamed field,
795
+ * is asked in the next round. The first round asks even when nothing is in question, so a statement no question consumed is
796
+ * refused before anything is done.
797
+ */
798
+ async function askPlanQuestions(input) {
799
+ let plan = input.plan;
800
+ let renames = input.renames;
801
+ const consented = /* @__PURE__ */ new Map();
802
+ const usedPreAnswers = /* @__PURE__ */ new Set();
803
+ for (let round = 0;; round += 1) {
804
+ const contracts = {
805
+ origin: input.origin,
806
+ originKnown: input.originKnown,
807
+ keepDataByHand: input.keepDataByHand,
808
+ destination: input.destination,
809
+ renames
810
+ };
811
+ const pending = (verb, planned) => [...new Map(planned.filter((entry) => !consented.has(questionKey(verb, entry))).map((entry) => [questionKey(verb, entry), entry])).values()];
812
+ const consent = (verb, entry, text) => consented.set(questionKey(verb, entry), {
813
+ verb,
814
+ subject: entry.subject,
815
+ text,
816
+ operationIndex: entry.operationIndex
817
+ });
818
+ for (const [verb, entries] of [["delete", pending("delete", plan.dataLoss)], ["allow", input.askAccess ? pending("allow", plan.accessWidening) : []]]) for (const entry of entries) {
819
+ const text = subjectText(entry.subject, contracts);
820
+ const given = givenFor(verb, text, input.preAnswers, usedPreAnswers);
821
+ for (const statement of given) usedPreAnswers.add(statement);
822
+ if (input.consentAll[verb] || given.length > 0) consent(verb, entry, text);
823
+ }
824
+ const losses = pending("delete", plan.dataLoss);
825
+ const widenings = input.askAccess ? pending("allow", plan.accessWidening) : [];
826
+ if (losses.length + widenings.length === 0 && round > 0) break;
827
+ const questions = [...withRecoveryOnFirstStorageQuestion(losses.map((loss) => ({
828
+ loss,
829
+ question: dataLossQuestion(loss, contracts)
830
+ })), !input.originKnown && input.keepDataByHand === void 0), ...widenings.map((widening) => accessWideningQuestion(widening, contracts))];
831
+ const answers = await input.answer(questions);
832
+ checkAnswers(questions, answers);
833
+ const typedRenames = [];
834
+ answers.forEach((answer, index) => {
835
+ const entry = [...losses, ...widenings][index];
836
+ const question = questions[index];
837
+ if (entry === void 0 || question === void 0) return;
838
+ if (answer.verb === "rename") typedRenames.push({
839
+ text: answer.text,
840
+ loss: entry
841
+ });
842
+ else consent(answer.verb, entry, question.subject);
843
+ });
844
+ if (typedRenames.length === 0) {
845
+ if (losses.length + widenings.length === 0) break;
846
+ continue;
847
+ }
848
+ renames = [...renames, ...typedRenames.map(({ text }) => ({
849
+ verb: "rename",
850
+ text
851
+ }))];
852
+ const replanned = await input.replan(renames);
853
+ if (!replanned.ok) return replanned;
854
+ plan = replanned.value;
855
+ for (const entry of plan.accessWidening) {
856
+ const allowed = consented.get(questionKey("allow", entry));
857
+ if (allowed !== void 0) consented.set(questionKey("allow", entry), {
858
+ ...allowed,
859
+ operationIndex: entry.operationIndex
860
+ });
861
+ }
862
+ const operationOf = (entry) => `${entry.label}:${keyOf(entry)}`;
863
+ const stillPlanned = new Set(plan.dataLoss.map(operationOf));
864
+ const unresolved = typedRenames.find(({ loss }) => stillPlanned.has(operationOf(loss)));
865
+ if (unresolved !== void 0) return notOk(errorStatementDidNotResolveLoss({
866
+ verb: "rename",
867
+ text: unresolved.text
868
+ }, subjectText(unresolved.loss.subject, contracts)));
869
+ }
870
+ const unused = input.preAnswers.filter((statement) => !usedPreAnswers.has(statement));
871
+ if (unused.length > 0) return notOk(errorStatementAnswersNoQuestion(unused, questionSubjects(plan, input.askAccess, {
872
+ ...input,
873
+ renames
874
+ })));
875
+ return ok({
876
+ plan,
877
+ renames,
878
+ consented: [...consented.values()]
879
+ });
880
+ }
881
+ function questionSubjects(plan, askAccess, contracts) {
882
+ const subjects = [...plan.dataLoss, ...askAccess ? plan.accessWidening : []].map((entry) => subjectText(entry.subject, contracts));
883
+ return [...new Set(subjects)];
884
+ }
885
+ /**
886
+ * Refuses the `delete` and `allow` statements that name no subject a plan asks about, without
887
+ * asking anything: a run that only plans still says which statements would consent to nothing.
888
+ */
889
+ function refuseUnusedConsents(input) {
890
+ const subjects = questionSubjects(input.plan, true, input.contracts);
891
+ const used = /* @__PURE__ */ new Set();
892
+ for (const [verb, entries] of [["delete", input.plan.dataLoss], ["allow", input.plan.accessWidening]]) for (const entry of entries) {
893
+ const text = subjectText(entry.subject, input.contracts);
894
+ for (const statement of givenFor(verb, text, input.statements, used)) used.add(statement);
895
+ }
896
+ const unused = input.statements.filter((statement) => statement.verb !== "rename" && !used.has(statement));
897
+ return unused.length === 0 ? ok(void 0) : notOk(errorStatementAnswersNoQuestion(unused, subjects));
898
+ }
899
+ /**
900
+ * `operationOffset` is the number of operations the result lists before the plan that applied the
901
+ * statements, so that each position indexes the result's `operations`.
902
+ */
903
+ function reportAppliedStatements(applied, fromContract, contract, operationOffset) {
904
+ return applied.map((entry) => ({
905
+ verb: "rename",
906
+ statement: migrationStatementJson(entry.statement),
907
+ operationIndexes: entry.operationIndexes.map((index) => operationOffset + index),
908
+ description: describeMigrationStatement(entry.statement, fromContract ?? contract, contract)
909
+ }));
910
+ }
911
+ /** A delete or allow statement a plan applied, with the positions of the operations it consented to. */
912
+ function reportConsentStatement(consented, operationIndexes) {
913
+ return {
914
+ verb: consented.verb,
915
+ statement: {
916
+ kind: consented.verb,
917
+ subject: migrationSubjectJson(consented.subject)
918
+ },
919
+ operationIndexes,
920
+ description: consentDescription(consented.verb, consented.subject, consented.text)
921
+ };
922
+ }
169
923
  /**
170
924
  * Project the CLI's `Config.extensions` array into the canonical
171
925
  * {@link ExtensionPackInput} shape. The single `as ExtensionPackLike`
@@ -450,7 +1204,8 @@ async function buildReadAggregate(config, options) {
450
1204
  if (!loaded.ok) return loaded;
451
1205
  return ok({
452
1206
  aggregate: loaded.value,
453
- contractHash
1207
+ contractHash,
1208
+ storageNameOf: (operation) => familyInstance.storageNameOf(operation)
454
1209
  });
455
1210
  } catch (error) {
456
1211
  return notOk(errorFromCaught(error, (message) => `Failed to read migrations directory: ${message}`));
@@ -468,20 +1223,6 @@ function stripOperations(operations) {
468
1223
  }));
469
1224
  }
470
1225
  /**
471
- * Content identity of a `db update` plan: what it does (the ordered display
472
- * operations) and where it lands (the destination storage hash). A
473
- * `DESTRUCTIVE_CHANGES` refusal names the refused plan by this hash, and the
474
- * apply that carries the consent back recomputes it to prove it is still
475
- * applying the plan that was consented to.
476
- */
477
- function computePlanHash(plan) {
478
- const canonical = canonicalizeJson({
479
- operations: plan.operations,
480
- destination: { storageHash: plan.destination.storageHash }
481
- });
482
- return createHash("sha256").update(canonical).digest("hex");
483
- }
484
- /**
485
1226
  * Span id emitted via `onProgress` for the run phase. Stable
486
1227
  * identifier consumed by the structured-output renderer and by tests.
487
1228
  */
@@ -663,6 +1404,25 @@ async function executeRun(options) {
663
1404
  if (!loaded.ok) throw loaded.failure;
664
1405
  const aggregate = loaded.value;
665
1406
  const markerRows = await familyInstance.readAllMarkers({ driver });
1407
+ const appOrigin = options.action === "dbUpdate" ? await readAppOrigin({
1408
+ marker: markerRows.get(aggregate.app.spaceId) ?? null,
1409
+ migrationsDir,
1410
+ deserializeContract: (json) => familyInstance.deserializeContract(json),
1411
+ ...ifDefined("verifySnapshotContent", options.verifySnapshotContent)
1412
+ }) : void 0;
1413
+ const fromContract = appOrigin?.contract ?? null;
1414
+ const statementTexts = options.action === "dbUpdate" ? options.statements : [];
1415
+ const resolveRenames = (texts) => {
1416
+ if (texts.length === 0 || appOrigin === void 0) return [];
1417
+ const resolved = resolveStatements({
1418
+ statements: texts,
1419
+ origin: appOrigin.origin,
1420
+ destination: contract
1421
+ });
1422
+ if (!resolved.ok) throw resolved.failure;
1423
+ return resolved.value;
1424
+ };
1425
+ const statements = resolveRenames(statementTexts);
666
1426
  if (mode === "apply") {
667
1427
  const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows);
668
1428
  if (orphanMarkerError !== null) throw orphanMarkerError;
@@ -683,44 +1443,124 @@ async function executeRun(options) {
683
1443
  spanId: SPAN_IDS$1.introspect,
684
1444
  outcome: "ok"
685
1445
  });
686
- onProgress?.({
687
- action,
688
- kind: "spanStart",
689
- spanId: SPAN_IDS$1.plan,
690
- label: "Planning migration"
691
- });
692
- const planResult = await planMigration({
693
- aggregate,
694
- currentDBState: {
695
- markersBySpaceId: markerRows,
696
- schemaIntrospection: schemaIR
697
- },
698
- adapter,
699
- migrations,
700
- frameworkComponents,
701
- callerPolicy: { ignoreGraphFor: /* @__PURE__ */ new Set([aggregate.app.spaceId]) },
702
- operationPolicy: policy
703
- });
704
- if (!planResult.ok) {
1446
+ const plan = async (resolved) => {
1447
+ onProgress?.({
1448
+ action,
1449
+ kind: "spanStart",
1450
+ spanId: SPAN_IDS$1.plan,
1451
+ label: "Planning migration"
1452
+ });
1453
+ const planned = await planMigration({
1454
+ aggregate,
1455
+ currentDBState: {
1456
+ markersBySpaceId: markerRows,
1457
+ schemaIntrospection: schemaIR
1458
+ },
1459
+ adapter,
1460
+ migrations,
1461
+ frameworkComponents,
1462
+ callerPolicy: { ignoreGraphFor: /* @__PURE__ */ new Set([aggregate.app.spaceId]) },
1463
+ operationPolicy: policy,
1464
+ appSpace: {
1465
+ fromContract,
1466
+ statements: resolved
1467
+ },
1468
+ storageNameOf: (operation) => familyInstance.storageNameOf(operation)
1469
+ });
1470
+ if (!planned.ok) {
1471
+ onProgress?.({
1472
+ action,
1473
+ kind: "spanEnd",
1474
+ spanId: SPAN_IDS$1.plan,
1475
+ outcome: "error"
1476
+ });
1477
+ return notOk(mapPlannerError(planned.failure));
1478
+ }
705
1479
  onProgress?.({
706
1480
  action,
707
1481
  kind: "spanEnd",
708
1482
  spanId: SPAN_IDS$1.plan,
709
- outcome: "error"
1483
+ outcome: "ok"
1484
+ });
1485
+ const orderedResolutions = collectOrdered(planned.value.applyOrder, planned.value.perSpace);
1486
+ const subjects = action === "dbUpdate" ? subjectsAcrossSpaces(orderedResolutions) : {
1487
+ dataLoss: [],
1488
+ accessWidening: []
1489
+ };
1490
+ const operations = orderedResolutions.flatMap((r) => r.entry.displayOps);
1491
+ const labelled = (entries) => entries.map((entry) => ({
1492
+ ...entry,
1493
+ label: operations[entry.operationIndex]?.label ?? JSON.stringify(entry.subject)
1494
+ }));
1495
+ return ok({
1496
+ planned: planned.value,
1497
+ orderedResolutions,
1498
+ subjects,
1499
+ dataLoss: labelled(subjects.dataLoss),
1500
+ accessWidening: labelled(subjects.accessWidening)
1501
+ });
1502
+ };
1503
+ const first = await plan(statements);
1504
+ if (!first.ok) return first.failure;
1505
+ let run = first.value;
1506
+ let renameTexts = statementTexts.filter((statement) => statement.verb === "rename");
1507
+ let consented = [];
1508
+ if (options.action === "dbUpdate" && mode === "apply") {
1509
+ const answered = await askPlanQuestions({
1510
+ plan: run,
1511
+ askAccess: true,
1512
+ renames: renameTexts,
1513
+ preAnswers: statementTexts.filter((statement) => statement.verb !== "rename"),
1514
+ consentAll: {
1515
+ delete: options.acceptDataLoss,
1516
+ allow: options.acceptAccessWidening
1517
+ },
1518
+ origin: fromContract ?? EMPTY_ORIGIN$1,
1519
+ originKnown: fromContract !== null,
1520
+ keepDataByHand: keepDataByHandFor(migrations, fromContract ?? EMPTY_ORIGIN$1),
1521
+ destination: contract,
1522
+ answer: options.answerQuestions,
1523
+ replan: (renames) => plan(resolveRenames(renames))
710
1524
  });
711
- return mapPlannerError(planResult.failure);
1525
+ if (!answered.ok) {
1526
+ if (CliStructuredError$1.is(answered.failure)) throw answered.failure;
1527
+ return answered.failure;
1528
+ }
1529
+ run = answered.value.plan;
1530
+ renameTexts = [...answered.value.renames];
1531
+ consented = answered.value.consented;
712
1532
  }
713
- onProgress?.({
714
- action,
715
- kind: "spanEnd",
716
- spanId: SPAN_IDS$1.plan,
717
- outcome: "ok"
718
- });
719
- const orderedResolutions = collectOrdered(planResult.value.applyOrder, planResult.value.perSpace);
1533
+ if (options.action === "dbUpdate" && mode === "plan") {
1534
+ const refused = refuseUnusedConsents({
1535
+ plan: run,
1536
+ statements: statementTexts,
1537
+ contracts: {
1538
+ origin: fromContract ?? EMPTY_ORIGIN$1,
1539
+ destination: contract,
1540
+ renames: renameTexts
1541
+ }
1542
+ });
1543
+ if (!refused.ok) throw refused.failure;
1544
+ }
1545
+ const { planned, orderedResolutions } = run;
720
1546
  const plannerWarnings = aggregatePlannerWarnings(orderedResolutions);
721
1547
  const appResolution = orderedResolutions.find((r) => r.spaceId === aggregate.app.spaceId);
722
1548
  if (!appResolution) throw new InternalError("Aggregate planner returned no plan for the app space — the planner is supposed to always emit one.");
723
1549
  const appPlan = appResolution.entry.plan;
1550
+ const appliedStatements = action === "dbUpdate" ? [...reportAppliedStatements(appResolution.entry.appliedStatements, fromContract, contract, operationsBefore(orderedResolutions, aggregate.app.spaceId)), ...consented.map((entry) => reportConsentStatement(entry, entry.verb === "allow" && entry.operationIndex !== void 0 ? [entry.operationIndex] : run.subjects.dataLoss.filter(({ subject }) => migrationSubjectKey(subject) === migrationSubjectKey(entry.subject)).map(({ operationIndex }) => operationIndex)))] : void 0;
1551
+ const contractsAsked = {
1552
+ origin: fromContract ?? EMPTY_ORIGIN$1,
1553
+ destination: contract,
1554
+ renames: renameTexts
1555
+ };
1556
+ const asked = (entries) => entries.map((entry) => ({
1557
+ ...entry,
1558
+ text: subjectText(entry.subject, contractsAsked)
1559
+ }));
1560
+ const subjects = action === "dbUpdate" ? {
1561
+ dataLoss: asked(run.subjects.dataLoss),
1562
+ accessWidening: asked(run.subjects.accessWidening)
1563
+ } : void 0;
724
1564
  if (mode === "plan") {
725
1565
  const aggregateOps = orderedResolutions.flatMap((r) => r.entry.displayOps);
726
1566
  const preview = hasOperationPreview(familyInstance) ? familyInstance.toOperationPreview(aggregateOps) : void 0;
@@ -732,31 +1572,15 @@ async function executeRun(options) {
732
1572
  preview,
733
1573
  perSpace,
734
1574
  summary,
735
- ...ifDefined("warnings", plannerWarnings)
736
- });
737
- }
738
- if (options.consentedPlanHash !== void 0) {
739
- const planHash = computePlanHash({
740
- operations: stripOperations(orderedResolutions.flatMap((r) => r.entry.displayOps)),
741
- destination: appPlan.destination
742
- });
743
- if (planHash !== options.consentedPlanHash) return notOk({
744
- code: "CONSENT_PLAN_MISMATCH",
745
- summary: "The plan changed between consent and apply",
746
- why: "The plan recomputed for the consented apply is not the plan that was consented to, so applying it could destroy something nobody agreed to.",
747
- conflicts: void 0,
748
- meta: void 0,
749
- consentPlanMismatch: {
750
- consentedPlanHash: options.consentedPlanHash,
751
- planHash
752
- },
1575
+ appliedStatements,
1576
+ subjects,
753
1577
  ...ifDefined("warnings", plannerWarnings)
754
1578
  });
755
1579
  }
756
1580
  const applied = await runMigration({
757
1581
  aggregate,
758
- perSpacePlans: planResult.value.perSpace,
759
- applyOrder: planResult.value.applyOrder,
1582
+ perSpacePlans: planned.perSpace,
1583
+ applyOrder: planned.applyOrder,
760
1584
  driver,
761
1585
  familyInstance,
762
1586
  migrations,
@@ -781,9 +1605,94 @@ async function executeRun(options) {
781
1605
  operationsExecuted: applied.value.totalOpsExecuted,
782
1606
  perSpace: applied.value.perSpace,
783
1607
  summary,
1608
+ appliedStatements,
1609
+ subjects,
784
1610
  ...ifDefined("warnings", plannerWarnings)
785
1611
  });
786
1612
  }
1613
+ /** The origin of a database whose marker names no readable contract: no models. */
1614
+ const EMPTY_ORIGIN$1 = { domain: { namespaces: {} } };
1615
+ /**
1616
+ * The contract the application space's marker names, from the local snapshot
1617
+ * store, or where it was looked for and why it could not be used.
1618
+ */
1619
+ async function readAppOrigin(input) {
1620
+ const snapshotsDir = join(input.migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME);
1621
+ if (input.marker === null) return {
1622
+ origin: {
1623
+ kind: "missing",
1624
+ hash: null,
1625
+ snapshotDirectory: snapshotsDir,
1626
+ unreadable: void 0
1627
+ },
1628
+ contract: null
1629
+ };
1630
+ const hash = input.marker.storageHash;
1631
+ if (!isStorageHashHex(hash)) return {
1632
+ origin: {
1633
+ kind: "missing",
1634
+ hash,
1635
+ snapshotDirectory: snapshotsDir,
1636
+ unreadable: void 0
1637
+ },
1638
+ contract: null
1639
+ };
1640
+ const snapshotDirectory = contractSnapshotDir(input.migrationsDir, hash);
1641
+ let json;
1642
+ try {
1643
+ json = await readContractSnapshotJson(input.migrationsDir, hash, input.verifySnapshotContent);
1644
+ } catch (error) {
1645
+ if (!MigrationToolsError.is(error)) throw error;
1646
+ return {
1647
+ origin: {
1648
+ kind: "missing",
1649
+ hash,
1650
+ snapshotDirectory,
1651
+ unreadable: error.code === "MIGRATION.CONTRACT_SNAPSHOT_MISSING" ? void 0 : error.why
1652
+ },
1653
+ contract: null
1654
+ };
1655
+ }
1656
+ try {
1657
+ const contract = input.deserializeContract(json);
1658
+ return {
1659
+ origin: {
1660
+ kind: "contract",
1661
+ contract
1662
+ },
1663
+ contract
1664
+ };
1665
+ } catch (error) {
1666
+ return {
1667
+ origin: {
1668
+ kind: "missing",
1669
+ hash,
1670
+ snapshotDirectory,
1671
+ unreadable: error instanceof Error ? error.message : String(error)
1672
+ },
1673
+ contract: null
1674
+ };
1675
+ }
1676
+ }
1677
+ /** How many operations the spaces applied before `spaceId` list ahead of it in `operations`. */
1678
+ function operationsBefore(orderedResolutions, spaceId) {
1679
+ const position = orderedResolutions.findIndex((resolution) => resolution.spaceId === spaceId);
1680
+ return orderedResolutions.slice(0, position).reduce((count, resolution) => count + resolution.entry.displayOps.length, 0);
1681
+ }
1682
+ /**
1683
+ * What the planned operations lose and whose access they widen, across every space, each at its
1684
+ * position in the operations the result reports.
1685
+ */
1686
+ function subjectsAcrossSpaces(orderedResolutions) {
1687
+ const offset = (resolution, entries) => entries.map((entry) => ({
1688
+ ...entry,
1689
+ operationIndex: entry.operationIndex + operationsBefore(orderedResolutions, resolution.spaceId)
1690
+ }));
1691
+ return {
1692
+ dataLoss: orderedResolutions.flatMap((resolution) => offset(resolution, resolution.entry.dataLoss)),
1693
+ accessWidening: orderedResolutions.flatMap((resolution) => offset(resolution, resolution.entry.accessWidening))
1694
+ };
1695
+ }
787
1696
  function aggregatePlannerWarnings(orderedResolutions) {
788
1697
  const warnings = orderedResolutions.flatMap((r) => r.entry.warnings ?? []);
789
1698
  return warnings.length > 0 ? warnings : void 0;
@@ -852,6 +1761,8 @@ function mapPlannerError(error) {
852
1761
  function wrapPlanResult(args) {
853
1762
  return ok({
854
1763
  mode: "plan",
1764
+ ...ifDefined("appliedStatements", args.appliedStatements),
1765
+ ...args.subjects,
855
1766
  plan: {
856
1767
  operations: stripOperations(args.operations),
857
1768
  ...ifDefined("preview", args.preview)
@@ -868,6 +1779,8 @@ function wrapPlanResult(args) {
868
1779
  function wrapApplyResult(args) {
869
1780
  return ok({
870
1781
  mode: "apply",
1782
+ ...ifDefined("appliedStatements", args.appliedStatements),
1783
+ ...args.subjects,
871
1784
  plan: { operations: stripOperations(args.operations) },
872
1785
  destination: {
873
1786
  storageHash: args.destination.storageHash,
@@ -1235,17 +2148,9 @@ const DB_UPDATE_POLICY = { allowedOperationClasses: [
1235
2148
  "widening",
1236
2149
  "destructive"
1237
2150
  ] };
1238
- /**
1239
- * Execute `db update` against the configured contract.
1240
- *
1241
- * Routes through the loader → planner → runner pipeline. Destructive
1242
- * operations require either `acceptDataLoss: true` or a prior
1243
- * `mode: 'plan'` invocation that surfaces the destructive ops; the
1244
- * confirmation gate is implemented here so the lower-level applier
1245
- * remains policy-agnostic.
1246
- */
2151
+ /** Execute `db update` against the configured contract. */
1247
2152
  async function executeDbUpdate(options) {
1248
- const sharedInputs = {
2153
+ return await executeRun({
1249
2154
  driver: options.driver,
1250
2155
  adapter: options.adapter,
1251
2156
  familyInstance: options.familyInstance,
@@ -1257,53 +2162,13 @@ async function executeDbUpdate(options) {
1257
2162
  extensions: options.extensions ?? [],
1258
2163
  policy: DB_UPDATE_POLICY,
1259
2164
  action: "dbUpdate",
2165
+ mode: options.mode,
2166
+ statements: options.statements ?? [],
2167
+ answerQuestions: options.answerQuestions,
2168
+ acceptDataLoss: options.acceptDataLoss ?? false,
2169
+ acceptAccessWidening: options.acceptAccessWidening ?? false,
1260
2170
  ...ifDefined("verifySnapshotContent", options.verifySnapshotContent),
1261
2171
  ...ifDefined("onProgress", options.onProgress)
1262
- };
1263
- if (options.mode === "apply" && !options.acceptDataLoss && options.consent === void 0) {
1264
- const refusal = await guardDestructiveChanges(sharedInputs);
1265
- if (refusal !== null) return refusal;
1266
- }
1267
- return await executeRun({
1268
- ...sharedInputs,
1269
- mode: options.mode,
1270
- ...ifDefined("consentedPlanHash", options.consent?.planHash)
1271
- });
1272
- }
1273
- /**
1274
- * Pre-plan once when running `db update apply` without `acceptDataLoss`.
1275
- * Surfaces destructive operations across every space; if any are
1276
- * planned, returns a `DESTRUCTIVE_CHANGES` failure that the CLI shows
1277
- * as a confirmation prompt. Returns `null` when the apply is safe to
1278
- * run.
1279
- */
1280
- async function guardDestructiveChanges(sharedInputs) {
1281
- const planResult = await executeRun({
1282
- ...sharedInputs,
1283
- mode: "plan"
1284
- });
1285
- if (!planResult.ok) return planResult;
1286
- const destructiveOps = planResult.value.plan.operations.filter((op) => op.operationClass === "destructive").map((op) => ({
1287
- id: op.id,
1288
- label: op.label
1289
- }));
1290
- if (destructiveOps.length === 0) return null;
1291
- const databaseName = await sharedInputs.driver.databaseName?.();
1292
- return notOk({
1293
- code: "DESTRUCTIVE_CHANGES",
1294
- summary: `Planned ${destructiveOps.length} destructive operation(s) that require confirmation`,
1295
- why: "Destructive operations require explicit consent, which the caller has not given",
1296
- conflicts: void 0,
1297
- meta: void 0,
1298
- destructiveChanges: {
1299
- destructiveOperations: destructiveOps,
1300
- databaseName,
1301
- planHash: computePlanHash({
1302
- operations: planResult.value.plan.operations,
1303
- destination: planResult.value.destination
1304
- })
1305
- },
1306
- ...ifDefined("warnings", planResult.value.warnings)
1307
2172
  });
1308
2173
  }
1309
2174
  function isRecord$2(value) {
@@ -1569,7 +2434,8 @@ async function executeMigrate(options) {
1569
2434
  targetHash: spaceTargetHash,
1570
2435
  refInvariants: isAppSpace && refHash !== void 0 ? refInvariants : void 0,
1571
2436
  liveMarker: markerRows.get(space.spaceId) ?? null,
1572
- ...isAppSpace ? { refName } : {}
2437
+ ...isAppSpace ? { refName } : {},
2438
+ storageNameOf: (operation) => familyInstance.storageNameOf(operation)
1573
2439
  });
1574
2440
  if (outcome.kind === "at-head") {
1575
2441
  plansKeptFromRunner.set(space.spaceId, outcome.plan);
@@ -1681,7 +2547,7 @@ async function executeMigrate(options) {
1681
2547
  *
1682
2548
  * @internal Exported for `executeMigrateShowCommand`.
1683
2549
  */
1684
- function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker, refName }) {
2550
+ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker, refName, storageNameOf }) {
1685
2551
  const isAppSpace = space.spaceId === aggregate.app.spaceId;
1686
2552
  const headRef = requireHeadRef(space);
1687
2553
  if (space.graph().nodes.size === 0) {
@@ -1734,7 +2600,8 @@ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker
1734
2600
  aggregateTargetId: aggregate.targetId,
1735
2601
  space: targetSpace,
1736
2602
  currentMarker: liveMarker,
1737
- ...isAppSpace && refName !== void 0 ? { refName } : {}
2603
+ ...isAppSpace && refName !== void 0 ? { refName } : {},
2604
+ storageNameOf
1738
2605
  });
1739
2606
  if (walked.kind === "unreachable") return {
1740
2607
  kind: "unreachable",
@@ -1783,6 +2650,9 @@ function buildAtHeadResolution(args) {
1783
2650
  displayOps: [],
1784
2651
  destinationContract: space.contract(),
1785
2652
  strategy: "declared-state",
2653
+ appliedStatements: [],
2654
+ dataLoss: [],
2655
+ accessWidening: [],
1786
2656
  migrationEdges: [buildFabricatedMigrationEdge({
1787
2657
  currentMarkerStorageHash: liveMarker?.storageHash,
1788
2658
  destinationStorageHash: targetHash,
@@ -2135,7 +3005,9 @@ var ControlClientImpl = class {
2135
3005
  targetId: this.options.target.targetId,
2136
3006
  extensions: this.options.extensions ?? [],
2137
3007
  ...ifDefined("acceptDataLoss", options.acceptDataLoss),
2138
- ...ifDefined("consent", options.consent),
3008
+ ...ifDefined("acceptAccessWidening", options.acceptAccessWidening),
3009
+ ...ifDefined("statements", options.statements),
3010
+ answerQuestions: options.answerQuestions,
2139
3011
  ...ifDefined("verifySnapshotContent", this.snapshotVerifier),
2140
3012
  ...ifDefined("onProgress", onProgress)
2141
3013
  });
@@ -2887,6 +3759,20 @@ async function advanceRefSafely(args) {
2887
3759
  throw error;
2888
3760
  }
2889
3761
  }
3762
+ const SHELL_SAFE = /^[A-Za-z0-9_.:/@%+,-]+$/;
3763
+ /** The value as a shell passes it through unchanged, single-quoted when needed. */
3764
+ function shellQuoted(value) {
3765
+ return SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
3766
+ }
3767
+ /**
3768
+ * A statement written as a flag a shell passes through unchanged: the value is single-quoted when
3769
+ * it has a character a shell would read, and joined with `=` when it starts with `-`, which a
3770
+ * parser would otherwise read as a flag.
3771
+ */
3772
+ function statementFlag(statement) {
3773
+ const value = shellQuoted(statement.text);
3774
+ return statement.text.startsWith("-") ? `--${statement.verb}=${value}` : `--${statement.verb} ${value}`;
3775
+ }
2890
3776
  const RECORDED_FORMS = [
2891
3777
  "hash",
2892
3778
  "prefix",
@@ -3009,6 +3895,7 @@ function retryCommandFor(args) {
3009
3895
  ...suggestsOffline ? ["--from <contract>"] : [],
3010
3896
  ...args.to === void 0 ? [] : [`--to ${args.to}`],
3011
3897
  ...args.advanceRef === void 0 ? [] : [`--advance-ref ${args.advanceRef}`],
3898
+ ...(args.statements ?? []).map(statementFlag),
3012
3899
  ...needsConnection ? ["--db $DATABASE_URL"] : []
3013
3900
  ].join(" ");
3014
3901
  }
@@ -3144,7 +4031,7 @@ async function executeMigrateShowPlan(options) {
3144
4031
  }
3145
4032
  const loaded = await buildReadAggregate(config, { migrationsDir });
3146
4033
  if (!loaded.ok) return notOk(loaded.failure);
3147
- const { aggregate, contractHash } = loaded.value;
4034
+ const { aggregate, contractHash, storageNameOf } = loaded.value;
3148
4035
  const appGraph = aggregate.app.graph();
3149
4036
  let targetHash = contractHash;
3150
4037
  let refInvariants;
@@ -3221,7 +4108,8 @@ async function executeMigrateShowPlan(options) {
3221
4108
  aggregate,
3222
4109
  targetHash: isAppSpace ? targetHash : headRef.hash,
3223
4110
  refInvariants: isAppSpace ? refInvariants : void 0,
3224
- liveMarker: markerBySpace.get(space.spaceId) ?? null
4111
+ liveMarker: markerBySpace.get(space.spaceId) ?? null,
4112
+ storageNameOf
3225
4113
  });
3226
4114
  if (outcome.kind === "at-head") continue;
3227
4115
  if (outcome.kind === "never-planned") return notOk(errorPathUnreachable({
@@ -4202,7 +5090,9 @@ function buildPlaceholderContractDts(spaceId) {
4202
5090
  function isEnoent(error) {
4203
5091
  return error instanceof Error && "code" in error && error.code === "ENOENT";
4204
5092
  }
4205
- async function runPlannerLeg(planner, migrations, frameworkComponents, contract, origin, destination, spaceId, ownership, snapshotsImportPath, resolveImportSpecifier) {
5093
+ /** The origin of a plan from an empty database: no models, so no statement resolves. */
5094
+ const EMPTY_ORIGIN = { domain: { namespaces: {} } };
5095
+ async function runPlannerLeg(planner, migrations, frameworkComponents, contract, origin, destination, statements, noOperationsExpected, spaceId, ownership, snapshotsImportPath, resolveImportSpecifier) {
4206
5096
  const fromContract = origin.kind === "contract" ? origin.contract : null;
4207
5097
  const fromSchema = migrations.contractToSchema(fromContract, frameworkComponents);
4208
5098
  const plannerResult = planner.plan({
@@ -4215,33 +5105,82 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
4215
5105
  "data"
4216
5106
  ] },
4217
5107
  fromContract,
5108
+ origin: planOriginOf(fromContract),
5109
+ statements,
4218
5110
  frameworkComponents,
4219
5111
  spaceId,
4220
5112
  ownership,
4221
5113
  snapshotsImportPath
4222
5114
  });
4223
- if (plannerResult.kind === "failure") return notOk(errorMigrationPlanningFailed({ conflicts: castAs(plannerResult.conflicts) }));
4224
- let plannedOps = [];
5115
+ if (plannerResult.kind === "failure") return notOk({
5116
+ reason: "refused",
5117
+ error: errorMigrationPlanningFailed({ conflicts: castAs(plannerResult.conflicts) })
5118
+ });
5119
+ let resolved = [];
4225
5120
  let hasPlaceholders = false;
4226
5121
  try {
4227
- plannedOps = await Promise.all(plannerResult.plan.operations);
4228
- if (plannedOps.length === 0) return notOk(errorPlanProducedNoOperations(origin, destination));
5122
+ resolved = await Promise.all(plannerResult.plan.operations);
5123
+ if (resolved.length === 0 && !noOperationsExpected) return notOk({
5124
+ reason: "noOperations",
5125
+ error: errorPlanProducedNoOperations(origin, destination)
5126
+ });
4229
5127
  } catch (e) {
4230
5128
  if (CliStructuredError$1.is(e) && e.code === "MIGRATION.UNFILLED_PLACEHOLDER") {
4231
5129
  hasPlaceholders = true;
4232
5130
  try {
4233
- plannedOps = (await Promise.allSettled(plannerResult.plan.operations)).flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []);
5131
+ resolved = (await Promise.allSettled(plannerResult.plan.operations)).map((entry) => entry.status === "fulfilled" ? entry.value : void 0);
4234
5132
  } catch {
4235
- plannedOps = [];
5133
+ resolved = [];
4236
5134
  }
4237
5135
  } else throw e;
4238
5136
  }
5137
+ const plannedOps = resolved.filter((op) => op !== void 0);
5138
+ const position = resolvedPositions(resolved);
4239
5139
  return ok({
4240
5140
  plannedOps,
4241
5141
  migrationTsContent: plannerResult.plan.renderTypeScript(resolveImportSpecifier),
4242
- hasPlaceholders
5142
+ hasPlaceholders,
5143
+ dataLoss: plannerResult.dataLoss.map(({ operationIndex, subject }) => ({
5144
+ operationIndex: position(operationIndex),
5145
+ subject,
5146
+ label: resolved[operationIndex]?.label ?? subjectText(subject, {
5147
+ origin: fromContract ?? EMPTY_ORIGIN,
5148
+ renames: []
5149
+ })
5150
+ })),
5151
+ appliedStatements: reportAppliedStatements(plannerResult.appliedStatements.map((applied) => ({
5152
+ ...applied,
5153
+ operationIndexes: applied.operationIndexes.flatMap((index) => {
5154
+ const at = position(index);
5155
+ return at === void 0 ? [] : [at];
5156
+ })
5157
+ })), fromContract, contract, 0)
4243
5158
  });
4244
5159
  }
5160
+ /**
5161
+ * Maps a position in the plan's operations to the position of that operation among those that
5162
+ * resolved, which is what a result's `operations` lists: `undefined` for an unfilled placeholder.
5163
+ */
5164
+ function resolvedPositions(resolved) {
5165
+ const positions = [];
5166
+ let next = 0;
5167
+ for (const op of resolved) {
5168
+ positions.push(op === void 0 ? void 0 : next);
5169
+ if (op !== void 0) next += 1;
5170
+ }
5171
+ return (planIndex) => positions[planIndex];
5172
+ }
5173
+ /**
5174
+ * The operations a result lists. For a leg with unfilled placeholders these are the operations
5175
+ * that resolved; the placeholders themselves are not operations yet.
5176
+ */
5177
+ function operationSummaries(ops) {
5178
+ return ops.map((op) => ({
5179
+ id: op.id,
5180
+ label: op.label,
5181
+ operationClass: op.operationClass
5182
+ }));
5183
+ }
4245
5184
  async function writePlannedMigrationPackage(packageDir, fromHash, toHash, createdAt, leg) {
4246
5185
  const opsForWrite = leg.hasPlaceholders ? [] : leg.plannedOps;
4247
5186
  const metadataWithInvariants = {
@@ -4257,46 +5196,42 @@ async function writePlannedMigrationPackage(packageDir, fromHash, toHash, create
4257
5196
  await writeMigrationTs(packageDir, leg.migrationTsContent);
4258
5197
  }
4259
5198
  /**
4260
- * The consent check for an auto-baseline write, mirroring `db update`'s
4261
- * destructive-changes refusal: a baseline leg carrying destructive operations
4262
- * is only written when the caller consents to that exact plan by its hash.
4263
- * Runs before the baseline and delta packages are written, so a refusal
4264
- * leaves the app-space migrations directory untouched (the extension seed
4265
- * phase runs earlier and unconditionally, as it does for no-op runs).
4266
- * A leg with unfilled placeholders is still checked over the operations
4267
- * that did resolve. Returns `null` when the write may proceed.
5199
+ * Asks about every operation of the planned legs that would lose data, until each is answered,
5200
+ * before anything is written. A delete answer consents to the loss of its subject. A rename typed
5201
+ * at the prompt is a statement the plan did not have, so the delta is planned again with it, and
5202
+ * the loss it answered must be gone.
4268
5203
  */
4269
- function refuseUnconsentedDestructiveBaseline(leg, baselineToHash, consent) {
4270
- const ops = leg.plannedOps;
4271
- const destructiveOps = ops.filter((op) => op.operationClass === "destructive");
4272
- if (destructiveOps.length === 0) return null;
4273
- const planHash = computePlanHash({
4274
- operations: ops.map((op) => ({
4275
- id: op.id,
4276
- label: op.label,
4277
- operationClass: op.operationClass
4278
- })),
4279
- destination: { storageHash: baselineToHash }
5204
+ async function answerPlannedDataLoss(input) {
5205
+ const legs = (delta) => ({
5206
+ delta,
5207
+ dataLoss: [...input.baseline?.dataLoss ?? [], ...delta?.dataLoss ?? []],
5208
+ accessWidening: []
4280
5209
  });
4281
- if (consent === void 0) {
4282
- const verdict = {
4283
- destructiveOperations: destructiveOps.map((op) => ({
4284
- id: op.id,
4285
- label: op.label
4286
- })),
4287
- planHash
4288
- };
4289
- return errorDestructiveChanges(`The baseline migration contains ${destructiveOps.length} destructive operation(s) that require confirmation`, {
4290
- why: "The migrations directory is empty, so planning writes a baseline derived from the `db` ref — and that baseline contains operations that would remove data when the migration is applied.",
4291
- fix: "Re-run `prisma migration plan` and type the project directory name when asked, or pass `--no-interactive --confirm <directory>` where there is nobody to ask.",
4292
- meta: { ...verdict }
4293
- });
4294
- }
4295
- if (consent.planHash !== planHash) return errorConsentPlanMismatch({
4296
- consentedPlanHash: consent.planHash,
4297
- planHash
5210
+ const answered = await askPlanQuestions({
5211
+ plan: legs(input.delta),
5212
+ askAccess: false,
5213
+ renames: input.renames,
5214
+ preAnswers: input.consents,
5215
+ consentAll: {
5216
+ delete: false,
5217
+ allow: false
5218
+ },
5219
+ origin: input.origin,
5220
+ originKnown: input.originKnown,
5221
+ keepDataByHand: input.keepDataByHand,
5222
+ destination: input.destination,
5223
+ answer: input.answer,
5224
+ replan: async (renames) => {
5225
+ const replanned = await input.planDelta(renames);
5226
+ return replanned.ok ? ok(legs(replanned.value)) : replanned;
5227
+ }
5228
+ });
5229
+ if (!answered.ok) return answered;
5230
+ const { delta } = answered.value.plan;
5231
+ return ok({
5232
+ delta,
5233
+ deletes: answered.value.consented.map((consented) => reportConsentStatement(consented, (delta?.dataLoss ?? []).filter((loss) => migrationSubjectKey(loss.subject) === migrationSubjectKey(consented.subject)).flatMap(({ operationIndex }) => operationIndex === void 0 ? [] : [operationIndex])))
4298
5234
  });
4299
- return null;
4300
5235
  }
4301
5236
  async function executeMigrationPlanCommand(options, startTime, callbacks) {
4302
5237
  try {
@@ -4401,6 +5336,20 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4401
5336
  toStorageHash = toResolution.value.hash;
4402
5337
  destinationInStore = true;
4403
5338
  }
5339
+ let statements = [];
5340
+ const statementTexts = options.statements ?? [];
5341
+ if (statementTexts.length > 0) {
5342
+ const resolved = resolveStatements({
5343
+ statements: statementTexts,
5344
+ origin: {
5345
+ kind: "contract",
5346
+ contract: fromContract ?? EMPTY_ORIGIN
5347
+ },
5348
+ destination: toContract
5349
+ });
5350
+ if (!resolved.ok) return notOk(resolved.failure);
5351
+ statements = resolved.value;
5352
+ }
4404
5353
  const resolveImportSpecifier = createProjectSpecifierResolver(options.projectDir);
4405
5354
  let destinationDeclarations = null;
4406
5355
  if (!destinationInStore && fromHash !== toStorageHash) {
@@ -4418,13 +5367,11 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4418
5367
  extensions: toExtensionInputs(config.extensions ?? [])
4419
5368
  });
4420
5369
  for (const record of seedResult.seeded) callbacks?.onSeeded?.(record);
4421
- const seededThisRun = seedResult.seeded.flatMap((r) => r.newMigrationDirs.map((dirName) => ({
5370
+ const emittedExtensionDirs = seedResult.seeded.flatMap((r) => r.newMigrationDirs.map((dirName) => ({
4422
5371
  spaceId: r.spaceId,
4423
5372
  dirName
4424
5373
  })));
4425
- const carried = options.carryEmittedExtensionDirs ?? [];
4426
- const emittedExtensionDirs = [...carried, ...seededThisRun.filter((entry) => !carried.some((prior) => prior.spaceId === entry.spaceId && prior.dirName === entry.dirName))];
4427
- if (fromHash === toStorageHash && !isAutoBaseline) return ok({
5374
+ if (fromHash === toStorageHash && !isAutoBaseline && statements.length === 0) return ok({
4428
5375
  ok: true,
4429
5376
  noOp: true,
4430
5377
  from: fromHash,
@@ -4432,6 +5379,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4432
5379
  operations: [],
4433
5380
  emittedExtensionDirs,
4434
5381
  ...warnings.length > 0 ? { warnings } : {},
5382
+ appliedStatements: [],
4435
5383
  summary: "No changes detected between contracts",
4436
5384
  timings: { total: Date.now() - startTime }
4437
5385
  });
@@ -4465,6 +5413,30 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4465
5413
  hash: toStorageHash,
4466
5414
  isEmitted: options.to === void 0
4467
5415
  };
5416
+ const answerDataLoss = (baseline, delta, planDelta) => answerPlannedDataLoss({
5417
+ baseline,
5418
+ delta,
5419
+ renames: statementTexts.filter((statement) => statement.verb === "rename"),
5420
+ consents: statementTexts.filter((statement) => statement.verb !== "rename"),
5421
+ origin: fromContract ?? EMPTY_ORIGIN,
5422
+ originKnown: true,
5423
+ keepDataByHand: keepDataByHandFor(migrations, fromContract ?? EMPTY_ORIGIN),
5424
+ destination: toContract,
5425
+ answer: options.answerQuestions,
5426
+ planDelta: async (renames) => {
5427
+ const resolved = resolveStatements({
5428
+ statements: renames,
5429
+ origin: {
5430
+ kind: "contract",
5431
+ contract: fromContract ?? EMPTY_ORIGIN
5432
+ },
5433
+ destination: toContract
5434
+ });
5435
+ if (!resolved.ok) return resolved;
5436
+ const leg = await planDelta(resolved.value);
5437
+ return leg.ok ? leg : notOk(leg.failure.error);
5438
+ }
5439
+ });
4468
5440
  if (isAutoBaseline && fromHash !== null && fromContract !== null && fromContractInStore) {
4469
5441
  const deltaTimestamp = /* @__PURE__ */ new Date();
4470
5442
  const baselineTimestamp = /* @__PURE__ */ new Date(deltaTimestamp.getTime() - 6e4);
@@ -4478,12 +5450,22 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4478
5450
  }, {
4479
5451
  hash: fromHash,
4480
5452
  isEmitted: false
4481
- }, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(baselinePackageDir, migrationsDir), resolveImportSpecifier);
4482
- if (!baselineLeg.ok) return notOk(baselineLeg.failure);
4483
- const consentFailure = refuseUnconsentedDestructiveBaseline(baselineLeg.value, fromHash, options.consent);
4484
- if (consentFailure !== null) return notOk(consentFailure);
5453
+ }, [], false, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(baselinePackageDir, migrationsDir), resolveImportSpecifier);
5454
+ if (!baselineLeg.ok) return notOk(baselineLeg.failure.error);
5455
+ const planBaselineDelta = (resolved) => runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, false, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(deltaPackageDir, migrationsDir), resolveImportSpecifier);
5456
+ const plannedDelta = fromHash === toStorageHash ? void 0 : await planBaselineDelta(statements);
5457
+ if (plannedDelta !== void 0 && !plannedDelta.ok && plannedDelta.failure.reason === "refused") return notOk(plannedDelta.failure.error);
5458
+ const answered = await answerDataLoss(baselineLeg.value, plannedDelta?.ok === true ? plannedDelta.value : void 0, planBaselineDelta);
5459
+ if (!answered.ok) return notOk(answered.failure);
5460
+ const deltaLeg = plannedDelta === void 0 || !plannedDelta.ok || answered.value.delta === void 0 ? plannedDelta : ok(answered.value.delta);
5461
+ const deletes = answered.value.deletes;
4485
5462
  await writePlannedMigrationPackage(baselinePackageDir, null, fromHash, baselineTimestamp, baselineLeg.value);
4486
- if (fromHash === toStorageHash) {
5463
+ if (deltaLeg !== void 0 && !deltaLeg.ok) return notOk(deltaLeg.failure.error);
5464
+ if (deltaLeg === void 0) {
5465
+ const statementsWithoutOperations = reportAppliedStatements(statements.map((statement) => ({
5466
+ statement,
5467
+ operationIndexes: []
5468
+ })), fromContract, aggregate.app.contract(), 0);
4487
5469
  const baselineOps = baselineLeg.value.hasPlaceholders ? [] : baselineLeg.value.plannedOps;
4488
5470
  if (baselineLeg.value.hasPlaceholders) {
4489
5471
  const baselineDir = relative(cwd, baselinePackageDir);
@@ -4494,10 +5476,11 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4494
5476
  to: toStorageHash,
4495
5477
  dir: baselineDir,
4496
5478
  baselineDir,
4497
- operations: [],
5479
+ operations: operationSummaries(baselineLeg.value.plannedOps),
4498
5480
  emittedExtensionDirs,
4499
5481
  ...warnings.length > 0 ? { warnings } : {},
4500
5482
  pendingPlaceholders: true,
5483
+ appliedStatements: [...statementsWithoutOperations, ...deletes],
4501
5484
  summary: "Planned baseline with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
4502
5485
  timings: { total: Date.now() - startTime }
4503
5486
  });
@@ -4517,12 +5500,11 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4517
5500
  emittedExtensionDirs,
4518
5501
  ...preview !== void 0 ? { preview } : {},
4519
5502
  ...warnings.length > 0 ? { warnings } : {},
5503
+ appliedStatements: [...statementsWithoutOperations, ...deletes],
4520
5504
  summary: buildAutoBaselinePlanSummary(baselineOps.length, 0, emittedExtensionDirs.length),
4521
5505
  timings: { total: Date.now() - startTime }
4522
5506
  });
4523
5507
  }
4524
- const deltaLeg = await runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(deltaPackageDir, migrationsDir), resolveImportSpecifier);
4525
- if (!deltaLeg.ok) return notOk(deltaLeg.failure);
4526
5508
  await writePlannedMigrationPackage(deltaPackageDir, fromHash, toStorageHash, deltaTimestamp, deltaLeg.value);
4527
5509
  await writeDestinationSnapshot(toStorageHash);
4528
5510
  const baselineOps = baselineLeg.value.hasPlaceholders ? [] : baselineLeg.value.plannedOps;
@@ -4534,10 +5516,12 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4534
5516
  to: toStorageHash,
4535
5517
  dir: relative(cwd, deltaPackageDir),
4536
5518
  baselineDir: relative(cwd, baselinePackageDir),
4537
- operations: [],
5519
+ operations: operationSummaries(deltaLeg.value.plannedOps),
5520
+ baselineOperations: operationSummaries(baselineLeg.value.plannedOps),
4538
5521
  emittedExtensionDirs,
4539
5522
  ...warnings.length > 0 ? { warnings } : {},
4540
5523
  pendingPlaceholders: true,
5524
+ appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
4541
5525
  summary: "Planned baseline + migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
4542
5526
  timings: { total: Date.now() - startTime }
4543
5527
  });
@@ -4562,14 +5546,32 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4562
5546
  emittedExtensionDirs,
4563
5547
  ...preview !== void 0 ? { preview } : {},
4564
5548
  ...warnings.length > 0 ? { warnings } : {},
5549
+ appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
4565
5550
  summary: buildAutoBaselinePlanSummary(baselineOps.length, deltaOps.length, emittedExtensionDirs.length),
4566
5551
  timings: { total: Date.now() - startTime }
4567
5552
  });
4568
5553
  }
4569
5554
  const timestamp = /* @__PURE__ */ new Date();
4570
5555
  const packageDir = join(appMigrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
4571
- const deltaLeg = await runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(packageDir, migrationsDir), resolveImportSpecifier);
4572
- if (!deltaLeg.ok) return notOk(deltaLeg.failure);
5556
+ const planDelta = (resolved) => runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, resolved.length > 0 && fromHash === toStorageHash, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(packageDir, migrationsDir), resolveImportSpecifier);
5557
+ const plannedDelta = await planDelta(statements);
5558
+ if (!plannedDelta.ok) return notOk(plannedDelta.failure.error);
5559
+ const answered = await answerDataLoss(void 0, plannedDelta.value, planDelta);
5560
+ if (!answered.ok) return notOk(answered.failure);
5561
+ const deltaLeg = ok(answered.value.delta ?? plannedDelta.value);
5562
+ const deletes = answered.value.deletes;
5563
+ if (!deltaLeg.value.hasPlaceholders && deltaLeg.value.plannedOps.length === 0) return ok({
5564
+ ok: true,
5565
+ noOp: true,
5566
+ from: fromHash,
5567
+ to: toStorageHash,
5568
+ operations: [],
5569
+ emittedExtensionDirs,
5570
+ ...warnings.length > 0 ? { warnings } : {},
5571
+ appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
5572
+ summary: "No changes to plan: the statements need no operations",
5573
+ timings: { total: Date.now() - startTime }
5574
+ });
4573
5575
  await writePlannedMigrationPackage(packageDir, fromHash, toStorageHash, timestamp, deltaLeg.value);
4574
5576
  await writeDestinationSnapshot(toStorageHash);
4575
5577
  if (deltaLeg.value.hasPlaceholders) return ok({
@@ -4578,11 +5580,12 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4578
5580
  from: fromHash,
4579
5581
  to: toStorageHash,
4580
5582
  dir: relative(cwd, packageDir),
4581
- operations: [],
5583
+ operations: operationSummaries(deltaLeg.value.plannedOps),
4582
5584
  emittedExtensionDirs,
4583
5585
  ...warnings.length > 0 ? { warnings } : {},
4584
5586
  pendingPlaceholders: true,
4585
5587
  ...fromDefaulted ? { fromDefaulted } : {},
5588
+ appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
4586
5589
  summary: "Planned migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
4587
5590
  timings: { total: Date.now() - startTime }
4588
5591
  });
@@ -4603,6 +5606,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
4603
5606
  ...preview !== void 0 ? { preview } : {},
4604
5607
  ...fromDefaulted ? { fromDefaulted } : {},
4605
5608
  ...warnings.length > 0 ? { warnings } : {},
5609
+ appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
4606
5610
  summary: buildPlanSummary(plannedOps.length, emittedExtensionDirs.length),
4607
5611
  timings: { total: Date.now() - startTime }
4608
5612
  });
@@ -4745,6 +5749,6 @@ async function executeRefListCommand(options) {
4745
5749
  }
4746
5750
  }
4747
5751
  //#endregion
4748
- export { refuseUnknownInvariants as $, executeRefListCommand as A, loadContractSourceWithStack as B, executeDbUpdate as C, executeMigrationPlanCommand as D, executeMigrationNewCommand as E, listRefsByContractHash as F, migrationSpaceListEntriesFromAggregate as G, looksLikePath as H, liveMarkerUse as I, refuseContractSpaceIntegrity as J, preflightRefAdvancement as K, loadAggregateIntegrityViolations as L, findPackageByDirPath as M, formatSourceDiagnostic as N, executeRefAdvancement as O, hasMigrationPath as P, refusePackageCorruptionOnAggregate as Q, loadContractRawSafely as R, executeDbSign as S, executeMigrateShowPlan as T, mapContractAtError as U, loadContractSpaceAggregateForCli as V, mapIntegrityViolations as W, refuseMarkerOutsideGraph as X, refuseDeclaredExtensionTargetMismatch as Y, refuseMissingInvariantPath as Z, disposeEmitQueue as _, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as a, resolveMigrationRef as at, executeContractEmit as b, appliedHashesFromLedger as c, runContractSpaceSeedPhase as ct, buildReadAggregate as d, snapshotVerifierFor as dt, requireDatabaseForLiveMarkerUse as et, buildRefAdvancementFields as f, sourceWarningDiagnostic as ft, deriveStatusEdgeAnnotations as g, createControlClient as h, validateLoadedContract as ht, RECORDED_CONTRACT_REF_FORMS as i, resolveFromForPlan as it, executeRefSetCommand as j, executeRefDeleteCommand as k, buildContractSpaceAggregate as l, runMigrationCheck as lt, computeRefAdvancementName as m, toDeclaredExtensionsFromRaw as mt, DB_UPDATE_POLICY as n, resolveContractRef$1 as nt, advanceRefSafely as o, resolveToForPlan as ot, checkSingleTarget as p, statusForMigrationHash as pt, readMigrationRefs as q, NO_REF_ADVANCEMENT as r, resolveContractRefToSnapshot as rt, appContractStandInFromIdentity as s, retryCommandFor as st, ALL_CONTRACT_REF_FORMS as t, resolveAppTargetPath as tt, buildMigrationSpaceGraphEntries as u, runMigrationList as ut, enrichContract as v, executeDbVerify as w, executeDbInit as x, enumerateCheckSpaces as y, loadContractSource as z };
5752
+ export { refuseUnknownInvariants as $, executeRefListCommand as A, loadContractSourceWithStack as B, executeDbUpdate as C, executeMigrationPlanCommand as D, executeMigrationNewCommand as E, listRefsByContractHash as F, migrationSpaceListEntriesFromAggregate as G, looksLikePath as H, liveMarkerUse as I, refuseContractSpaceIntegrity as J, preflightRefAdvancement as K, loadAggregateIntegrityViolations as L, findPackageByDirPath as M, formatSourceDiagnostic as N, executeRefAdvancement as O, hasMigrationPath as P, refusePackageCorruptionOnAggregate as Q, loadContractRawSafely as R, executeDbSign as S, executeMigrateShowPlan as T, mapContractAtError as U, loadContractSpaceAggregateForCli as V, mapIntegrityViolations as W, refuseMarkerOutsideGraph as X, refuseDeclaredExtensionTargetMismatch as Y, refuseMissingInvariantPath as Z, disposeEmitQueue as _, toDeclaredExtensionsFromRaw as _t, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as a, resolveMigrationRef as at, executeContractEmit as b, appliedHashesFromLedger as c, retryCommandFor as ct, buildReadAggregate as d, runMigrationList as dt, requireDatabaseForLiveMarkerUse as et, buildRefAdvancementFields as f, shellQuoted as ft, deriveStatusEdgeAnnotations as g, statusForMigrationHash as gt, createControlClient as h, statementFlag as ht, RECORDED_CONTRACT_REF_FORMS as i, resolveFromForPlan as it, executeRefSetCommand as j, executeRefDeleteCommand as k, buildContractSpaceAggregate as l, runContractSpaceSeedPhase as lt, computeRefAdvancementName as m, sourceWarningDiagnostic as mt, DB_UPDATE_POLICY as n, resolveContractRef$1 as nt, advanceRefSafely as o, resolveStatements as ot, checkSingleTarget as p, snapshotVerifierFor as pt, readMigrationRefs as q, NO_REF_ADVANCEMENT as r, resolveContractRefToSnapshot as rt, appContractStandInFromIdentity as s, resolveToForPlan as st, ALL_CONTRACT_REF_FORMS as t, resolveAppTargetPath as tt, buildMigrationSpaceGraphEntries as u, runMigrationCheck as ut, enrichContract as v, validateLoadedContract as vt, executeDbVerify as w, executeDbInit as x, enumerateCheckSpaces as y, loadContractSource as z };
4749
5753
 
4750
- //# sourceMappingURL=ref-BCEAH4F9-Bgr9vmL7.mjs.map
5754
+ //# sourceMappingURL=ref-Cc_CTagE-C070Ym7p.mjs.map