@prisma/orm-toolchain 8.0.0-rc.2-dev.3 → 8.0.0-rc.20

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 (196) hide show
  1. package/README.md +1 -5
  2. package/dist/{aggregate-DLUJLq5Y.d.mts → aggregate-BpcQdygS.d.mts} +83 -36
  3. package/dist/aggregate-BpcQdygS.d.mts.map +1 -0
  4. package/dist/{aggregate-CPZB020V.mjs → aggregate-T_HG6gq6.mjs} +118 -57
  5. package/dist/aggregate-T_HG6gq6.mjs.map +1 -0
  6. package/dist/caught-errors-Bmbi1dBu-DKO5X2tN.mjs +1026 -0
  7. package/dist/caught-errors-Bmbi1dBu-DKO5X2tN.mjs.map +1 -0
  8. package/dist/cli-telemetry.d.mts +9 -8
  9. package/dist/cli-telemetry.d.mts.map +1 -1
  10. package/dist/cli-telemetry.mjs +30 -27
  11. package/dist/cli-telemetry.mjs.map +1 -1
  12. package/dist/cli.d.mts +7 -14
  13. package/dist/cli.d.mts.map +1 -1
  14. package/dist/cli.mjs +3769 -1506
  15. package/dist/cli.mjs.map +1 -1
  16. package/dist/cli__control-api.d.mts +233 -93
  17. package/dist/cli__control-api.d.mts.map +1 -1
  18. package/dist/cli__control-api.mjs +3 -2
  19. package/dist/cli__control-api__testing.d.mts +5 -4
  20. package/dist/cli__control-api__testing.d.mts.map +1 -1
  21. package/dist/cli__control-api__testing.mjs +21 -16
  22. package/dist/cli__control-api__testing.mjs.map +1 -1
  23. package/dist/cli__init-output.d.mts +11 -1
  24. package/dist/cli__init-output.d.mts.map +1 -1
  25. package/dist/cli__init-output.mjs +1 -1
  26. package/dist/cli__migration-cli.d.mts +1 -1
  27. package/dist/cli__migration-cli.mjs +65 -19
  28. package/dist/cli__migration-cli.mjs.map +1 -1
  29. package/dist/config-loader.d.mts +2 -2
  30. package/dist/config-loader.mjs +2 -2
  31. package/dist/{contract-snapshot-store-B0G1Fw_F-CHc4QfKb.mjs → contract-snapshot-store-6gIBcUeb-DJK3OM0j.mjs} +44 -16
  32. package/dist/contract-snapshot-store-6gIBcUeb-DJK3OM0j.mjs.map +1 -0
  33. package/dist/contract-snapshot-store-Bok5nQYi-D3g_P7im.d.mts +59 -0
  34. package/dist/contract-snapshot-store-Bok5nQYi-D3g_P7im.d.mts.map +1 -0
  35. package/dist/contract-snapshot-store-DrIwu5pn.d.mts +2 -0
  36. package/dist/{db-verify-BwgNK50T-DGvKgFCK.d.mts → db-sign-gvrl0kFE-D-nTGx88.d.mts} +330 -230
  37. package/dist/db-sign-gvrl0kFE-D-nTGx88.d.mts.map +1 -0
  38. package/dist/{domain-type-generation-bpSO3Y0L-jo2C7LlH.mjs → domain-type-generation-B4m774CV-WAjyhZHw.mjs} +144 -154
  39. package/dist/domain-type-generation-B4m774CV-WAjyhZHw.mjs.map +1 -0
  40. package/dist/domain-type-generation-DZjtzrbE-BpOOD3YV.d.mts +78 -0
  41. package/dist/domain-type-generation-DZjtzrbE-BpOOD3YV.d.mts.map +1 -0
  42. package/dist/emitter.d.mts +3 -3
  43. package/dist/emitter.mjs +3 -3
  44. package/dist/emitter__domain-type-generation.d.mts +2 -2
  45. package/dist/emitter__domain-type-generation.mjs +2 -2
  46. package/dist/{errors-D59OCpoI.d.mts → errors-CLwhWJiz.d.mts} +14 -3
  47. package/dist/errors-CLwhWJiz.d.mts.map +1 -0
  48. package/dist/{errors-CXbGUWGu-CstQHPh6.mjs → errors-DXha_4l--relAaiI4.mjs} +37 -42
  49. package/dist/errors-DXha_4l--relAaiI4.mjs.map +1 -0
  50. package/dist/exports-BCIlMjIW-DkUBVDzl.mjs +421 -0
  51. package/dist/exports-BCIlMjIW-DkUBVDzl.mjs.map +1 -0
  52. package/dist/exports-BlYTE3-J.mjs +539 -0
  53. package/dist/exports-BlYTE3-J.mjs.map +1 -0
  54. package/dist/exports-CKgwcXbp.mjs +3973 -0
  55. package/dist/exports-CKgwcXbp.mjs.map +1 -0
  56. package/dist/graph-membership-DxpNgxfZ-BfqA-H7V.mjs +19 -0
  57. package/dist/graph-membership-DxpNgxfZ-BfqA-H7V.mjs.map +1 -0
  58. package/dist/{hash-DH8hl5Rq-BpM2t3Nu.mjs → hash-BAZVWU4a-BQovI7hF.mjs} +24 -3
  59. package/dist/hash-BAZVWU4a-BQovI7hF.mjs.map +1 -0
  60. package/dist/hash-CwWGlFWV.d.mts +1 -0
  61. package/dist/{hash-XZYYKJ-i.d.mts → hash-DclMqd7S-WBvXJ_4C.d.mts} +17 -4
  62. package/dist/hash-DclMqd7S-WBvXJ_4C.d.mts.map +1 -0
  63. package/dist/{import-roots-CfoYgejL.d.mts → import-roots-ARK1wjzc.d.mts} +3 -3
  64. package/dist/{import-roots-CfoYgejL.d.mts.map → import-roots-ARK1wjzc.d.mts.map} +1 -1
  65. package/dist/{import-roots-CNFBPAT1.mjs → import-roots-BPn2s_fq.mjs} +6 -6
  66. package/dist/import-roots-BPn2s_fq.mjs.map +1 -0
  67. package/dist/index-CWPFeYyi.d.mts +204 -0
  68. package/dist/index-CWPFeYyi.d.mts.map +1 -0
  69. package/dist/{index-Dgwl8Tzs.d.mts → index-tAySVPvZ.d.mts} +16 -4
  70. package/dist/index-tAySVPvZ.d.mts.map +1 -0
  71. package/dist/{invariants-CTHy88OP-CYI2a8IO.mjs → invariants-DrF9p5Gd-BF70vGl1.mjs} +3 -3
  72. package/dist/{invariants-CTHy88OP-CYI2a8IO.mjs.map → invariants-DrF9p5Gd-BF70vGl1.mjs.map} +1 -1
  73. package/dist/{io-635GlNx1-D3zrw2qu.mjs → io-BNxFm3eg-DYD82QeZ.mjs} +8 -8
  74. package/dist/io-BNxFm3eg-DYD82QeZ.mjs.map +1 -0
  75. package/dist/io-D8Epu7iY.d.mts +1 -0
  76. package/dist/{io-sr4CO9_t-C3eV_kn-.d.mts → io-DZfMV51z-BKlH5Dhb.d.mts} +9 -2
  77. package/dist/io-DZfMV51z-BKlH5Dhb.d.mts.map +1 -0
  78. package/dist/{migration-B2ljMJim.d.mts → migration-Bjz05034.d.mts} +12 -5
  79. package/dist/migration-Bjz05034.d.mts.map +1 -0
  80. package/dist/{migration-hspPIEeV.mjs → migration-CWyjX9vz.mjs} +18 -6
  81. package/dist/migration-CWyjX9vz.mjs.map +1 -0
  82. package/dist/{migration-graph-_SJImD5V-BURyY1KM.mjs → migration-graph-BoiiZAaU-DLht12k7.mjs} +6 -89
  83. package/dist/migration-graph-BoiiZAaU-DLht12k7.mjs.map +1 -0
  84. package/dist/{migration-graph-tarTxJ99-BrGBANeE.d.mts → migration-graph-D8IuOkZb-pSI7-k4_.d.mts} +7 -29
  85. package/dist/migration-graph-D8IuOkZb-pSI7-k4_.d.mts.map +1 -0
  86. package/dist/migration-graph-Dra4CcyN.d.mts +14 -0
  87. package/dist/migration-graph-Dra4CcyN.d.mts.map +1 -0
  88. package/dist/migration-tools.d.mts +17 -15
  89. package/dist/migration-tools.mjs +15 -15
  90. package/dist/migration-tools__aggregate.d.mts +2 -2
  91. package/dist/migration-tools__aggregate.mjs +2 -2
  92. package/dist/migration-tools__contract-snapshot-store.d.mts +4 -2
  93. package/dist/migration-tools__contract-snapshot-store.mjs +2 -2
  94. package/dist/migration-tools__errors.d.mts +2 -2
  95. package/dist/migration-tools__errors.mjs +1 -1
  96. package/dist/migration-tools__hash.d.mts +2 -1
  97. package/dist/migration-tools__hash.mjs +1 -1
  98. package/dist/migration-tools__invariants.mjs +1 -1
  99. package/dist/migration-tools__io.d.mts +2 -2
  100. package/dist/migration-tools__io.mjs +1 -1
  101. package/dist/migration-tools__migration-graph.d.mts +3 -3
  102. package/dist/migration-tools__migration-graph.mjs +3 -3
  103. package/dist/migration-tools__migration-ts.d.mts +2 -2
  104. package/dist/migration-tools__migration-ts.mjs +2 -2
  105. package/dist/migration-tools__migration.d.mts +1 -1
  106. package/dist/migration-tools__migration.mjs +1 -1
  107. package/dist/migration-tools__ref-resolution.d.mts +2 -2
  108. package/dist/migration-tools__ref-resolution.mjs +2 -2
  109. package/dist/migration-tools__refs.mjs +1 -1
  110. package/dist/migration-tools__spaces.d.mts +1 -1
  111. package/dist/migration-tools__spaces.mjs +2 -2
  112. package/dist/{migration-ts-DdVm0rws.mjs → migration-ts-DDgjsR1O.mjs} +6 -5
  113. package/dist/migration-ts-DDgjsR1O.mjs.map +1 -0
  114. package/dist/{migration-ts-CNaAtK8C.d.mts → migration-ts-SGer0PXq.d.mts} +4 -2
  115. package/dist/migration-ts-SGer0PXq.d.mts.map +1 -0
  116. package/dist/op-schema-3tXg0LTS-DqpOKDEa.mjs +23 -0
  117. package/dist/op-schema-3tXg0LTS-DqpOKDEa.mjs.map +1 -0
  118. package/dist/output-BcC8eB0h-C5bRd-aC.mjs +129 -0
  119. package/dist/output-BcC8eB0h-C5bRd-aC.mjs.map +1 -0
  120. package/dist/publish-surface.d.mts +1 -1
  121. package/dist/publish-surface.mjs +2 -2
  122. package/dist/publish-surface__import-roots.d.mts +1 -1
  123. package/dist/publish-surface__import-roots.mjs +1 -1
  124. package/dist/publish-surface__shells.mjs +1 -1
  125. package/dist/quick-reference-mongo.md +12 -12
  126. package/dist/quick-reference-postgres.md +10 -10
  127. package/dist/quick-reference-prisma7.md +80 -0
  128. package/dist/readme-mongo.md +6 -6
  129. package/dist/readme-postgres.md +6 -6
  130. package/dist/ref-DEiY2Cbd-1ZImpUEN.mjs +6663 -0
  131. package/dist/ref-DEiY2Cbd-1ZImpUEN.mjs.map +1 -0
  132. package/dist/{ref-resolution-COGOSL57.d.mts → ref-resolution-BPhR-kta.d.mts} +29 -11
  133. package/dist/ref-resolution-BPhR-kta.d.mts.map +1 -0
  134. package/dist/{ref-resolution-HeNBXW53.mjs → ref-resolution-Eo0QHp4f.mjs} +30 -6
  135. package/dist/ref-resolution-Eo0QHp4f.mjs.map +1 -0
  136. package/dist/{refs-WK86uYYp-gM8tvWQP.mjs → refs-DM3q3IZC-BC6H6P0X.mjs} +9 -9
  137. package/dist/refs-DM3q3IZC-BC6H6P0X.mjs.map +1 -0
  138. package/dist/{shells-C4HbRAr5.mjs → shells-w_yEDhe8.mjs} +98 -31
  139. package/dist/shells-w_yEDhe8.mjs.map +1 -0
  140. package/dist/{spaces-Dj65JrwZ.d.mts → spaces-BWULKO54.d.mts} +3 -3
  141. package/dist/{spaces-Dj65JrwZ.d.mts.map → spaces-BWULKO54.d.mts.map} +1 -1
  142. package/dist/{spaces-4qMOAYE9.mjs → spaces-c9xdiXW8.mjs} +14 -13
  143. package/dist/spaces-c9xdiXW8.mjs.map +1 -0
  144. package/dist/{verify-contract-spaces-DhJTb0zM-B62maCfE.mjs → verify-contract-spaces-YzEHF9zj-DGZgox_3.mjs} +7 -7
  145. package/dist/{verify-contract-spaces-DhJTb0zM-B62maCfE.mjs.map → verify-contract-spaces-YzEHF9zj-DGZgox_3.mjs.map} +1 -1
  146. package/dist/vite-plugin-contract-emit.d.mts +1 -1
  147. package/dist/vite-plugin-contract-emit.mjs +10 -10
  148. package/dist/vite-plugin-contract-emit.mjs.map +1 -1
  149. package/package.json +16 -15
  150. package/dist/aggregate-CPZB020V.mjs.map +0 -1
  151. package/dist/aggregate-DLUJLq5Y.d.mts.map +0 -1
  152. package/dist/contract-snapshot-store-B0G1Fw_F-CHc4QfKb.mjs.map +0 -1
  153. package/dist/contract-snapshot-store-CbqynbtE.d.mts +0 -28
  154. package/dist/contract-snapshot-store-CbqynbtE.d.mts.map +0 -1
  155. package/dist/db-verify-BwgNK50T-DGvKgFCK.d.mts.map +0 -1
  156. package/dist/domain-type-generation-PkAb39ob-Ct8AGqow.d.mts +0 -63
  157. package/dist/domain-type-generation-PkAb39ob-Ct8AGqow.d.mts.map +0 -1
  158. package/dist/domain-type-generation-bpSO3Y0L-jo2C7LlH.mjs.map +0 -1
  159. package/dist/errors-CXbGUWGu-CstQHPh6.mjs.map +0 -1
  160. package/dist/errors-D59OCpoI.d.mts.map +0 -1
  161. package/dist/exports-8ZUN43ve.mjs +0 -1734
  162. package/dist/exports-8ZUN43ve.mjs.map +0 -1
  163. package/dist/exports-BCLg4CiV-05kuwcb0.mjs +0 -160
  164. package/dist/exports-BCLg4CiV-05kuwcb0.mjs.map +0 -1
  165. package/dist/exports-BZaG8_w_.mjs +0 -243
  166. package/dist/exports-BZaG8_w_.mjs.map +0 -1
  167. package/dist/graph-membership-BViWUMpP-C4lYYJdU.mjs +0 -14
  168. package/dist/graph-membership-BViWUMpP-C4lYYJdU.mjs.map +0 -1
  169. package/dist/hash-DH8hl5Rq-BpM2t3Nu.mjs.map +0 -1
  170. package/dist/hash-XZYYKJ-i.d.mts.map +0 -1
  171. package/dist/import-roots-CNFBPAT1.mjs.map +0 -1
  172. package/dist/index-DRs7L6N0.d.mts +0 -57
  173. package/dist/index-DRs7L6N0.d.mts.map +0 -1
  174. package/dist/index-Dgwl8Tzs.d.mts.map +0 -1
  175. package/dist/io-635GlNx1-D3zrw2qu.mjs.map +0 -1
  176. package/dist/io-DYfeLJxR.d.mts +0 -1
  177. package/dist/io-sr4CO9_t-C3eV_kn-.d.mts.map +0 -1
  178. package/dist/migration-B2ljMJim.d.mts.map +0 -1
  179. package/dist/migration-graph-Dqndu0i5.d.mts +0 -9
  180. package/dist/migration-graph-Dqndu0i5.d.mts.map +0 -1
  181. package/dist/migration-graph-_SJImD5V-BURyY1KM.mjs.map +0 -1
  182. package/dist/migration-graph-tarTxJ99-BrGBANeE.d.mts.map +0 -1
  183. package/dist/migration-hspPIEeV.mjs.map +0 -1
  184. package/dist/migration-ts-CNaAtK8C.d.mts.map +0 -1
  185. package/dist/migration-ts-DdVm0rws.mjs.map +0 -1
  186. package/dist/op-schema-BSVHzEQN-DIWt28D8.mjs +0 -13
  187. package/dist/op-schema-BSVHzEQN-DIWt28D8.mjs.map +0 -1
  188. package/dist/output-CovTDY14-CUoAqLML.mjs +0 -77
  189. package/dist/output-CovTDY14-CUoAqLML.mjs.map +0 -1
  190. package/dist/ref-h6InR6dO-rGfl18Jv.mjs +0 -4686
  191. package/dist/ref-h6InR6dO-rGfl18Jv.mjs.map +0 -1
  192. package/dist/ref-resolution-COGOSL57.d.mts.map +0 -1
  193. package/dist/ref-resolution-HeNBXW53.mjs.map +0 -1
  194. package/dist/refs-WK86uYYp-gM8tvWQP.mjs.map +0 -1
  195. package/dist/shells-C4HbRAr5.mjs.map +0 -1
  196. package/dist/spaces-4qMOAYE9.mjs.map +0 -1
@@ -0,0 +1,1026 @@
1
+ import "./constants-CM-w38DQ-Cz_EXbOc.mjs";
2
+ import { c as spaceMigrationDirectory, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-YzEHF9zj-DGZgox_3.mjs";
3
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
4
+ import { CliStructuredError as CliStructuredError$1, errorConfigValidation as errorConfigValidation$1, errorContractConfigMissing, errorContractValidationFailed, errorDatabaseConnectionRequired, errorDriverRequired, errorFileNotFound, errorMigrationPlanningFailed, errorTargetMigrationNotSupported, errorUnexpected } from "@prisma/orm-framework/errors/control";
5
+ import { APP_SPACE_ID, hasMigrations } from "@prisma/orm-framework/components/control";
6
+ import { InternalError, isInternalError } from "@prisma/orm-framework/utils/internal-error";
7
+ import { isStructuredError } from "@prisma/orm-framework/utils/structured-error";
8
+ import { relative, resolve } from "pathe";
9
+ import { errorHashMismatch, errorMarkerMissing, errorRuntime, errorTargetMismatch } from "@prisma/orm-framework/errors/execution";
10
+ import "@prisma/orm-framework/errors/migration";
11
+ import { readFile } from "node:fs/promises";
12
+ //#region ../../../1-framework/3-tooling/cli/dist/caught-errors-Bmbi1dBu.mjs
13
+ const SHELL_SAFE = /^[A-Za-z0-9_.:/@%+,-]+$/;
14
+ /** The value as a shell passes it through unchanged, single-quoted when needed. */
15
+ function shellQuoted(value) {
16
+ return SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
17
+ }
18
+ /**
19
+ * A statement written as a flag a shell passes through unchanged: the value is single-quoted when
20
+ * it has a character a shell would read, and joined with `=` when it starts with `-`, which a
21
+ * parser would otherwise read as a flag.
22
+ */
23
+ function statementFlag(statement) {
24
+ const value = shellQuoted(statement.text);
25
+ return statement.text.startsWith("-") ? `--${statement.verb}=${value}` : `--${statement.verb} ${value}`;
26
+ }
27
+ /**
28
+ * The typed remediation the CLI attaches to its own errors and findings.
29
+ * Constructors live here rather than in any library the CLI calls: naming a
30
+ * runnable invocation is something only the CLI can do.
31
+ */
32
+ function runCommandAction(label, command) {
33
+ return {
34
+ kind: "run-command",
35
+ label,
36
+ command
37
+ };
38
+ }
39
+ /** Advice the user carries out or decides on themselves, such as changing data in the database or choosing between plans; it has no command to run and edits no file. */
40
+ function chooseAction(label) {
41
+ return {
42
+ kind: "user-choice",
43
+ label
44
+ };
45
+ }
46
+ /** Advice that changes a file before anything runs again. */
47
+ function editFileAction(label) {
48
+ return {
49
+ kind: "edit-file",
50
+ label
51
+ };
52
+ }
53
+ /** The invocation of a command run with `ctx`, given `--db` when `db` is defined. */
54
+ function cliInvocation(ctx, db) {
55
+ return {
56
+ cwd: ctx.cwd,
57
+ configPath: ctx.configPath,
58
+ dbGiven: db !== void 0
59
+ };
60
+ }
61
+ /** The commands that connect to a database: those whose flags include `dbFlag`, which a test checks. */
62
+ const COMMANDS_TAKING_DB = /* @__PURE__ */ new Set([
63
+ "contract infer",
64
+ "db init",
65
+ "db migrate",
66
+ "db schema",
67
+ "db sign",
68
+ "db update",
69
+ "db verify",
70
+ "migration log",
71
+ "migration status"
72
+ ]);
73
+ function configWords(configPath) {
74
+ return configPath === void 0 ? [] : ["--config", shellQuoted(configPath)];
75
+ }
76
+ /**
77
+ * A CLI command as advice prints it: `{bin}`, the command and its arguments, the `--config` the CLI
78
+ * was given, and, for a command that connects to a database, `--db <url>` when the CLI was given
79
+ * `--db`, so it runs as printed from the directory the CLI ran in, against the same database. The
80
+ * URL stays a placeholder because it can hold credentials.
81
+ */
82
+ function cliCommand(invocation, command, args = []) {
83
+ return [
84
+ "{bin}",
85
+ command,
86
+ ...args,
87
+ ...configWords(invocation?.configPath),
88
+ ...invocation?.dbGiven === true && COMMANDS_TAKING_DB.has(command) ? ["--db", "<url>"] : []
89
+ ].join(" ");
90
+ }
91
+ /**
92
+ * The `migration plan` command advice prints: it starts from `from`, the contract the database is
93
+ * at, whenever that is known, because `migration plan` cannot find its origin without it once
94
+ * migrations exist and no `db` ref names one.
95
+ */
96
+ function printedPlanCommand(invocation, from, flags) {
97
+ return cliCommand(invocation, "migration plan", [...from === void 0 ? [] : ["--from", from], ...flags]);
98
+ }
99
+ /**
100
+ * The command that runs a `migration.ts`, named relative to the directory the CLI ran in, with the
101
+ * `--config` the CLI was given, so it loads the same config.
102
+ */
103
+ function selfEmitCommand(invocation, migrationTs) {
104
+ return [
105
+ "node",
106
+ shellQuoted(printedPath(invocation, migrationTs)),
107
+ ...configWords(invocation.configPath)
108
+ ].join(" ");
109
+ }
110
+ /** A path as advice prints it: relative to the directory the CLI ran in. */
111
+ function printedPath(invocation, path) {
112
+ return relative(invocation.cwd, path);
113
+ }
114
+ /**
115
+ * A CLI-raised error that carries the typed remediation as well as the prose.
116
+ * Only the CLI knows which invocation fixes a failure, so only errors raised
117
+ * here spell one; the foundation classes every library also raises keep
118
+ * carrying `code`, `why` and `fix` alone.
119
+ *
120
+ * Both fields are required: the `fix` prose is what the commander shell still
121
+ * renders, and the handler boundary drops it in favour of `nextActions` when it
122
+ * settles the engine's envelope.
123
+ */
124
+ var ActionableCliError = class extends CliStructuredError$1 {
125
+ nextActions;
126
+ constructor(code, summary, options) {
127
+ super(code, summary, options);
128
+ this.nextActions = options.nextActions;
129
+ }
130
+ };
131
+ /**
132
+ * A command that accepts a contract reference both as a positional and as a
133
+ * flag was given both. Structured rather than a bare stderr line, so a script
134
+ * sees the same envelope every other invocation failure produces.
135
+ */
136
+ function errorContractArgConflict(options) {
137
+ const fix = "Pass the contract reference once — either as the positional argument or as --contract.";
138
+ return new ActionableCliError("CLI.CONTRACT_ARG_CONFLICT", "Cannot specify both a positional contract argument and --contract", {
139
+ why: `The positional argument names "${options.positional}" and --contract names "${options.flag}"; there is no rule for which wins.`,
140
+ fix,
141
+ nextActions: [chooseAction(fix)],
142
+ meta: {
143
+ positional: options.positional,
144
+ flag: options.flag
145
+ }
146
+ });
147
+ }
148
+ /**
149
+ * A command was told both which ref to advance and not to advance any ref.
150
+ * Same envelope as the positional/flag contract conflict, so a script sees
151
+ * every invocation conflict in one shape.
152
+ */
153
+ function errorAdvanceRefArgConflict(options) {
154
+ const fix = "Pass either --advance-ref <name> or --no-advance-ref, not both.";
155
+ return new ActionableCliError("CLI.ADVANCE_REF_ARG_CONFLICT", "Cannot specify both --advance-ref and --no-advance-ref", {
156
+ why: `--advance-ref names "${options.advanceRef}" while --no-advance-ref asks for no ref to be written; there is no rule for which wins.`,
157
+ fix,
158
+ nextActions: [chooseAction(fix)],
159
+ meta: { advanceRef: options.advanceRef }
160
+ });
161
+ }
162
+ function quotedSpaces(spaces) {
163
+ return spaces.map((space) => `"${space}"`).join(", ");
164
+ }
165
+ function notSignedSentence(spaces, because, becausePlural) {
166
+ if (spaces.length === 0) return "";
167
+ return spaces.length === 1 ? ` Space ${quotedSpaces(spaces)} was not signed, because ${because}.` : ` Spaces ${quotedSpaces(spaces)} were not signed, because ${becausePlural}.`;
168
+ }
169
+ /**
170
+ * `db sign` wrote the markers, then failed to write one or more refs or their snapshots. The database is signed; running the command again writes the refs. The error also names the spaces it did not sign: those whose schema failed verification, and those whose marker changed while it ran.
171
+ */
172
+ function errorSignRefsNotWritten(options) {
173
+ const { signedSpaces, failedSpaces, conflictSpaces, unwrittenRefs, rerunCommand } = options;
174
+ const markers = signedSpaces.length === 1 ? `the marker of space ${quotedSpaces(signedSpaces)} holds its contract` : `the markers of spaces ${quotedSpaces(signedSpaces)} hold their contracts`;
175
+ const notSigned = notSignedSentence(failedSpaces, "its schema does not satisfy its contract", "their schemas do not satisfy their contracts") + notSignedSentence(conflictSpaces, "its marker changed while db sign ran", "their markers changed while db sign ran");
176
+ const refs = unwrittenRefs.map((ref) => `ref "${ref.name}" of space "${ref.space}" (${ref.reason})`).join("; ");
177
+ const count = unwrittenRefs.length;
178
+ return new ActionableCliError("MIGRATION.SIGN_REFS_NOT_WRITTEN", `Database signed, but ${count} ${count === 1 ? "ref was" : "refs were"} not written`, {
179
+ why: `The database was signed: ${markers}.${notSigned} These refs were not written: ${refs}.`,
180
+ fix: `Fix what stopped the write, then run \`${rerunCommand}\` again: the markers already hold the contracts, so it writes only the refs.`,
181
+ nextActions: [runCommandAction("Sign again to write the refs that were not written", rerunCommand)],
182
+ meta: {
183
+ signedSpaces,
184
+ failedSpaces,
185
+ conflictSpaces,
186
+ unwrittenRefs,
187
+ advancedRefs: options.advancedRefs
188
+ },
189
+ cause: options.cause
190
+ });
191
+ }
192
+ function errorRefSetHashNotInGraph(resolvedHash, reachableHashes) {
193
+ const reachableList = reachableHashes.length > 0 ? reachableHashes.join(", ") : "(none — migration graph is empty)";
194
+ const fix = reachableHashes.length > 0 ? "Set the ref to the `to` hash of an on-disk migration; `{bin} migration list` shows them." : "Run `{bin} migration plan` first.";
195
+ const nextActions = reachableHashes.length > 0 ? [runCommandAction("List the migrations and their destination hashes", "{bin} migration list"), chooseAction("Set the ref to the `to` hash of one of them")] : [runCommandAction("Plan the first migration", "{bin} migration plan")];
196
+ return new ActionableCliError("MIGRATION.HASH_NOT_IN_GRAPH", `Resolved contract hash is not in the migration graph: ${resolvedHash}`, {
197
+ why: reachableHashes.length > 0 ? `The migration graph reaches ${reachableList}; resolved ${resolvedHash} isn't a graph node.` : "The migration graph is empty — no hashes reachable.",
198
+ fix,
199
+ nextActions,
200
+ meta: {
201
+ resolvedHash,
202
+ reachableHashes: [...reachableHashes]
203
+ }
204
+ });
205
+ }
206
+ function errorRefSetEmptySentinel(hash) {
207
+ return new ActionableCliError("MIGRATION.REF_SET_EMPTY_SENTINEL", `Cannot set ref to the empty-database sentinel: ${hash}`, {
208
+ why: "The empty-database sentinel is a planner internal; it is not a valid ref target.",
209
+ fix: "Set the ref to a contract hash from the migration graph, or use another ref name.",
210
+ nextActions: [chooseAction("Set the ref to a contract hash from the migration graph"), chooseAction("Or use another ref name")],
211
+ meta: { hash }
212
+ });
213
+ }
214
+ /**
215
+ * `--legend` was combined with a machine-readable or silent output flag.
216
+ * The legend is human-only decoration on stderr.
217
+ */
218
+ function errorLegendHumanOnly(conflictingFlag) {
219
+ return new ActionableCliError("MIGRATION.LEGEND_HUMAN_ONLY", "`--legend` is only available for human-readable output", {
220
+ why: `\`--legend\` prints a glyph key to stderr and cannot be combined with ${conflictingFlag}.`,
221
+ fix: `Omit ${conflictingFlag} to print the legend alongside the tree, or omit --legend when using ${conflictingFlag}.`,
222
+ nextActions: [chooseAction(`Omit ${conflictingFlag} to print the legend alongside the tree`), chooseAction(`Or omit --legend when using ${conflictingFlag}`)],
223
+ meta: { conflictingFlag }
224
+ });
225
+ }
226
+ /**
227
+ * `--space <id>` was given a value that doesn't satisfy the contract-space
228
+ * naming rule (`[a-z][a-z0-9_-]{0,63}` per `isValidSpaceId`). Fires before
229
+ * any fs work — the input is syntactically rejected the same way an on-disk
230
+ * directory with that name would be skipped by the enumerator.
231
+ */
232
+ function errorInvalidSpaceId(spaceId) {
233
+ return new ActionableCliError("MIGRATION.INVALID_SPACE_ID", `Invalid contract space id: ${spaceId}`, {
234
+ why: "Contract space ids must match [a-z][a-z0-9_-]{0,63} (lowercase, starts with a letter, max 64 characters — the rule applied to every on-disk space directory).",
235
+ fix: "Pass a space id that matches the directory naming rule, or omit --space to list every space.",
236
+ nextActions: [chooseAction("Pass a space id matching [a-z][a-z0-9_-]{0,63}"), runCommandAction("Or list every space", "{bin} migration list")],
237
+ meta: { spaceId }
238
+ });
239
+ }
240
+ /**
241
+ * `migration list --space <id>` was given a contract-space id that has no
242
+ * directory under `migrations/`. Distinct from "the space exists but is
243
+ * empty" — that path renders the empty-state line and exits 0 per the
244
+ * slice spec § Empty-state. This error fires only when `<projectMigrationsDir>/<spaceId>`
245
+ * does not exist on disk.
246
+ *
247
+ * `availableSpaces` lists the contract-space directory names actually
248
+ * present, sorted lex-asc, so the diagnostic can suggest a near match
249
+ * without making the user reach for `ls`.
250
+ */
251
+ function errorSpaceNotFound(spaceId, availableSpaces) {
252
+ const availableList = availableSpaces.length > 0 ? availableSpaces.join(", ") : "(none — no contract spaces on disk yet)";
253
+ const fix = availableSpaces.length > 0 ? `Pick one of: ${availableList}. Run \`{bin} migration list\` (no --space) to see every space's migrations.` : "Author a migration with `{bin} migration new` to create the first contract-space directory.";
254
+ const nextActions = availableSpaces.length > 0 ? [chooseAction(`Pick one of: ${availableList}`), runCommandAction("See every space's migrations", "{bin} migration list")] : [runCommandAction("Author the first migration, which creates the contract-space directory", "{bin} migration new")];
255
+ return new ActionableCliError("MIGRATION.SPACE_NOT_FOUND", `Unknown contract space: ${spaceId}`, {
256
+ why: `No directory named "${spaceId}" exists under the migrations root.`,
257
+ fix,
258
+ nextActions,
259
+ meta: {
260
+ spaceId,
261
+ availableSpaces: [...availableSpaces]
262
+ }
263
+ });
264
+ }
265
+ /**
266
+ * A `migration show` target resolved to a directory or a graph node, but no
267
+ * on-disk package was loaded for it.
268
+ */
269
+ function errorMigrationPackageNotFound(why) {
270
+ return new ActionableCliError("MIGRATION.PACKAGE_NOT_FOUND", "Migration package not found", {
271
+ why,
272
+ fix: "Pass a directory name, hash prefix, or path to an on-disk app-space migration package.",
273
+ nextActions: [chooseAction("Pass a directory name, hash prefix, or path to an on-disk app-space migration package"), runCommandAction("List what is on disk", "{bin} migration list")]
274
+ });
275
+ }
276
+ /** The app space has no migration packages at all, so no target can resolve. */
277
+ function errorNoMigrations(appMigrationsRelative) {
278
+ return new ActionableCliError("MIGRATION.NO_MIGRATIONS", "No migrations found", {
279
+ why: `No migration packages found in ${appMigrationsRelative}`,
280
+ fix: "Run `{bin} migration plan` to create a migration first.",
281
+ nextActions: [runCommandAction("Create the first migration", "{bin} migration plan")]
282
+ });
283
+ }
284
+ function errorRefSetBundleNotFound(hash) {
285
+ return new ActionableCliError("MIGRATION.REF_SET_BUNDLE_NOT_FOUND", `No migration bundle matches graph-node hash ${hash}`, {
286
+ why: `The hash is a graph node but no on-disk bundle has metadata.to = ${hash}.`,
287
+ fix: "Run `pnpm fixtures:check`, or re-emit the migration that produces this hash so its bundle is restored.",
288
+ nextActions: [runCommandAction("Restore the checked-in fixtures", "pnpm fixtures:check"), chooseAction("Or re-emit the migration that produces this hash")],
289
+ meta: { hash }
290
+ });
291
+ }
292
+ function errorPlanForgotTheFlag(resolvedHash, reachableRefs, options) {
293
+ const reachableList = reachableRefs.length > 0 ? reachableRefs.map((r) => `${r.name} (${r.hash})`).join(", ") : "(none)";
294
+ const refFix = reachableRefs.length > 0 ? `Run migration plan with ${reachableRefs.map((r) => `--from ${r.name}`).join(" or ")}.` : "Pass --from <contract> naming the `to` hash of an on-disk migration (`{bin} migration list` shows them), or point the db ref at one with `{bin} migration ref set db <contract>`.";
295
+ const nextActions = reachableRefs.length > 0 ? reachableRefs.map((ref) => runCommandAction(`Plan from ${ref.name}`, `{bin} migration plan --from ${ref.name}`)) : [runCommandAction("Plan from an explicit origin", "{bin} migration plan --from <contract>"), runCommandAction("Point the db ref at a graph node", "{bin} migration ref set db <contract>")];
296
+ return new ActionableCliError("MIGRATION.HASH_NOT_IN_GRAPH", `Resolved from-hash is not in the migration graph: ${resolvedHash}`, {
297
+ why: `The migration graph reaches ${reachableList}; resolved ${resolvedHash} isn't a graph node.`,
298
+ fix: refFix,
299
+ nextActions,
300
+ meta: {
301
+ resolvedHash,
302
+ reachableRefs: reachableRefs.map((r) => r.name)
303
+ },
304
+ ...ifDefined("cause", options?.cause)
305
+ });
306
+ }
307
+ /**
308
+ * `viaRef: true` (the default) mirrors migration-tools' `errorRefNotResolvable`:
309
+ * a ref name with no pointer file, where the fallback hash isn't a graph
310
+ * node either — there's nothing to materialize a contract from.
311
+ * `viaRef: false` is a distinct, ref-independent case: an explicit `--from
312
+ * <hash>` that doesn't name a ref, on an empty migration graph, so there is
313
+ * no graph node and no ref to resolve a contract through.
314
+ */
315
+ function errorSnapshotMissing(identifier, options) {
316
+ const viaRef = options?.viaRef !== false;
317
+ const fix = viaRef ? `Create the ref with "{bin} migration ref set ${identifier} <hash>" (or advance it via "{bin} db update --advance-ref ${identifier}"), or pass a hash that is a node in the migration graph.` : `No contract source exists for hash "${identifier}" on an empty migration graph. Use --from with a ref name (its contract resolves through the snapshot store), or run db update first.`;
318
+ const nextActions = viaRef ? [
319
+ runCommandAction(`Create the ref "${identifier}"`, `{bin} migration ref set ${identifier} <hash>`),
320
+ runCommandAction("Or advance it from the database", `{bin} db update --advance-ref ${identifier}`),
321
+ chooseAction("Or pass a hash that is a node in the migration graph")
322
+ ] : [chooseAction("Pass --from a ref name, whose contract resolves through the snapshot store"), runCommandAction("Or populate the graph first", "{bin} db update")];
323
+ return new ActionableCliError("MIGRATION.SNAPSHOT_MISSING", viaRef ? `Ref "${identifier}" is not resolvable` : `No contract source for from-hash "${identifier}"`, {
324
+ why: viaRef ? `Ref "${identifier}" has no pointer file, and the hash being resolved is not a node in the migration graph either.` : `Hash "${identifier}" is not a node in the migration graph (the graph is empty), and it does not name a ref either.`,
325
+ fix,
326
+ nextActions,
327
+ meta: {
328
+ identifier,
329
+ viaRef
330
+ },
331
+ ...ifDefined("cause", options?.cause)
332
+ });
333
+ }
334
+ /**
335
+ * Default origin resolution for `migration plan` found nothing (no `--from`,
336
+ * no `db` ref) while migrations already exist on disk. Planning would silently
337
+ * produce an empty-origin migration that ignores the existing history — almost
338
+ * always a mistake — so the command refuses and names the three exits.
339
+ */
340
+ function errorPlanOriginUnknown(reachableRefs) {
341
+ const fromSuggestion = reachableRefs.length > 0 ? reachableRefs.map((r) => `--from ${r.name}`).join(" or ") : "--from <contract>";
342
+ const refSetCommand = "{bin} migration ref set db <contract>";
343
+ return new ActionableCliError("MIGRATION.PLAN_ORIGIN_UNKNOWN", "Cannot determine the plan origin: migrations exist but no origin is named", {
344
+ why: "Migrations exist on disk, but there is no `db` ref and no --from was given, so the plan origin would silently fall back to an empty database and the resulting migration would recreate everything the existing migrations already create.",
345
+ fix: [
346
+ `Set the \`db\` ref to the contract your dev database is at (\`${refSetCommand}\`), or advance it via \`{bin} db update\`.`,
347
+ `Or pass the origin explicitly: \`{bin} migration plan ${fromSuggestion}\`.`,
348
+ "Or pass --from @empty to deliberately plan from an empty database."
349
+ ].join("\n"),
350
+ nextActions: [
351
+ runCommandAction("Point the db ref at the origin contract", refSetCommand),
352
+ ...reachableRefs.length > 0 ? reachableRefs.map((ref) => runCommandAction(`Plan from ${ref.name}`, `{bin} migration plan --from ${ref.name}`)) : [runCommandAction("Plan from an explicit origin", `{bin} migration plan ${fromSuggestion}`)],
353
+ runCommandAction("Plan from an empty database deliberately", "{bin} migration plan --from @empty")
354
+ ],
355
+ meta: { reachableRefs: reachableRefs.map((r) => r.name) }
356
+ });
357
+ }
358
+ function errorStatementInvalid(statement, why, fix) {
359
+ return new ActionableCliError("MIGRATION.STATEMENT_INVALID", `Invalid statement "--${statement.verb} ${statement.text}"`, {
360
+ why,
361
+ fix,
362
+ nextActions: [chooseAction(fix)],
363
+ meta: {
364
+ statement: statement.text,
365
+ verb: statement.verb
366
+ }
367
+ });
368
+ }
369
+ /**
370
+ * A statement is well formed, but its names do not resolve in the
371
+ * origin and destination contracts the way a rename requires.
372
+ */
373
+ function errorStatementUnresolved(statement, why, fix) {
374
+ return new ActionableCliError("MIGRATION.STATEMENT_UNRESOLVED", `Cannot resolve statement "--${statement.verb} ${statement.text}"`, {
375
+ why,
376
+ fix,
377
+ nextActions: [chooseAction(fix)],
378
+ meta: {
379
+ statement: statement.text,
380
+ verb: statement.verb
381
+ }
382
+ });
383
+ }
384
+ /**
385
+ * A rename or convert typed in answer to a data-loss question was planned, and the plan still loses
386
+ * the subject's data: the statement does not account for the operation the question was about.
387
+ */
388
+ function errorStatementDidNotResolveLoss(statement, subject) {
389
+ const fix = `Answer the question about "${subject}" with ${statementFlag({
390
+ verb: "delete",
391
+ text: subject
392
+ })} if its data may be lost, or give a ${statement.verb} statement that keeps that data.`;
393
+ return new ActionableCliError("MIGRATION.STATEMENT_DID_NOT_RESOLVE_LOSS", `"--${statement.verb} ${statement.text}" does not keep the data of "${subject}"`, {
394
+ why: `The plan was made again with the statement, and it still loses the data of "${subject}".`,
395
+ fix,
396
+ nextActions: [chooseAction(fix)],
397
+ meta: {
398
+ statement: statement.text,
399
+ verb: statement.verb,
400
+ subject
401
+ }
402
+ });
403
+ }
404
+ /** `--convert` and `--delete` name the same field, and each answers its type change differently. */
405
+ function errorConvertAndDelete(field) {
406
+ const fix = `Give one of them: ${statementFlag({
407
+ verb: "convert",
408
+ text: field
409
+ })}, or ${statementFlag({
410
+ verb: "delete",
411
+ text: field
412
+ })}.`;
413
+ return new ActionableCliError("MIGRATION.STATEMENT_INVALID", `"--convert ${field}" and "--delete ${field}" conflict`, {
414
+ why: `Both answer the type change of "${field}": --convert converts each value with code you write in migration.ts, and --delete lets the database cast each value, losing those it cannot keep.`,
415
+ fix,
416
+ nextActions: [chooseAction(fix)],
417
+ meta: {
418
+ statement: field,
419
+ verb: "convert"
420
+ }
421
+ });
422
+ }
423
+ const MIGRATION_PLAN_VERBS = [
424
+ "rename",
425
+ "delete",
426
+ "convert",
427
+ "backfill"
428
+ ];
429
+ /**
430
+ * `--convert` or `--backfill` statements were given to `db update`, which applies its plan
431
+ * directly and so has no migration file whose slot the user could fill. `statements` are every
432
+ * statement the user gave, in the order given: the `migration plan` command the error suggests
433
+ * carries each one that command accepts, and starts from `databaseStorageHash`, the contract the
434
+ * database is at, when it is known. Its commands repeat the `--config` of `invocation`.
435
+ */
436
+ function errorStatementNeedsMigrationFile(statements, invocation, databaseStorageHash) {
437
+ const refused = statements.filter(({ verb }) => verb === "convert" || verb === "backfill");
438
+ const written = refused.map(({ verb, text }) => `"--${verb} ${text}"`);
439
+ const listed = written.length === 1 ? written[0] : `${written.slice(0, -1).join(", ")} and ${written.at(-1)}`;
440
+ const plan = printedPlanCommand(invocation, databaseStorageHash, statements.filter(({ verb }) => MIGRATION_PLAN_VERBS.includes(verb)).map(statementFlag));
441
+ return new ActionableCliError("MIGRATION.STATEMENT_NEEDS_MIGRATION_FILE", `db update cannot carry out ${listed}`, {
442
+ why: "--convert and --backfill ask for a migration file with a slot for the code that converts or fills in the values, and db update has no migration file to fill: it applies its plan directly.",
443
+ fix: `Plan the change with ${plan}, fill in the migration.ts it writes, run that migration.ts with the \`node\` command \`migration plan\` prints, and apply it with ${cliCommand(invocation, "db migrate")}. Or leave out these statements: db update then asks before it loses any data.`,
444
+ nextActions: [runCommandAction("Plan the change into a migration file to fill in", plan), chooseAction("Or run db update without these statements")],
445
+ meta: { statements: refused.map(({ verb, text }) => ({
446
+ verb,
447
+ text
448
+ })) }
449
+ });
450
+ }
451
+ function unusedConsentSentence({ verb, text, alreadyAnsweredBy: answeredBy }) {
452
+ if (answeredBy === void 0) return `--${verb} ${text} was given but nothing in this run asked about ${text}.`;
453
+ if (answeredBy.kind === "namespace") return `--${verb} ${text} was given, but every question about namespace "${answeredBy.namespace}" was already answered by another flag.`;
454
+ return `--${verb} ${text} was given, but the question about ${answeredBy.subject} was already answered by --${answeredBy.flag.verb} ${answeredBy.flag.text}.`;
455
+ }
456
+ function errorConsentUnused(unused, asked) {
457
+ const actions = [...unused.some(({ alreadyAnsweredBy }) => alreadyAnsweredBy === void 0) ? ["Remove the flag, or spell the subject the way the command names it."] : [], ...unused.some(({ alreadyAnsweredBy }) => alreadyAnsweredBy !== void 0) ? ["Give one flag per question."] : []];
458
+ return new CliStructuredError$1("CLI.CONSENT_UNUSED", unused.map(unusedConsentSentence).join(" "), {
459
+ ...ifDefined("why", asked.length === 0 ? void 0 : `The run asked about ${asked.join(", ")}.`),
460
+ nextActions: actions.map((label) => ({
461
+ kind: "user-choice",
462
+ label
463
+ })),
464
+ meta: {
465
+ unused: unused.map(({ verb, text }) => ({
466
+ verb,
467
+ values: [text]
468
+ })),
469
+ ...asked.length === 0 ? {} : { asked }
470
+ }
471
+ });
472
+ }
473
+ /**
474
+ * `delete` or `allow` statements given to a programmatic call match no question the plan asks,
475
+ * so they consent to nothing.
476
+ */
477
+ function errorStatementAnswersNoQuestion(statements, subjects) {
478
+ const written = statements.map(({ verb, text }) => `"--${verb} ${text}"`);
479
+ const listed = written.length === 1 ? `Statement ${written[0]} answers` : `Statements ${written.slice(0, -1).join(", ")} and ${written.at(-1)} answer`;
480
+ const fix = subjects.length === 0 ? "Leave the statements out: the plan asks no question." : `Leave them out, or name a subject the plan asks about: ${subjects.join(", ")}.`;
481
+ return new ActionableCliError("MIGRATION.STATEMENT_ANSWERS_NO_QUESTION", `${listed} no question of the plan`, {
482
+ why: "A delete or allow statement consents to an operation the plan asks about, and these name no subject the plan would lose data from or change access to.",
483
+ fix,
484
+ nextActions: [chooseAction(fix)],
485
+ meta: {
486
+ statements: statements.map(({ verb, text }) => ({
487
+ verb,
488
+ text
489
+ })),
490
+ subjects
491
+ }
492
+ });
493
+ }
494
+ /**
495
+ * Without statements, `db update` drops a renamed table or column and creates it again under the
496
+ * new name, so any advice to run without them says so.
497
+ */
498
+ const WITHOUT_STATEMENTS_DROPS = "A plan made without statements drops the storage of each renamed model or field with its data and creates it again under the new name, and asks for consent before it does.";
499
+ /** How to store the snapshot of the contract the database is at, so statements can resolve. */
500
+ const STORE_ORIGIN_SNAPSHOT_STEPS = [
501
+ "1. Put the contract source back to the version the database is at, and run `{bin} contract emit`.",
502
+ "2. Run `{bin} db update --advance-ref <name> --dry-run`, with the same `--db` as this command if it has one, and check that it plans no operations. Then run it again without `--dry-run`: the database matches that contract, so this changes nothing in it, and it stores the contract snapshot. If the dry run plans operations, the database has drifted from that contract; settle that before you go on.",
503
+ "3. Put the new contract source back, run `{bin} contract emit`, and run this command again with `--advance-ref <name>`."
504
+ ];
505
+ /**
506
+ * Statements were given, but there is no origin contract to resolve their old
507
+ * names against.
508
+ */
509
+ function errorStatementOriginUnknown(origin) {
510
+ if (origin.hash === null) return new ActionableCliError("MIGRATION.STATEMENT_ORIGIN_UNKNOWN", "Cannot resolve statements: the database has no marker", {
511
+ why: "The database has no marker: Prisma has never initialised or updated it, so there is no earlier contract whose names a statement could rename.",
512
+ fix: `Leave out the statements. If the database already holds data under the old names, preview the plan with --dry-run first. ${WITHOUT_STATEMENTS_DROPS}`,
513
+ nextActions: [chooseAction(`Leave out the statements, and preview the plan with --dry-run first. ${WITHOUT_STATEMENTS_DROPS}`)],
514
+ meta: {
515
+ hash: null,
516
+ snapshotDirectory: origin.snapshotDirectory
517
+ }
518
+ });
519
+ const meta = {
520
+ hash: origin.hash,
521
+ snapshotDirectory: origin.snapshotDirectory,
522
+ ...ifDefined("unreadable", origin.unreadable)
523
+ };
524
+ if (origin.unreadable !== void 0) return new ActionableCliError("MIGRATION.STATEMENT_ORIGIN_UNKNOWN", "Cannot resolve statements: the origin contract snapshot cannot be read", {
525
+ why: `The contract snapshot for hash "${origin.hash}" in ${origin.snapshotDirectory} could not be read: ${origin.unreadable}`,
526
+ fix: ["Restore migrations/snapshots/ from version control. If no good copy exists, store the snapshot again:", ...STORE_ORIGIN_SNAPSHOT_STEPS].join("\n"),
527
+ nextActions: [chooseAction("Restore migrations/snapshots/ from version control"), chooseAction("Or store the snapshot again from the contract the database is at")],
528
+ meta
529
+ });
530
+ return new ActionableCliError("MIGRATION.STATEMENT_ORIGIN_UNKNOWN", "Cannot resolve statements: the origin contract is unknown", {
531
+ why: `No contract snapshot for hash "${origin.hash}" was found in ${origin.snapshotDirectory}. Statements name things in the contract the database is at, so the command needs that contract. \`db update\` stores the snapshot of the contract it applies only when it advances a ref: the \`db\` ref by default, or with \`--db <url>\` only the ref named by \`--advance-ref <name>\`. Most likely the run that brought the database to this contract advanced no ref.`,
532
+ fix: [
533
+ "Store the snapshot of the contract the database is at, then run the rename:",
534
+ ...STORE_ORIGIN_SNAPSHOT_STEPS,
535
+ "Adding --advance-ref to this command alone does not help: it would store the new contract, not the one the database is at. `migration plan --from` does not apply to `db update`."
536
+ ].join("\n"),
537
+ nextActions: [
538
+ chooseAction("Put the contract source back to the version the database is at, and emit it"),
539
+ runCommandAction("Check that it plans no operations (with the same --db as this command, if any)", "{bin} db update --advance-ref <name> --dry-run"),
540
+ runCommandAction("Then store its snapshot, which changes nothing in the database", "{bin} db update --advance-ref <name>"),
541
+ chooseAction("Put the new contract source back, emit it, and run this command again with --advance-ref <name>")
542
+ ],
543
+ meta
544
+ });
545
+ }
546
+ const REPORT_MISSED_CHANGE = "If you expected the database to change, migration plan missed it: report it with the output of `prisma migration plan --json`.";
547
+ function noOperationsConflict(origin, destination) {
548
+ switch (origin.kind) {
549
+ case "empty": return {
550
+ kind: "nothingToCreate",
551
+ summary: "This contract describes nothing migration plan can create, so there is no first migration to plan.",
552
+ why: destination.isEmitted ? "If the database needs something the contract does not describe, run `prisma migration new`, add its operations to the new `migration.ts`, then run that `migration.ts` with `node` to write `ops.json`." : "`prisma migration new` writes a migration only to the emitted contract. If the database needs something this contract does not describe, emit it, run `prisma migration new`, add its operations to the new `migration.ts`, then run that `migration.ts` with `node` to write `ops.json`."
553
+ };
554
+ case "baseline": return {
555
+ kind: "nothingToBaseline",
556
+ summary: `The migrations directory is empty, so migration plan starts the migration history with a baseline migration to the contract the db ref points at, ${origin.hash}. That contract describes nothing migration plan can create, so there is no baseline to plan.`,
557
+ why: "No command writes a baseline migration with no operations. If you manage the database with `prisma db init` or `prisma db update`, keep using `prisma db update`. No command can start a migration history from this database yet; report it with the output of `prisma migration plan --json`."
558
+ };
559
+ case "contract": return {
560
+ kind: "noDatabaseChange",
561
+ summary: "The contract changed, but migration plan found nothing to change in the database. That is expected after a Prisma upgrade that changes how contract.json records values, after you switch a field to another codec of the same type, or after you change a control policy.",
562
+ why: destination.isEmitted ? `If you deploy with migrations, run \`prisma migration new --from ${origin.hash}\` to write a migration with no operations, then \`prisma db migrate\`. If you manage the database with \`prisma db init\` or \`prisma db update\`, run \`prisma db sign\` on each database instead. ${REPORT_MISSED_CHANGE}` : `\`prisma migration new\` writes a migration only to the emitted contract; to write one to this target, emit it first. If you manage the database with \`prisma db init\` or \`prisma db update\`, run \`prisma db sign ${destination.hash}\` on each database. ${REPORT_MISSED_CHANGE}`
563
+ };
564
+ }
565
+ }
566
+ /** `migration plan` refuses a leg whose planner produced no operations, and says how to proceed from where it planned. */
567
+ function errorPlanProducedNoOperations(origin, destination) {
568
+ return errorMigrationPlanningFailed({ conflicts: [noOperationsConflict(origin, destination)] });
569
+ }
570
+ function errorMarkerMismatch(markerHash, reachableHashes) {
571
+ return new ActionableCliError("MIGRATION.MARKER_MISMATCH", "Database marker is not reachable in the on-disk migration graph", {
572
+ why: `DB marker is ${markerHash}, but the on-disk migration graph reaches: ${reachableHashes.length > 0 ? reachableHashes.join(", ") : "(none — migration graph is empty)"}.`,
573
+ fix: [
574
+ "Run `{bin} db sign` to overwrite the marker if the database already matches the contract.",
575
+ "Run `{bin} migration plan --from <contract>`, naming the graph node the database was migrated from, if the live marker is canonical and the on-disk graph needs catching up.",
576
+ `Run \`{bin} migration ref set db ${markerHash}\` if the on-disk graph is canonical and the local \`db\` ref drifted.`,
577
+ "Investigate whether the database was migrated by an out-of-band process."
578
+ ].join("\n"),
579
+ nextActions: [
580
+ runCommandAction("Overwrite the marker if the database already matches the contract", "{bin} db sign"),
581
+ runCommandAction("Catch the on-disk graph up to the live marker", "{bin} migration plan --from <contract>"),
582
+ runCommandAction("Point the local db ref at the live marker", `{bin} migration ref set db ${markerHash}`),
583
+ chooseAction("Investigate whether the database was migrated by an out-of-band process")
584
+ ],
585
+ meta: {
586
+ markerHash,
587
+ reachableHashes: [...reachableHashes]
588
+ }
589
+ });
590
+ }
591
+ const ROLLBACK_IS_DESTRUCTIVE = "A rollback (reverse) plan is expected to contain destructive (DROP) operations — review them before applying";
592
+ const RENAMES_AND_DATA_NEED_MORE = "Plan a rename with --rename old:new; re-adding a required field without a safe default, or a type change that needs data, may need you to fill in the planned migration.ts";
593
+ function planThenApply(meta) {
594
+ const planCommand = meta.kind === "neverPlanned" ? "{bin} migration plan --name <slug>" : meta.fromHash === "empty" ? `{bin} migration plan --to ${meta.targetHash} --name <slug>` : `{bin} migration plan --from ${meta.fromHash} --to ${meta.targetHash} --name <slug>`;
595
+ const applyCommand = meta.kind === "neverPlanned" ? "{bin} db migrate" : `{bin} db migrate --to ${meta.targetHash}`;
596
+ return {
597
+ fix: [
598
+ "Plan the missing edge, then apply it:",
599
+ ` 1. ${planCommand}`,
600
+ ` 2. ${applyCommand}`,
601
+ `${ROLLBACK_IS_DESTRUCTIVE}.`,
602
+ `${RENAMES_AND_DATA_NEED_MORE}.`,
603
+ "Inspect the on-disk graph with `{bin} migration list`, or `{bin} migration show <bundle>` for any bundle in the path you expected."
604
+ ].join("\n"),
605
+ nextActions: [
606
+ runCommandAction("Plan the missing edge", planCommand),
607
+ runCommandAction("Apply it", applyCommand),
608
+ chooseAction(ROLLBACK_IS_DESTRUCTIVE),
609
+ chooseAction(RENAMES_AND_DATA_NEED_MORE),
610
+ runCommandAction("Inspect the on-disk graph", "{bin} migration list"),
611
+ runCommandAction("Inspect a bundle in the path you expected", "{bin} migration show <bundle>")
612
+ ]
613
+ };
614
+ }
615
+ /** `MIGRATION.PATH_UNREACHABLE`, advising to plan the missing edge and apply it unless `advice` says otherwise. */
616
+ function errorPathUnreachable(failure, advice = planThenApply(failure.meta)) {
617
+ return new ActionableCliError("MIGRATION.PATH_UNREACHABLE", failure.summary, {
618
+ why: failure.why,
619
+ fix: advice.fix,
620
+ nextActions: advice.nextActions,
621
+ meta: failure.meta
622
+ });
623
+ }
624
+ /**
625
+ * Shared "needs a live database" precondition for read verbs that consult the
626
+ * marker/ledger (`migration log`, `migration status`). A command needs both a
627
+ * connection string and a control-plane driver; either missing yields the same
628
+ * `CONFIG.DB_CONNECTION_REQUIRED` envelope with `meta.missingFlags` (canonical long-form flags
629
+ * per CLI Style Guide §Errors) so callers can react programmatically. Returns
630
+ * `null` when both are present.
631
+ */
632
+ function requireLiveDatabase(args) {
633
+ if (args.dbConnection && args.hasDriver) return null;
634
+ const missingFlags = args.dbConnection ? [] : ["--db"];
635
+ return errorDatabaseConnectionRequired({
636
+ why: args.why,
637
+ missingFlags,
638
+ ...ifDefined("commandName", args.commandName),
639
+ ...ifDefined("retryCommand", args.retryCommand)
640
+ });
641
+ }
642
+ /**
643
+ * Maps a `RefResolutionError` from the contract/migration reference
644
+ * resolver into a CLI structured error envelope.
645
+ */
646
+ /**
647
+ * A migration ref (dirName or hash-prefix) resolves in more than one contract
648
+ * space. The user must qualify with `--space <id>` to disambiguate.
649
+ */
650
+ function errorAmbiguousMigrationRef(ref, spaceIds) {
651
+ const spaceList = spaceIds.join(", ");
652
+ return new ActionableCliError("MIGRATION.AMBIGUOUS_MIGRATION_REF", `Ambiguous migration reference: "${ref}" resolves in multiple spaces — qualify with --space <id>`, {
653
+ why: `"${ref}" matches migrations in spaces: ${spaceList}.`,
654
+ fix: `Qualify with --space <id> to select one space. Available matching spaces: ${spaceList}.`,
655
+ nextActions: [chooseAction(`Qualify with --space <id>, one of: ${spaceList}`)],
656
+ meta: {
657
+ ref,
658
+ spaceIds: [...spaceIds]
659
+ }
660
+ });
661
+ }
662
+ function mapRefResolutionError(error) {
663
+ switch (error.kind) {
664
+ case "not-found": {
665
+ const fix = error.grammar === "contract" ? "Provide a valid contract hash, ref name, or migration directory name." : "Provide a valid migration directory name or migration hash.";
666
+ return new ActionableCliError("MIGRATION.REF_NOT_FOUND", `Not a known ${error.grammar} reference: "${error.input}"`, {
667
+ why: `No ${error.grammar} matching "${error.input}" exists in the migration graph or refs index.`,
668
+ fix,
669
+ nextActions: [chooseAction(fix)],
670
+ meta: {
671
+ input: error.input,
672
+ grammar: error.grammar
673
+ }
674
+ });
675
+ }
676
+ case "ambiguous": return new ActionableCliError("MIGRATION.REF_AMBIGUOUS", `Ambiguous ${error.grammar} reference: "${error.input}"`, {
677
+ why: `"${error.input}" matches multiple ${error.grammar}s: ${error.candidates.join(", ")}`,
678
+ fix: "Provide a longer prefix or use the full hash to disambiguate.",
679
+ nextActions: [chooseAction("Provide a longer prefix or use the full hash to disambiguate")],
680
+ meta: {
681
+ input: error.input,
682
+ candidates: error.candidates,
683
+ grammar: error.grammar
684
+ }
685
+ });
686
+ case "wrong-grammar": return new ActionableCliError("MIGRATION.REF_WRONG_GRAMMAR", error.message, {
687
+ why: error.message,
688
+ fix: error.fix,
689
+ nextActions: [chooseAction(error.fix)],
690
+ meta: {
691
+ input: error.input,
692
+ expectedGrammar: error.expectedGrammar
693
+ }
694
+ });
695
+ case "invalid-format": return new ActionableCliError("MIGRATION.REF_INVALID_FORMAT", `Invalid reference format: "${error.input}"`, {
696
+ why: error.reason,
697
+ fix: "Provide a valid contract hash, ref name, or migration directory name.",
698
+ nextActions: [chooseAction("Provide a valid contract hash, ref name, or migration directory name")],
699
+ meta: { input: error.input }
700
+ });
701
+ }
702
+ }
703
+ /**
704
+ * The directory of the config file that wrote the section, recorded when the
705
+ * engine validated it. Every command runs behind that validation, so its
706
+ * absence here is a bug.
707
+ */
708
+ function baseDirFor(config) {
709
+ if (config.baseDir === void 0) throw new InternalError("the orm config section reached a command without baseDir");
710
+ return config.baseDir;
711
+ }
712
+ /**
713
+ * Where a config keeps its migrations: `migrations.dir`, default `migrations`, resolved against the config's `baseDir`. `base` stands in for `baseDir` when a config built in memory carries none.
714
+ */
715
+ function migrationsDirFor(config, base) {
716
+ return resolve(config.baseDir ?? base ?? baseDirFor(config), config.migrations?.dir ?? "migrations");
717
+ }
718
+ /** The app subspace under {@link migrationsDirFor}. */
719
+ function appMigrationsDirFor(config) {
720
+ return spaceMigrationDirectory(migrationsDirFor(config), APP_SPACE_ID);
721
+ }
722
+ /**
723
+ * Where refs live. The framework keeps them under the app subspace rather than
724
+ * at the migrations root.
725
+ */
726
+ function appRefsDirFor(config) {
727
+ return resolve(appMigrationsDirFor(config), "refs");
728
+ }
729
+ /** The emitted contract; the validated config carries `contract.output` absolute. */
730
+ function contractPathFor(config) {
731
+ return config.contract?.output;
732
+ }
733
+ /**
734
+ * The header's rendering of a path: relative to where the user invoked the
735
+ * CLI, as the commander shell rendered it against the config file.
736
+ */
737
+ function displayPath(path, cwd) {
738
+ return relative(cwd, path);
739
+ }
740
+ const MASK = "****";
741
+ const URL_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
742
+ const LEADING_URL_USERINFO = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#\s]+)@/;
743
+ const URL_USERINFO = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/?#\s]+)@/g;
744
+ const PASSWORD_QUERY_PARAMETER = /([?&][^=&#\s]*password[^=&#\s]*=)([^&#\s]*)/gi;
745
+ function hasUrlScheme(text) {
746
+ return URL_SCHEME.test(text);
747
+ }
748
+ /**
749
+ * Reads the userinfo of a URL without parsing its hosts, so it works for URLs `new URL` rejects,
750
+ * such as a seed list of several `host:port` pairs. The userinfo ends at the last `@` before the
751
+ * first `/`, `?` or `#`.
752
+ */
753
+ function urlUserinfo(url) {
754
+ return splitUserinfo(url.match(LEADING_URL_USERINFO)?.[1] ?? "");
755
+ }
756
+ /**
757
+ * Reads the values of the query parameters whose key contains `password`, the same ones
758
+ * `redactUrlCredentials` masks, without parsing hosts.
759
+ */
760
+ function passwordQueryValues(url) {
761
+ return [...url.matchAll(PASSWORD_QUERY_PARAMETER)].map((match) => match[2] ?? "");
762
+ }
763
+ /**
764
+ * Masks the userinfo and any password query parameter of every URL in `text`, without parsing
765
+ * hosts. The masked form matches what `new URL` gives when its username and password are set to
766
+ * `****`.
767
+ */
768
+ function redactUrlCredentials(text) {
769
+ return text.replace(URL_USERINFO, (_match, scheme, userinfo) => `${scheme}${maskUserinfo(splitUserinfo(userinfo))}@`).replace(PASSWORD_QUERY_PARAMETER, `$1${MASK}`);
770
+ }
771
+ function splitUserinfo(userinfo) {
772
+ const colon = userinfo.indexOf(":");
773
+ if (colon === -1) return {
774
+ username: userinfo,
775
+ password: ""
776
+ };
777
+ return {
778
+ username: userinfo.slice(0, colon),
779
+ password: userinfo.slice(colon + 1)
780
+ };
781
+ }
782
+ function maskUserinfo({ username, password }) {
783
+ return `${username ? MASK : ""}${password ? `:${MASK}` : ""}`;
784
+ }
785
+ const PASSWORD_QUERY_KEY = /password/i;
786
+ /**
787
+ * Resolves the absolute path to contract.json from the config.
788
+ */
789
+ function resolveContractPath(config) {
790
+ if (config.contract?.output === void 0) throw errorRuntime("CONFIG.VALIDATION_FAILED", "config.contract.output is required to resolve the contract path", {
791
+ why: "CLI commands read the emitted contract from config.contract.output; the config has no value to read.",
792
+ fix: "Ensure your prisma.config.ts goes through `defineConfig()`, which normalises a default output when the provider supplies an input path, or set `contract.output` explicitly."
793
+ });
794
+ return resolve(config.contract.output);
795
+ }
796
+ /**
797
+ * Resolves the migrations directory and config path from CLI options.
798
+ * Shared by migrate, migration-plan, and migration-status.
799
+ *
800
+ * - `migrationsDir` is the project's top-level `migrations/` directory
801
+ * (the root that the aggregate loader walks for every contract space).
802
+ * - `appMigrationsDir` is the app subspace directory under it
803
+ * (`<migrationsDir>/<APP_SPACE_ID>/`). Every per-app reader / writer
804
+ * (`migration new`, `migration plan`, `migrate`,
805
+ * `migration status`, `migration show`, `migration ref`) operates on
806
+ * this directory. Extensions own their own `migrations/<spaceId>/`.
807
+ * - `refsDir` is the app's refs directory (`<appMigrationsDir>/refs/`).
808
+ * The framework does not maintain refs at the migrations root.
809
+ *
810
+ * `cwd` is the directory the command was invoked from; every relative path in
811
+ * the result is computed against it.
812
+ */
813
+ function resolveMigrationPaths(config, cwd) {
814
+ const configPath = "prisma.config.ts";
815
+ const migrationsDir = migrationsDirFor(config, cwd);
816
+ const migrationsRelative = relative(cwd, migrationsDir);
817
+ const appMigrationsDir = spaceMigrationDirectory(migrationsDir, APP_SPACE_ID$1);
818
+ return {
819
+ configPath,
820
+ migrationsDir,
821
+ migrationsRelative,
822
+ appMigrationsDir,
823
+ appMigrationsRelative: relative(cwd, appMigrationsDir),
824
+ refsDir: resolve(appMigrationsDir, "refs")
825
+ };
826
+ }
827
+ function collectDeclaredInvariants(graph) {
828
+ const declared = /* @__PURE__ */ new Set();
829
+ for (const edges of graph.forwardChain.values()) for (const edge of edges) for (const inv of edge.invariants) declared.add(inv);
830
+ return declared;
831
+ }
832
+ /**
833
+ * Maps a `MigrationEdge` to the structural-edge shape used in the
834
+ * `MIGRATION.NO_INVARIANT_PATH` error envelope. Shared between
835
+ * `migrate` and `migration status` so both commands surface
836
+ * the same JSON wire shape when an invariant-aware route is unsatisfiable.
837
+ */
838
+ function toStructuralEdge(edge) {
839
+ return {
840
+ dirName: edge.dirName,
841
+ migrationHash: edge.migrationHash,
842
+ from: edge.from,
843
+ to: edge.to,
844
+ invariants: edge.invariants
845
+ };
846
+ }
847
+ function targetSupportsMigrations(target) {
848
+ return hasMigrations(target);
849
+ }
850
+ /**
851
+ * Hangs up without letting the hang-up decide the command's result. A rejection out of a
852
+ * `finally` replaces the value the `try`/`catch` already returned, so an unguarded close turns a
853
+ * mapped connection error into an unmapped one — and that is the case it hits most, because a
854
+ * `connect()` that failed leaves nothing to close.
855
+ */
856
+ async function closeQuietly(client) {
857
+ try {
858
+ await client.close();
859
+ } catch {}
860
+ }
861
+ function getTargetMigrations(target) {
862
+ return hasMigrations(target) ? target.migrations : void 0;
863
+ }
864
+ /**
865
+ * Reads and parses contract.json, validating the framework-level envelope
866
+ * fields (storageHash, schemaVersion, target, targetFamily).
867
+ *
868
+ * Family-specific validation (storage structure, codec mappings, etc.)
869
+ * happens downstream in the control client via the family instance.
870
+ */
871
+ async function readContractEnvelope(config) {
872
+ const contractPath = resolveContractPath(config);
873
+ const content = await readFile(contractPath, "utf-8");
874
+ const json = JSON.parse(content);
875
+ const { schemaVersion, target, targetFamily, profileHash } = json;
876
+ const storageHash = json["storage"]?.["storageHash"];
877
+ if (typeof storageHash !== "string") throw new CliStructuredError$1("CONTRACT.VALIDATION_FAILED", `Contract at ${relative(process.cwd(), contractPath)} is missing a valid storage.storageHash. Run \`{bin} contract emit\` to regenerate.`, { where: { path: contractPath } });
878
+ if (typeof schemaVersion !== "string") throw new CliStructuredError$1("CONTRACT.VALIDATION_FAILED", `Contract at ${relative(process.cwd(), contractPath)} is missing schemaVersion.`, { where: { path: contractPath } });
879
+ if (typeof target !== "string") throw new CliStructuredError$1("CONTRACT.VALIDATION_FAILED", `Contract at ${relative(process.cwd(), contractPath)} is missing target.`, { where: { path: contractPath } });
880
+ if (typeof targetFamily !== "string") throw new CliStructuredError$1("CONTRACT.VALIDATION_FAILED", `Contract at ${relative(process.cwd(), contractPath)} is missing targetFamily.`, { where: { path: contractPath } });
881
+ return {
882
+ ...json,
883
+ storageHash,
884
+ schemaVersion,
885
+ target,
886
+ targetFamily,
887
+ ...typeof profileHash === "string" ? { profileHash } : {}
888
+ };
889
+ }
890
+ /**
891
+ * Masks credentials in a database connection URL.
892
+ * Handles standard URLs (username + password + query params), URLs `new URL` rejects (such as
893
+ * multi-host URLs), and libpq-style key=value strings.
894
+ */
895
+ function maskConnectionUrl(url) {
896
+ try {
897
+ const parsed = new URL(url);
898
+ if (parsed.username) parsed.username = "****";
899
+ if (parsed.password) parsed.password = "****";
900
+ for (const key of [...parsed.searchParams.keys()]) if (PASSWORD_QUERY_KEY.test(key)) parsed.searchParams.set(key, "****");
901
+ return parsed.toString();
902
+ } catch {
903
+ return hasUrlScheme(url) ? redactUrlCredentials(url) : maskKeyValueCredentials(url);
904
+ }
905
+ }
906
+ /**
907
+ * Strips raw connection URL fragments from an error message to prevent credential leakage.
908
+ * Call this before surfacing driver errors to the user.
909
+ */
910
+ function sanitizeErrorMessage(message, connectionUrl) {
911
+ if (!connectionUrl) return message;
912
+ const secrets = connectionUrlSecrets(connectionUrl);
913
+ if (secrets === void 0) return maskKeyValueCredentials(message);
914
+ let sanitized = message.replaceAll(connectionUrl, maskConnectionUrl(connectionUrl));
915
+ for (const secret of secrets.filter(Boolean).sort(longestFirst)) sanitized = sanitized.replaceAll(secret, "****");
916
+ return sanitized;
917
+ }
918
+ /** A next action with the connection string removed from each of its strings. */
919
+ function nextActionWithoutConnectionString(action, connectionUrl) {
920
+ const clean = (text) => sanitizeErrorMessage(text, connectionUrl);
921
+ return {
922
+ kind: action.kind,
923
+ label: clean(action.label),
924
+ ...ifDefined("command", action.command === void 0 ? void 0 : clean(action.command)),
925
+ ...ifDefined("commands", action.commands?.map(clean)),
926
+ ...ifDefined("url", action.url === void 0 ? void 0 : clean(action.url)),
927
+ ...ifDefined("reason", action.reason === void 0 ? void 0 : clean(action.reason))
928
+ };
929
+ }
930
+ /** `meta` with the connection string removed from every string it holds, however deeply nested. */
931
+ function metaWithoutConnectionString(meta, connectionUrl) {
932
+ const clean = (value) => {
933
+ if (typeof value === "string") return sanitizeErrorMessage(value, connectionUrl);
934
+ if (Array.isArray(value)) return value.map(clean);
935
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, clean(entry)]));
936
+ return value;
937
+ };
938
+ return Object.fromEntries(Object.entries(meta).map(([key, value]) => [key, clean(value)]));
939
+ }
940
+ function connectionUrlSecrets(connectionUrl) {
941
+ try {
942
+ const { username, password, searchParams } = new URL(connectionUrl);
943
+ return [
944
+ username,
945
+ password,
946
+ ...[...searchParams].filter(([key]) => PASSWORD_QUERY_KEY.test(key)).map(([, value]) => value)
947
+ ];
948
+ } catch {
949
+ if (!hasUrlScheme(connectionUrl)) return;
950
+ const { username, password } = urlUserinfo(connectionUrl);
951
+ return [
952
+ username,
953
+ password,
954
+ ...passwordQueryValues(connectionUrl)
955
+ ];
956
+ }
957
+ }
958
+ function longestFirst(a, b) {
959
+ return b.length - a.length;
960
+ }
961
+ function maskKeyValueCredentials(text) {
962
+ return text.replace(/password\s*=\s*\S+/gi, "password=****").replace(/user\s*=\s*\S+/gi, "user=****");
963
+ }
964
+ /**
965
+ * The error a command reports for one it caught. A CLI error is reported as it is, and so is any other error a library raised with a structured code, such as `CONTRACT.DEFAULT_INVALID` for a stale contract's default or `CONTRACT.TYPE_PARAMS_INVALID` for its type parameters: the code says what went wrong better than the command can. An `InternalError` is thrown again, so the command boundary, `defineOrmCommand`, lets the engine report it as a bug. Anything else is reported as `CLI.UNEXPECTED` with the `why` the command gives for the error's message, and a `code` it carries that is not a structured one, such as a driver's `ECONNREFUSED` or a SQLSTATE, in `meta.code`.
966
+ *
967
+ * A command that holds a database connection passes its connection string, which is then removed from every string the reported error carries, whichever of those it is.
968
+ */
969
+ function errorFromCaught(error, why, options = {}) {
970
+ const reported = reportedError(error, why);
971
+ return options.connection === void 0 ? reported : withoutConnectionString(reported, options.connection);
972
+ }
973
+ /** A structured error a library raised, reported under its own code, message and fields. */
974
+ function cliErrorFromStructured(error) {
975
+ if (CliStructuredError$1.is(error)) return error;
976
+ return new CliStructuredError$1(error.code, error.message, {
977
+ ...ifDefined("severity", error.severity),
978
+ ...ifDefined("why", error.why),
979
+ ...ifDefined("fix", error.fix),
980
+ ...ifDefined("nextActions", error.nextActions),
981
+ ...ifDefined("where", error.where),
982
+ ...ifDefined("meta", error.meta),
983
+ ...ifDefined("docsUrl", error.docsUrl),
984
+ cause: error
985
+ });
986
+ }
987
+ function reportedError(error, why) {
988
+ if (isInternalError(error)) throw error;
989
+ if (CliStructuredError$1.is(error)) return error;
990
+ if (isStructuredError(error)) return cliErrorFromStructured(error);
991
+ const message = error instanceof Error ? error.message : String(error);
992
+ const driverCode = error instanceof Error ? Reflect.get(error, "code") : void 0;
993
+ return errorUnexpected(message, {
994
+ why: why(message),
995
+ ...ifDefined("meta", typeof driverCode === "string" ? { code: driverCode } : void 0),
996
+ cause: error
997
+ });
998
+ }
999
+ function withoutConnectionString(error, connection) {
1000
+ const clean = (text) => sanitizeErrorMessage(text, connection);
1001
+ return new CliStructuredError$1(error.code, clean(error.message), {
1002
+ severity: error.severity,
1003
+ ...ifDefined("why", error.why === void 0 ? void 0 : clean(error.why)),
1004
+ ...ifDefined("fix", error.fix === void 0 ? void 0 : clean(error.fix)),
1005
+ ...ifDefined("nextActions", error.nextActions?.map((action) => nextActionWithoutConnectionString(action, connection))),
1006
+ ...ifDefined("diagnostics", error.diagnostics?.map((diagnostic) => diagnosticWithoutConnectionString(diagnostic, connection))),
1007
+ ...ifDefined("where", error.where),
1008
+ ...ifDefined("meta", error.meta === void 0 ? void 0 : metaWithoutConnectionString(error.meta, connection)),
1009
+ ...ifDefined("docsUrl", error.docsUrl),
1010
+ cause: error.cause
1011
+ });
1012
+ }
1013
+ function diagnosticWithoutConnectionString(diagnostic, connection) {
1014
+ const clean = (text) => sanitizeErrorMessage(text, connection);
1015
+ return {
1016
+ ...diagnostic,
1017
+ summary: clean(diagnostic.summary),
1018
+ ...ifDefined("why", diagnostic.why === void 0 ? void 0 : clean(diagnostic.why)),
1019
+ nextActions: diagnostic.nextActions.map((action) => nextActionWithoutConnectionString(action, connection)),
1020
+ ...ifDefined("meta", diagnostic.meta === void 0 ? void 0 : metaWithoutConnectionString(diagnostic.meta, connection))
1021
+ };
1022
+ }
1023
+ //#endregion
1024
+ export { errorTargetMigrationNotSupported as $, errorLegendHumanOnly as A, errorRefSetBundleNotFound as B, errorConvertAndDelete as C, errorFromCaught as D, errorFileNotFound as E, errorNoMigrations as F, errorSnapshotMissing as G, errorRefSetHashNotInGraph as H, errorPathUnreachable as I, errorStatementDidNotResolveLoss as J, errorSpaceNotFound as K, errorPlanForgotTheFlag as L, errorMarkerMissing as M, errorMigrationPackageNotFound as N, errorHashMismatch as O, errorMigrationPlanningFailed as P, errorStatementUnresolved as Q, errorPlanOriginUnknown as R, errorContractValidationFailed as S, errorDriverRequired as T, errorRuntime as U, errorRefSetEmptySentinel as V, errorSignRefsNotWritten as W, errorStatementNeedsMigrationFile as X, errorStatementInvalid as Y, errorStatementOriginUnknown as Z, errorAmbiguousMigrationRef as _, targetSupportsMigrations as _t, appRefsDirFor as a, migrationsDirFor as at, errorContractArgConflict as b, cliCommand as c, readContractEnvelope as ct, closeQuietly as d, resolveContractPath as dt, errorTargetMismatch as et, collectDeclaredInvariants as f, resolveMigrationPaths as ft, errorAdvanceRefArgConflict as g, statementFlag as gt, editFileAction as h, shellQuoted as ht, appMigrationsDirFor as i, maskConnectionUrl as it, errorMarkerMismatch as j, errorInvalidSpaceId as k, cliErrorFromStructured as l, redactUrlCredentials as lt, displayPath as m, selfEmitCommand as mt, CliStructuredError$1 as n, getTargetMigrations as nt, baseDirFor as o, printedPath as ot, contractPathFor as p, runCommandAction as pt, errorStatementAnswersNoQuestion as q, STORE_ORIGIN_SNAPSHOT_STEPS as r, mapRefResolutionError as rt, chooseAction as s, printedPlanCommand as st, ActionableCliError as t, errorUnexpected as tt, cliInvocation as u, requireLiveDatabase as ut, errorConfigValidation$1 as v, toStructuralEdge as vt, errorDatabaseConnectionRequired as w, errorContractConfigMissing as x, errorConsentUnused as y, errorPlanProducedNoOperations as z };
1025
+
1026
+ //# sourceMappingURL=caught-errors-Bmbi1dBu-DKO5X2tN.mjs.map