@prisma/orm-toolchain 8.0.0-rc.20-dev.8 → 8.0.0-rc.20-dev.9

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.
@@ -8,7 +8,7 @@ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigratio
8
8
  import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
9
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-B12R3P5U-CfBKlBjj.mjs";
10
10
  import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-B0zxbzdl.mjs";
11
- import { $ as errorTargetMigrationNotSupported, B as errorRefSetBundleNotFound, D as errorFromCaught, E as errorFileNotFound, G as errorSnapshotMissing, H as errorRefSetHashNotInGraph, I as errorPathUnreachable, J as errorStatementDidNotResolveLoss, K as errorSpaceNotFound, L as errorPlanForgotTheFlag, P as errorMigrationPlanningFailed, Q as errorStatementUnresolved, R as errorPlanOriginUnknown, S as errorContractValidationFailed, U as errorRuntime, V as errorRefSetEmptySentinel, X as errorStatementNeedsMigrationFile, Y as errorStatementInvalid, Z as errorStatementOriginUnknown, _ as errorAmbiguousMigrationRef, c as cliCommand, ct as readContractEnvelope, d as closeQuietly, dt as resolveContractPath, f as collectDeclaredInvariants, ft as resolveMigrationPaths, gt as statementFlag, h as editFileAction, j as errorMarkerMismatch, k as errorInvalidSpaceId, l as cliErrorFromStructured, mt as selfEmitCommand, n as CliStructuredError$1, nt as getTargetMigrations, ot as printedPath, pt as runCommandAction, q as errorStatementAnswersNoQuestion, r as STORE_ORIGIN_SNAPSHOT_STEPS, rt as mapRefResolutionError, s as chooseAction, st as printedPlanCommand, t as ActionableCliError, tt as errorUnexpected, ut as requireLiveDatabase, v as errorConfigValidation$1, vt as toStructuralEdge, x as errorContractConfigMissing, y as errorConsentUnused, z as errorPlanProducedNoOperations } from "./caught-errors-Bmbi1dBu-DKj0QTCf.mjs";
11
+ import { $ as errorTargetMigrationNotSupported, B as errorRefSetBundleNotFound, D as errorFromCaught, E as errorFileNotFound, G as errorSnapshotMissing, H as errorRefSetHashNotInGraph, I as errorPathUnreachable, J as errorStatementDidNotResolveLoss, K as errorSpaceNotFound, L as errorPlanForgotTheFlag, P as errorMigrationPlanningFailed, Q as errorStatementUnresolved, R as errorPlanOriginUnknown, S as errorContractValidationFailed, U as errorRuntime, V as errorRefSetEmptySentinel, X as errorStatementNeedsMigrationFile, Y as errorStatementInvalid, Z as errorStatementOriginUnknown, _ as errorAmbiguousMigrationRef, c as cliCommand, ct as readContractEnvelope, d as closeQuietly, dt as resolveContractPath, f as collectDeclaredInvariants, ft as resolveMigrationPaths, gt as statementFlag, h as editFileAction, j as errorMarkerMismatch, k as errorInvalidSpaceId, l as cliErrorFromStructured, mt as selfEmitCommand, n as CliStructuredError$1, nt as getTargetMigrations, ot as printedPath, pt as runCommandAction, q as errorStatementAnswersNoQuestion, r as STORE_ORIGIN_SNAPSHOT_STEPS, rt as mapRefResolutionError, s as chooseAction, st as printedPlanCommand, t as ActionableCliError, tt as errorUnexpected, ut as requireLiveDatabase, v as errorConfigValidation$1, vt as toStructuralEdge, x as errorContractConfigMissing, y as errorConsentUnused, yt as writtenMigrationRunCommand, z as errorPlanProducedNoOperations } from "./caught-errors-ChEu1-VS-CYbzB68y.mjs";
12
12
  import { r as getEmittedArtifactPaths, t as emit } from "./exports-BCIlMjIW-DkUBVDzl.mjs";
13
13
  import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-DxpNgxfZ-BfqA-H7V.mjs";
14
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-DM3q3IZC-BC6H6P0X.mjs";
@@ -19,7 +19,7 @@ import { a as writeMigrationTs } from "./migration-ts-DDgjsR1O.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, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, planOriginOf } from "@prisma/orm-framework/components/control";
22
+ import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, planOriginOf } from "@prisma/orm-framework/components/control";
23
23
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
24
24
  import { docsUrlFor, isStructuredError, isStructuredErrorCode, structuredError } from "@prisma/orm-framework/utils/structured-error";
25
25
  import { basename, dirname, isAbsolute, join, relative, resolve } from "pathe";
@@ -34,7 +34,7 @@ import { asNamespaceId } from "@prisma/orm-framework/contract/types";
34
34
  import { isDeepStrictEqual } from "node:util";
35
35
  import { abortable } from "@prisma/orm-framework/utils/abortable";
36
36
  import { resolve as resolve$1 } from "node:path";
37
- //#region ../../../1-framework/3-tooling/cli/dist/ref-CGWRjVD8.mjs
37
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-C1IRwZNR.mjs
38
38
  /**
39
39
  * The meta of a contract that failed to load because the family refused it, such as the columns whose defaults it refused, for the command to report: the refusal's own meta, or the `refusedDefaults` a migration-tools error kept from it.
40
40
  */
@@ -206,12 +206,16 @@ function failedTypeChangeText(change) {
206
206
  case "expressionError": return `The conversion of field "${change.field}" failed with an error in its expression.`;
207
207
  }
208
208
  }
209
- function quoted(command) {
209
+ function quoted$1(command) {
210
210
  return `\`${command}\``;
211
211
  }
212
212
  /** A `db migrate` command as advice prints it. */
213
213
  function dbMigrateCommand(invocation) {
214
- return quoted(cliCommand(invocation, "db migrate"));
214
+ return quoted$1(cliCommand(invocation, "db migrate"));
215
+ }
216
+ /** The steps after filling the migration.ts a `migration plan` wrote with no placeholders: run it, which writes its operations, and apply it. */
217
+ function runWrittenFile(invocation) {
218
+ return `run ${quoted$1(writtenMigrationRunCommand(invocation))} for the directory it writes, and apply it with ${dbMigrateCommand(invocation)}`;
215
219
  }
216
220
  /** The step between filling a planned migration.ts and applying it, which writes its operations. */
217
221
  const RUN_PLANNED_FILE = "run that migration.ts with the `node` command `migration plan` prints";
@@ -229,12 +233,12 @@ function dbUpdateFailedTypeChangeAdvice(change, databaseStorageHash, invocation)
229
233
  verb: "convert",
230
234
  text: change.field
231
235
  })]);
232
- return [chooseAction(`${failedTypeChangeText(change)} Plan the change with ${quoted(plan)}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`)];
236
+ return [chooseAction(`${failedTypeChangeText(change)} Plan the change with ${quoted$1(plan)}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`)];
233
237
  }
234
238
  /** The way out of rows without a value for `db update`, which plans and applies in one step. */
235
239
  function dbUpdateRowsWithoutValueAdvice(reports, databaseStorageHash, invocation) {
236
240
  const flags = backfillFlags(reports);
237
- const planned = flags.length === 0 ? [] : [chooseAction(`Plan it with ${quoted(printedPlanCommand(invocation, databaseStorageHash, flags))}, fill the backfill steps in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`)];
241
+ const planned = flags.length === 0 ? [] : [chooseAction(`Plan it with ${quoted$1(printedPlanCommand(invocation, databaseStorageHash, flags))}, fill the backfill steps in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`)];
238
242
  const [first] = reports;
239
243
  if (first?.reason === "nullValues") return [
240
244
  chooseAction(`Set a value in ${theRows(first.rows)}`),
@@ -243,13 +247,58 @@ function dbUpdateRowsWithoutValueAdvice(reports, databaseStorageHash, invocation
243
247
  ];
244
248
  return [...planned, editFileAction("Make the field optional in the contract source")];
245
249
  }
250
+ function renameToNewMember(report) {
251
+ return statementFlag({
252
+ verb: "rename",
253
+ text: `${report.enumValue}:${report.enumName}.<new member>`
254
+ });
255
+ }
256
+ function newMember(report, invocation) {
257
+ return `To keep that data under a new enum value, add a member to enum "${report.enumName}" in the contract source, run ${quoted$1(cliCommand(invocation, "contract emit"))}`;
258
+ }
259
+ /** The edit the target gives that keeps the data, as the advice writes it. */
260
+ function swapCalls(edit) {
261
+ return `replace ${edit.remove} with ${edit.replaceWith}`;
262
+ }
263
+ const KEPT_VALUE = "where \"<stored value>\" is a stored value the enum keeps";
264
+ /** The run's statements, without the delete of `enumValue` that failed. */
265
+ function otherStatements$1(invocation, enumValue) {
266
+ const failed = statementFlag({
267
+ verb: "delete",
268
+ text: enumValue
269
+ });
270
+ return (invocation.statementArgs ?? []).filter((flag) => flag !== failed);
271
+ }
272
+ /** The way out when a required column's data holds a stored value `db update` removes. */
273
+ function dbUpdateRowsHoldingValueAdvice(report, databaseStorageHash, invocation) {
274
+ const others = otherStatements$1(invocation, report.enumValue);
275
+ const deleteFlag = statementFlag({
276
+ verb: "delete",
277
+ text: report.enumValue
278
+ });
279
+ const rename = chooseAction(`${newMember(report, invocation)}, then run ${quoted$1(cliCommand(invocation, "db update", [...others, renameToNewMember(report)]))}`);
280
+ if (databaseStorageHash === void 0) return [rename, chooseAction(`To keep that data under another stored value, change the stored value ${JSON.stringify(report.value)} to one the enum keeps in the database yourself, then re-run ${quoted$1(cliCommand(invocation, "db update", [...others, deleteFlag]))}`)];
281
+ const { keepDataEdit } = report;
282
+ if (keepDataEdit === void 0) return [rename];
283
+ return [rename, chooseAction(`To keep that data by hand, plan the change with ${quoted$1(printedPlanCommand(invocation, databaseStorageHash, [...others, deleteFlag]))}, ${swapCalls(keepDataEdit)} in the migration.ts it writes, ${KEPT_VALUE}, ${runWrittenFile(invocation)}`)];
284
+ }
285
+ function migrateRowsHoldingValueAdvice(report, failedMigration, invocation) {
286
+ const { file, run } = failedMigrationFile(failedMigration);
287
+ const { keepDataEdit } = report;
288
+ const byHand = keepDataEdit === void 0 ? [] : [editFileAction(`To keep that data by hand, ${swapCalls(keepDataEdit)} in ${file}, ${KEPT_VALUE}, ${run}, and re-run ${dbMigrateCommand(invocation)}`)];
289
+ if (failedMigration === void 0) return byHand;
290
+ return [replan(`${newMember(report, invocation)}, delete`, [renameToNewMember(report)], failedMigration, `\`${statementFlag({
291
+ verb: "delete",
292
+ text: report.enumValue
293
+ })}\``, `put any code you copied into the migration.ts it writes, ${runWrittenFile(invocation)}`), ...byHand];
294
+ }
246
295
  /**
247
296
  * The way out of rows without a value for `db init`: a migration plan needs an origin contract,
248
297
  * which a database that `db init` never initialized does not have.
249
298
  */
250
299
  function dbInitRowsWithoutValueAdvice(reports, invocation) {
251
300
  const field = reports[0]?.field;
252
- return [editFileAction(`Make ${field === void 0 ? "it" : `field "${field}"`} optional in the contract source, run ${quoted(cliCommand(invocation, "db init"))}, then make it required with ${quoted(cliCommand(invocation, "db update"))}, which says how to give the rows a value`)];
301
+ return [editFileAction(`Make ${field === void 0 ? "it" : `field "${field}"`} optional in the contract source, run ${quoted$1(cliCommand(invocation, "db init"))}, then make it required with ${quoted$1(cliCommand(invocation, "db update"))}, which says how to give the rows a value`)];
253
302
  }
254
303
  function failedMigrationText(failed, invocation) {
255
304
  const dirName = basename(failed.directory);
@@ -265,14 +314,14 @@ function failedMigrationText(failed, invocation) {
265
314
  * Planning the failed migration again with `flags`. `opening` is the words before the directory,
266
315
  * so the sentence can start the advice or follow why it is needed.
267
316
  */
268
- function replan(opening, flags, failed, except = void 0) {
317
+ function replan(opening, flags, failed, except = void 0, afterPlan = `fill in the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(failed.invocation)}`) {
269
318
  const others = except === void 0 ? OTHER_STATEMENTS : `${OTHER_STATEMENTS} except any ${except}`;
270
319
  const plan = printedPlanCommand(failed.invocation, failed.from, [
271
320
  "--name",
272
321
  failed.name,
273
322
  ...flags
274
323
  ]);
275
- return chooseAction(`${opening} \`${failed.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${quoted(plan)}, ${others}, fill in the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(failed.invocation)}`);
324
+ return chooseAction(`${opening} \`${failed.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${quoted$1(plan)}, ${others}, ${afterPlan}`);
276
325
  }
277
326
  /**
278
327
  * Where to fix code written in the failed migration's `migration.ts`, and the command that runs the
@@ -296,7 +345,7 @@ function migrateFailedTypeChangeAdvice(change, failedMigration, invocation) {
296
345
  verb: "convert",
297
346
  text: change.field
298
347
  });
299
- if (failedMigration === void 0) return [chooseAction(`${changeText} Plan the type change again with ${quoted(printedPlanCommand(invocation, void 0, [convert]))}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`)];
348
+ if (failedMigration === void 0) return [chooseAction(`${changeText} Plan the type change again with ${quoted$1(printedPlanCommand(invocation, void 0, [convert]))}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`)];
300
349
  const deleted = `\`${statementFlag({
301
350
  verb: "delete",
302
351
  text: change.field
@@ -332,7 +381,7 @@ function migrateRowsWithoutValueAdvice(reports, failedMigration, invocation) {
332
381
  }
333
382
  function keepOptional(fields, pronoun, failedMigration, invocation) {
334
383
  const plan = printedPlanCommand(invocation, failedMigration.from, ["--name", failedMigration.name]);
335
- return editFileAction(`Keep ${fields} optional: make ${pronoun} optional in the contract source again, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), and plan it again with ${quoted(plan)}, ${OTHER_STATEMENTS}, put back any code you copied, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`);
384
+ return editFileAction(`Keep ${fields} optional: make ${pronoun} optional in the contract source again, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), and plan it again with ${quoted$1(plan)}, ${OTHER_STATEMENTS}, put back any code you copied, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`);
336
385
  }
337
386
  function theRows(rows) {
338
387
  return rows === 1 ? "that row" : `those ${rows} rows`;
@@ -341,11 +390,11 @@ function fieldList(reports) {
341
390
  return reports.map(({ field }) => field === void 0 ? void 0 : `"${field}"`).filter((field) => field !== void 0).join(", ");
342
391
  }
343
392
  function migrateSchemaCheckAdvice(failedMigration, invocation) {
344
- const emit = quoted(cliCommand(invocation, "contract emit"));
393
+ const emit = quoted$1(cliCommand(invocation, "contract emit"));
345
394
  const plan = printedPlanCommand(invocation, failedMigration?.from, failedMigration === void 0 ? [] : ["--name", failedMigration.name]);
346
395
  const directory = failedMigration === void 0 ? "the failed migration's directory" : `\`${failedMigration.directory}\``;
347
396
  const { file, run } = failedMigrationFile(failedMigration);
348
- return [editFileAction(`If the contract source does not describe the schema you want, change it to resolve the issues listed, re-run ${emit}, delete ${directory} (copy any code you wrote in its migration.ts first), plan it again with ${quoted(plan)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}`), editFileAction(`If ${file} does not reach its destination contract, for example after a hand edit, change its operations to resolve the issues listed, ${run}, and run ${dbMigrateCommand(invocation)}`)];
397
+ return [editFileAction(`If the contract source does not describe the schema you want, change it to resolve the issues listed, re-run ${emit}, delete ${directory} (copy any code you wrote in its migration.ts first), plan it again with ${quoted$1(plan)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}`), editFileAction(`If ${file} does not reach its destination contract, for example after a hand edit, change its operations to resolve the issues listed, ${run}, and run ${dbMigrateCommand(invocation)}`)];
349
398
  }
350
399
  /** The way out when objects in the database keep an operation from running. */
351
400
  function blockingObjectsAdvice(objects, rerun) {
@@ -362,6 +411,7 @@ function migrateAdvice(failure, facts, failedOnDisk, invocation) {
362
411
  if (blockingObjects !== void 0) return blockingObjectsAdvice(blockingObjects, cliCommand(invocation, "db migrate", invocation.rerunArgs ?? []));
363
412
  if (facts.failedTypeChange !== void 0) return migrateFailedTypeChangeAdvice(facts.failedTypeChange, failedMigration, invocation);
364
413
  if (facts.rowsWithoutValue !== void 0) return migrateRowsWithoutValueAdvice(facts.rowsWithoutValue, failedMigration, invocation);
414
+ if (facts.rowsHoldingValue !== void 0) return migrateRowsHoldingValueAdvice(facts.rowsHoldingValue, failedMigration, invocation);
365
415
  if (schemaCheckIssues(failure) !== void 0) return migrateSchemaCheckAdvice(failedMigration, invocation);
366
416
  if (facts.failedPrecheck !== void 0) return migrateFailedPrecheckAdvice(facts.failedPrecheck, invocation);
367
417
  return [chooseAction(`Fix the issue and re-run \`${cliCommand(invocation, "db migrate", ["--to", "<contract>"])}\``)];
@@ -439,7 +489,7 @@ function dbUpdateRunnerFailureError(failure, facts, context) {
439
489
  const { databaseStorageHash, invocation } = context;
440
490
  const update = cliCommand(invocation, "db update");
441
491
  const { blockingObjects } = failure.meta;
442
- return runnerFailureError(failure, blockingObjects !== void 0 ? blockingObjectsAdvice(blockingObjects, cliCommand(invocation, "db update", invocation.rerunArgs ?? [])) : facts.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeAdvice(facts.failedTypeChange, databaseStorageHash, invocation) : facts.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueAdvice(facts.rowsWithoutValue, databaseStorageHash, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${update}\``)] : [chooseAction(`Inspect the reported conflict, reconcile schema drift if needed, then re-run \`${update}\``)]);
492
+ return runnerFailureError(failure, blockingObjects !== void 0 ? blockingObjectsAdvice(blockingObjects, cliCommand(invocation, "db update", invocation.rerunArgs ?? [])) : facts.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeAdvice(facts.failedTypeChange, databaseStorageHash, invocation) : facts.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueAdvice(facts.rowsWithoutValue, databaseStorageHash, invocation) : facts.rowsHoldingValue !== void 0 ? dbUpdateRowsHoldingValueAdvice(facts.rowsHoldingValue, databaseStorageHash, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${update}\``)] : [chooseAction(`Inspect the reported conflict, reconcile schema drift if needed, then re-run \`${update}\``)]);
443
493
  }
444
494
  function startText(fromHash) {
445
495
  return fromHash === "empty" ? "the empty contract (the space has no marker)" : `the contract its marker names ("${fromHash}")`;
@@ -488,6 +538,96 @@ function errorExtensionNoInvariantPath(space) {
488
538
  }
489
539
  });
490
540
  }
541
+ function editsText(edits) {
542
+ return edits.map(({ remove, replaceWith }) => `replace ${remove} with ${replaceWith}`).join(", and ");
543
+ }
544
+ function quoted(command) {
545
+ return `\`${command}\``;
546
+ }
547
+ /** How `migration plan` says to keep the data of a subject: answer with a delete, then make the edits in the file it writes. */
548
+ function migrationPlanKeepDataEditAdvice(invocation) {
549
+ return (subject, edits) => ({
550
+ lead: void 0,
551
+ ways: [`To keep that data, answer with ${statementFlag({
552
+ verb: "delete",
553
+ text: subject
554
+ })}, then in the migration.ts this command writes ${editsText(edits)}, ${runWrittenFile(invocation)}.`]
555
+ });
556
+ }
557
+ /** The run's statements, without the delete that answers `subject`. */
558
+ function otherStatements(invocation, subject) {
559
+ const answer = statementFlag({
560
+ verb: "delete",
561
+ text: subject
562
+ });
563
+ return (invocation.statementArgs ?? []).filter((flag) => flag !== answer);
564
+ }
565
+ /** Two runs of `db update`: one renames the member to a new member with the new stored value, and the next renames it back. */
566
+ function twoRuns(invocation, subject) {
567
+ const dot = subject.lastIndexOf(".");
568
+ const enumName = subject.slice(0, dot);
569
+ const member = subject.slice(dot + 1);
570
+ const emit = quoted(cliCommand(invocation, "contract emit"));
571
+ const rename = statementFlag({
572
+ verb: "rename",
573
+ text: `${subject}:${enumName}.<new member>`
574
+ });
575
+ return `To keep it with db update, rename member ${member} of enum ${enumName} in the contract source to a name the enum does not have, keep its new stored value, run ${emit}, and run ${quoted(cliCommand(invocation, "db update", [...otherStatements(invocation, subject), rename]))}. Then rename the member back to ${member}, run ${emit}, and run ${quoted(cliCommand(invocation, "db update"))} again.`;
576
+ }
577
+ /**
578
+ * How `db update` says to keep the data of a subject: it cannot in one run. It plans the change
579
+ * with `migration plan` from the contract the database is at, when a migration ends there, or
580
+ * renames the member to a new member and back in two runs.
581
+ */
582
+ function dbUpdateKeepDataEditAdvice(invocation, databaseStorageHash) {
583
+ return (subject, edits, others) => {
584
+ const deleteFlag = statementFlag({
585
+ verb: "delete",
586
+ text: subject
587
+ });
588
+ const swaps = edits.some(({ swapsValues }) => swapsValues === true);
589
+ const lead = swaps ? `db update cannot keep that data, because members of the enum swap stored values, and ${deleteFlag} removes it.` : `db update cannot keep that data in one run, and ${deleteFlag} removes it.`;
590
+ if (databaseStorageHash === void 0) return swaps ? {
591
+ lead: `${lead} Only a migration can keep it, and no migration ends at the contract the database is at.`,
592
+ ways: []
593
+ } : {
594
+ lead,
595
+ ways: [twoRuns(invocation, subject)]
596
+ };
597
+ const deletes = [subject, ...others].map((text) => statementFlag({
598
+ verb: "delete",
599
+ text
600
+ }));
601
+ return {
602
+ lead,
603
+ ways: [`To keep it, plan the change with ${quoted(printedPlanCommand(invocation, databaseStorageHash, [...otherStatements(invocation, subject).filter((flag) => !deletes.includes(flag)), ...deletes]))}, in the migration.ts it writes ${editsText(edits)}, ${runWrittenFile(invocation)}.`, ...swaps ? [] : [twoRuns(invocation, subject)]]
604
+ };
605
+ };
606
+ }
607
+ /**
608
+ * The planner's refusal as the CLI reports it. When a conflict can be written by hand, its next
609
+ * action prints the plan to write it in: the run's statements without the ones the conflict leaves
610
+ * out, from the contract the database is at when that is known.
611
+ */
612
+ function planningRefusedError(conflicts, context) {
613
+ const refused = errorMigrationPlanningFailed({ conflicts });
614
+ const leaveOut = new Set(conflicts.flatMap(({ leaveOut: statements }) => (statements ?? []).map((statement) => JSON.stringify(statement))));
615
+ if (leaveOut.size === 0) return refused;
616
+ const left = context.statements.filter(({ verb }) => verb !== "delete" && verb !== "allow").filter((_, index) => {
617
+ const resolved = context.resolved[index];
618
+ return resolved !== void 0 && leaveOut.has(JSON.stringify(resolved));
619
+ });
620
+ const kept = context.statements.filter((statement) => !left.includes(statement));
621
+ const plan = printedPlanCommand(context.invocation, context.from, [...context.to === void 0 ? [] : ["--to", context.to], ...kept.map(statementFlag)]);
622
+ const action = chooseAction(`To write the rewrites by hand, plan the change without ${left.map(statementFlag).join(" and ")} with \`${plan}\`, add the rewrites the message describes to the migration.ts it writes, ${runWrittenFile(context.invocation)}`);
623
+ return new ActionableCliError(refused.code, refused.message, {
624
+ why: refused.why,
625
+ fix: refused.fix ?? action.label,
626
+ nextActions: [action],
627
+ ...ifDefined("meta", refused.meta),
628
+ ...ifDefined("docsUrl", refused.docsUrl)
629
+ });
630
+ }
491
631
  function formsFix$1(verb) {
492
632
  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.";
493
633
  }
@@ -583,14 +723,40 @@ function parseRenameStatement(statement) {
583
723
  to: to.value
584
724
  });
585
725
  }
726
+ const STATEMENT_VERBS = [
727
+ "rename",
728
+ "delete",
729
+ "allow",
730
+ "convert",
731
+ "backfill"
732
+ ];
733
+ function isStatementVerb(verb) {
734
+ return STATEMENT_VERBS.includes(verb);
735
+ }
736
+ function isPlannedStatement(statement) {
737
+ return statement.verb === "rename" || statement.verb === "convert" || statement.verb === "backfill";
738
+ }
739
+ /** The field a `convert` and a `delete` of the same run both name, which conflict; `undefined` when none does. */
740
+ function convertAndDelete(statements) {
741
+ const deleted = new Set(statements.filter(({ verb }) => verb === "delete").map(({ text }) => text));
742
+ return statements.find(({ verb, text }) => verb === "convert" && deleted.has(text))?.text;
743
+ }
744
+ /** Each kind of thing a statement or a question can name, as messages write it. */
745
+ const ENTITY_WORDS = {
746
+ model: "model",
747
+ field: "field",
748
+ enumValue: "enum value",
749
+ storage: "storage"
750
+ };
586
751
  const NAMESPACE_RENAMES = "namespace";
752
+ const ENUM_VALUE_RENAMES = "enumValue";
587
753
  const MODEL_RENAMES = "model";
588
754
  const FIELD_RENAMES = "field";
589
755
  const LISTED_LIMIT = 20;
590
756
  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.";
591
757
  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.";
592
758
  const VALUE_OBJECT_FIX = "Leave value objects and their fields out of the statements.";
593
- const REPEATED_NAME_FIX = "Give each model or field at most one statement, and each new name to one model or field only.";
759
+ const REPEATED_NAME_FIX = "Give each model, field or enum value at most one statement, and each new name to one model, field or enum value only.";
594
760
  function qualifiedModel(coordinate) {
595
761
  return modelDisplayName(coordinate);
596
762
  }
@@ -603,6 +769,16 @@ function displayName(namespaceId, name) {
603
769
  function qualifiedField(coordinate) {
604
770
  return `${qualifiedModel(coordinate)}.${coordinate.field}`;
605
771
  }
772
+ /** An enum as a contract names it in messages: with its namespace only when the contract has several. */
773
+ function enumText(contract, namespaceId, name) {
774
+ return modelStatementText(contract.contract, {
775
+ namespaceId: asNamespaceId(namespaceId),
776
+ model: name
777
+ });
778
+ }
779
+ function qualifiedEnumValue(coordinate) {
780
+ return `${displayName(coordinate.namespaceId, coordinate.enum)}.${coordinate.member}`;
781
+ }
606
782
  function listed(names) {
607
783
  if (names.length === 0) return "(none)";
608
784
  const sorted = [...names].sort();
@@ -700,6 +876,94 @@ function lookupModel(contract, namespaceId, name) {
700
876
  ...missing(`the ${contract.name} contract has no model "${name}" (models: ${listed(modelNames(contract))})`)
701
877
  };
702
878
  }
879
+ function enumsOf(namespace) {
880
+ return namespace.enum ?? {};
881
+ }
882
+ function lookupEnum(contract, namespaceId, name) {
883
+ const namespaces = contract.contract.domain.namespaces;
884
+ const declaring = Object.entries(namespaces).filter(([id, namespace]) => (namespaceId === void 0 || id === namespaceId) && Object.hasOwn(enumsOf(namespace), name));
885
+ const [only] = declaring;
886
+ if (only !== void 0 && declaring.length === 1) {
887
+ const members = enumsOf(only[1])[name]?.members.map((member) => member.name) ?? [];
888
+ return {
889
+ kind: "found",
890
+ namespaceId: only[0],
891
+ members
892
+ };
893
+ }
894
+ if (declaring.length > 1) {
895
+ const candidates = declaring.map(([id]) => `${id}.${name}`).sort();
896
+ return {
897
+ kind: "refused",
898
+ reason: `"${name}" is an enum in more than one namespace of the ${contract.name} contract (${listed(candidates)})`,
899
+ fix: `Name the enum with its namespace, for example ${candidates[0]}.`
900
+ };
901
+ }
902
+ const enums = Object.entries(namespaces).flatMap(([id, namespace]) => namespaceId === void 0 || id === namespaceId ? Object.keys(enumsOf(namespace)) : []);
903
+ const within = namespaceId === void 0 ? "" : ` in namespace "${namespaceId}"`;
904
+ const there = namespaceId === void 0 ? "" : " there";
905
+ const known = enums.length === 0 ? "" : ` (enums${there}: ${listed([...new Set(enums)])})`;
906
+ return {
907
+ kind: "missing",
908
+ ...missing(`the ${contract.name} contract has no enum "${name}"${within}${known}`)
909
+ };
910
+ }
911
+ function readEnumValue(state, side, namespaceId, name, member) {
912
+ const contract = side === "old" ? state.origin : state.destination;
913
+ const lookup = lookupEnum(contract, (side === "old" && namespaceId !== void 0 ? state.originOfRenamedNamespace.get(namespaceId) : void 0) ?? namespaceId, name);
914
+ if (lookup.kind !== "found") return notOk(lookup);
915
+ if (!lookup.members.includes(member)) return notOk(missing(`the ${contract.name} enum "${enumText(contract, lookup.namespaceId, name)}" has no value "${member}" (values: ${listed(lookup.members)})`));
916
+ return ok({
917
+ entity: "enumValue",
918
+ coordinate: {
919
+ namespaceId: asNamespaceId(lookup.namespaceId),
920
+ enum: name,
921
+ member
922
+ },
923
+ members: lookup.members
924
+ });
925
+ }
926
+ function declaresEnums(contract) {
927
+ return Object.values(contract.contract.domain.namespaces).some((namespace) => Object.keys(enumsOf(namespace)).length > 0);
928
+ }
929
+ function readingText(reading) {
930
+ switch (reading.entity) {
931
+ case "model": return `namespace "${reading.coordinate.namespaceId}" model "${reading.coordinate.model}"`;
932
+ case "field": return `model "${reading.coordinate.model}" field "${reading.coordinate.field}"`;
933
+ case "enumValue": return `enum "${reading.coordinate.enum}" value "${reading.coordinate.member}"`;
934
+ }
935
+ }
936
+ function qualifiedReading(reading) {
937
+ switch (reading.entity) {
938
+ case "model": return qualifiedModel(reading.coordinate);
939
+ case "field": return qualifiedField(reading.coordinate);
940
+ case "enumValue": return qualifiedEnumValue(reading.coordinate);
941
+ }
942
+ }
943
+ /** What a reading sits in, which a rename can give another name so that the reading stops colliding. */
944
+ function readingContainer(reading) {
945
+ switch (reading.entity) {
946
+ case "model": return `namespace "${reading.coordinate.namespaceId}"`;
947
+ case "field": return `model "${reading.coordinate.model}"`;
948
+ case "enumValue": return `enum "${reading.coordinate.enum}"`;
949
+ }
950
+ }
951
+ /**
952
+ * An enum value reading beside the model and field readings of the same name: the one that
953
+ * resolves, or a refusal naming each reading when more than one does.
954
+ */
955
+ function withEnumValueReading(text, other, enumValue) {
956
+ if (!enumValue.ok) return other;
957
+ if (!other.ok) return enumValue;
958
+ const readings = [other.value, enumValue.value];
959
+ const nameable = readings.filter((reading) => qualifiedReading(reading) !== text);
960
+ const unnameable = readings.find((reading) => qualifiedReading(reading) === text);
961
+ const written = nameable.map((reading) => `${qualifiedReading(reading)} for the ${ENTITY_WORDS[reading.entity]}`);
962
+ return notOk({
963
+ reason: `"${text}" resolves both as ${readingText(other.value)} and as ${readingText(enumValue.value)}`,
964
+ fix: unnameable === void 0 ? `Name it with its namespace: ${written.join(", ")}.` : `Write ${written.join(", ")}. The ${ENTITY_WORDS[unnameable.entity]} cannot be named apart from it: rename ${readings.map(readingContainer).join(" or ")} so that only one reading resolves.`
965
+ });
966
+ }
703
967
  function readModel(state, side, namespaceId, name) {
704
968
  const lookup = lookupModel(side === "old" ? state.origin : state.destination, namespaceId, name);
705
969
  if (lookup.kind !== "found") return notOk(lookup);
@@ -769,6 +1033,7 @@ function readField(state, side, namespaceId, modelName, field) {
769
1033
  }
770
1034
  function readSide(state, side, segments) {
771
1035
  if (segments.length === 1) return readModel(state, side, void 0, segments[0]);
1036
+ const contract = side === "old" ? state.origin : state.destination;
772
1037
  if (segments.length === 3) {
773
1038
  const [first, second, third] = segments;
774
1039
  const qualified = readField(state, side, first, second, third);
@@ -777,24 +1042,54 @@ function readSide(state, side, segments) {
777
1042
  reason: `"${first}.${second}.${third}" resolves both as namespace "${first}" model "${second}" field "${third}" and as model "${first}" field "${second}.${third}"`,
778
1043
  fix: `Give the field a stored name without "." with @map, or rename namespace "${first}" or model "${first}", so that only one reading resolves.`
779
1044
  });
780
- return qualified.ok || !dotted.ok ? qualified : dotted;
1045
+ const asField = qualified.ok || !dotted.ok ? qualified : dotted;
1046
+ const asEnumValue = readEnumValue(state, side, first, second, third);
1047
+ if (asField.ok || asEnumValue.ok || !declaresEnums(contract)) return withEnumValueReading(segments.join("."), asField, asEnumValue);
1048
+ return notOk({
1049
+ ...missing(`"${segments.join(".")}" resolves neither as namespace.Model.field (${asField.failure.reason}) nor as namespace.Enum.value (${asEnumValue.failure.reason})`),
1050
+ ...ifDefined("modelWithoutCounterpart", asField.failure.modelWithoutCounterpart)
1051
+ });
781
1052
  }
782
1053
  const [first, second] = segments;
783
1054
  const asModel = readModel(state, side, first, second);
784
1055
  const asField = readField(state, side, void 0, first, second);
1056
+ const asEnumValue = readEnumValue(state, side, void 0, first, second);
785
1057
  if (asModel.ok && asField.ok) return notOk({
786
1058
  reason: `"${first}.${second}" resolves both as namespace "${first}" model "${second}" and as model "${first}" field "${second}"`,
787
1059
  fix: "Write the field as namespace.Model.field if you mean the field."
788
1060
  });
789
- if (asModel.ok) return asModel;
790
- if (asField.ok) return asField;
791
- const contract = side === "old" ? state.origin : state.destination;
792
- if (!Object.keys(contract.contract.domain.namespaces).some((id) => id !== UNBOUND_NAMESPACE_ID)) return asField;
1061
+ if (asModel.ok || asField.ok) return withEnumValueReading(`${first}.${second}`, asModel.ok ? asModel : asField, asEnumValue);
1062
+ if (asEnumValue.ok) return asEnumValue;
1063
+ const names = containerNames(contract);
1064
+ if (names.enums.has(first) && !names.namespaces.has(first) && !names.models.has(first)) return asEnumValue;
1065
+ const hasNamespaces = names.namespaces.size > 0;
1066
+ const hasEnums = declaresEnums(contract);
1067
+ if (!hasNamespaces && !hasEnums) return asField;
1068
+ const readings = [
1069
+ ...hasNamespaces ? [`as namespace.Model (${asModel.failure.reason})`] : [],
1070
+ `as Model.field (${asField.failure.reason})`,
1071
+ ...hasEnums ? [`as Enum.value (${asEnumValue.failure.reason})`] : []
1072
+ ];
1073
+ const sameButCase = [
1074
+ ...names.namespaces,
1075
+ ...names.models,
1076
+ ...names.enums
1077
+ ].find((name) => name !== first && name.toLowerCase() === first.toLowerCase());
793
1078
  return notOk({
794
- ...missing(`"${first}.${second}" resolves neither as namespace.Model (${asModel.failure.reason}) nor as Model.field (${asField.failure.reason})`),
1079
+ reason: `"${first}.${second}" resolves neither ${readings.slice(0, -1).join(", ")}${readings.length > 2 ? "," : ""} nor ${readings.at(-1)}`,
1080
+ fix: sameButCase === void 0 ? CHECK_NAMES_FIX : `Names match exactly, including case: write ${sameButCase}, not ${first}.`,
795
1081
  ...ifDefined("modelWithoutCounterpart", asField.failure.modelWithoutCounterpart)
796
1082
  });
797
1083
  }
1084
+ /** The names a side's first segment can be: a namespace, a model, or an enum of the contract. */
1085
+ function containerNames(contract) {
1086
+ const namespaces = Object.entries(contract.contract.domain.namespaces);
1087
+ return {
1088
+ namespaces: new Set(namespaces.flatMap(([id]) => id === UNBOUND_NAMESPACE_ID ? [] : [id])),
1089
+ models: new Set(namespaces.flatMap(([, namespace]) => Object.keys(namespace.models))),
1090
+ enums: new Set(namespaces.flatMap(([, namespace]) => Object.keys(enumsOf(namespace))))
1091
+ };
1092
+ }
798
1093
  function resolveModelRename(state, statement, from, to) {
799
1094
  const fromKey = `${MODEL_RENAMES}:${qualifiedModel(from)}`;
800
1095
  const toKey = `${MODEL_RENAMES}:${qualifiedModel(to)}`;
@@ -873,6 +1168,32 @@ function resolveFieldRename(state, statement, from, to) {
873
1168
  to: to.coordinate
874
1169
  });
875
1170
  }
1171
+ function resolveEnumValueRename(state, statement, from, to) {
1172
+ const oldEnum = enumText(state.origin, from.coordinate.namespaceId, from.coordinate.enum);
1173
+ const newEnum = enumText(state.destination, to.coordinate.namespaceId, to.coordinate.enum);
1174
+ const toNamespaceInOrigin = state.originOfRenamedNamespace.get(to.coordinate.namespaceId) ?? to.coordinate.namespaceId;
1175
+ if (from.coordinate.namespaceId !== toNamespaceInOrigin || from.coordinate.enum !== to.coordinate.enum) return notOk(errorStatementInvalid(statement, `The old name is a value of enum "${oldEnum}" and the new name a value of enum "${newEnum}"; a value cannot move between enums.`, `Rename a value within one enum: --${statement.verb} ${statement.from.join(".")}:${statement.from.slice(0, -1).join(".")}.<new name>.`));
1176
+ const oldMember = from.coordinate.member;
1177
+ const newMember = to.coordinate.member;
1178
+ const fromKey = `${ENUM_VALUE_RENAMES}:${qualifiedEnumValue(from.coordinate)}`;
1179
+ const toKey = `${ENUM_VALUE_RENAMES}:${qualifiedEnumValue(to.coordinate)}`;
1180
+ if (state.renamedFrom.has(fromKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames "${qualifiedEnumValue(from.coordinate)}".`, REPEATED_NAME_FIX));
1181
+ if (state.renamedTo.has(toKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames a value to "${qualifiedEnumValue(to.coordinate)}".`, REPEATED_NAME_FIX));
1182
+ if (oldMember === newMember) return notOk(errorStatementInvalid(statement, `The statement renames enum value "${qualifiedEnumValue(from.coordinate)}" to itself.`, `Leave out --${statement.verb} ${statement.text}.`));
1183
+ const newInOrigin = from.members.includes(newMember);
1184
+ const oldInDestination = to.members.includes(oldMember);
1185
+ if (newInOrigin && oldInDestination) return notOk(swapRefusal(statement, "enumValue", `${newEnum}.${oldMember}`, `${newEnum}.${newMember}`));
1186
+ if (newInOrigin) return notOk(errorStatementUnresolved(statement, `The value "${newMember}" already exists in the origin enum "${oldEnum}", so it cannot be the new name of a value.`, CHECK_NAMES_FIX));
1187
+ if (oldInDestination) return notOk(errorStatementUnresolved(statement, `The value "${oldMember}" still exists in the destination enum "${newEnum}", so it was not renamed.`, CHECK_NAMES_FIX));
1188
+ state.renamedFrom.add(fromKey);
1189
+ state.renamedTo.add(toKey);
1190
+ return ok({
1191
+ kind: "rename",
1192
+ entity: "enumValue",
1193
+ from: from.coordinate,
1194
+ to: to.coordinate
1195
+ });
1196
+ }
876
1197
  /**
877
1198
  * Two names that trade places: each is an old name and a new name, which one plan cannot do.
878
1199
  * Statements resolve against contracts, so the swap takes three plans through a temporary name.
@@ -881,8 +1202,9 @@ function swapRefusal(statement, entity, first, second) {
881
1202
  const verb = statement.verb;
882
1203
  const oldName = statement.from.join(".");
883
1204
  const newName = statement.to.join(".");
884
- const temporary = entity === "field" ? `${statement.to.slice(0, -1).join(".")}.<temporary name>` : "<temporary name>";
885
- 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}.`);
1205
+ const temporary = entity === "model" ? "<temporary name>" : `${statement.to.slice(0, -1).join(".")}.<temporary name>`;
1206
+ const keptNames = entity === "enumValue" ? " If the members keep their names and only their stored values trade places, leave out the statement: the plan asks about each value and names the edits that keep its data." : "";
1207
+ 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}.${keptNames}`);
886
1208
  }
887
1209
  /**
888
1210
  * The old side does not resolve. Says so in terms of what the user can do next when the statement
@@ -980,9 +1302,15 @@ function resolveStatement(state, statement, later) {
980
1302
  const from = readSide(state, "old", statement.from);
981
1303
  if (!from.ok) return notOk(oldSideRefusal(state, statement, later, from.failure));
982
1304
  const to = readSide(state, "new", statement.to);
1305
+ if (!to.ok && from.value.entity === "enumValue" && statement.to.length === 1) {
1306
+ const enumPart = statement.from.slice(0, -1).join(".");
1307
+ return notOk(errorStatementUnresolved(statement, sentence(to.failure.reason), `Write the new name with its enum: --${statement.verb} ${statement.from.join(".")}:${enumPart}.${statement.to[0]}.`));
1308
+ }
983
1309
  if (!to.ok) return notOk(unresolved(statement, to.failure));
984
1310
  if (from.value.entity === "model" && to.value.entity === "model") return resolveModelRename(state, statement, from.value.coordinate, to.value.coordinate);
985
1311
  if (from.value.entity === "field" && to.value.entity === "field") return resolveFieldRename(state, statement, from.value, to.value);
1312
+ if (from.value.entity === "enumValue" && to.value.entity === "enumValue") return resolveEnumValueRename(state, statement, from.value, to.value);
1313
+ if (from.value.entity === "enumValue" || to.value.entity === "enumValue") return notOk(errorStatementInvalid(statement, "The statement names an enum value on one side and a model or field on the other.", "Rename an enum value to another value of the same enum, as Enum.value:Enum.<new name>."));
986
1314
  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)));
987
1315
  }
988
1316
  function typeText(type) {
@@ -1065,6 +1393,21 @@ function deleteOfRenamed(deletes, renames) {
1065
1393
  }
1066
1394
  }
1067
1395
  /**
1396
+ * A delete that names what a rename among `statements` renames, which contradict each other: the
1397
+ * commands check it before they plan, since they hand the deletes to their questions, not here.
1398
+ */
1399
+ function renamedAndDeleted(statements) {
1400
+ const renames = statements.flatMap((entry) => {
1401
+ if (entry.verb !== "rename") return [];
1402
+ const parsed = parseRenameStatement({
1403
+ ...entry,
1404
+ verb: entry.verb
1405
+ });
1406
+ return parsed.ok ? [parsed.value] : [];
1407
+ });
1408
+ return deleteOfRenamed(statements.filter(({ verb }) => verb === "delete"), renames);
1409
+ }
1410
+ /**
1068
1411
  * Resolves the statements a user gave against the origin and destination contracts. Renames
1069
1412
  * resolve first, in the order given, so a convert or backfill statement can name a renamed field
1070
1413
  * by its new name wherever it is given; the result keeps the order given. A delete or allow
@@ -1188,6 +1531,16 @@ function destinationField(coordinate, contracts) {
1188
1531
  field: coordinate.field
1189
1532
  };
1190
1533
  }
1534
+ /** An enum value under the namespace a namespace rename of `contracts` gives its enum, when the destination has the enum there. */
1535
+ function renamedEnumValue(value, contracts) {
1536
+ for (const statement of resolvedRenames(contracts)) if (statement.kind === "rename" && statement.entity === "namespace" && statement.from === value.namespaceId) {
1537
+ const renamed = {
1538
+ ...value,
1539
+ namespaceId: statement.to
1540
+ };
1541
+ return contracts.destination?.domain.namespaces[statement.to]?.enum?.[value.enum] === void 0 ? void 0 : renamed;
1542
+ }
1543
+ }
1191
1544
  /**
1192
1545
  * The subject as a statement names it: `Model` or `Model.field`, with the namespace when its
1193
1546
  * contract has several, or the storage name when no model stores what the operation is about. A
@@ -1204,6 +1557,10 @@ function subjectText(subject, contracts) {
1204
1557
  const renamed = renamedModel(subject, contracts);
1205
1558
  return `${renamed === void 0 || contracts.destination === void 0 ? modelStatementText(contracts.origin, subject) : modelStatementText(contracts.destination, renamed)}.${subject.field}`;
1206
1559
  }
1560
+ case "enumValue": {
1561
+ const renamed = renamedEnumValue(subject, contracts);
1562
+ return renamed === void 0 || contracts.destination === void 0 ? enumValueStatementText(contracts.origin, subject) : enumValueStatementText(contracts.destination, renamed);
1563
+ }
1207
1564
  case "storage": return subject.name;
1208
1565
  }
1209
1566
  }
@@ -1213,12 +1570,14 @@ function subjectText(subject, contracts) {
1213
1570
  * type change, which keeps the field and lets the database cast its values, cutting or rounding some.
1214
1571
  */
1215
1572
  function consentDescription(verb, subject, text, loss) {
1216
- return verb === "delete" && loss === "typeChange" ? `accept lossy type change of ${subject.kind} "${text}"` : `${verb} ${subject.kind} "${text}"`;
1573
+ const kind = ENTITY_WORDS[subject.kind];
1574
+ return verb === "delete" && loss === "typeChange" ? `accept lossy type change of ${kind} "${text}"` : `${verb} ${kind} "${text}"`;
1217
1575
  }
1218
1576
  function lossText(subject, text, originKnown, loss) {
1219
1577
  switch (subject.kind) {
1220
1578
  case "model": return `would lose the data of model "${text}"`;
1221
1579
  case "field": return loss === "typeChange" ? `would change the type of field "${text}" and can change or lose its values` : `would lose the values of field "${text}"`;
1580
+ case "enumValue": return `would lose enum value "${text}" from the data that holds it`;
1222
1581
  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 that data`;
1223
1582
  }
1224
1583
  }
@@ -1231,6 +1590,7 @@ function lossText(subject, text, originKnown, loss) {
1231
1590
  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("\n");
1232
1591
  function sameCoordinate(statement, subject) {
1233
1592
  if (statement.kind !== "rename" || statement.entity === "namespace" || subject.kind === "storage") return false;
1593
+ if (statement.entity === "enumValue" || subject.kind === "enumValue") return statement.entity === "enumValue" && subject.kind === "enumValue" && statement.from.namespaceId === subject.namespaceId && statement.from.enum === subject.enum && statement.from.member === subject.member;
1234
1594
  const { from } = statement;
1235
1595
  if (from.namespaceId !== subject.namespaceId || from.model !== subject.model) return false;
1236
1596
  return subject.kind === "field" ? statement.entity === "field" && statement.from.field === subject.field : statement.entity === "model";
@@ -1243,8 +1603,27 @@ function modelRenameAdvice(model, contracts) {
1243
1603
  return `The destination contract has no model "${name}"; to keep the values instead, also pass --rename ${name}:<new model name>, naming the model that stores them now, and the question then offers to rename the field.`;
1244
1604
  }
1245
1605
  /** A rename as a statement is written: a field's new name keeps the model, `User.nickname:User.<new name>`. */
1246
- function renameForm(subject, text) {
1247
- return subject.kind === "field" ? `${text}:${text.slice(0, text.lastIndexOf("."))}.<new name>` : `${text}:<new name>`;
1606
+ /**
1607
+ * The member an enum value can only have been renamed to: the one member of the destination enum
1608
+ * that the origin enum does not have and no rename of the plan names.
1609
+ */
1610
+ function onlyNewMember(subject, contracts) {
1611
+ const value = renamedEnumValue(subject, contracts) ?? subject;
1612
+ const originMembers = contracts.origin.domain.namespaces[subject.namespaceId]?.enum?.[subject.enum]?.members ?? [];
1613
+ const renamedTo = new Set(resolvedRenames(contracts).flatMap((statement) => statement.kind === "rename" && statement.entity === "enumValue" ? [statement.to.member] : []));
1614
+ const added = (contracts.destination.domain.namespaces[value.namespaceId]?.enum?.[value.enum]?.members ?? []).filter(({ name }) => !renamedTo.has(name) && !originMembers.some((member) => member.name === name));
1615
+ return added.length === 1 ? added[0]?.name : void 0;
1616
+ }
1617
+ function renameForm(subject, text, contracts) {
1618
+ if (subject.kind === "field" || subject.kind === "enumValue") return `${text}:${text.slice(0, text.lastIndexOf("."))}.${(subject.kind === "enumValue" ? onlyNewMember(subject, contracts) : void 0) ?? "<new name>"}`;
1619
+ return `${text}:<new name>`;
1620
+ }
1621
+ /** The labels of the operations a question is about, as one phrase. */
1622
+ function labelsText(labels) {
1623
+ const [first, ...rest] = [...new Set(labels)];
1624
+ const lowered = rest.map((label) => label.charAt(0).toLowerCase() + label.slice(1));
1625
+ const all = [first ?? "", ...lowered];
1626
+ return all.length === 1 ? all.join("") : `${all.slice(0, -1).join(", ")} and ${all.at(-1)}`;
1248
1627
  }
1249
1628
  /** Whether a rename statement of the plan already gives the subject a new name. */
1250
1629
  function renamedByPlan(subject, contracts) {
@@ -1254,6 +1633,10 @@ function renamedByPlan(subject, contracts) {
1254
1633
  /** Whether the destination still has the subject's model or field, under the name a rename gives it. */
1255
1634
  function inDestination(subject, contracts) {
1256
1635
  if (subject.kind === "storage") return false;
1636
+ if (subject.kind === "enumValue") {
1637
+ const value = renamedEnumValue(subject, contracts) ?? subject;
1638
+ return (contracts.destination.domain.namespaces[value.namespaceId]?.enum?.[value.enum])?.members.some(({ name }) => name === subject.member) === true;
1639
+ }
1257
1640
  const model = renamedModel(subject, contracts) ?? subject;
1258
1641
  const destinationModel = contracts.destination.domain.namespaces[model.namespaceId]?.models[model.model];
1259
1642
  if (destinationModel === void 0) return false;
@@ -1292,18 +1675,22 @@ function missingFieldModel(subject, contracts) {
1292
1675
  * after a statement renames the model, so the question says to pass one. The question ends with
1293
1676
  * the planner's advice on keeping the data, when it gives any.
1294
1677
  */
1295
- function dataLossQuestion(loss, contracts) {
1678
+ function dataLossQuestion(loss, contracts, edits = [], labels = [loss.label]) {
1296
1679
  const subject = subjectText(loss.subject, contracts);
1297
1680
  const deleteNames = namesSubject("delete", subject);
1298
1681
  const missingModel = missingFieldModel(loss.subject, contracts);
1682
+ const keepData = edits.length === 0 || contracts.keepDataEditAdvice === void 0 ? void 0 : contracts.keepDataEditAdvice(subject, edits, (contracts.keptSubjects ?? []).filter((other) => other !== subject));
1299
1683
  const question = [
1300
- `${loss.label} ${lossText(loss.subject, subject, contracts.originKnown, loss.loss)}.`,
1684
+ `${labelsText(labels)} ${lossText(loss.subject, subject, contracts.originKnown, loss.loss)}.`,
1301
1685
  ...missingModel === void 0 ? [] : [modelRenameAdvice(missingModel, contracts)],
1302
- ...loss.keepDataAdvice === void 0 ? [] : [loss.keepDataAdvice]
1686
+ ...loss.keepDataAdvice === void 0 ? [] : [loss.keepDataAdvice],
1687
+ ...keepData?.lead === void 0 ? [] : [keepData.lead],
1688
+ ...keepData?.ways ?? []
1303
1689
  ].join(" ");
1304
1690
  if (loss.loss === "typeChange" && loss.subject.kind === "field") {
1305
1691
  if (!contracts.canConvert) return {
1306
1692
  question,
1693
+ ...ifDefined("keepDataWays", keepData?.ways),
1307
1694
  subject,
1308
1695
  verbs: ["delete"],
1309
1696
  forms: {},
@@ -1313,6 +1700,7 @@ function dataLossQuestion(loss, contracts) {
1313
1700
  const convert = fieldStatementText(contracts.destination, field);
1314
1701
  return {
1315
1702
  question,
1703
+ ...ifDefined("keepDataWays", keepData?.ways),
1316
1704
  subject,
1317
1705
  verbs: ["convert", "delete"],
1318
1706
  forms: { convert },
@@ -1333,9 +1721,10 @@ function dataLossQuestion(loss, contracts) {
1333
1721
  const renamable = missingModel === void 0 && loss.subject.kind !== "storage" && !inDestination(loss.subject, contracts) && !renamedByPlan(loss.subject, contracts);
1334
1722
  return {
1335
1723
  question,
1724
+ ...ifDefined("keepDataWays", keepData?.ways),
1336
1725
  subject,
1337
1726
  verbs: renamable ? ["rename", "delete"] : ["delete"],
1338
- forms: renamable ? { rename: renameForm(loss.subject, subject) } : {},
1727
+ forms: renamable ? { rename: renameForm(loss.subject, subject, contracts) } : {},
1339
1728
  validate: (verb, text) => {
1340
1729
  if (verb !== "rename") return deleteNames(text);
1341
1730
  const resolved = resolvesWith({
@@ -1343,7 +1732,7 @@ function dataLossQuestion(loss, contracts) {
1343
1732
  text
1344
1733
  }, contracts);
1345
1734
  if (!resolved.ok) return resolved.failure;
1346
- return resolved.value !== void 0 && sameCoordinate(resolved.value, loss.subject) ? void 0 : `The rename's old name is not "${subject}". Write it as ${renameForm(loss.subject, subject)}.`;
1735
+ return resolved.value !== void 0 && sameCoordinate(resolved.value, loss.subject) ? void 0 : `The rename's old name is not "${subject}". Write it as ${renameForm(loss.subject, subject, contracts)}.`;
1347
1736
  }
1348
1737
  };
1349
1738
  }
@@ -1483,7 +1872,8 @@ async function askPlanQuestions(input) {
1483
1872
  originKnown: input.originKnown,
1484
1873
  destination: input.destination,
1485
1874
  canConvert: input.canConvert,
1486
- statements
1875
+ statements,
1876
+ ...ifDefined("keepDataEditAdvice", input.keepDataEditAdvice)
1487
1877
  };
1488
1878
  const pending = (verb, planned) => [...new Map(planned.filter((entry) => !consented.has(questionKey(verb, entry))).map((entry) => [questionKey(verb, entry), entry])).values()];
1489
1879
  const consent = (verb, entry, text) => consented.set(questionKey(verb, entry), {
@@ -1509,11 +1899,16 @@ async function askPlanQuestions(input) {
1509
1899
  });
1510
1900
  }
1511
1901
  const losses = pending("delete", plan.dataLoss);
1902
+ const sameSubject = (loss) => plan.dataLoss.filter((entry) => questionKey("delete", entry) === questionKey("delete", loss));
1903
+ const roundContracts = {
1904
+ ...contracts,
1905
+ keptSubjects: losses.filter((loss) => sameSubject(loss).some(({ keepDataEdit }) => keepDataEdit !== void 0)).map((loss) => subjectText(loss.subject, contracts))
1906
+ };
1512
1907
  const accessChanges = input.askAccess ? pending("allow", plan.accessChanges) : [];
1513
1908
  if (losses.length + accessChanges.length === 0 && round > 0) break;
1514
1909
  const questions = [...withNamespaceDeleteOnFirstQuestion(withRecoveryOnFirstStorageQuestion(losses.map((loss) => ({
1515
1910
  loss,
1516
- question: acceptingNamespaceAnswers(dataLossQuestion(loss, contracts), removedNamespaceOf(loss.subject, plan.namespaces), contracts)
1911
+ question: acceptingNamespaceAnswers(dataLossQuestion(loss, roundContracts, sameSubject(loss).flatMap((entry) => entry.keepDataEdit === void 0 ? [] : [entry.keepDataEdit]), loss.subject.kind === "enumValue" ? sameSubject(loss).map(({ label }) => label) : [loss.label]), removedNamespaceOf(loss.subject, plan.namespaces), contracts)
1517
1912
  })), !input.originKnown), plan.namespaces?.added ?? []), ...accessChanges.map((change) => accessChangeQuestion(change, contracts))];
1518
1913
  const answers = await input.answer(questions);
1519
1914
  checkAnswers(questions, answers);
@@ -1594,6 +1989,32 @@ function refuseUnusedConsents(input) {
1594
1989
  return unused.length === 0 ? ok(void 0) : notOk(errorConsentUnused(unused, subjects));
1595
1990
  }
1596
1991
  /**
1992
+ * The subjects the `delete` and `allow` flags a run was given consent to, or every subject of a
1993
+ * verb `consentAll` names: what an apply would consent to without asking, which a dry run reports.
1994
+ */
1995
+ function givenConsents(input) {
1996
+ const consented = [];
1997
+ for (const [verb, planned] of [["delete", input.plan.dataLoss], ["allow", input.plan.accessChanges]]) {
1998
+ const entries = [...new Map(planned.map((entry) => [questionKey(verb, entry), entry])).values()];
1999
+ const texts = entries.map((entry) => subjectText(entry.subject, input.contracts));
2000
+ const matched = matchConsents(verb, entries.map((entry, index) => ({
2001
+ text: texts[index] ?? "",
2002
+ removedNamespace: removedNamespaceOf(entry.subject, input.plan.namespaces)
2003
+ })), input.statements.filter((statement) => statement.verb === verb).map(({ text }) => text));
2004
+ entries.forEach((entry, index) => {
2005
+ if (!input.consentAll[verb] && !matched.answered.has(index)) return;
2006
+ consented.push({
2007
+ verb,
2008
+ subject: entry.subject,
2009
+ text: texts[index] ?? "",
2010
+ operationIndex: entry.operationIndex,
2011
+ loss: verb === "delete" && "loss" in entry ? entry.loss : void 0
2012
+ });
2013
+ });
2014
+ }
2015
+ return consented;
2016
+ }
2017
+ /**
1597
2018
  * Matches `--delete` or `--allow` flags to questions as an apply does, whatever their order. A
1598
2019
  * `delete` naming a subject answers every question about it; then a `delete` naming a removed
1599
2020
  * namespace answers the questions of the namespace still open. An `allow` answers one operation,
@@ -1666,24 +2087,6 @@ function reportConsentStatement(consented, operationIndexes) {
1666
2087
  description: consentDescription(consented.verb, consented.subject, consented.text, consented.loss)
1667
2088
  };
1668
2089
  }
1669
- const STATEMENT_VERBS = [
1670
- "rename",
1671
- "delete",
1672
- "allow",
1673
- "convert",
1674
- "backfill"
1675
- ];
1676
- function isStatementVerb(verb) {
1677
- return STATEMENT_VERBS.includes(verb);
1678
- }
1679
- function isPlannedStatement(statement) {
1680
- return statement.verb === "rename" || statement.verb === "convert" || statement.verb === "backfill";
1681
- }
1682
- /** The field a `convert` and a `delete` of the same run both name, which conflict; `undefined` when none does. */
1683
- function convertAndDelete(statements) {
1684
- const deleted = new Set(statements.filter(({ verb }) => verb === "delete").map(({ text }) => text));
1685
- return statements.find(({ verb, text }) => verb === "convert" && deleted.has(text))?.text;
1686
- }
1687
2090
  /** The fields of `values` named as `destination` names them; a column no field stores is left out. */
1688
2091
  function reportTemporaryValues(values, destination) {
1689
2092
  return values.flatMap(({ subject, value }) => subject.kind === "field" ? [{
@@ -2042,6 +2445,19 @@ function failedTypeChangeReport(change, field) {
2042
2445
  reason: change.reason
2043
2446
  };
2044
2447
  }
2448
+ function rowsHoldingValueReport(fact, contract) {
2449
+ const enumValue = enumValueCoordinateFromJson(fact.enumValue);
2450
+ return {
2451
+ enumValue: enumValueStatementText(contract, enumValue),
2452
+ enumName: modelStatementText(contract, {
2453
+ namespaceId: enumValue.namespaceId,
2454
+ model: enumValue.enum
2455
+ }),
2456
+ value: fact.value,
2457
+ rows: fact.rows,
2458
+ ...ifDefined("keepDataEdit", fact.keepDataEdit)
2459
+ };
2460
+ }
2045
2461
  /** What the runner said blocked the failed operation, named as the advice names it. */
2046
2462
  function failureReports(failure, resolutions) {
2047
2463
  const resolution = resolutions.find(({ spaceId }) => spaceId === failure.meta.failingSpace);
@@ -2050,8 +2466,8 @@ function failureReports(failure, resolutions) {
2050
2466
  origin: resolution.entry.destinationContract,
2051
2467
  statements: []
2052
2468
  });
2053
- const { failedTypeChange, rowsWithoutValue } = failure.meta;
2054
- const operationIndex = failedTypeChange?.operationIndex ?? rowsWithoutValue?.[0]?.operationIndex;
2469
+ const { failedTypeChange, rowsWithoutValue, rowsHoldingValue } = failure.meta;
2470
+ const operationIndex = failedTypeChange?.operationIndex ?? rowsWithoutValue?.[0]?.operationIndex ?? rowsHoldingValue?.operationIndex;
2055
2471
  const edge = operationIndex !== void 0 ? edgeOfOperation(resolution.entry.migrationEdges, operationIndex) : schemaCheckIssues(failure) !== void 0 ? resolution.entry.migrationEdges.at(-1) : void 0;
2056
2472
  return {
2057
2473
  ...ifDefined("failedTypeChange", failedTypeChange === void 0 ? void 0 : failedTypeChangeReport(failedTypeChange, fieldText(failedTypeChange.field))),
@@ -2060,6 +2476,7 @@ function failureReports(failure, resolutions) {
2060
2476
  reason,
2061
2477
  rows
2062
2478
  }))),
2479
+ ...ifDefined("rowsHoldingValue", rowsHoldingValue === void 0 ? void 0 : rowsHoldingValueReport(rowsHoldingValue, resolution.entry.destinationContract)),
2063
2480
  ...ifDefined("failedMigration", edge === void 0 ? void 0 : {
2064
2481
  spaceId: resolution.spaceId,
2065
2482
  edge
@@ -2269,7 +2686,8 @@ async function executeRun(options) {
2269
2686
  if (!resolved.ok) throw resolved.failure;
2270
2687
  return resolved.value;
2271
2688
  };
2272
- const statements = resolveRenames(statementTexts);
2689
+ const consentTexts = statementTexts.filter((statement) => !isPlannedStatement(statement));
2690
+ const firstResolved = resolveRenames(statementTexts);
2273
2691
  if (mode === "apply") {
2274
2692
  const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows, familyInstance.markerLocation);
2275
2693
  if (orphanMarkerError !== null) throw orphanMarkerError;
@@ -2290,7 +2708,7 @@ async function executeRun(options) {
2290
2708
  spanId: SPAN_IDS$1.introspect,
2291
2709
  outcome: "ok"
2292
2710
  });
2293
- const plan = async (resolved) => {
2711
+ const plan = async (texts, resolved) => {
2294
2712
  onProgress?.({
2295
2713
  action,
2296
2714
  kind: "spanStart",
@@ -2325,7 +2743,9 @@ async function executeRun(options) {
2325
2743
  action,
2326
2744
  aggregate,
2327
2745
  markerRows,
2328
- invocation: options.invocation
2746
+ invocation: options.invocation,
2747
+ statements: texts,
2748
+ resolved
2329
2749
  }) });
2330
2750
  }
2331
2751
  onProgress?.({
@@ -2357,7 +2777,7 @@ async function executeRun(options) {
2357
2777
  ...ifDefined("namespaces", orderedResolutions.find(({ spaceId }) => spaceId === aggregate.app.spaceId)?.entry.namespaces)
2358
2778
  });
2359
2779
  };
2360
- const first = await plan(statements);
2780
+ const first = await plan(statementTexts, firstResolved);
2361
2781
  if (!first.ok) return notOk(first.failure.refused);
2362
2782
  let run = first.value;
2363
2783
  let plannedTexts = statementTexts.filter(isPlannedStatement);
@@ -2368,7 +2788,7 @@ async function executeRun(options) {
2368
2788
  askAccess: true,
2369
2789
  canConvert: false,
2370
2790
  statements: plannedTexts,
2371
- preAnswers: statementTexts.filter((statement) => !isPlannedStatement(statement)),
2791
+ preAnswers: consentTexts,
2372
2792
  consentAll: {
2373
2793
  delete: options.acceptDataLoss,
2374
2794
  allow: options.acceptAccessChanges
@@ -2377,7 +2797,8 @@ async function executeRun(options) {
2377
2797
  originKnown: fromContract !== null,
2378
2798
  destination: contract,
2379
2799
  answer: options.answerQuestions,
2380
- replan: (planned) => plan(resolveRenames(planned))
2800
+ keepDataEditAdvice: dbUpdateKeepDataEditAdvice(options.invocation, recordedDatabaseContract(aggregate, markerRows)),
2801
+ replan: (planned) => plan([...consentTexts, ...planned], resolveRenames(planned))
2381
2802
  });
2382
2803
  if (!answered.ok) {
2383
2804
  if (CliStructuredError$1.is(answered.failure)) throw answered.failure;
@@ -2398,6 +2819,19 @@ async function executeRun(options) {
2398
2819
  }
2399
2820
  });
2400
2821
  if (!refused.ok) throw refused.failure;
2822
+ consented = givenConsents({
2823
+ plan: run,
2824
+ statements: statementTexts,
2825
+ consentAll: {
2826
+ delete: options.acceptDataLoss,
2827
+ allow: options.acceptAccessChanges
2828
+ },
2829
+ contracts: {
2830
+ origin: fromContract ?? EMPTY_ORIGIN$1,
2831
+ destination: contract,
2832
+ statements: plannedTexts
2833
+ }
2834
+ });
2401
2835
  }
2402
2836
  const { planned, orderedResolutions } = run;
2403
2837
  const plannerWarnings = aggregatePlannerWarnings(orderedResolutions);
@@ -2593,7 +3027,13 @@ function detectOrphanMarkers(aggregate, markerRows, markerLocation) {
2593
3027
  });
2594
3028
  }
2595
3029
  function mapPlannerError(error, context) {
2596
- if (error.kind === "planFromDiffFailed") return context.action === "dbInit" ? dbInitPlanningFailedError(error.conflicts) : errorMigrationPlanningFailed({ conflicts: error.conflicts });
3030
+ if (error.kind === "planFromDiffFailed") return context.action === "dbInit" ? dbInitPlanningFailedError(error.conflicts) : planningRefusedError(error.conflicts, {
3031
+ invocation: context.invocation,
3032
+ from: recordedDatabaseContract(context.aggregate, context.markerRows),
3033
+ to: void 0,
3034
+ statements: context.statements,
3035
+ resolved: context.resolved
3036
+ });
2597
3037
  if (error.kind === "policyConflict") throw new InternalError(`The planner refused the planning policy db init and db update give it, which plans the app space from the diff and walks every extension space's graph: ${error.detail}`);
2598
3038
  const space = context.aggregate.extensions.find(({ spaceId }) => spaceId === error.spaceId);
2599
3039
  if (space === void 0) throw new InternalError(`The planner named extension space "${error.spaceId}", which the aggregate does not hold.`);
@@ -6019,7 +6459,7 @@ function invocationOf(options) {
6019
6459
  }
6020
6460
  /** The origin of a plan from an empty database: no models, so no statement resolves. */
6021
6461
  const EMPTY_ORIGIN = { domain: { namespaces: {} } };
6022
- async function runPlannerLeg(planner, migrations, frameworkComponents, contract, origin, destination, statements, noOperationsExpected, spaceId, ownership, snapshotsImportPath, resolveImportSpecifier) {
6462
+ async function runPlannerLeg(planner, migrations, frameworkComponents, contract, origin, destination, statements, noOperationsExpected, spaceId, ownership, snapshotsImportPath, resolveImportSpecifier, refused = (conflicts) => errorMigrationPlanningFailed({ conflicts: castAs(conflicts) })) {
6023
6463
  const fromContract = origin.kind === "contract" ? origin.contract : null;
6024
6464
  const fromSchema = migrations.contractToSchema(fromContract, frameworkComponents);
6025
6465
  const plannerResult = planner.plan({
@@ -6041,7 +6481,7 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
6041
6481
  });
6042
6482
  if (plannerResult.kind === "failure") return notOk({
6043
6483
  reason: "refused",
6044
- error: errorMigrationPlanningFailed({ conflicts: castAs(plannerResult.conflicts) })
6484
+ error: refused(plannerResult.conflicts)
6045
6485
  });
6046
6486
  let resolved = [];
6047
6487
  let hasPlaceholders = false;
@@ -6067,12 +6507,13 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
6067
6507
  plannedOps,
6068
6508
  migrationTsContent: plannerResult.plan.renderTypeScript(resolveImportSpecifier),
6069
6509
  hasPlaceholders,
6070
- dataLoss: plannerResult.dataLoss.map(({ operationIndex, subject, loss, label, keepDataAdvice }) => ({
6510
+ dataLoss: plannerResult.dataLoss.map(({ operationIndex, subject, loss, label, keepDataAdvice, keepDataEdit }) => ({
6071
6511
  operationIndex: position(operationIndex),
6072
6512
  subject,
6073
6513
  loss,
6074
6514
  label,
6075
- ...ifDefined("keepDataAdvice", keepDataAdvice)
6515
+ ...ifDefined("keepDataAdvice", keepDataAdvice),
6516
+ ...ifDefined("keepDataEdit", keepDataEdit)
6076
6517
  })),
6077
6518
  appliedStatements: reportAppliedStatements(plannerResult.appliedStatements.map((applied) => ({
6078
6519
  ...applied,
@@ -6150,6 +6591,7 @@ async function answerPlannedDataLoss(input) {
6150
6591
  originKnown: input.originKnown,
6151
6592
  destination: input.destination,
6152
6593
  answer: input.answer,
6594
+ keepDataEditAdvice: migrationPlanKeepDataEditAdvice(input.invocation),
6153
6595
  replan: async (statements) => {
6154
6596
  const replanned = await input.planDelta(statements);
6155
6597
  return replanned.ok ? ok(legs(replanned.value)) : replanned;
@@ -6270,6 +6712,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
6270
6712
  }
6271
6713
  let statements = [];
6272
6714
  const statementTexts = options.statements ?? [];
6715
+ const consentTexts = statementTexts.filter((statement) => !isPlannedStatement(statement));
6273
6716
  if (statementTexts.length > 0) {
6274
6717
  const resolved = resolveStatements({
6275
6718
  statements: statementTexts,
@@ -6282,6 +6725,13 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
6282
6725
  if (!resolved.ok) return notOk(resolved.failure);
6283
6726
  statements = resolved.value;
6284
6727
  }
6728
+ const refusedWith = (texts, resolved) => (conflicts) => planningRefusedError(conflicts, {
6729
+ invocation: invocationOf(options),
6730
+ from: fromHash ?? void 0,
6731
+ to: options.to,
6732
+ statements: texts,
6733
+ resolved
6734
+ });
6285
6735
  const resolveImportSpecifier = createProjectSpecifierResolver(options.projectDir);
6286
6736
  let destinationDeclarations = null;
6287
6737
  if (!destinationInStore && fromHash !== toStorageHash) {
@@ -6350,11 +6800,12 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
6350
6800
  baseline,
6351
6801
  delta,
6352
6802
  statements: statementTexts.filter(isPlannedStatement),
6353
- consents: statementTexts.filter((statement) => !isPlannedStatement(statement)),
6803
+ consents: consentTexts,
6354
6804
  origin: fromContract ?? EMPTY_ORIGIN,
6355
6805
  originKnown: true,
6356
6806
  destination: toContract,
6357
6807
  answer: options.answerQuestions,
6808
+ invocation: invocationOf(options),
6358
6809
  planDelta: async (planned) => {
6359
6810
  const resolved = resolveStatements({
6360
6811
  statements: planned,
@@ -6365,7 +6816,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
6365
6816
  destination: toContract
6366
6817
  });
6367
6818
  if (!resolved.ok) return resolved;
6368
- const leg = await planDelta(resolved.value);
6819
+ const leg = await planDelta([...consentTexts, ...planned], resolved.value);
6369
6820
  return leg.ok ? leg : notOk(leg.failure.error);
6370
6821
  }
6371
6822
  });
@@ -6384,8 +6835,8 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
6384
6835
  isEmitted: false
6385
6836
  }, [], false, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(baselinePackageDir, migrationsDir), resolveImportSpecifier);
6386
6837
  if (!baselineLeg.ok) return notOk(baselineLeg.failure.error);
6387
- const planBaselineDelta = (resolved) => runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, false, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(deltaPackageDir, migrationsDir), resolveImportSpecifier);
6388
- const plannedDelta = fromHash === toStorageHash ? void 0 : await planBaselineDelta(statements);
6838
+ const planBaselineDelta = (texts, resolved) => runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, false, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(deltaPackageDir, migrationsDir), resolveImportSpecifier, refusedWith(texts, resolved));
6839
+ const plannedDelta = fromHash === toStorageHash ? void 0 : await planBaselineDelta(statementTexts, statements);
6389
6840
  if (plannedDelta !== void 0 && !plannedDelta.ok && plannedDelta.failure.reason === "refused") return notOk(plannedDelta.failure.error);
6390
6841
  const answered = await answerDataLoss(baselineLeg.value, plannedDelta?.ok === true ? plannedDelta.value : void 0, planBaselineDelta);
6391
6842
  if (!answered.ok) return notOk(answered.failure);
@@ -6495,8 +6946,8 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
6495
6946
  }
6496
6947
  const timestamp = /* @__PURE__ */ new Date();
6497
6948
  const packageDir = join(appMigrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
6498
- 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);
6499
- const plannedDelta = await planDelta(statements);
6949
+ const planDelta = (texts, resolved) => runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, resolved.length > 0 && fromHash === toStorageHash, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(packageDir, migrationsDir), resolveImportSpecifier, refusedWith(texts, resolved));
6950
+ const plannedDelta = await planDelta(statementTexts, statements);
6500
6951
  if (!plannedDelta.ok) return notOk(plannedDelta.failure.error);
6501
6952
  const answered = await answerDataLoss(void 0, plannedDelta.value, planDelta);
6502
6953
  if (!answered.ok) return notOk(answered.failure);
@@ -6698,6 +7149,6 @@ async function executeRefListCommand(options) {
6698
7149
  }
6699
7150
  }
6700
7151
  //#endregion
6701
- export { refuseMarkerOutsideGraph as $, executeRefDeleteCommand as A, loadContractRawSafely as B, executeDbSign as C, executeMigrationNewCommand as D, executeMigrateShowPlan as E, hasMigrationPath as F, mapContractAtError as G, loadContractSourceWithStack as H, isStatementVerb as I, migrationSpaceListEntriesFromAggregate as J, mapIntegrityViolations as K, listRefsByContractHash as L, executeRefSetCommand as M, findPackageByDirPath as N, executeMigrationPlanCommand as O, formatSourceDiagnostic as P, refuseDeclaredExtensionTargetMismatch as Q, liveMarkerUse as R, executeDbInit as S, executeDbVerify as T, loadContractSpaceAggregateForCli as U, loadContractSource as V, looksLikePath as W, readMigrationRefs as X, preflightRefAdvancement as Y, refuseContractSpaceIntegrity as Z, deriveStatusEdgeAnnotations as _, statusForMigrationHash as _t, advanceRefSafely as a, resolveContractRef$1 as at, enumerateCheckSpaces as b, withWarningFindings as bt, buildContractSpaceAggregate as c, resolveMigrationRef as ct, buildRefAdvancementFields as d, retryCommandFor as dt, refuseMissingInvariantPath as et, checkSingleTarget as f, runContractSpaceSeedPhase as ft, createControlClient as g, sourceWarningDiagnostic as gt, convertAndDelete as h, snapshotVerifierFor as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, resolveAppTargetPath as it, executeRefListCommand as j, executeRefAdvancement as k, buildMigrationSpaceGraphEntries as l, resolveStatements as lt, contractValidationMeta as m, runMigrationList as mt, NO_REF_ADVANCEMENT as n, refuseUnknownInvariants as nt, appContractStandInFromIdentity as o, resolveContractRefToSnapshot as ot, computeRefAdvancementName as p, runMigrationCheck as pt, matchConsents as q, RECORDED_CONTRACT_REF_FORMS as r, requireDatabaseForLiveMarkerUse as rt, appliedHashesFromLedger as s, resolveFromForPlan as st, ALL_CONTRACT_REF_FORMS as t, refusePackageCorruptionOnAggregate as tt, buildReadAggregate as u, resolveToForPlan as ut, disposeEmitQueue as v, toDeclaredExtensionsFromRaw as vt, executeDbUpdate as w, executeContractEmit as x, enrichContract as y, validateLoadedContract as yt, loadAggregateIntegrityViolations as z };
7152
+ export { refuseDeclaredExtensionTargetMismatch as $, executeRefDeleteCommand as A, loadAggregateIntegrityViolations as B, executeDbSign as C, executeMigrationNewCommand as D, executeMigrateShowPlan as E, hasMigrationPath as F, looksLikePath as G, loadContractSource as H, isStatementVerb as I, matchConsents as J, mapContractAtError as K, labelsText as L, executeRefSetCommand as M, findPackageByDirPath as N, executeMigrationPlanCommand as O, formatSourceDiagnostic as P, refuseContractSpaceIntegrity as Q, listRefsByContractHash as R, executeDbInit as S, withWarningFindings as St, executeDbVerify as T, loadContractSourceWithStack as U, loadContractRawSafely as V, loadContractSpaceAggregateForCli as W, preflightRefAdvancement as X, migrationSpaceListEntriesFromAggregate as Y, readMigrationRefs as Z, deriveStatusEdgeAnnotations as _, snapshotVerifierFor as _t, advanceRefSafely as a, requireDatabaseForLiveMarkerUse as at, enumerateCheckSpaces as b, toDeclaredExtensionsFromRaw as bt, buildContractSpaceAggregate as c, resolveContractRefToSnapshot as ct, buildRefAdvancementFields as d, resolveStatements as dt, refuseMarkerOutsideGraph as et, checkSingleTarget as f, resolveToForPlan as ft, createControlClient as g, runMigrationList as gt, convertAndDelete as h, runMigrationCheck as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, renamedAndDeleted as it, executeRefListCommand as j, executeRefAdvancement as k, buildMigrationSpaceGraphEntries as l, resolveFromForPlan as lt, contractValidationMeta as m, runContractSpaceSeedPhase as mt, NO_REF_ADVANCEMENT as n, refusePackageCorruptionOnAggregate as nt, appContractStandInFromIdentity as o, resolveAppTargetPath as ot, computeRefAdvancementName as p, retryCommandFor as pt, mapIntegrityViolations as q, RECORDED_CONTRACT_REF_FORMS as r, refuseUnknownInvariants as rt, appliedHashesFromLedger as s, resolveContractRef$1 as st, ALL_CONTRACT_REF_FORMS as t, refuseMissingInvariantPath as tt, buildReadAggregate as u, resolveMigrationRef as ut, disposeEmitQueue as v, sourceWarningDiagnostic as vt, executeDbUpdate as w, executeContractEmit as x, validateLoadedContract as xt, enrichContract as y, statusForMigrationHash as yt, liveMarkerUse as z };
6702
7153
 
6703
- //# sourceMappingURL=ref-CGWRjVD8-DhlaBwJ7.mjs.map
7154
+ //# sourceMappingURL=ref-C1IRwZNR-CW8ayjUw.mjs.map