@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
package/dist/cli.mjs CHANGED
@@ -1,25 +1,25 @@
1
- import { h as requireConfigSections, i as expandContractInputs, m as ormConfigSection, n as buildLoadedConfig, r as evaluateConfigModule, s as globContractInputMatching, u as loadConfigFiles } from "./exports-Czq5v0Dn.mjs";
1
+ import { h as requireConfigSections, i as expandContractInputs, m as ormConfigSection, n as buildLoadedConfig, r as evaluateConfigModule, s as globContractInputMatching, u as loadConfigFiles } from "./exports-C7GzkPEc.mjs";
2
2
  import { t as MigrationToolsError } from "./errors-DD6iLGXk-6I9PqjpZ.mjs";
3
- import { t as contractSnapshotDir } from "./contract-snapshot-store-1S_6vaGt-CQPNFWho.mjs";
3
+ import { t as contractSnapshotDir } from "./contract-snapshot-store-1S_6vaGt-HJIMKsVd.mjs";
4
4
  import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
5
- import { c as spaceMigrationDirectory, l as spaceRefsDirectory } from "./verify-contract-spaces-CYjc343k-FXABEJZE.mjs";
6
- import { B as errorTargetMismatch, C as errorMarkerMissing, D as errorPathUnreachable, E as errorNoMigrations, F as errorRuntime, G as readContractEnvelope, I as errorSignRefsNotWritten, K as redactUrlCredentials, P as errorRunnerFailed, T as errorMigrationPlanningFailed, W as maskConnectionUrl, X as runCommandAction, Z as targetSupportsMigrations, _ as errorFileNotFound, a as closeQuietly, d as errorContractArgConflict, f as errorContractConfigMissing, g as errorDriverRequired, h as errorDestructiveChanges, i as chooseAction, l as errorConfigValidation$1, m as errorDatabaseConnectionRequired, n as CliStructuredError$1$1, p as errorContractValidationFailed, q as requireLiveDatabase, r as ERROR_CODE_DESTRUCTIVE_CHANGES, s as errorAdvanceRefArgConflict, t as ActionableCliError, u as errorConsentPlanMismatch, v as errorFromCaught, w as errorMigrationPackageNotFound, x as errorLegendHumanOnly, y as errorHashMismatch, z as errorTargetMigrationNotSupported } from "./caught-errors-N266GMql-B7p73Xyj.mjs";
5
+ import { c as spaceMigrationDirectory, l as spaceRefsDirectory } from "./verify-contract-spaces-CYjc343k-ClHHEkJF.mjs";
6
+ import { $ as runCommandAction, C as errorMigrationPlanningFailed, H as errorTargetMigrationNotSupported, J as readContractEnvelope, M as errorRunnerFailed, N as errorRuntime, P as errorSignRefsNotWritten, S as errorMigrationPackageNotFound, T as errorPathUnreachable, U as errorTargetMismatch, X as requireLiveDatabase, Y as redactUrlCredentials, _ as errorHashMismatch, a as closeQuietly, d as errorContractConfigMissing, et as targetSupportsMigrations, f as errorContractValidationFailed, g as errorFromCaught, h as errorFileNotFound, i as chooseAction, l as errorConfigValidation$1, m as errorDriverRequired, n as CliStructuredError$1$1, p as errorDatabaseConnectionRequired, q as maskConnectionUrl, s as errorAdvanceRefArgConflict, t as ActionableCliError, u as errorContractArgConflict, w as errorNoMigrations, x as errorMarkerMissing, y as errorLegendHumanOnly } from "./caught-errors-HFQjjQVE-b_GDV-6J.mjs";
7
7
  import { r as getEmittedArtifactPaths } from "./exports-DaDckULH-JNQeM6Nn.mjs";
8
8
  import { r as isInSpaceHistory } from "./graph-membership-C_ZO26nT-B7C4CJsh.mjs";
9
- import { d as writeRef, r as readRef } from "./refs-qwvw4_dV-X8sR92eT.mjs";
10
- import { a as contractHashAtMarker } from "./aggregate-C7IHVcsV.mjs";
9
+ import { d as writeRef, r as readRef } from "./refs-qwvw4_dV-DNg_7WTD.mjs";
10
+ import { a as contractHashAtMarker } from "./aggregate-DlfOyErc.mjs";
11
11
  import { i as createScaffoldSpecifierResolver } from "./import-roots-BeAYfehL.mjs";
12
- import { o as isLiveMarkerRef } from "./ref-resolution-d7rcmU6F.mjs";
13
- import { $ as refuseUnknownInvariants, A as executeRefListCommand, B as loadContractSourceWithStack, D as executeMigrationPlanCommand, E as executeMigrationNewCommand, F as listRefsByContractHash, G as migrationSpaceListEntriesFromAggregate, H as looksLikePath, I as liveMarkerUse, J as refuseContractSpaceIntegrity, K as preflightRefAdvancement, L as loadAggregateIntegrityViolations, M as findPackageByDirPath, N as formatSourceDiagnostic, P as hasMigrationPath, Q as refusePackageCorruptionOnAggregate, R as loadContractRawSafely, T as executeMigrateShowPlan, U as mapContractAtError, V as loadContractSpaceAggregateForCli, X as refuseMarkerOutsideGraph, Z as refuseMissingInvariantPath, a as RECORDED_OR_EMPTY_CONTRACT_REF_FORMS, at as resolveMigrationRef, b as executeContractEmit, c as appliedHashesFromLedger, d as buildReadAggregate, dt as snapshotVerifierFor, et as requireDatabaseForLiveMarkerUse, f as buildRefAdvancementFields, ft as sourceWarningDiagnostic, g as deriveStatusEdgeAnnotations, h as createControlClient, ht as validateLoadedContract, i as RECORDED_CONTRACT_REF_FORMS, j as executeRefSetCommand, k as executeRefDeleteCommand, lt as runMigrationCheck, m as computeRefAdvancementName, mt as toDeclaredExtensionsFromRaw, n as DB_UPDATE_POLICY, nt as resolveContractRef$1, o as advanceRefSafely, p as checkSingleTarget, pt as statusForMigrationHash, q as readMigrationRefs, r as NO_REF_ADVANCEMENT, rt as resolveContractRefToSnapshot, st as retryCommandFor, t as ALL_CONTRACT_REF_FORMS, tt as resolveAppTargetPath, u as buildMigrationSpaceGraphEntries, ut as runMigrationList, y as enumerateCheckSpaces, z as loadContractSource } from "./ref-BCEAH4F9-Bgr9vmL7.mjs";
12
+ import { o as isLiveMarkerRef } from "./ref-resolution-Be_zewf7.mjs";
13
+ import { $ as refuseUnknownInvariants, A as executeRefListCommand, B as loadContractSourceWithStack, D as executeMigrationPlanCommand, E as executeMigrationNewCommand, F as listRefsByContractHash, G as migrationSpaceListEntriesFromAggregate, H as looksLikePath, I as liveMarkerUse, J as refuseContractSpaceIntegrity, K as preflightRefAdvancement, L as loadAggregateIntegrityViolations, M as findPackageByDirPath, N as formatSourceDiagnostic, P as hasMigrationPath, Q as refusePackageCorruptionOnAggregate, R as loadContractRawSafely, T as executeMigrateShowPlan, U as mapContractAtError, V as loadContractSpaceAggregateForCli, X as refuseMarkerOutsideGraph, Z as refuseMissingInvariantPath, _t as toDeclaredExtensionsFromRaw, a as RECORDED_OR_EMPTY_CONTRACT_REF_FORMS, at as resolveMigrationRef, b as executeContractEmit, c as appliedHashesFromLedger, ct as retryCommandFor, d as buildReadAggregate, dt as runMigrationList, et as requireDatabaseForLiveMarkerUse, f as buildRefAdvancementFields, ft as shellQuoted, g as deriveStatusEdgeAnnotations, gt as statusForMigrationHash, h as createControlClient, ht as statementFlag, i as RECORDED_CONTRACT_REF_FORMS, j as executeRefSetCommand, k as executeRefDeleteCommand, m as computeRefAdvancementName, mt as sourceWarningDiagnostic, n as DB_UPDATE_POLICY, nt as resolveContractRef$1, o as advanceRefSafely, p as checkSingleTarget, pt as snapshotVerifierFor, q as readMigrationRefs, r as NO_REF_ADVANCEMENT, rt as resolveContractRefToSnapshot, t as ALL_CONTRACT_REF_FORMS, tt as resolveAppTargetPath, u as buildMigrationSpaceGraphEntries, ut as runMigrationCheck, vt as validateLoadedContract, y as enumerateCheckSpaces, z as loadContractSource } from "./ref-Cc_CTagE-C070Ym7p.mjs";
14
14
  import { a as PRISMA7_QUICK_REFERENCE_STEP, i as PRISMA7_LOOP_STEP, n as InitOutputSchema, o as buildNextSteps, r as NEXT_STEPS_BEFORE_SCAFFOLD, t as DB_SIGN_STEP } from "./output-BcC8eB0h-C5bRd-aC.mjs";
15
15
  import { createRequire } from "node:module";
16
16
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
17
17
  import { CliStructuredError } from "@prisma/orm-framework/errors/control";
18
- import { APP_SPACE_ID, VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_SCHEMA_FAILURE, VERIFY_CODE_TARGET_MISMATCH, createControlStack, hasPslContractBuild, issueOutcome } from "@prisma/orm-framework/components/control";
18
+ import { APP_SPACE_ID, VERIFY_CODE_HASH_MISMATCH, VERIFY_CODE_MARKER_MISSING, VERIFY_CODE_SCHEMA_FAILURE, VERIFY_CODE_TARGET_MISMATCH, createControlStack, hasPslContractBuild, issueOutcome, migrationSubjectJson } from "@prisma/orm-framework/components/control";
19
19
  import { InternalError, assertNever, isInternalError } from "@prisma/orm-framework/utils/internal-error";
20
20
  import { DOCS_BASE, docsUrlFor, isStructuredError, isStructuredErrorCode } from "@prisma/orm-framework/utils/structured-error";
21
- import { mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
22
21
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "pathe";
22
+ import { mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
23
23
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
24
24
  import { type } from "arktype";
25
25
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -39,7 +39,7 @@ import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
39
39
  import stringWidth from "string-width";
40
40
  import { bold, createColors, cyan, cyanBright, dim, green, yellow } from "colorette";
41
41
  import { build } from "esbuild";
42
- //#region ../../../1-framework/3-tooling/cli/dist/load-config-Da-DjM2u.mjs
42
+ //#region ../../../1-framework/3-tooling/cli/dist/load-config-BoV4P1CO.mjs
43
43
  /**
44
44
  * `isStructuredError` is the repo's own check, and it is the one that matters here: it holds the
45
45
  * regular expression for a dotted `NAMESPACE.SUBCODE`, so only a code the protocol accepts
@@ -800,7 +800,7 @@ function createContractPrintCommand({ printPsl }) {
800
800
  });
801
801
  }
802
802
  const contractPrintCommand = createContractPrintCommand({ printPsl });
803
- const DB_INIT_ADDITIVE_ONLY_FIX = "`db init` applies only additive changes. Run `{bin} db update`, which also applies widening and destructive ones after you confirm them by typing the database name, or pass `--no-interactive --confirm <database>` where there is nobody to ask.";
803
+ const DB_INIT_ADDITIVE_ONLY_FIX = "`db init` applies only additive changes. Run `{bin} db update`, which also applies widening and destructive ones once you answer what each operation that would lose data means, with `--delete` or `--rename`.";
804
804
  const DB_INIT_NEEDS_MIGRATION_FIX = "`db init` applies only additive changes, and `db update` does not apply data operations. Plan a migration with `{bin} migration plan`, which can include them, and apply it with `{bin} db migrate`.";
805
805
  /**
806
806
  * What to do instead of `db init` when its additive-only policy refused operations of the given classes: `db update` when its policy allows all of them, otherwise a planned migration.
@@ -813,7 +813,7 @@ function adviceForRefusedClasses(refused) {
813
813
  };
814
814
  return {
815
815
  fix: DB_INIT_ADDITIVE_ONLY_FIX,
816
- nextAction: runCommandAction(refused.has("destructive") ? "Apply the change with db update, which lists the destructive operations and asks you to confirm them" : "Apply the change with db update", "{bin} db update")
816
+ nextAction: runCommandAction(refused.has("destructive") ? "Apply the change with db update, which asks what each operation that would lose data means" : "Apply the change with db update", "{bin} db update")
817
817
  };
818
818
  }
819
819
  function markerMismatchDetail(failure) {
@@ -892,6 +892,25 @@ function renderPreviewStatement(text, language) {
892
892
  function previewBlockHeader(preview) {
893
893
  return preview.statements.length > 0 && preview.statements.every((s) => s.language === "sql") ? "DDL preview" : "Operation preview";
894
894
  }
895
+ function operationCountText(count) {
896
+ if (count === 0) return "no operations";
897
+ return count === 1 ? "1 operation" : `${count} operations`;
898
+ }
899
+ /**
900
+ * The `Statements applied` tree: one line per statement in the order given,
901
+ * each described in domain names, with the number of operations it
902
+ * accounts for. Nothing when no statements were given.
903
+ */
904
+ function appliedStatementBlocks(applied) {
905
+ if (applied.length === 0) return [];
906
+ return [{
907
+ kind: "tree",
908
+ roots: [{
909
+ label: "Statements applied",
910
+ children: applied.map((entry) => ({ label: `${entry.description} (${operationCountText(entry.operationIndexes.length)})` }))
911
+ }]
912
+ }];
913
+ }
895
914
  function operationNode(operation) {
896
915
  return operation.operationClass === "destructive" ? {
897
916
  label: operation.label,
@@ -1001,6 +1020,30 @@ function applySummaryText(result) {
1001
1020
  if (executed === 0) return `Database already matches contract${across}`;
1002
1021
  return `Applied ${executed} operation(s)${across}`;
1003
1022
  }
1023
+ /**
1024
+ * The questions an apply would ask, as a dry run lists them: each operation that would lose data,
1025
+ * answered by `--delete` or `--rename`, and each that would widen access, answered by `--allow`.
1026
+ */
1027
+ function questionBlocks(result) {
1028
+ const entries = [...(result.dataLoss ?? []).map((entry) => ({
1029
+ entry,
1030
+ verb: "delete"
1031
+ })), ...(result.accessWidening ?? []).map((entry) => ({
1032
+ entry,
1033
+ verb: "allow"
1034
+ }))];
1035
+ if (entries.length === 0) return [];
1036
+ return [{
1037
+ kind: "tree",
1038
+ roots: [{
1039
+ label: "An apply asks about",
1040
+ children: entries.map(({ entry, verb }) => ({ label: `${result.plan.operations[entry.operationIndex]?.label ?? "an operation"}: ${statementFlag({
1041
+ verb,
1042
+ text: entry.text
1043
+ })}${entry.answered ? " (answered)" : ""}` }))
1044
+ }]
1045
+ }];
1046
+ }
1004
1047
  function planBlocks$1(result) {
1005
1048
  const planned = result.plannedAdvanceRef;
1006
1049
  return [
@@ -1011,6 +1054,8 @@ function planBlocks$1(result) {
1011
1054
  },
1012
1055
  ...plannerWarningBlocks(result),
1013
1056
  ...operationBlocks$2(result),
1057
+ ...appliedStatementBlocks(result.appliedStatements ?? []),
1058
+ ...questionBlocks(result),
1014
1059
  {
1015
1060
  kind: "fields",
1016
1061
  rows: [{
@@ -1072,6 +1117,7 @@ function applyBlocks(result) {
1072
1117
  },
1073
1118
  ...plannerWarningBlocks(result),
1074
1119
  ...operationBlocks$2(result),
1120
+ ...appliedStatementBlocks(result.appliedStatements ?? []),
1075
1121
  ...fallbackMarkerBlocks(result),
1076
1122
  ...advanced === null || advanced === void 0 ? [] : [{
1077
1123
  kind: "summary",
@@ -1122,7 +1168,7 @@ async function prepareMigrationRun(inputs) {
1122
1168
  why: `Database connection is required for ${commandName} (set db.connection in prisma.config.ts, or pass --db <url>)`,
1123
1169
  commandName,
1124
1170
  missingFlags: ["--db"],
1125
- ...ifDefined("retryCommand", inputs.retryCommand)
1171
+ ...ifDefined("retryCommand", typeof inputs.retryCommand === "function" ? inputs.retryCommand() : inputs.retryCommand)
1126
1172
  })));
1127
1173
  if (config.driver === void 0) return notOk$1(normalizeError(errorDriverRequired({ why: `Config.driver is required for ${commandName}` })));
1128
1174
  if (!targetSupportsMigrations(config.target)) return notOk$1(normalizeError(errorTargetMigrationNotSupported({ why: `Target "${config.target.id}" does not support migrations` })));
@@ -2095,10 +2141,6 @@ const dbSignCommand = createDbSignCommand();
2095
2141
  /**
2096
2142
  * A `db update` failure as the CLI's structured error.
2097
2143
  *
2098
- * `DESTRUCTIVE_CHANGES` is handled by the command, which asks for consent and
2099
- * calls again; it is mapped here for the case the control API returns it from a
2100
- * call that already carried consent, which would otherwise degrade silently.
2101
- *
2102
2144
  * The `assertNever` is deliberate: a control-API failure code this does not
2103
2145
  * handle must stop the command rather than degrade into a generic message.
2104
2146
  */
@@ -2116,55 +2158,46 @@ function mapDbUpdateFailure(failure) {
2116
2158
  ...ifDefined("cause", failure.cause)
2117
2159
  });
2118
2160
  }
2119
- if (failure.code === "DESTRUCTIVE_CHANGES") return errorDestructiveChanges(failure.summary, {
2120
- ...ifDefined("why", failure.why),
2121
- fix: "Re-run `{bin} db update` and type the database name when asked, or pass `--no-interactive --confirm <database>` where there is nobody to ask. Use `--dry-run` to preview the operations first.",
2122
- ...failure.destructiveChanges ? { meta: {
2123
- destructiveOperations: failure.destructiveChanges.destructiveOperations,
2124
- databaseName: failure.destructiveChanges.databaseName,
2125
- planHash: failure.destructiveChanges.planHash
2126
- } } : {}
2127
- });
2128
- if (failure.code === "CONSENT_PLAN_MISMATCH") return errorConsentPlanMismatch({
2129
- consentedPlanHash: failure.consentPlanMismatch?.consentedPlanHash ?? "",
2130
- planHash: failure.consentPlanMismatch?.planHash ?? "",
2131
- ...ifDefined("why", failure.why)
2132
- });
2133
2161
  const exhaustive = failure.code;
2134
2162
  return assertNever(exhaustive, `Unhandled DbUpdateFailure code: ${String(exhaustive)}`);
2135
2163
  }
2136
2164
  /**
2137
- * A token nobody can type is not consent: an empty one makes the engine's
2138
- * type-to-confirm accept a bare Enter, and `--confirm ""` grant outright.
2139
- */
2140
- function errorConsentTokenUnresolved(targetId) {
2141
- return new CliStructuredError$1("CLI.CONSENT_TOKEN_UNRESOLVED", "The database this run would change has no name to confirm.", {
2142
- why: `The connected database reports no name, and the target id "${targetId}" yields none either, so the consent prompt has nothing to ask you to type and the destructive operations cannot be authorised.`,
2143
- nextActions: [{
2144
- kind: "user-choice",
2145
- label: "Name the database in `db.connection` (or pass `--db <url>`) and run `{bin} db update` again."
2146
- }]
2147
- });
2148
- }
2149
- /** A prompt that names nothing cannot be consented to knowingly. */
2150
- function errorConsentOperationsMissing(options) {
2151
- return new CliStructuredError$1("CLI.CONSENT_OPERATIONS_MISSING", "The plan was refused as destructive but named no operations to confirm.", {
2152
- why: "The consent prompt has to list what is about to be destroyed, and the refusal carried no operations to list.",
2153
- nextActions: [{
2154
- kind: "run-command",
2155
- label: "Preview the plan",
2156
- command: options?.previewCommand ?? "{bin} db update --dry-run"
2157
- }]
2158
- });
2159
- }
2160
- /** The indented per-operation list every destructive-consent question renders. */
2161
- function destructiveOperationList(operations) {
2162
- return operations.map((operation) => ` - ${operation.label}`).join("\n");
2163
- }
2164
- /** The question the user answers before anything is dropped. */
2165
- function destructiveConsentQuestion(operations, token) {
2166
- return [`Apply ${operations.length} destructive operation(s) to ${token}? Data they remove cannot be recovered:`, destructiveOperationList(operations)].join("\n");
2165
+ * Asks a plan's questions through the engine's statement prompt, all in one batch that refuses a
2166
+ * statement nothing consumed before the command acts. Flags answer first; where nobody can answer,
2167
+ * the engine refuses and lists every question.
2168
+ */
2169
+ function promptPlanQuestions(prompt) {
2170
+ return async (questions) => {
2171
+ return (await prompt.statements(questions.map((question) => ({
2172
+ question: question.question,
2173
+ subject: question.subject,
2174
+ verbs: question.verbs,
2175
+ forms: question.forms,
2176
+ validate: question.validate
2177
+ })), { last: true })).map(({ verb, text }) => ({
2178
+ verb,
2179
+ text
2180
+ }));
2181
+ };
2167
2182
  }
2183
+ /**
2184
+ * The statement verbs the ORM commands declare. Each command declares the verbs its questions
2185
+ * use: `migration plan` takes `rename` and `delete`, and `db update` also `allow`.
2186
+ */
2187
+ const ormStatementVerbs = {
2188
+ rename: {
2189
+ arity: 1,
2190
+ brief: "Rename a model or field instead of dropping it: old:new, each side Model, namespace.Model, Model.field or namespace.Model.field; repeat for several, applied in order"
2191
+ },
2192
+ delete: {
2193
+ arity: 1,
2194
+ brief: "Let the command lose the data of a model, field or storage name the refusal lists: --delete Model"
2195
+ },
2196
+ allow: {
2197
+ arity: 1,
2198
+ brief: "Let the command widen who can read or write the rows of a model: --allow Model"
2199
+ }
2200
+ };
2168
2201
  function updatePresentations(inputs) {
2169
2202
  const { document, database, dryRun } = inputs;
2170
2203
  return {
@@ -2192,9 +2225,33 @@ function updatePresentations(inputs) {
2192
2225
  ]
2193
2226
  }, ...migrationResultBlocks(document)],
2194
2227
  json: () => document,
2195
- next: () => migrationResultNextActions(document, "{bin} db update")
2228
+ next: () => migrationResultNextActions(document, [
2229
+ "{bin} db update",
2230
+ ...inputs.to === void 0 ? [] : [`--to ${shellQuoted(inputs.to)}`],
2231
+ ...inputs.dbGiven ? ["--db <url>"] : [],
2232
+ ...inputs.advanceRef === void 0 ? [] : [`--advance-ref ${shellQuoted(inputs.advanceRef)}`],
2233
+ ...inputs.statements.map(statementFlag)
2234
+ ].join(" "))
2196
2235
  };
2197
2236
  }
2237
+ /**
2238
+ * The entries a dry run lists, each marked answered when a flag it was given answers its question:
2239
+ * a `--delete` answers every loss of its subject, and an `--allow` one operation, in order.
2240
+ */
2241
+ function subjectEntriesJson(entries, verb, given) {
2242
+ const flagsLeft = /* @__PURE__ */ new Map();
2243
+ for (const statement of given) if (statement.verb === verb) flagsLeft.set(statement.text, (flagsLeft.get(statement.text) ?? 0) + 1);
2244
+ return entries.map((entry) => {
2245
+ const left = flagsLeft.get(entry.text) ?? 0;
2246
+ if (left > 0 && verb === "allow") flagsLeft.set(entry.text, left - 1);
2247
+ return {
2248
+ operationIndex: entry.operationIndex,
2249
+ subject: migrationSubjectJson(entry.subject),
2250
+ text: entry.text,
2251
+ answered: left > 0
2252
+ };
2253
+ });
2254
+ }
2198
2255
  function updateDocument(inputs) {
2199
2256
  const { value } = inputs;
2200
2257
  return {
@@ -2222,6 +2279,11 @@ function updateDocument(inputs) {
2222
2279
  ...ifDefined("profileHash", value.marker.profileHash)
2223
2280
  } },
2224
2281
  ...ifDefined("perSpace", value.perSpace),
2282
+ appliedStatements: value.appliedStatements,
2283
+ ...value.mode === "plan" ? {
2284
+ dataLoss: subjectEntriesJson(value.dataLoss, "delete", inputs.statements),
2285
+ accessWidening: subjectEntriesJson(value.accessWidening, "allow", inputs.statements)
2286
+ } : {},
2225
2287
  ...ifDefined("warnings", value.warnings),
2226
2288
  advancedRef: inputs.advancedRef,
2227
2289
  plannedAdvanceRef: inputs.plannedAdvanceRef,
@@ -2229,15 +2291,23 @@ function updateDocument(inputs) {
2229
2291
  timings: { total: Date.now() - inputs.startedAt }
2230
2292
  };
2231
2293
  }
2294
+ /** The delete and allow values the engine still holds for the questions, read without taking them. */
2295
+ function unansweredConsents(statements) {
2296
+ return statements.values().flatMap(({ verb, text }) => verb === "delete" || verb === "allow" ? [{
2297
+ verb,
2298
+ text
2299
+ }] : []);
2300
+ }
2232
2301
  function createDbUpdateCommand(createClient) {
2233
2302
  return defineOrmCommand({
2234
2303
  help: {
2235
2304
  summary: "Update your database schema to match your contract",
2236
- description: "Compares the database to the emitted contract and applies the changes that\nclose the gap, whether or not the database was bootstrapped with `db init`.\nAn operation that would destroy data is applied only with your consent: the\ncommand asks you to type the database name. A run with nobody to ask — a CI\njob, or `--no-interactive` — takes it from `--confirm <database>` instead.\nUse --dry-run to see the operations without applying them.",
2305
+ description: "Compares the database to the emitted contract and applies the changes that\nclose the gap, whether or not the database was bootstrapped with `db init`.\nBefore it applies an operation that would lose data, it asks what the\noperation means: --rename keeps the data under a new name, --delete lets it\ngo. Before it widens who can read or write rows, it asks for --allow. Where\nnobody can answer, it refuses and lists every question. Use --dry-run to see\nthe operations and the questions without applying anything.",
2237
2306
  examples: [
2238
2307
  "db update",
2239
2308
  "db update --dry-run",
2240
- "db update --no-interactive --confirm appdb",
2309
+ "db update --delete Legacy",
2310
+ "db update --rename Profile:User --allow User",
2241
2311
  "db update --to production"
2242
2312
  ]
2243
2313
  },
@@ -2253,9 +2323,21 @@ function createDbUpdateCommand(createClient) {
2253
2323
  placeholder: "name"
2254
2324
  })
2255
2325
  } },
2326
+ statements: ormStatementVerbs,
2256
2327
  needs: { config: ormConfigSection },
2257
2328
  handler: async (args, ctx) => {
2258
2329
  const startedAt = Date.now();
2330
+ const renames = ctx.statements.take("rename").map(({ text }) => ({
2331
+ verb: "rename",
2332
+ text
2333
+ }));
2334
+ const previewConsents = args.flags.dryRun ? [...ctx.statements.take("delete").map(({ text }) => ({
2335
+ verb: "delete",
2336
+ text
2337
+ })), ...ctx.statements.take("allow").map(({ text }) => ({
2338
+ verb: "allow",
2339
+ text
2340
+ }))] : [];
2259
2341
  let destination;
2260
2342
  if (args.flags.to !== void 0) {
2261
2343
  const resolved = await resolveContractRefToSnapshot({
@@ -2274,10 +2356,15 @@ function createDbUpdateCommand(createClient) {
2274
2356
  db: args.flags.db,
2275
2357
  commandName: "db update",
2276
2358
  createClient,
2277
- retryCommand: retryCommandFor({
2359
+ retryCommand: () => retryCommandFor({
2278
2360
  commandName: args.flags.dryRun ? "db update --dry-run" : "db update",
2279
2361
  to: args.flags.to,
2280
2362
  advanceRef: args.flags.advanceRef,
2363
+ statements: [
2364
+ ...renames,
2365
+ ...previewConsents,
2366
+ ...unansweredConsents(ctx.statements)
2367
+ ],
2281
2368
  canRunOffline: false
2282
2369
  })
2283
2370
  });
@@ -2308,34 +2395,21 @@ function createDbUpdateCommand(createClient) {
2308
2395
  let document;
2309
2396
  try {
2310
2397
  await client.connect(dbConnection);
2311
- const update = (consent) => client.dbUpdate({
2398
+ const reportPlannerWarnings = (warnings) => {
2399
+ for (const warning of warnings) ctx.report({
2400
+ kind: "message",
2401
+ severity: "warn",
2402
+ text: warning.summary
2403
+ });
2404
+ };
2405
+ const result = await client.dbUpdate({
2312
2406
  contract: contractJson,
2313
2407
  mode,
2314
2408
  migrationsDir,
2315
- ...consent === void 0 ? {} : { consent },
2409
+ statements: [...renames, ...previewConsents],
2410
+ answerQuestions: promptPlanQuestions(ctx.prompt),
2316
2411
  onProgress: controlProgressReporter(ctx.report)
2317
2412
  });
2318
- const reported = /* @__PURE__ */ new Set();
2319
- const reportPlannerWarnings = (warnings) => {
2320
- for (const warning of warnings) if (!reported.has(warning.summary)) {
2321
- reported.add(warning.summary);
2322
- ctx.report({
2323
- kind: "message",
2324
- severity: "warn",
2325
- text: warning.summary
2326
- });
2327
- }
2328
- };
2329
- let result = await update();
2330
- if (mode === "apply" && !result.ok && result.failure.code === "DESTRUCTIVE_CHANGES") {
2331
- reportPlannerWarnings(result.failure.warnings ?? []);
2332
- const refusal = result.failure.destructiveChanges;
2333
- if (refusal === void 0 || refusal.destructiveOperations.length === 0) return notOk$1(normalizeError(errorConsentOperationsMissing()));
2334
- const token = refusal.databaseName ?? "";
2335
- if (token.trim().length === 0) return notOk$1(normalizeError(errorConsentTokenUnresolved(ctx.config.target.targetId)));
2336
- if (!await ctx.prompt.consent(destructiveConsentQuestion(refusal.destructiveOperations, token), { token })) return notOk$1(normalizeError(mapDbUpdateFailure(result.failure)));
2337
- result = await update({ planHash: refusal.planHash });
2338
- }
2339
2413
  if (!result.ok) {
2340
2414
  reportPlannerWarnings(result.failure.warnings ?? []);
2341
2415
  return notOk$1(normalizeError(mapDbUpdateFailure(result.failure)));
@@ -2355,7 +2429,8 @@ function createDbUpdateCommand(createClient) {
2355
2429
  targetId: ctx.config.target.targetId,
2356
2430
  advancedRef: advanced.value.advancedRef,
2357
2431
  plannedAdvanceRef: advanced.value.plannedAdvanceRef,
2358
- startedAt
2432
+ startedAt,
2433
+ statements: previewConsents
2359
2434
  });
2360
2435
  } catch (error) {
2361
2436
  if (error instanceof CliStructuredError$1) throw error;
@@ -2374,7 +2449,10 @@ function createDbUpdateCommand(createClient) {
2374
2449
  contractPath: prepared.value.contractDisplayPath,
2375
2450
  database: prepared.value.database,
2376
2451
  to: args.flags.to,
2377
- dryRun: args.flags.dryRun
2452
+ dryRun: args.flags.dryRun,
2453
+ dbGiven: args.flags.db !== void 0,
2454
+ advanceRef: args.flags.advanceRef,
2455
+ statements: [...renames, ...previewConsents]
2378
2456
  })));
2379
2457
  }
2380
2458
  });
@@ -6866,7 +6944,7 @@ const lspCommand = defineServerCommand({
6866
6944
  } },
6867
6945
  handler: async (args, io) => {
6868
6946
  const exitCode = await withoutClientProcessIdInArgv(async () => {
6869
- const { startServer } = await import("./exports-CBfiI5mf.mjs");
6947
+ const { startServer } = await import("./exports-Bd3uWDtm.mjs");
6870
6948
  return startServer({
6871
6949
  stdin: io.stdin,
6872
6950
  stdout: io.stdout,
@@ -10343,8 +10421,9 @@ function planBlocks(result, migrationsRelative) {
10343
10421
  {
10344
10422
  kind: "summary",
10345
10423
  status: "ok",
10346
- text: "No changes detected"
10424
+ text: result.appliedStatements.length > 0 ? result.summary : "No changes detected"
10347
10425
  },
10426
+ ...appliedStatementBlocks(result.appliedStatements),
10348
10427
  outcome
10349
10428
  ];
10350
10429
  if (result.pendingPlaceholders === true) return [
@@ -10355,6 +10434,8 @@ function planBlocks(result, migrationsRelative) {
10355
10434
  text: result.summary
10356
10435
  },
10357
10436
  ...originNoticeBlocks(result),
10437
+ ...operationBlocks$1(result),
10438
+ ...appliedStatementBlocks(result.appliedStatements),
10358
10439
  outcome
10359
10440
  ];
10360
10441
  return [
@@ -10366,6 +10447,7 @@ function planBlocks(result, migrationsRelative) {
10366
10447
  },
10367
10448
  ...originNoticeBlocks(result),
10368
10449
  ...operationBlocks$1(result),
10450
+ ...appliedStatementBlocks(result.appliedStatements),
10369
10451
  outcome,
10370
10452
  ...previewBlocks$1(result)
10371
10453
  ];
@@ -10423,19 +10505,16 @@ function planPresentations(inputs) {
10423
10505
  next: () => planNextActions(inputs.document, inputs.migrationsRelative)
10424
10506
  };
10425
10507
  }
10426
- /** The question the user answers before a destructive baseline is written. */
10427
- function destructiveBaselineQuestion(operations) {
10428
- return [`Write a baseline migration containing ${operations.length} destructive operation(s)? Applying it would remove data that cannot be recovered:`, destructiveOperationList(operations)].join("\n");
10429
- }
10430
10508
  function createMigrationPlanCommand(createClient) {
10431
10509
  return defineOrmCommand({
10432
10510
  help: {
10433
10511
  summary: "Plan a migration from contract changes",
10434
- description: "Compares the emitted contract against the latest on-disk migration state\nand produces a new migration package with the required operations.\nOn an empty migrations directory a baseline package is derived from the\n`db` ref first; a baseline containing destructive operations is only\nwritten with your consent: the command asks you to type the project\ndirectory name, or takes `--confirm <directory>` where there is nobody\nto ask. Offline — does not consult the database.",
10512
+ description: "Compares the emitted contract against the latest on-disk migration state\nand produces a new migration package with the required operations.\nOn an empty migrations directory a baseline package is derived from the\n`db` ref first. A plan that would lose data is written only once you say\nwhat each such operation means: --rename to keep the data under a new\nname, or --delete to let it go. Where nobody can answer, the command\nrefuses and lists every question. Offline — does not consult the database.",
10435
10513
  examples: [
10436
10514
  "migration plan",
10437
10515
  "migration plan --name add-users-table",
10438
10516
  "migration plan --to <migration-dir>^ --name rollback",
10517
+ "migration plan --rename Profile:User --delete Legacy",
10439
10518
  "migration plan --json"
10440
10519
  ]
10441
10520
  },
@@ -10453,15 +10532,14 @@ function createMigrationPlanCommand(createClient) {
10453
10532
  placeholder: "contract"
10454
10533
  })
10455
10534
  } },
10535
+ statements: {
10536
+ rename: ormStatementVerbs.rename,
10537
+ delete: ormStatementVerbs.delete
10538
+ },
10456
10539
  needs: { config: ormConfigSection },
10457
10540
  handler: async (args, ctx) => {
10458
- const seededDirs = [];
10459
10541
  const seeded = (record) => {
10460
10542
  if (record.action !== "updated") return;
10461
- for (const dirName of record.newMigrationDirs) seededDirs.push({
10462
- spaceId: record.spaceId,
10463
- dirName
10464
- });
10465
10543
  const step = `Seed contract space ${record.spaceId}`;
10466
10544
  ctx.report({
10467
10545
  kind: "step-started",
@@ -10479,15 +10557,18 @@ function createMigrationPlanCommand(createClient) {
10479
10557
  }
10480
10558
  });
10481
10559
  };
10482
- const plan = (consent) => executeMigrationPlanCommand({
10560
+ const planned = await executeMigrationPlanCommand({
10483
10561
  config: ctx.config,
10484
10562
  cwd: ctx.cwd,
10485
10563
  projectDir: baseDirFor(ctx.config),
10486
10564
  ...ifDefined("name", args.flags.name),
10487
10565
  ...ifDefined("from", args.flags.from),
10488
10566
  ...ifDefined("to", args.flags.to),
10489
- ...ifDefined("consent", consent),
10490
- ...ifDefined("carryEmittedExtensionDirs", consent !== void 0 && seededDirs.length > 0 ? [...seededDirs] : void 0),
10567
+ statements: ctx.statements.take("rename").map(({ text }) => ({
10568
+ verb: "rename",
10569
+ text
10570
+ })),
10571
+ answerQuestions: promptPlanQuestions(ctx.prompt),
10491
10572
  client: createClient({
10492
10573
  family: ctx.config.family,
10493
10574
  target: ctx.config.target,
@@ -10496,14 +10577,6 @@ function createMigrationPlanCommand(createClient) {
10496
10577
  extensions: ctx.config.extensions ?? []
10497
10578
  })
10498
10579
  }, Date.now(), { onSeeded: seeded });
10499
- let planned = await plan();
10500
- if (!planned.ok && planned.failure.code === ERROR_CODE_DESTRUCTIVE_CHANGES) {
10501
- const verdict = blindCast(planned.failure.meta ?? {});
10502
- if (verdict.destructiveOperations === void 0 || verdict.destructiveOperations.length === 0 || verdict.planHash === void 0) return notOk$1(normalizeError(errorConsentOperationsMissing({ previewCommand: "{bin} migration plan" })));
10503
- const token = consentToken(ctx.cwd);
10504
- if (!await ctx.prompt.consent(destructiveBaselineQuestion(verdict.destructiveOperations), { token })) return notOk$1(normalizeError(planned.failure));
10505
- planned = await plan({ planHash: verdict.planHash });
10506
- }
10507
10580
  if (!planned.ok) return notOk$1(normalizeError(planned.failure));
10508
10581
  ctx.report({
10509
10582
  kind: "message",