prisma-next 0.5.0-dev.9 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/cli-errors-B9OBbled.d.mts +3 -0
  2. package/dist/cli-errors-D3_sMh2K.mjs +33 -0
  3. package/dist/cli-errors-D3_sMh2K.mjs.map +1 -0
  4. package/dist/cli.mjs +16 -78
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/client-qVH-rEgd.mjs +1595 -0
  7. package/dist/client-qVH-rEgd.mjs.map +1 -0
  8. package/dist/{result-handler-Ba3zWQsI.mjs → command-helpers-BeZHkxV8.mjs} +70 -47
  9. package/dist/command-helpers-BeZHkxV8.mjs.map +1 -0
  10. package/dist/commands/contract-emit.d.mts.map +1 -1
  11. package/dist/commands/contract-emit.mjs +2 -4
  12. package/dist/commands/contract-infer.d.mts.map +1 -1
  13. package/dist/commands/contract-infer.mjs +2 -4
  14. package/dist/commands/db-init.d.mts.map +1 -1
  15. package/dist/commands/db-init.mjs +16 -13
  16. package/dist/commands/db-init.mjs.map +1 -1
  17. package/dist/commands/db-schema.d.mts.map +1 -1
  18. package/dist/commands/db-schema.mjs +6 -7
  19. package/dist/commands/db-schema.mjs.map +1 -1
  20. package/dist/commands/db-sign.d.mts.map +1 -1
  21. package/dist/commands/db-sign.mjs +9 -9
  22. package/dist/commands/db-sign.mjs.map +1 -1
  23. package/dist/commands/db-update.d.mts.map +1 -1
  24. package/dist/commands/db-update.mjs +15 -13
  25. package/dist/commands/db-update.mjs.map +1 -1
  26. package/dist/commands/db-verify.d.mts.map +1 -1
  27. package/dist/commands/db-verify.mjs +1 -321
  28. package/dist/commands/migration-apply.d.mts +28 -13
  29. package/dist/commands/migration-apply.d.mts.map +1 -1
  30. package/dist/commands/migration-apply.mjs +55 -151
  31. package/dist/commands/migration-apply.mjs.map +1 -1
  32. package/dist/commands/migration-new.d.mts +0 -1
  33. package/dist/commands/migration-new.d.mts.map +1 -1
  34. package/dist/commands/migration-new.mjs +34 -40
  35. package/dist/commands/migration-new.mjs.map +1 -1
  36. package/dist/commands/migration-plan.d.mts +33 -6
  37. package/dist/commands/migration-plan.d.mts.map +1 -1
  38. package/dist/commands/migration-plan.mjs +2 -348
  39. package/dist/commands/migration-ref.d.mts +1 -1
  40. package/dist/commands/migration-ref.d.mts.map +1 -1
  41. package/dist/commands/migration-ref.mjs +8 -12
  42. package/dist/commands/migration-ref.mjs.map +1 -1
  43. package/dist/commands/migration-show.d.mts +13 -7
  44. package/dist/commands/migration-show.d.mts.map +1 -1
  45. package/dist/commands/migration-show.mjs +35 -36
  46. package/dist/commands/migration-show.mjs.map +1 -1
  47. package/dist/commands/migration-status.d.mts +126 -5
  48. package/dist/commands/migration-status.d.mts.map +1 -1
  49. package/dist/commands/migration-status.mjs +2 -4
  50. package/dist/{config-loader-C25b63rJ.mjs → config-loader-B6sJjXTv.mjs} +3 -5
  51. package/dist/config-loader-B6sJjXTv.mjs.map +1 -0
  52. package/dist/config-loader.d.mts +0 -1
  53. package/dist/config-loader.d.mts.map +1 -1
  54. package/dist/config-loader.mjs +2 -3
  55. package/dist/contract-emit-9DBda5Ou.mjs +150 -0
  56. package/dist/contract-emit-9DBda5Ou.mjs.map +1 -0
  57. package/dist/contract-emit-B77TsJqf.mjs +327 -0
  58. package/dist/contract-emit-B77TsJqf.mjs.map +1 -0
  59. package/dist/{contract-enrichment-CAOELa-H.mjs → contract-enrichment-Dani0mMW.mjs} +4 -6
  60. package/dist/contract-enrichment-Dani0mMW.mjs.map +1 -0
  61. package/dist/{contract-infer-D9cC3rJm.mjs → contract-infer-BK9YFGEG.mjs} +13 -22
  62. package/dist/contract-infer-BK9YFGEG.mjs.map +1 -0
  63. package/dist/db-verify-C0y1PCO2.mjs +404 -0
  64. package/dist/db-verify-C0y1PCO2.mjs.map +1 -0
  65. package/dist/exports/config-types.mjs +1 -2
  66. package/dist/exports/control-api.d.mts +101 -586
  67. package/dist/exports/control-api.d.mts.map +1 -1
  68. package/dist/exports/control-api.mjs +4 -6
  69. package/dist/exports/index.d.mts.map +1 -1
  70. package/dist/exports/index.mjs +28 -30
  71. package/dist/exports/index.mjs.map +1 -1
  72. package/dist/exports/init-output.d.mts +2 -4
  73. package/dist/exports/init-output.d.mts.map +1 -1
  74. package/dist/exports/init-output.mjs +2 -3
  75. package/dist/extension-pack-inputs-C7xgE-vv.mjs +74 -0
  76. package/dist/extension-pack-inputs-C7xgE-vv.mjs.map +1 -0
  77. package/dist/{framework-components-Cr--XBKy.mjs → framework-components-ChqVUxR-.mjs} +3 -4
  78. package/dist/{framework-components-Cr--XBKy.mjs.map → framework-components-ChqVUxR-.mjs.map} +1 -1
  79. package/dist/global-flags-Icqpxk23.d.mts +12 -0
  80. package/dist/global-flags-Icqpxk23.d.mts.map +1 -0
  81. package/dist/helpers-eqdN8tH6.mjs +25 -0
  82. package/dist/helpers-eqdN8tH6.mjs.map +1 -0
  83. package/dist/{init-C5220SY9.mjs → init-DETSgw3h.mjs} +40 -49
  84. package/dist/init-DETSgw3h.mjs.map +1 -0
  85. package/dist/{inspect-live-schema-yrHAvG71.mjs → inspect-live-schema-CWYxGKlb.mjs} +10 -11
  86. package/dist/inspect-live-schema-CWYxGKlb.mjs.map +1 -0
  87. package/dist/migration-cli.d.mts +41 -12
  88. package/dist/migration-cli.d.mts.map +1 -1
  89. package/dist/migration-cli.mjs +309 -86
  90. package/dist/migration-cli.mjs.map +1 -1
  91. package/dist/{migration-command-scaffold-B3B09et6.mjs → migration-command-scaffold-B5dORFEv.mjs} +8 -9
  92. package/dist/migration-command-scaffold-B5dORFEv.mjs.map +1 -0
  93. package/dist/migration-plan-C6lVaHsO.mjs +554 -0
  94. package/dist/migration-plan-C6lVaHsO.mjs.map +1 -0
  95. package/dist/{migration-status-DUMiH8_G.mjs → migration-status-CZ-D5k7k.mjs} +272 -65
  96. package/dist/migration-status-CZ-D5k7k.mjs.map +1 -0
  97. package/dist/migrations-D_UJnpuW.mjs +216 -0
  98. package/dist/migrations-D_UJnpuW.mjs.map +1 -0
  99. package/dist/{output-BpcQrnnq.mjs → output-B16Kefzx.mjs} +9 -3
  100. package/dist/output-B16Kefzx.mjs.map +1 -0
  101. package/dist/{progress-adapter-DvQWB1nK.mjs → progress-adapter-DFfvZcYL.mjs} +2 -2
  102. package/dist/{progress-adapter-DvQWB1nK.mjs.map → progress-adapter-DFfvZcYL.mjs.map} +1 -1
  103. package/dist/result-handler-rmPVKIP2.mjs +25 -0
  104. package/dist/result-handler-rmPVKIP2.mjs.map +1 -0
  105. package/dist/rolldown-runtime-twds-ZHy.mjs +14 -0
  106. package/dist/{terminal-ui-C3ZLwQxK.mjs → terminal-ui-C_hFNbAn.mjs} +4 -28
  107. package/dist/terminal-ui-C_hFNbAn.mjs.map +1 -0
  108. package/dist/types-D7x-IFLO.d.mts +858 -0
  109. package/dist/types-D7x-IFLO.d.mts.map +1 -0
  110. package/dist/{verify-Bkycc-Tf.mjs → verify-CiwNWM9N.mjs} +3 -4
  111. package/dist/verify-CiwNWM9N.mjs.map +1 -0
  112. package/package.json +19 -17
  113. package/dist/cli-errors-BFYgBH3L.d.mts +0 -4
  114. package/dist/cli-errors-Cd79vmTH.mjs +0 -5
  115. package/dist/client-CrsnY58k.mjs +0 -997
  116. package/dist/client-CrsnY58k.mjs.map +0 -1
  117. package/dist/commands/db-verify.mjs.map +0 -1
  118. package/dist/commands/migration-plan.mjs.map +0 -1
  119. package/dist/config-loader-C25b63rJ.mjs.map +0 -1
  120. package/dist/contract-emit--feXyNd7.mjs +0 -4
  121. package/dist/contract-emit-NJ01hiiv.mjs +0 -195
  122. package/dist/contract-emit-NJ01hiiv.mjs.map +0 -1
  123. package/dist/contract-emit-V5SSitUT.mjs +0 -122
  124. package/dist/contract-emit-V5SSitUT.mjs.map +0 -1
  125. package/dist/contract-enrichment-CAOELa-H.mjs.map +0 -1
  126. package/dist/contract-infer-D9cC3rJm.mjs.map +0 -1
  127. package/dist/extract-operation-statements-DsFfxXVZ.mjs +0 -13
  128. package/dist/extract-operation-statements-DsFfxXVZ.mjs.map +0 -1
  129. package/dist/extract-sql-ddl-D9UbZDyz.mjs +0 -26
  130. package/dist/extract-sql-ddl-D9UbZDyz.mjs.map +0 -1
  131. package/dist/init-C5220SY9.mjs.map +0 -1
  132. package/dist/inspect-live-schema-yrHAvG71.mjs.map +0 -1
  133. package/dist/migration-command-scaffold-B3B09et6.mjs.map +0 -1
  134. package/dist/migration-status-DUMiH8_G.mjs.map +0 -1
  135. package/dist/migrations-Bo5WtTla.mjs +0 -153
  136. package/dist/migrations-Bo5WtTla.mjs.map +0 -1
  137. package/dist/output-BpcQrnnq.mjs.map +0 -1
  138. package/dist/result-handler-Ba3zWQsI.mjs.map +0 -1
  139. package/dist/terminal-ui-C3ZLwQxK.mjs.map +0 -1
  140. package/dist/validate-contract-deps-B_Cs29TL.mjs +0 -37
  141. package/dist/validate-contract-deps-B_Cs29TL.mjs.map +0 -1
  142. package/dist/verify-Bkycc-Tf.mjs.map +0 -1
@@ -1,12 +1,13 @@
1
- import { t as loadConfig } from "./config-loader-C25b63rJ.mjs";
2
- import { readFileSync, writeFileSync } from "node:fs";
3
- import { CliStructuredError, errorMigrationCliInvalidConfigArg } from "@prisma-next/errors/control";
1
+ import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
2
+ import { CliStructuredError, errorMigrationCliInvalidConfigArg, errorMigrationCliUnknownFlag } from "@prisma-next/errors/control";
4
3
  import { dirname, join } from "pathe";
5
4
  import { createControlStack } from "@prisma-next/framework-components/control";
6
5
  import { errorMigrationTargetMismatch } from "@prisma-next/errors/migration";
6
+ import { readFileSync, realpathSync, writeFileSync } from "node:fs";
7
+ import { MigrationToolsError, errorInvalidJson } from "@prisma-next/migration-tools/errors";
7
8
  import { fileURLToPath } from "node:url";
8
- import { buildMigrationArtifacts, isDirectEntrypoint, printMigrationHelp } from "@prisma-next/migration-tools/migration";
9
-
9
+ import { buildMigrationArtifacts } from "@prisma-next/migration-tools/migration";
10
+ import { Cli, Command, Option, UsageError } from "clipanion";
10
11
  //#region src/migration-cli.ts
11
12
  /**
12
13
  * The migration-file CLI interface: the actor invoked when the author runs
@@ -25,7 +26,8 @@ import { buildMigrationArtifacts, isDirectEntrypoint, printMigrationHelp } from
25
26
  * entrypoint (`node migration.ts`), the CLI:
26
27
  *
27
28
  * 1. Detects whether the file is the direct entrypoint (no-op when imported).
28
- * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`).
29
+ * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`) via
30
+ * [clipanion](https://github.com/arcanis/clipanion).
29
31
  * 3. Loads the project's `prisma-next.config.ts` via the same `loadConfig`
30
32
  * the CLI commands use, walking up from the migration file's directory.
31
33
  * 4. Probe-instantiates the migration class without a stack so it can read
@@ -44,44 +46,62 @@ import { buildMigrationArtifacts, isDirectEntrypoint, printMigrationHelp } from
44
46
  * on-disk persistence. `@prisma-next/migration-tools` owns the pure
45
47
  * conversion from a `Migration` instance to artifact strings; `Migration`
46
48
  * stays a pure abstract class.
49
+ *
50
+ * Parser library: clipanion (chosen over Commander/citty/`node:util.parseArgs`
51
+ * for its in-process testability and runtime-agnostic execution surface; see
52
+ * `docs/architecture docs/research/commander-friction-points.md` for the
53
+ * evaluation rubric and the durable rationale that drove the choice).
47
54
  */
48
55
  /**
49
- * Parse the subset of `process.argv` that `MigrationCLI.run` cares about.
50
- * Recognised flags: `--help`, `--dry-run`, `--config <path>` /
51
- * `--config=<path>`. Unknown flags are ignored to keep the surface
52
- * forgiving for ad-hoc tooling that wraps a migration file.
56
+ * Flags exposed by the migration-file CLI.
53
57
  *
54
- * Throws `errorMigrationCliInvalidConfigArg` (`PN-CLI-4012`) when
55
- * `--config` is missing its path argument or is followed by another flag
56
- * (e.g. `--config --dry-run`); silently consuming the next flag would
57
- * either drop dry-run handling or serialize against the wrong project.
58
- *
59
- * NOTE: this hand-rolled parser is a known wart, tracked separately by
60
- * TML-2318 ("Migration CLI: replace handrolled arg parser with shared
61
- * CLI library"). Until that lands the surface is intentionally tiny.
58
+ * Must stay in sync with the `Option` declarations on
59
+ * `MigrationFileCommand` below. This list is rendered in the
60
+ * `errorMigrationCliUnknownFlag` envelope's `fix` text and `meta`,
61
+ * so order matters for user-visible output (declaration order is the
62
+ * order users see when they run `--help`).
63
+ */
64
+ const KNOWN_FLAGS = [
65
+ "--help",
66
+ "--dry-run",
67
+ "--config"
68
+ ];
69
+ /**
70
+ * The clipanion command that owns the migration-file CLI's option
71
+ * declarations. The class is internal — `MigrationCLI.run` is the
72
+ * stable public surface. Adding a flag here automatically updates
73
+ * `--help` rendering and the `KNOWN_FLAGS` list (the latter must be
74
+ * updated in tandem).
62
75
  */
63
- function parseArgs(argv) {
64
- let help = false;
65
- let dryRun = false;
66
- let configPath;
67
- for (let i = 0; i < argv.length; i++) {
68
- const arg = argv[i];
69
- if (arg === "--help" || arg === "-h") help = true;
70
- else if (arg === "--dry-run") dryRun = true;
71
- else if (arg === "--config") {
72
- const next = argv[i + 1];
73
- if (next === void 0) throw errorMigrationCliInvalidConfigArg();
74
- if (next.startsWith("-")) throw errorMigrationCliInvalidConfigArg({ nextToken: next });
75
- configPath = next;
76
- i++;
77
- } else if (arg.startsWith("--config=")) configPath = arg.slice(9);
76
+ var MigrationFileCommand = class extends Command {
77
+ static paths = [Command.Default];
78
+ static usage = Command.Usage({
79
+ description: "Self-emit ops.json and migration.json from a class-flow migration",
80
+ details: `
81
+ Loads the project's prisma-next.config.ts, assembles a ControlStack
82
+ from the configured target/adapter/extensions, and serializes the
83
+ migration's operations + metadata next to this file.
84
+ `,
85
+ examples: [
86
+ ["Self-emit ops.json + migration.json next to migration.ts", "$0"],
87
+ ["Preview without writing files", "$0 --dry-run"],
88
+ ["Use a non-default config path", "$0 --config ./custom.config.ts"]
89
+ ]
90
+ });
91
+ dryRun = Option.Boolean("--dry-run", false, { description: "Print operations to stdout without writing files" });
92
+ config = Option.String("--config", { description: "Path to prisma-next.config.ts" });
93
+ /**
94
+ * Unused: orchestration runs inside `MigrationCLI.run` so error
95
+ * routing stays under our control (clipanion's `cli.run` writes
96
+ * error output to `context.stdout`, but our contract requires
97
+ * structured errors on stderr). `cli.process` is used to parse
98
+ * argv into a populated `MigrationFileCommand` instance whose
99
+ * fields drive the orchestration directly.
100
+ */
101
+ async execute() {
102
+ return 0;
78
103
  }
79
- return {
80
- help,
81
- dryRun,
82
- configPath
83
- };
84
- }
104
+ };
85
105
  /**
86
106
  * The CLI surface invoked by an authored `migration.ts` file. Exposed as
87
107
  * a class with a static `run` method (rather than a free function) to
@@ -96,59 +116,243 @@ function parseArgs(argv) {
96
116
  */
97
117
  var MigrationCLI = class {
98
118
  /**
99
- * Orchestrates a class-flow `migration.ts` script run. Awaitable:
100
- * callers may `await MigrationCLI.run(...)` to surface async failures
101
- * from config loading, but the typical usage pattern (top-level call
102
- * after the class definition) does not require awaiting because
103
- * node's module evaluation keeps the promise alive until completion.
119
+ * Orchestrates a class-flow `migration.ts` script run.
120
+ *
121
+ * The third argument is the in-process testability surface: callers
122
+ * (and tests) may inject `argv`, `stdout`, and `stderr` instead of
123
+ * relying on `process.argv` / `process.stdout` / `process.stderr`.
124
+ * Each option defaults to its `process` global when omitted, so
125
+ * existing two-argument call sites
126
+ * (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to
127
+ * compile and behave identically.
104
128
  *
105
- * Any throwable inside this function must surface through the internal
106
- * try/catch script callers do not await, so an unhandled rejection
107
- * would silently exit 0. Treat the try/catch as load-bearing for the
108
- * no-await usage pattern.
129
+ * Returns the exit code so the caller can branch on it. Also writes
130
+ * the same code to `process.exitCode` so script-style callers that
131
+ * don't await the return value still surface a non-zero exit when
132
+ * something fails.
133
+ *
134
+ * Exit codes:
135
+ * - 0 — success, or `--help`, or imported-not-entrypoint no-op.
136
+ * - 1 — runtime/orchestration error (config not found, target
137
+ * mismatch, etc.).
138
+ * - 2 — usage error (unknown flag, malformed `--config`). Aligns
139
+ * with `docs/CLI Style Guide.md` § Exit Codes.
109
140
  */
110
- static async run(importMetaUrl, MigrationClass) {
111
- if (!importMetaUrl) return;
112
- if (!isDirectEntrypoint(importMetaUrl)) return;
113
- try {
114
- const args = parseArgs(process.argv.slice(2));
115
- if (args.help) {
116
- printMigrationHelp();
117
- return;
141
+ static async run(importMetaUrl, MigrationClass, options = {}) {
142
+ if (!importMetaUrl) return 0;
143
+ const argv = options.argv ?? process.argv;
144
+ const stdout = options.stdout ?? process.stdout;
145
+ const stderr = options.stderr ?? process.stderr;
146
+ if (!isDirectEntrypoint(importMetaUrl, argv)) return 0;
147
+ const exitCode = await orchestrate(importMetaUrl, MigrationClass, {
148
+ argv,
149
+ stdout,
150
+ stderr
151
+ });
152
+ if (exitCode !== 0 || !process.exitCode) process.exitCode = exitCode;
153
+ return exitCode;
154
+ }
155
+ };
156
+ /**
157
+ * Argv-aware variant of the entrypoint guard. The shared
158
+ * `@prisma-next/migration-tools` helper of the same name reads
159
+ * `process.argv[1]` directly, which doesn't compose with the new
160
+ * in-process testability surface (tests inject `argv` without mutating
161
+ * the process global). Inlined here so the migration-file CLI's check
162
+ * follows the injected `argv[1]` consistently.
163
+ */
164
+ function isDirectEntrypoint(importMetaUrl, argv) {
165
+ const argv1 = argv[1];
166
+ if (!argv1) return false;
167
+ try {
168
+ return realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(argv1);
169
+ } catch {
170
+ return false;
171
+ }
172
+ }
173
+ /**
174
+ * Argv-and-stream-driven orchestration body. Pulled out of the static
175
+ * method so the entrypoint guard / process-default plumbing stays
176
+ * separate from the parse + load + serialize steps.
177
+ */
178
+ async function orchestrate(importMetaUrl, MigrationClass, ctx) {
179
+ const cli = Cli.from([MigrationFileCommand], {
180
+ binaryName: "migration.ts",
181
+ binaryLabel: "Migration file CLI"
182
+ });
183
+ const input = ctx.argv.slice(2);
184
+ const configError = detectInvalidConfig(input);
185
+ if (configError) {
186
+ writeStructuredError(ctx.stderr, configError);
187
+ return 2;
188
+ }
189
+ let parsed;
190
+ try {
191
+ const command = cli.process({
192
+ input: [...input],
193
+ context: {
194
+ stdout: ctx.stdout,
195
+ stderr: ctx.stderr
118
196
  }
119
- const migrationDir = dirname(fileURLToPath(importMetaUrl));
120
- const config = await loadConfig(args.configPath);
121
- const probe = new MigrationClass();
122
- if (probe.targetId !== config.target.targetId) throw errorMigrationTargetMismatch({
123
- migrationTargetId: probe.targetId,
124
- configTargetId: config.target.targetId
125
- });
126
- serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, args.dryRun);
127
- } catch (err) {
128
- if (CliStructuredError.is(err)) process.stderr.write(`${err.message}: ${err.why}\n`);
129
- else process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
130
- process.exitCode = 1;
197
+ });
198
+ if (!(command instanceof MigrationFileCommand)) {
199
+ ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));
200
+ return 0;
131
201
  }
202
+ parsed = command;
203
+ } catch (err) {
204
+ return renderParseError(err, input, ctx.stderr);
132
205
  }
133
- };
206
+ if (parsed.help) {
207
+ ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));
208
+ return 0;
209
+ }
210
+ try {
211
+ await runMigration(importMetaUrl, MigrationClass, parsed, ctx);
212
+ return 0;
213
+ } catch (err) {
214
+ if (CliStructuredError.is(err)) writeStructuredError(ctx.stderr, err);
215
+ else if (MigrationToolsError.is(err)) {
216
+ const fix = err.fix ? `\n${err.fix}` : "";
217
+ ctx.stderr.write(`${err.code}: ${err.message}\n${err.why}${fix}\n`);
218
+ } else ctx.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
219
+ return 1;
220
+ }
221
+ }
222
+ /**
223
+ * Returns an `errorMigrationCliInvalidConfigArg` envelope when `input`
224
+ * contains a malformed `--config`:
225
+ *
226
+ * - `--config` as the last token (no value follows).
227
+ * - `--config <flag>` where `<flag>` starts with `-` (silently
228
+ * consuming the next flag would either drop the flag or serialize
229
+ * against the wrong project).
230
+ * - `--config <empty>` where the value is the empty string. Shells
231
+ * expand `--config ""` (or `--config "$UNSET_VAR"`) into a real
232
+ * empty argv token; treating that as a usage error here surfaces
233
+ * `PN-CLI-4012` instead of a less actionable loader error on an
234
+ * empty path.
235
+ * - `--config=` (the equals form with an empty value). Same shape as
236
+ * the empty-string case above; the user expressed intent to override
237
+ * the config path but the override is empty.
238
+ *
239
+ * `--config=<value>` and `--config <value>` with a non-empty value are
240
+ * both valid (and the equals form's value is allowed to start with
241
+ * `-` — the `=` makes the binding explicit).
242
+ */
243
+ function detectInvalidConfig(input) {
244
+ for (let i = 0; i < input.length; i++) {
245
+ const token = input[i];
246
+ if (token === "--config") {
247
+ const next = input[i + 1];
248
+ if (next === void 0 || next === "") return errorMigrationCliInvalidConfigArg();
249
+ if (next.startsWith("-")) return errorMigrationCliInvalidConfigArg({ nextToken: next });
250
+ continue;
251
+ }
252
+ if (token === "--config=") return errorMigrationCliInvalidConfigArg();
253
+ }
254
+ return null;
255
+ }
256
+ /**
257
+ * Translate clipanion's parse-time errors into the project's structured
258
+ * error envelopes.
259
+ *
260
+ * - `UnknownSyntaxError` covers both unknown flags (`--frobnicate`) and
261
+ * the bare-trailing `--config` case (where arity-1 needs a value but
262
+ * none was supplied). Distinguished by inspecting the input array.
263
+ * - `UsageError` covers schema/validator failures from typanion. None
264
+ * of the migration-file CLI's options have validators today, but we
265
+ * still translate it as a usage error (exit 2) for forward-compat.
266
+ * - Anything else re-throws — caller's outer catch will surface it as
267
+ * exit 1 (runtime error).
268
+ */
269
+ function renderParseError(err, input, stderr) {
270
+ if (isUnknownSyntaxError(err)) {
271
+ writeStructuredError(stderr, errorMigrationCliUnknownFlag({
272
+ flag: findOffendingFlag(input),
273
+ knownFlags: KNOWN_FLAGS
274
+ }));
275
+ return 2;
276
+ }
277
+ if (err instanceof UsageError) {
278
+ writeStructuredError(stderr, errorMigrationCliInvalidConfigArg({ nextToken: err.message }));
279
+ return 2;
280
+ }
281
+ throw err;
282
+ }
283
+ /**
284
+ * Duck-type check for clipanion's `UnknownSyntaxError`: the class is
285
+ * thrown by the parser but is not re-exported from the package's main
286
+ * entry (only `UsageError` is — see clipanion's `advanced/index.d.ts`).
287
+ * Identified by `name === 'UnknownSyntaxError'` and the
288
+ * `clipanion.type === 'none'` discriminator that clipanion's
289
+ * `ErrorWithMeta` interface guarantees.
290
+ */
291
+ function isUnknownSyntaxError(err) {
292
+ if (!(err instanceof Error) || err.name !== "UnknownSyntaxError") return false;
293
+ const meta = err.clipanion;
294
+ return typeof meta === "object" && meta !== null && meta.type === "none";
295
+ }
296
+ /**
297
+ * Best-effort: pull the first input token that doesn't match a known
298
+ * flag. Falls back to the first token when we can't pinpoint it. The
299
+ * returned name is rendered into the user-visible PN-CLI-4013 envelope
300
+ * (`Unknown flag \`<name>\``) and round-tripped via `meta.flag` so
301
+ * agent consumers can render their own "did you mean" suggestions.
302
+ */
303
+ function findOffendingFlag(input) {
304
+ for (const token of input) {
305
+ if (!token.startsWith("-")) continue;
306
+ const head = token.split("=", 1)[0] ?? token;
307
+ if (!KNOWN_FLAGS.includes(head) && head !== "-h") return head;
308
+ }
309
+ return input[0] ?? "";
310
+ }
311
+ /**
312
+ * Write a `CliStructuredError` envelope to the given stream. Format
313
+ * matches the legacy hand-rolled writer (`message: why`) so the rest of
314
+ * the project's error rendering stays consistent across surfaces. The
315
+ * full PN code (`PN-<domain>-<code>`) is included so consumers can
316
+ * grep for stable identifiers.
317
+ */
318
+ function writeStructuredError(stream, err) {
319
+ const envelope = err.toEnvelope();
320
+ const why = envelope.why ?? envelope.summary;
321
+ const fix = envelope.fix ? `\n${envelope.fix}` : "";
322
+ stream.write(`${envelope.code}: ${envelope.summary}\n${why}${fix}\n`);
323
+ }
134
324
  /**
135
325
  * Read a previously-scaffolded `migration.json` from disk, returning
136
- * `null` when the file is missing or unparseable. The CLI feeds this into
137
- * `buildMigrationArtifacts` so the pure builder can preserve fields owned
138
- * by `migration plan` (contract bookends, hints, labels, `createdAt`)
139
- * across re-emits.
326
+ * `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`
327
+ * when the file is present but cannot be parsed as JSON. The CLI feeds
328
+ * this into `buildMigrationArtifacts` so the pure builder can preserve
329
+ * fields owned by `migration plan` (contract bookends, hints, labels,
330
+ * `createdAt`) across re-emits.
331
+ *
332
+ * Author-time path: this loader still does not verify the manifest hash
333
+ * or schema — that is the apply-time loader's job. Hash mismatch is the
334
+ * *expected* outcome of a re-author (the developer's source changes
335
+ * invalidate the prior hash by construction), and verification here
336
+ * would block legitimate regenerations. Syntactic JSON-parse failure,
337
+ * however, is now surfaced rather than swallowed: a malformed
338
+ * `migration.json` indicates either a hand-edit gone wrong or partial
339
+ * write, and silently rebuilding from `describe()` would discard the
340
+ * user's on-disk content (preserved bookends, hints, labels,
341
+ * `createdAt`) without any indication something was wrong on disk.
342
+ * Apply-time consumers always route through the verifying
343
+ * `readMigrationPackage` in `@prisma-next/migration-tools/io` instead.
140
344
  */
141
- function readExistingManifest(manifestPath) {
345
+ function readExistingMetadata(metadataPath) {
142
346
  let raw;
143
347
  try {
144
- raw = readFileSync(manifestPath, "utf-8");
348
+ raw = readFileSync(metadataPath, "utf-8");
145
349
  } catch {
146
350
  return null;
147
351
  }
148
352
  try {
149
353
  return JSON.parse(raw);
150
- } catch {
151
- return null;
354
+ } catch (e) {
355
+ throw errorInvalidJson(metadataPath, e instanceof Error ? e.message : String(e));
152
356
  }
153
357
  }
154
358
  /**
@@ -165,20 +369,39 @@ function readExistingManifest(manifestPath) {
165
369
  * legitimate site for combining config loading, stack assembly, and
166
370
  * filesystem persistence.
167
371
  */
168
- function serializeMigrationToDisk(instance, migrationDir, dryRun) {
169
- const manifestPath = join(migrationDir, "migration.json");
170
- const { opsJson, manifestJson } = buildMigrationArtifacts(instance, readExistingManifest(manifestPath));
372
+ function serializeMigrationToDisk(instance, migrationDir, dryRun, stdout) {
373
+ const metadataPath = join(migrationDir, "migration.json");
374
+ const { opsJson, metadataJson } = buildMigrationArtifacts(instance, readExistingMetadata(metadataPath));
171
375
  if (dryRun) {
172
- process.stdout.write(`--- migration.json ---\n${manifestJson}\n`);
173
- process.stdout.write("--- ops.json ---\n");
174
- process.stdout.write(`${opsJson}\n`);
376
+ stdout.write(`--- migration.json ---\n${metadataJson}\n`);
377
+ stdout.write("--- ops.json ---\n");
378
+ stdout.write(`${opsJson}\n`);
175
379
  return;
176
380
  }
177
381
  writeFileSync(join(migrationDir, "ops.json"), opsJson);
178
- writeFileSync(manifestPath, manifestJson);
179
- process.stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\n`);
382
+ writeFileSync(metadataPath, metadataJson);
383
+ stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\n`);
384
+ }
385
+ /**
386
+ * Inner orchestration: load config, probe-construct the migration,
387
+ * verify target, assemble the stack, construct with the stack, persist.
388
+ *
389
+ * Throws `CliStructuredError` for known failure modes (config not
390
+ * found, target mismatch); the outer `orchestrate` translates those to
391
+ * exit 1.
392
+ */
393
+ async function runMigration(importMetaUrl, MigrationClass, parsed, ctx) {
394
+ const migrationDir = dirname(fileURLToPath(importMetaUrl));
395
+ const config = await loadConfig(parsed.config);
396
+ const probe = new MigrationClass();
397
+ if (probe.targetId !== config.target.targetId) throw errorMigrationTargetMismatch({
398
+ migrationTargetId: probe.targetId,
399
+ configTargetId: config.target.targetId
400
+ });
401
+ serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, parsed.dryRun, ctx.stdout);
402
+ ctx.stderr;
180
403
  }
181
-
182
404
  //#endregion
183
405
  export { MigrationCLI };
406
+
184
407
  //# sourceMappingURL=migration-cli.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration-cli.mjs","names":["configPath: string | undefined","raw: string"],"sources":["../src/migration-cli.ts"],"sourcesContent":["/**\n * The migration-file CLI interface: the actor invoked when the author runs\n * `node migration.ts` directly.\n *\n * Naming: this is *not* a \"migration runner\" in the apply-time sense. The\n * apply-time runner is the thing `prisma-next migration apply` uses to\n * execute migration JSON ops against a database. `MigrationCLI` is the\n * tiny CLI surface owned by an authored `migration.ts` file: parse the\n * file's argv, load the project's `prisma-next.config.ts`, assemble a\n * `ControlStack`, instantiate the migration class, and serialize.\n *\n * The user authors a migration class, then calls\n * `MigrationCLI.run(import.meta.url, MigrationClass)` at module scope\n * after the class definition. When the file is invoked as a node\n * entrypoint (`node migration.ts`), the CLI:\n *\n * 1. Detects whether the file is the direct entrypoint (no-op when imported).\n * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`).\n * 3. Loads the project's `prisma-next.config.ts` via the same `loadConfig`\n * the CLI commands use, walking up from the migration file's directory.\n * 4. Probe-instantiates the migration class without a stack so it can read\n * `targetId` and verify it matches `config.target.targetId`\n * (`PN-MIG-2006` on mismatch) before any stack-driven adapter\n * construction runs.\n * 5. Assembles a `ControlStack` from the loaded config descriptors and\n * constructs the migration with that stack.\n * 6. Reads any previously-scaffolded `migration.json`, then calls\n * `buildMigrationArtifacts` from `@prisma-next/migration-tools` to\n * produce in-memory `ops.json` + `migration.json` content. Persists\n * the result to disk (or prints in dry-run mode).\n *\n * File I/O lives here, in `@prisma-next/cli`: this is the only place\n * that legitimately combines config loading, stack assembly, and\n * on-disk persistence. `@prisma-next/migration-tools` owns the pure\n * conversion from a `Migration` instance to artifact strings; `Migration`\n * stays a pure abstract class.\n */\n\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { CliStructuredError, errorMigrationCliInvalidConfigArg } from '@prisma-next/errors/control';\nimport { errorMigrationTargetMismatch } from '@prisma-next/errors/migration';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport {\n buildMigrationArtifacts,\n isDirectEntrypoint,\n type Migration,\n printMigrationHelp,\n} from '@prisma-next/migration-tools/migration';\nimport type { MigrationManifest } from '@prisma-next/migration-tools/types';\nimport { dirname, join } from 'pathe';\nimport { loadConfig } from './config-loader';\n\n/**\n * Constructor shape accepted by `MigrationCLI.run`. `Migration` subclasses\n * accept an optional `ControlStack` in their constructor (each subclass\n * narrows the stack to its own family/target generics); the CLI always\n * passes one assembled from the loaded config. We use a rest-args `any[]`\n * constructor signature so that subclass constructors with narrower\n * parameter types remain assignable - constructor type compatibility in\n * TS is contravariant in the parameter, and a wider `unknown` parameter\n * on the alias side would reject any narrower subclass signature.\n *\n * The CLI only ever passes one argument (`new MigrationClass(stack)`);\n * the rest-arity is purely a type-compatibility concession for subclass\n * constructors that declare narrower parameter types, not an extension\n * point for additional construction arguments.\n */\n// biome-ignore lint/suspicious/noExplicitAny: see JSDoc - rest args with any are the idiomatic TS pattern for accepting arbitrary subclass constructor signatures\nexport type MigrationConstructor = new (...args: any[]) => Migration;\n\ninterface ParsedArgs {\n readonly help: boolean;\n readonly dryRun: boolean;\n readonly configPath: string | undefined;\n}\n\n/**\n * Parse the subset of `process.argv` that `MigrationCLI.run` cares about.\n * Recognised flags: `--help`, `--dry-run`, `--config <path>` /\n * `--config=<path>`. Unknown flags are ignored to keep the surface\n * forgiving for ad-hoc tooling that wraps a migration file.\n *\n * Throws `errorMigrationCliInvalidConfigArg` (`PN-CLI-4012`) when\n * `--config` is missing its path argument or is followed by another flag\n * (e.g. `--config --dry-run`); silently consuming the next flag would\n * either drop dry-run handling or serialize against the wrong project.\n *\n * NOTE: this hand-rolled parser is a known wart, tracked separately by\n * TML-2318 (\"Migration CLI: replace handrolled arg parser with shared\n * CLI library\"). Until that lands the surface is intentionally tiny.\n */\nfunction parseArgs(argv: readonly string[]): ParsedArgs {\n let help = false;\n let dryRun = false;\n let configPath: string | undefined;\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (arg === '--help' || arg === '-h') {\n help = true;\n } else if (arg === '--dry-run') {\n dryRun = true;\n } else if (arg === '--config') {\n const next = argv[i + 1];\n if (next === undefined) {\n throw errorMigrationCliInvalidConfigArg();\n }\n if (next.startsWith('-')) {\n throw errorMigrationCliInvalidConfigArg({ nextToken: next });\n }\n configPath = next;\n i++;\n } else if (arg.startsWith('--config=')) {\n configPath = arg.slice('--config='.length);\n }\n }\n\n return { help, dryRun, configPath };\n}\n\n/**\n * The CLI surface invoked by an authored `migration.ts` file. Exposed as\n * a class with a static `run` method (rather than a free function) to\n * give the concept a stable identity in the ubiquitous language: this is\n * the \"migration-file CLI\", distinct from the apply-time runner that\n * executes migration JSON ops.\n *\n * Currently a single static method. Future surface (e.g. a programmatic\n * `MigrationCLI.serializeOnly(...)` for tests, or extra subcommands) can\n * land here without changing the import shape used by every authored\n * migration.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: see JSDoc - intentional class facade for the migration-file CLI surface; future methods will share state derived from argv/config.\nexport class MigrationCLI {\n /**\n * Orchestrates a class-flow `migration.ts` script run. Awaitable:\n * callers may `await MigrationCLI.run(...)` to surface async failures\n * from config loading, but the typical usage pattern (top-level call\n * after the class definition) does not require awaiting because\n * node's module evaluation keeps the promise alive until completion.\n *\n * Any throwable inside this function must surface through the internal\n * try/catch — script callers do not await, so an unhandled rejection\n * would silently exit 0. Treat the try/catch as load-bearing for the\n * no-await usage pattern.\n */\n static async run(importMetaUrl: string, MigrationClass: MigrationConstructor): Promise<void> {\n if (!importMetaUrl) return;\n if (!isDirectEntrypoint(importMetaUrl)) return;\n\n try {\n const args = parseArgs(process.argv.slice(2));\n\n if (args.help) {\n printMigrationHelp();\n return;\n }\n\n const migrationFile = fileURLToPath(importMetaUrl);\n const migrationDir = dirname(migrationFile);\n\n const config = await loadConfig(args.configPath);\n\n // Probe-instantiate without a stack so we can read `targetId` before\n // any target-specific constructor side effects (e.g.\n // `PostgresMigration`'s `stack.adapter.create(stack)`) run. Concrete\n // subclasses are required to accept the no-arg form; the abstract\n // `Migration` constructor declares `stack?` and target subclasses\n // (Postgres, Mongo) propagate that optionality. This makes the\n // target-mismatch guard fail fast with `PN-MIG-2006` before any\n // stack-driven adapter construction begins, even if the wrong-target\n // adapter's `create` would otherwise succeed and silently misshapen\n // the stored adapter cast.\n const probe = new MigrationClass();\n\n if (probe.targetId !== config.target.targetId) {\n throw errorMigrationTargetMismatch({\n migrationTargetId: probe.targetId,\n configTargetId: config.target.targetId,\n });\n }\n\n const stack = createControlStack(config);\n const instance = new MigrationClass(stack);\n\n serializeMigrationToDisk(instance, migrationDir, args.dryRun);\n } catch (err) {\n if (CliStructuredError.is(err)) {\n process.stderr.write(`${err.message}: ${err.why}\\n`);\n } else {\n process.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n }\n process.exitCode = 1;\n }\n }\n}\n\n/**\n * Read a previously-scaffolded `migration.json` from disk, returning\n * `null` when the file is missing or unparseable. The CLI feeds this into\n * `buildMigrationArtifacts` so the pure builder can preserve fields owned\n * by `migration plan` (contract bookends, hints, labels, `createdAt`)\n * across re-emits.\n */\nfunction readExistingManifest(manifestPath: string): Partial<MigrationManifest> | null {\n let raw: string;\n try {\n raw = readFileSync(manifestPath, 'utf-8');\n } catch {\n return null;\n }\n try {\n return JSON.parse(raw) as Partial<MigrationManifest>;\n } catch {\n return null;\n }\n}\n\n/**\n * Persist a migration instance's artifacts to `migrationDir`. In\n * `dryRun` mode the artifacts are printed to stdout (with the same\n * `--- migration.json --- / --- ops.json ---` framing the legacy\n * `serializeMigration` helper used) and no files are written. Otherwise\n * `ops.json` and `migration.json` are written next to `migration.ts` and\n * a confirmation line is printed.\n *\n * File I/O lives in the CLI rather than `@prisma-next/migration-tools`\n * so the migration-tools package stays focused on the pure\n * `Migration` → in-memory artifact conversion. The CLI is the only\n * legitimate site for combining config loading, stack assembly, and\n * filesystem persistence.\n */\nfunction serializeMigrationToDisk(\n instance: Migration,\n migrationDir: string,\n dryRun: boolean,\n): void {\n const manifestPath = join(migrationDir, 'migration.json');\n const existing = readExistingManifest(manifestPath);\n const { opsJson, manifestJson } = buildMigrationArtifacts(instance, existing);\n\n if (dryRun) {\n process.stdout.write(`--- migration.json ---\\n${manifestJson}\\n`);\n process.stdout.write('--- ops.json ---\\n');\n process.stdout.write(`${opsJson}\\n`);\n return;\n }\n\n writeFileSync(join(migrationDir, 'ops.json'), ops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OAAO;WACtD,KAAK;AACZ,OAAI,mBAAmB,GAAG,IAAI,CAC5B,SAAQ,OAAO,MAAM,GAAG,IAAI,QAAQ,IAAI,IAAI,IAAI,IAAI;OAEpD,SAAQ,OAAO,MAAM,GAAG,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,CAAC,IAAI;AAE/E,WAAQ,WAAW;;;;;;;;;;;AAYzB,SAAS,qBAAqB,cAAyD;CACrF,IAAIC;AACJ,KAAI;AACF,QAAM,aAAa,cAAc,QAAQ;SACnC;AACN,SAAO;;AAET,KAAI;AACF,SAAO,KAAK,MAAM,IAAI;SAChB;AACN,SAAO;;;;;;;;;;;;;;;;;AAkBX,SAAS,yBACP,UACA,cACA,QACM;CACN,MAAM,eAAe,KAAK,cAAc,iBAAiB;CAEzD,MAAM,EAAE,SAAS,iBAAiB,wBAAwB,UADzC,qBAAqB,aAAa,CAC0B;AAE7E,KAAI,QAAQ;AACV,UAAQ,OAAO,MAAM,2BAA2B,aAAa,IAAI;AACjE,UAAQ,OAAO,MAAM,qBAAqB;AAC1C,UAAQ,OAAO,MAAM,GAAG,QAAQ,IAAI;AACpC;;AAGF,eAAc,KAAK,cAAc,WAAW,EAAE,QAAQ;AACtD,eAAc,cAAc,aAAa;AAEzC,SAAQ,OAAO,MAAM,sCAAsC,aAAa,IAAI"}
1
+ {"version":3,"file":"migration-cli.mjs","names":[],"sources":["../src/migration-cli.ts"],"sourcesContent":["/**\n * The migration-file CLI interface: the actor invoked when the author runs\n * `node migration.ts` directly.\n *\n * Naming: this is *not* a \"migration runner\" in the apply-time sense. The\n * apply-time runner is the thing `prisma-next migration apply` uses to\n * execute migration JSON ops against a database. `MigrationCLI` is the\n * tiny CLI surface owned by an authored `migration.ts` file: parse the\n * file's argv, load the project's `prisma-next.config.ts`, assemble a\n * `ControlStack`, instantiate the migration class, and serialize.\n *\n * The user authors a migration class, then calls\n * `MigrationCLI.run(import.meta.url, MigrationClass)` at module scope\n * after the class definition. When the file is invoked as a node\n * entrypoint (`node migration.ts`), the CLI:\n *\n * 1. Detects whether the file is the direct entrypoint (no-op when imported).\n * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`) via\n * [clipanion](https://github.com/arcanis/clipanion).\n * 3. Loads the project's `prisma-next.config.ts` via the same `loadConfig`\n * the CLI commands use, walking up from the migration file's directory.\n * 4. Probe-instantiates the migration class without a stack so it can read\n * `targetId` and verify it matches `config.target.targetId`\n * (`PN-MIG-2006` on mismatch) before any stack-driven adapter\n * construction runs.\n * 5. Assembles a `ControlStack` from the loaded config descriptors and\n * constructs the migration with that stack.\n * 6. Reads any previously-scaffolded `migration.json`, then calls\n * `buildMigrationArtifacts` from `@prisma-next/migration-tools` to\n * produce in-memory `ops.json` + `migration.json` content. Persists\n * the result to disk (or prints in dry-run mode).\n *\n * File I/O lives here, in `@prisma-next/cli`: this is the only place\n * that legitimately combines config loading, stack assembly, and\n * on-disk persistence. `@prisma-next/migration-tools` owns the pure\n * conversion from a `Migration` instance to artifact strings; `Migration`\n * stays a pure abstract class.\n *\n * Parser library: clipanion (chosen over Commander/citty/`node:util.parseArgs`\n * for its in-process testability and runtime-agnostic execution surface; see\n * `docs/architecture docs/research/commander-friction-points.md` for the\n * evaluation rubric and the durable rationale that drove the choice).\n */\n\nimport { readFileSync, realpathSync, writeFileSync } from 'node:fs';\nimport type { Writable } from 'node:stream';\nimport { fileURLToPath } from 'node:url';\nimport {\n CliStructuredError,\n errorMigrationCliInvalidConfigArg,\n errorMigrationCliUnknownFlag,\n} from '@prisma-next/errors/control';\nimport { errorMigrationTargetMismatch } from '@prisma-next/errors/migration';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { errorInvalidJson, MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport { buildMigrationArtifacts, type Migration } from '@prisma-next/migration-tools/migration';\nimport { Cli, Command, Option, UsageError } from 'clipanion';\nimport { dirname, join } from 'pathe';\nimport { loadConfig } from './config-loader';\n\n/**\n * Constructor shape accepted by `MigrationCLI.run`. `Migration` subclasses\n * accept an optional `ControlStack` in their constructor (each subclass\n * narrows the stack to its own family/target generics); the CLI always\n * passes one assembled from the loaded config. We use a rest-args `any[]`\n * constructor signature so that subclass constructors with narrower\n * parameter types remain assignable - constructor type compatibility in\n * TS is contravariant in the parameter, and a wider `unknown` parameter\n * on the alias side would reject any narrower subclass signature.\n *\n * The CLI only ever passes one argument (`new MigrationClass(stack)`);\n * the rest-arity is purely a type-compatibility concession for subclass\n * constructors that declare narrower parameter types, not an extension\n * point for additional construction arguments.\n */\n// biome-ignore lint/suspicious/noExplicitAny: see JSDoc - rest args with any are the idiomatic TS pattern for accepting arbitrary subclass constructor signatures\nexport type MigrationConstructor = new (...args: any[]) => Migration;\n\n/**\n * Stream surface accepted by `MigrationCLI.run`'s `options.stdout` /\n * `options.stderr`. Aliases node's `Writable` because clipanion's\n * `BaseContext.stdout`/`stderr` are typed as `Writable`, and the CLI\n * forwards the injected streams into clipanion's context.\n *\n * `process.stdout` and `process.stderr` are `Writable`-shaped, so the\n * default-fallback path remains a no-op for existing two-argument\n * callers like `MigrationCLI.run(import.meta.url, MyMigration)`.\n *\n * Tests inject a `Writable` subclass that captures chunks for\n * assertions.\n */\nexport type MigrationCliWritable = Writable;\n\n/**\n * Flags exposed by the migration-file CLI.\n *\n * Must stay in sync with the `Option` declarations on\n * `MigrationFileCommand` below. This list is rendered in the\n * `errorMigrationCliUnknownFlag` envelope's `fix` text and `meta`,\n * so order matters for user-visible output (declaration order is the\n * order users see when they run `--help`).\n */\nconst KNOWN_FLAGS: readonly string[] = ['--help', '--dry-run', '--config'];\n\n/**\n * The clipanion command that owns the migration-file CLI's option\n * declarations. The class is internal — `MigrationCLI.run` is the\n * stable public surface. Adding a flag here automatically updates\n * `--help` rendering and the `KNOWN_FLAGS` list (the latter must be\n * updated in tandem).\n */\nclass MigrationFileCommand extends Command {\n static override paths = [Command.Default];\n\n static override usage = Command.Usage({\n description: 'Self-emit ops.json and migration.json from a class-flow migration',\n details: `\n Loads the project's prisma-next.config.ts, assembles a ControlStack\n from the configured target/adapter/extensions, and serializes the\n migration's operations + metadata next to this file.\n `,\n examples: [\n ['Self-emit ops.json + migration.json next to migration.ts', '$0'],\n ['Preview without writing files', '$0 --dry-run'],\n ['Use a non-default config path', '$0 --config ./custom.config.ts'],\n ],\n });\n\n dryRun = Option.Boolean('--dry-run', false, {\n description: 'Print operations to stdout without writing files',\n });\n\n config = Option.String('--config', {\n description: 'Path to prisma-next.config.ts',\n });\n\n /**\n * Unused: orchestration runs inside `MigrationCLI.run` so error\n * routing stays under our control (clipanion's `cli.run` writes\n * error output to `context.stdout`, but our contract requires\n * structured errors on stderr). `cli.process` is used to parse\n * argv into a populated `MigrationFileCommand` instance whose\n * fields drive the orchestration directly.\n */\n override async execute(): Promise<number> {\n return 0;\n }\n}\n\n/**\n * The CLI surface invoked by an authored `migration.ts` file. Exposed as\n * a class with a static `run` method (rather than a free function) to\n * give the concept a stable identity in the ubiquitous language: this is\n * the \"migration-file CLI\", distinct from the apply-time runner that\n * executes migration JSON ops.\n *\n * Currently a single static method. Future surface (e.g. a programmatic\n * `MigrationCLI.serializeOnly(...)` for tests, or extra subcommands) can\n * land here without changing the import shape used by every authored\n * migration.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: see JSDoc - intentional class facade for the migration-file CLI surface; future methods will share state derived from argv/config.\nexport class MigrationCLI {\n /**\n * Orchestrates a class-flow `migration.ts` script run.\n *\n * The third argument is the in-process testability surface: callers\n * (and tests) may inject `argv`, `stdout`, and `stderr` instead of\n * relying on `process.argv` / `process.stdout` / `process.stderr`.\n * Each option defaults to its `process` global when omitted, so\n * existing two-argument call sites\n * (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to\n * compile and behave identically.\n *\n * Returns the exit code so the caller can branch on it. Also writes\n * the same code to `process.exitCode` so script-style callers that\n * don't await the return value still surface a non-zero exit when\n * something fails.\n *\n * Exit codes:\n * - 0 — success, or `--help`, or imported-not-entrypoint no-op.\n * - 1 — runtime/orchestration error (config not found, target\n * mismatch, etc.).\n * - 2 — usage error (unknown flag, malformed `--config`). Aligns\n * with `docs/CLI Style Guide.md` § Exit Codes.\n */\n static async run(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n options: {\n readonly argv?: readonly string[];\n readonly stdout?: MigrationCliWritable;\n readonly stderr?: MigrationCliWritable;\n } = {},\n ): Promise<number> {\n if (!importMetaUrl) {\n return 0;\n }\n\n const argv = options.argv ?? process.argv;\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n\n if (!isDirectEntrypoint(importMetaUrl, argv)) {\n return 0;\n }\n\n const exitCode = await orchestrate(importMetaUrl, MigrationClass, {\n argv,\n stdout,\n stderr,\n });\n // Preserve any pre-existing non-zero `process.exitCode` set by code\n // running alongside `MigrationCLI.run` (an unhandled rejection\n // upstream, an explicit `process.exitCode = N` from another\n // module). Overwriting it with our success would mask the upstream\n // failure for script-style callers that don't await the return\n // value. Failures we return here are still surfaced — non-zero\n // codes always win over the prior status — but successes never\n // clear it.\n if (exitCode !== 0 || !process.exitCode) {\n process.exitCode = exitCode;\n }\n return exitCode;\n }\n}\n\n/**\n * Argv-aware variant of the entrypoint guard. The shared\n * `@prisma-next/migration-tools` helper of the same name reads\n * `process.argv[1]` directly, which doesn't compose with the new\n * in-process testability surface (tests inject `argv` without mutating\n * the process global). Inlined here so the migration-file CLI's check\n * follows the injected `argv[1]` consistently.\n */\nfunction isDirectEntrypoint(importMetaUrl: string, argv: readonly string[]): boolean {\n const argv1 = argv[1];\n if (!argv1) {\n return false;\n }\n try {\n return realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(argv1);\n } catch {\n return false;\n }\n}\n\n/**\n * Argv-and-stream-driven orchestration body. Pulled out of the static\n * method so the entrypoint guard / process-default plumbing stays\n * separate from the parse + load + serialize steps.\n */\nasync function orchestrate(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n ctx: {\n readonly argv: readonly string[];\n readonly stdout: MigrationCliWritable;\n readonly stderr: MigrationCliWritable;\n },\n): Promise<number> {\n const cli = Cli.from([MigrationFileCommand], {\n binaryName: 'migration.ts',\n binaryLabel: 'Migration file CLI',\n });\n\n const input = ctx.argv.slice(2);\n\n // Pre-scan for malformed `--config` (no value, or value-shaped-as-flag)\n // before delegating to clipanion. The legacy parser surfaced both as\n // `errorMigrationCliInvalidConfigArg` (`PN-CLI-4012`); pre-scanning\n // here keeps that contract independent of how clipanion classifies\n // the error internally (it variably throws `UnknownSyntaxError` or\n // accepts the flag-shaped token as the value depending on what other\n // options are registered).\n const configError = detectInvalidConfig(input);\n if (configError) {\n writeStructuredError(ctx.stderr, configError);\n return 2;\n }\n\n let parsed: MigrationFileCommand;\n try {\n const command = cli.process({\n input: [...input],\n context: { stdout: ctx.stdout, stderr: ctx.stderr },\n });\n if (!(command instanceof MigrationFileCommand)) {\n // The only registered command class is `MigrationFileCommand`;\n // any other concrete type indicates clipanion emitted its\n // built-in `HelpCommand`. Render usage directly so we don't\n // depend on calling `cli.run` (which routes errors to stdout —\n // wrong stream for our contract).\n ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n return 0;\n }\n parsed = command;\n } catch (err) {\n return renderParseError(err, input, ctx.stderr);\n }\n\n if (parsed.help) {\n ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n return 0;\n }\n\n try {\n await runMigration(importMetaUrl, MigrationClass, parsed, ctx);\n return 0;\n } catch (err) {\n if (CliStructuredError.is(err)) {\n writeStructuredError(ctx.stderr, err);\n } else if (MigrationToolsError.is(err)) {\n // Migration-tools errors (e.g. `errorInvalidJson` thrown by\n // `readExistingMetadata` when migration.json is malformed) carry\n // their own `code`/`why`/`fix` shape. Render them with the same\n // visual structure as `CliStructuredError` so consumers grepping\n // for `MIGRATION.<CODE>` see consistent output across surfaces.\n const fix = err.fix ? `\\n${err.fix}` : '';\n ctx.stderr.write(`${err.code}: ${err.message}\\n${err.why}${fix}\\n`);\n } else {\n ctx.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n }\n return 1;\n }\n}\n\n/**\n * Returns an `errorMigrationCliInvalidConfigArg` envelope when `input`\n * contains a malformed `--config`:\n *\n * - `--config` as the last token (no value follows).\n * - `--config <flag>` where `<flag>` starts with `-` (silently\n * consuming the next flag would either drop the flag or serialize\n * against the wrong project).\n * - `--config <empty>` where the value is the empty string. Shells\n * expand `--config \"\"` (or `--config \"$UNSET_VAR\"`) into a real\n * empty argv token; treating that as a usage error here surfaces\n * `PN-CLI-4012` instead of a less actionable loader error on an\n * empty path.\n * - `--config=` (the equals form with an empty value). Same shape as\n * the empty-string case above; the user expressed intent to override\n * the config path but the override is empty.\n *\n * `--config=<value>` and `--config <value>` with a non-empty value are\n * both valid (and the equals form's value is allowed to start with\n * `-` — the `=` makes the binding explicit).\n */\nfunction detectInvalidConfig(input: readonly string[]): CliStructuredError | null {\n for (let i = 0; i < input.length; i++) {\n const token = input[i];\n if (token === '--config') {\n const next = input[i + 1];\n if (next === undefined || next === '') {\n return errorMigrationCliInvalidConfigArg();\n }\n if (next.startsWith('-')) {\n return errorMigrationCliInvalidConfigArg({ nextToken: next });\n }\n continue;\n }\n if (token === '--config=') {\n return errorMigrationCliInvalidConfigArg();\n }\n }\n return null;\n}\n\n/**\n * Translate clipanion's parse-time errors into the project's structured\n * error envelopes.\n *\n * - `UnknownSyntaxError` covers both unknown flags (`--frobnicate`) and\n * the bare-trailing `--config` case (where arity-1 needs a value but\n * none was supplied). Distinguished by inspecting the input array.\n * - `UsageError` covers schema/validator failures from typanion. None\n * of the migration-file CLI's options have validators today, but we\n * still translate it as a usage error (exit 2) for forward-compat.\n * - Anything else re-throws — caller's outer catch will surface it as\n * exit 1 (runtime error).\n */\nfunction renderParseError(\n err: unknown,\n input: readonly string[],\n stderr: MigrationCliWritable,\n): number {\n if (isUnknownSyntaxError(err)) {\n const flag = findOffendingFlag(input);\n writeStructuredError(stderr, errorMigrationCliUnknownFlag({ flag, knownFlags: KNOWN_FLAGS }));\n return 2;\n }\n if (err instanceof UsageError) {\n // typanion validator failures and similar usage errors. None of\n // the migration-file CLI's options have validators today, so this\n // branch is forward-compat scaffolding — kept so that a future\n // option declaration with a validator routes through the same PN\n // envelope path rather than escaping as exit 1.\n writeStructuredError(stderr, errorMigrationCliInvalidConfigArg({ nextToken: err.message }));\n return 2;\n }\n throw err;\n}\n\n/**\n * Duck-type check for clipanion's `UnknownSyntaxError`: the class is\n * thrown by the parser but is not re-exported from the package's main\n * entry (only `UsageError` is — see clipanion's `advanced/index.d.ts`).\n * Identified by `name === 'UnknownSyntaxError'` and the\n * `clipanion.type === 'none'` discriminator that clipanion's\n * `ErrorWithMeta` interface guarantees.\n */\nfunction isUnknownSyntaxError(err: unknown): err is Error {\n if (!(err instanceof Error) || err.name !== 'UnknownSyntaxError') {\n return false;\n }\n // clipanion's `ErrorWithMeta` interface guarantees a `clipanion` field with\n // a `type` discriminator on every error it throws. Read it via a structural\n // shape rather than importing the class (it's not re-exported from the\n // package main).\n const meta = (err as { clipanion?: { type?: string } }).clipanion;\n return typeof meta === 'object' && meta !== null && meta.type === 'none';\n}\n\n/**\n * Best-effort: pull the first input token that doesn't match a known\n * flag. Falls back to the first token when we can't pinpoint it. The\n * returned name is rendered into the user-visible PN-CLI-4013 envelope\n * (`Unknown flag \\`<name>\\``) and round-tripped via `meta.flag` so\n * agent consumers can render their own \"did you mean\" suggestions.\n */\nfunction findOffendingFlag(input: readonly string[]): string {\n for (const token of input) {\n if (!token.startsWith('-')) {\n continue;\n }\n const head = token.split('=', 1)[0] ?? token;\n if (!KNOWN_FLAGS.includes(head) && head !== '-h') {\n return head;\n }\n }\n return input[0] ?? '';\n}\n\n/**\n * Write a `CliStructuredError` envelope to the given stream. Format\n * matches the legacy hand-rolled writer (`message: why`) so the rest of\n * the project's error rendering stays consistent across surfaces. The\n * full PN code (`PN-<domain>-<code>`) is included so consumers can\n * grep for stable identifiers.\n */\nfunction writeStructuredError(stream: MigrationCliWritable, err: CliStructuredError): void {\n const envelope = err.toEnvelope();\n const why = envelope.why ?? envelope.summary;\n const fix = envelope.fix ? `\\n${envelope.fix}` : '';\n stream.write(`${envelope.code}: ${envelope.summary}\\n${why}${fix}\\n`);\n}\n\n/**\n * Read a previously-scaffolded `migration.json` from disk, returning\n * `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`\n * when the file is present but cannot be parsed as JSON. The CLI feeds\n * this into `buildMigrationArtifacts` so the pure builder can preserve\n * fields owned by `migration plan` (contract bookends, hints, labels,\n * `createdAt`) across re-emits.\n *\n * Author-time path: this loader still does not verify the manifest hash\n * or schema — that is the apply-time loader's job. Hash mismatch is the\n * *expected* outcome of a re-author (the developer's source changes\n * invalidate the prior hash by construction), and verification here\n * would block legitimate regenerations. Syntactic JSON-parse failure,\n * however, is now surfaced rather than swallowed: a malformed\n * `migration.json` indicates either a hand-edit gone wrong or partial\n * write, and silently rebuilding from `describe()` would discard the\n * user's on-disk content (preserved bookends, hints, labels,\n * `createdAt`) without any indication something was wrong on disk.\n * Apply-time consumers always route through the verifying\n * `readMigrationPackage` in `@prisma-next/migration-tools/io` instead.\n */\nfunction readExistingMetadata(metadataPath: string): Partial<MigrationMetadata> | null {\n let raw: string;\n try {\n raw = readFileSync(metadataPath, 'utf-8');\n } catch {\n return null;\n }\n try {\n return JSON.parse(raw) as Partial<MigrationMetadata>;\n } catch (e) {\n throw errorInvalidJson(metadataPath, e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Persist a migration instance's artifacts to `migrationDir`. In\n * `dryRun` mode the artifacts are printed to stdout (with the same\n * `--- migration.json --- / --- ops.json ---` framing the legacy\n * `serializeMigration` helper used) and no files are written. Otherwise\n * `ops.json` and `migration.json` are written next to `migration.ts` and\n * a confirmation line is printed.\n *\n * File I/O lives in the CLI rather than `@prisma-next/migration-tools`\n * so the migration-tools package stays focused on the pure\n * `Migration` → in-memory artifact conversion. The CLI is the only\n * legitimate site for combining config loading, stack assembly, and\n * filesystem persistence.\n */\nfunction serializeMigrationToDisk(\n instance: Migration,\n migrationDir: string,\n dryRun: boolean,\n stdout: MigrationCliWritable,\n): void {\n const metadataPath = join(migrationDir, 'migration.json');\n const existing = readExistingMetadata(metadataPath);\n const { opsJson, metadataJson } = buildMigrationArtifacts(instance, existing);\n\n if (dryRun) {\n stdout.write(`--- migration.json ---\\n${metadataJson}\\n`);\n stdout.write('--- ops.json ---\\n');\n stdout.write(`${opsJson}\\n`);\n return;\n }\n\n writeFileSync(join(migrationDir, 'ops.json'), opsJson);\n writeFileSync(metadataPath, metadataJson);\n\n stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\\n`);\n}\n\n/**\n * Inner orchestration: load config, probe-construct the migration,\n * verify target, assemble the stack, construct with the stack, persist.\n *\n * Throws `CliStructuredError` for known failure modes (config not\n * found, target mismatch); the outer `orchestrate` translates those to\n * exit 1.\n */\nasync function runMigration(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n parsed: MigrationFileCommand,\n ctx: {\n readonly stdout: MigrationCliWritable;\n readonly stderr: MigrationCliWritable;\n },\n): Promise<void> {\n const migrationFile = fileURLToPath(importMetaUrl);\n const migrationDir = dirname(migrationFile);\n\n const config = await loadConfig(parsed.config);\n\n // Probe-instantiate without a stack so we can read `targetId` before\n // any target-specific constructor side effects (e.g.\n // `PostgresMigration`'s `stack.adapter.create(stack)`) run. Concrete\n // subclasses are required to accept the no-arg form; the abstract\n // `Migration` constructor declares `stack?` and target subclasses\n // (Postgres, Mongo) propagate that optionality. This makes the\n // target-mismatch guard fail fast with `PN-MIG-2006` before any\n // stack-driven adapter construction begins, even if the wrong-target\n // adapter's `create` would otherwise succeed and silently misshapen\n // the stored adapter cast.\n const probe = new MigrationClass();\n\n if (probe.targetId !== config.target.targetId) {\n throw errorMigrationTargetMismatch({\n migrationTargetId: probe.targetId,\n configTargetId: config.target.targetId,\n });\n }\n\n const stack = createControlStack(config);\n const instance = new MigrationClass(stack);\n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AAG,SAAS,KAAK,IAAI,SAAS,QAAQ,IAAI,MAAM,IAAI,IAAI;;;;;;;;;;;;;;;;;;;;;;;AAwBvE,SAAS,qBAAqB,cAAyD;CACrF,IAAI;CACJ,IAAI;EACF,MAAM,aAAa,cAAc,QAAQ;SACnC;EACN,OAAO;;CAET,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;UACf,GAAG;EACV,MAAM,iBAAiB,cAAc,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE,CAAC;;;;;;;;;;;;;;;;;AAkBpF,SAAS,yBACP,UACA,cACA,QACA,QACM;CACN,MAAM,eAAe,KAAK,cAAc,iBAAiB;CAEzD,MAAM,EAAE,SAAS,iBAAiB,wBAAwB,UADzC,qBAAqB,aACsC,CAAC;CAE7E,IAAI,QAAQ;EACV,OAAO,MAAM,2BAA2B,aAAa,IAAI;EACzD,OAAO,MAAM,qBAAqB;EAClC,OAAO,MAAM,GAAG,QAAQ,IAAI;EAC5B;;CAGF,cAAc,KAAK,cAAc,WAAW,EAAE,QAAQ;CACtD,cAAc,cAAc,aAAa;CAEzC,OAAO,MAAM,sCAAsC,aAAa,IAAI;;;;;;;;;;AAWtE,eAAe,aACb,eACA,gBACA,QACA,KAIe;CAEf,MAAM,eAAe,QADC,cAAc,cACM,CAAC;CAE3C,MAAM,SAAS,MAAM,WAAW,OAAO,OAAO;CAY9C,MAAM,QAAQ,IAAI,gBAAgB;CAElC,IAAI,MAAM,aAAa,OAAO,OAAO,UACnC,MAAM,6BAA6B;EACjC,mBAAmB,MAAM;EACzB,gBAAgB,OAAO,OAAO;EAC/B,CAAC;CAMJ,yBAAyB,IAFJ,eADP,mBAAmB,OACQ,CAER,EAAE,cAAc,OAAO,QAAQ,IAAI,OAAO;CAC3E,IAAS"}
@@ -1,13 +1,12 @@
1
- import { t as loadConfig } from "./config-loader-C25b63rJ.mjs";
2
- import { _ as errorUnexpected, a as errorContractValidationFailed, c as errorDriverRequired, h as errorTargetMigrationNotSupported, l as errorFileNotFound, o as errorDatabaseConnectionRequired } from "./cli-errors-Cd79vmTH.mjs";
3
- import { t as createControlClient } from "./client-CrsnY58k.mjs";
4
- import { _ as formatStyledHeader, a as maskConnectionUrl, n as addGlobalOptions, s as resolveContractPath } from "./result-handler-Ba3zWQsI.mjs";
5
- import { t as createProgressAdapter } from "./progress-adapter-DvQWB1nK.mjs";
1
+ import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
2
+ import { _ as errorUnexpected, a as errorContractValidationFailed, c as errorDriverRequired, h as errorTargetMigrationNotSupported, l as errorFileNotFound, o as errorDatabaseConnectionRequired } from "./cli-errors-D3_sMh2K.mjs";
3
+ import { c as resolveContractPath, o as maskConnectionUrl, t as addGlobalOptions, y as formatStyledHeader } from "./command-helpers-BeZHkxV8.mjs";
4
+ import { t as createProgressAdapter } from "./progress-adapter-DFfvZcYL.mjs";
5
+ import { t as createControlClient } from "./client-qVH-rEgd.mjs";
6
6
  import { notOk, ok } from "@prisma-next/utils/result";
7
- import { hasMigrations } from "@prisma-next/framework-components/control";
8
7
  import { readFile } from "node:fs/promises";
8
+ import { hasMigrations } from "@prisma-next/framework-components/control";
9
9
  import { relative, resolve } from "node:path";
10
-
11
10
  //#region src/utils/migration-command-scaffold.ts
12
11
  /**
13
12
  * Prepares the shared context for migration commands (db init, db update).
@@ -99,7 +98,7 @@ function addMigrationCommandOptions(command) {
99
98
  addGlobalOptions(command);
100
99
  return command.option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--dry-run", "Preview planned operations without applying", false);
101
100
  }
102
-
103
101
  //#endregion
104
102
  export { prepareMigrationContext as n, addMigrationCommandOptions as t };
105
- //# sourceMappingURL=migration-command-scaffold-B3B09et6.mjs.map
103
+
104
+ //# sourceMappingURL=migration-command-scaffold-B5dORFEv.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-command-scaffold-B5dORFEv.mjs","names":[],"sources":["../src/utils/migration-command-scaffold.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport { hasMigrations } from '@prisma-next/framework-components/control';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport type { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { ControlClient } from '../control-api/types';\nimport {\n type CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from './cli-errors';\nimport { addGlobalOptions, maskConnectionUrl, resolveContractPath } from './command-helpers';\nimport { formatStyledHeader } from './formatters/styled';\nimport type { GlobalFlags } from './global-flags';\nimport { createProgressAdapter } from './progress-adapter';\nimport type { TerminalUI } from './terminal-ui';\n\n/**\n * Resolved context for a migration command.\n * Contains everything needed to invoke a control-api operation.\n */\nexport interface MigrationContext {\n readonly client: ControlClient;\n readonly contractJson: Record<string, unknown>;\n readonly dbConnection: unknown;\n readonly onProgress: ReturnType<typeof createProgressAdapter>;\n readonly configPath: string;\n readonly contractPath: string;\n readonly contractPathAbsolute: string;\n readonly config: Awaited<ReturnType<typeof loadConfig>>;\n}\n\n/**\n * Command-specific configuration for the shared scaffold.\n */\nexport interface MigrationCommandDescriptor {\n readonly commandName: string;\n readonly description: string;\n readonly url: string;\n}\n\n/**\n * Prepares the shared context for migration commands (db init, db update).\n *\n * Handles: config loading, contract file reading, JSON parsing, connection resolution,\n * driver/migration-support validation, client creation, and header output.\n *\n * Returns a Result with either the resolved context or a structured error.\n */\nexport async function prepareMigrationContext(\n options: { readonly db?: string; readonly config?: string; readonly dryRun?: boolean },\n flags: GlobalFlags,\n ui: TerminalUI,\n descriptor: MigrationCommandDescriptor,\n): Promise<Result<MigrationContext, CliStructuredError>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header to stderr (decoration)\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n }\n if (options.dryRun) {\n details.push({ label: 'mode', value: 'dry run' });\n }\n const header = formatStyledHeader({\n command: descriptor.commandName,\n description: descriptor.description,\n url: descriptor.url,\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n // Parse contract JSON\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for ${descriptor.commandName} (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: descriptor.commandName,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(\n errorDriverRequired({ why: `Config.driver is required for ${descriptor.commandName}` }),\n );\n }\n\n if (!hasMigrations(config.target)) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ ui, flags });\n\n return ok({\n client,\n contractJson,\n dbConnection,\n onProgress,\n configPath,\n contractPath,\n contractPathAbsolute,\n config,\n });\n}\n\n/**\n * Registers the shared CLI options for migration commands (db init, db update).\n */\nexport function addMigrationCommandOptions(command: Command): Command {\n addGlobalOptions(command);\n return command\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--dry-run', 'Preview planned operations without applying', false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuDA,eAAsB,wBACpB,SACA,OACA,IACA,YACuD;CAEvD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,KAAK,EAAE,QAAQ,QAAQ,OAAO,CAAC,GAChD;CACJ,MAAM,uBAAuB,oBAAoB,OAAO;CACxD,MAAM,eAAe,SAAS,QAAQ,KAAK,EAAE,qBAAqB;CAGlE,IAAI,CAAC,MAAM,QAAQ,CAAC,MAAM,OAAO;EAC/B,MAAM,UAAmD,CACvD;GAAE,OAAO;GAAU,OAAO;GAAY,EACtC;GAAE,OAAO;GAAY,OAAO;GAAc,CAC3C;EACD,IAAI,QAAQ,IACV,QAAQ,KAAK;GAAE,OAAO;GAAY,OAAO,kBAAkB,QAAQ,GAAG;GAAE,CAAC;EAE3E,IAAI,QAAQ,QACV,QAAQ,KAAK;GAAE,OAAO;GAAQ,OAAO;GAAW,CAAC;EAEnD,MAAM,SAAS,mBAAmB;GAChC,SAAS,WAAW;GACpB,aAAa,WAAW;GACxB,KAAK,WAAW;GAChB;GACA;GACD,CAAC;EACF,GAAG,OAAO,OAAO;;CAInB,IAAI;CACJ,IAAI;EACF,sBAAsB,MAAM,SAAS,sBAAsB,QAAQ;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