@prisma-next/cli 0.5.0-dev.24 → 0.5.0-dev.26

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.
@@ -1,4 +1,5 @@
1
1
  import { Migration } from "@prisma-next/migration-tools/migration";
2
+ import { Writable } from "node:stream";
2
3
 
3
4
  //#region src/migration-cli.d.ts
4
5
 
@@ -18,6 +19,20 @@ import { Migration } from "@prisma-next/migration-tools/migration";
18
19
  * point for additional construction arguments.
19
20
  */
20
21
  type MigrationConstructor = new (...args: any[]) => Migration;
22
+ /**
23
+ * Stream surface accepted by `MigrationCLI.run`'s `options.stdout` /
24
+ * `options.stderr`. Aliases node's `Writable` because clipanion's
25
+ * `BaseContext.stdout`/`stderr` are typed as `Writable`, and the CLI
26
+ * forwards the injected streams into clipanion's context.
27
+ *
28
+ * `process.stdout` and `process.stderr` are `Writable`-shaped, so the
29
+ * default-fallback path remains a no-op for existing two-argument
30
+ * callers like `MigrationCLI.run(import.meta.url, MyMigration)`.
31
+ *
32
+ * Tests inject a `Writable` subclass that captures chunks for
33
+ * assertions.
34
+ */
35
+ type MigrationCliWritable = Writable;
21
36
  /**
22
37
  * The CLI surface invoked by an authored `migration.ts` file. Exposed as
23
38
  * a class with a static `run` method (rather than a free function) to
@@ -32,19 +47,34 @@ type MigrationConstructor = new (...args: any[]) => Migration;
32
47
  */
33
48
  declare class MigrationCLI {
34
49
  /**
35
- * Orchestrates a class-flow `migration.ts` script run. Awaitable:
36
- * callers may `await MigrationCLI.run(...)` to surface async failures
37
- * from config loading, but the typical usage pattern (top-level call
38
- * after the class definition) does not require awaiting because
39
- * node's module evaluation keeps the promise alive until completion.
50
+ * Orchestrates a class-flow `migration.ts` script run.
51
+ *
52
+ * The third argument is the in-process testability surface: callers
53
+ * (and tests) may inject `argv`, `stdout`, and `stderr` instead of
54
+ * relying on `process.argv` / `process.stdout` / `process.stderr`.
55
+ * Each option defaults to its `process` global when omitted, so
56
+ * existing two-argument call sites
57
+ * (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to
58
+ * compile and behave identically.
59
+ *
60
+ * Returns the exit code so the caller can branch on it. Also writes
61
+ * the same code to `process.exitCode` so script-style callers that
62
+ * don't await the return value still surface a non-zero exit when
63
+ * something fails.
40
64
  *
41
- * Any throwable inside this function must surface through the internal
42
- * try/catchscript callers do not await, so an unhandled rejection
43
- * would silently exit 0. Treat the try/catch as load-bearing for the
44
- * no-await usage pattern.
65
+ * Exit codes:
66
+ * - 0 success, or `--help`, or imported-not-entrypoint no-op.
67
+ * - 1 runtime/orchestration error (config not found, target
68
+ * mismatch, etc.).
69
+ * - 2 — usage error (unknown flag, malformed `--config`). Aligns
70
+ * with `docs/CLI Style Guide.md` § Exit Codes.
45
71
  */
46
- static run(importMetaUrl: string, MigrationClass: MigrationConstructor): Promise<void>;
72
+ static run(importMetaUrl: string, MigrationClass: MigrationConstructor, options?: {
73
+ readonly argv?: readonly string[];
74
+ readonly stdout?: MigrationCliWritable;
75
+ readonly stderr?: MigrationCliWritable;
76
+ }): Promise<number>;
47
77
  }
48
78
  //#endregion
49
- export { MigrationCLI, MigrationConstructor };
79
+ export { MigrationCLI, MigrationCliWritable, MigrationConstructor };
50
80
  //# sourceMappingURL=migration-cli.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration-cli.d.mts","names":[],"sources":["../src/migration-cli.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;KAsEY,oBAAA,2BAA+C;;;;;;;;;;;;;cAiE9C,YAAA;;;;;;;;;;;;;oDAa6C,uBAAuB"}
1
+ {"version":3,"file":"migration-cli.d.mts","names":[],"sources":["../src/migration-cli.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;KA6EY,oBAAA,2BAA+C;;;;;;;;;;;;;;KAe/C,oBAAA,GAAuB;;;;;;;;;;;;;cAuEtB,YAAA;;;;;;;;;;;;;;;;;;;;;;;;oDA0BO;;sBAGI;sBACA;MAEnB"}
@@ -1,12 +1,13 @@
1
1
  import { t as loadConfig } from "./config-loader-ih8ViDb_.mjs";
2
- import { CliStructuredError, errorMigrationCliInvalidConfigArg } from "@prisma-next/errors/control";
2
+ import { CliStructuredError, errorMigrationCliInvalidConfigArg, errorMigrationCliUnknownFlag } from "@prisma-next/errors/control";
3
3
  import { dirname, join } from "pathe";
4
4
  import { createControlStack } from "@prisma-next/framework-components/control";
5
5
  import { errorMigrationTargetMismatch } from "@prisma-next/errors/migration";
6
- import { readFileSync, writeFileSync } from "node:fs";
6
+ import { readFileSync, realpathSync, writeFileSync } from "node:fs";
7
7
  import { MigrationToolsError, errorInvalidJson } from "@prisma-next/migration-tools/errors";
8
8
  import { fileURLToPath } from "node:url";
9
- import { buildMigrationArtifacts, isDirectEntrypoint, printMigrationHelp } from "@prisma-next/migration-tools/migration";
9
+ import { buildMigrationArtifacts } from "@prisma-next/migration-tools/migration";
10
+ import { Cli, Command, Option, UsageError } from "clipanion";
10
11
 
11
12
  //#region src/migration-cli.ts
12
13
  /**
@@ -26,7 +27,8 @@ import { buildMigrationArtifacts, isDirectEntrypoint, printMigrationHelp } from
26
27
  * entrypoint (`node migration.ts`), the CLI:
27
28
  *
28
29
  * 1. Detects whether the file is the direct entrypoint (no-op when imported).
29
- * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`).
30
+ * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`) via
31
+ * [clipanion](https://github.com/arcanis/clipanion).
30
32
  * 3. Loads the project's `prisma-next.config.ts` via the same `loadConfig`
31
33
  * the CLI commands use, walking up from the migration file's directory.
32
34
  * 4. Probe-instantiates the migration class without a stack so it can read
@@ -45,44 +47,62 @@ import { buildMigrationArtifacts, isDirectEntrypoint, printMigrationHelp } from
45
47
  * on-disk persistence. `@prisma-next/migration-tools` owns the pure
46
48
  * conversion from a `Migration` instance to artifact strings; `Migration`
47
49
  * stays a pure abstract class.
50
+ *
51
+ * Parser library: clipanion (chosen over Commander/citty/`node:util.parseArgs`
52
+ * for its in-process testability and runtime-agnostic execution surface; see
53
+ * `docs/architecture docs/research/commander-friction-points.md` for the
54
+ * evaluation rubric and the durable rationale that drove the choice).
48
55
  */
49
56
  /**
50
- * Parse the subset of `process.argv` that `MigrationCLI.run` cares about.
51
- * Recognised flags: `--help`, `--dry-run`, `--config <path>` /
52
- * `--config=<path>`. Unknown flags are ignored to keep the surface
53
- * forgiving for ad-hoc tooling that wraps a migration file.
54
- *
55
- * Throws `errorMigrationCliInvalidConfigArg` (`PN-CLI-4012`) when
56
- * `--config` is missing its path argument or is followed by another flag
57
- * (e.g. `--config --dry-run`); silently consuming the next flag would
58
- * either drop dry-run handling or serialize against the wrong project.
57
+ * Flags exposed by the migration-file CLI.
59
58
  *
60
- * NOTE: this hand-rolled parser is a known wart, tracked separately by
61
- * TML-2318 ("Migration CLI: replace handrolled arg parser with shared
62
- * CLI library"). Until that lands the surface is intentionally tiny.
59
+ * Must stay in sync with the `Option` declarations on
60
+ * `MigrationFileCommand` below. This list is rendered in the
61
+ * `errorMigrationCliUnknownFlag` envelope's `fix` text and `meta`,
62
+ * so order matters for user-visible output (declaration order is the
63
+ * order users see when they run `--help`).
64
+ */
65
+ const KNOWN_FLAGS = [
66
+ "--help",
67
+ "--dry-run",
68
+ "--config"
69
+ ];
70
+ /**
71
+ * The clipanion command that owns the migration-file CLI's option
72
+ * declarations. The class is internal — `MigrationCLI.run` is the
73
+ * stable public surface. Adding a flag here automatically updates
74
+ * `--help` rendering and the `KNOWN_FLAGS` list (the latter must be
75
+ * updated in tandem).
63
76
  */
64
- function parseArgs(argv) {
65
- let help = false;
66
- let dryRun = false;
67
- let configPath;
68
- for (let i = 0; i < argv.length; i++) {
69
- const arg = argv[i];
70
- if (arg === "--help" || arg === "-h") help = true;
71
- else if (arg === "--dry-run") dryRun = true;
72
- else if (arg === "--config") {
73
- const next = argv[i + 1];
74
- if (next === void 0) throw errorMigrationCliInvalidConfigArg();
75
- if (next.startsWith("-")) throw errorMigrationCliInvalidConfigArg({ nextToken: next });
76
- configPath = next;
77
- i++;
78
- } else if (arg.startsWith("--config=")) configPath = arg.slice(9);
77
+ var MigrationFileCommand = class extends Command {
78
+ static paths = [Command.Default];
79
+ static usage = Command.Usage({
80
+ description: "Self-emit ops.json and migration.json from a class-flow migration",
81
+ details: `
82
+ Loads the project's prisma-next.config.ts, assembles a ControlStack
83
+ from the configured target/adapter/extensions, and serializes the
84
+ migration's operations + metadata next to this file.
85
+ `,
86
+ examples: [
87
+ ["Self-emit ops.json + migration.json next to migration.ts", "$0"],
88
+ ["Preview without writing files", "$0 --dry-run"],
89
+ ["Use a non-default config path", "$0 --config ./custom.config.ts"]
90
+ ]
91
+ });
92
+ dryRun = Option.Boolean("--dry-run", false, { description: "Print operations to stdout without writing files" });
93
+ config = Option.String("--config", { description: "Path to prisma-next.config.ts" });
94
+ /**
95
+ * Unused: orchestration runs inside `MigrationCLI.run` so error
96
+ * routing stays under our control (clipanion's `cli.run` writes
97
+ * error output to `context.stdout`, but our contract requires
98
+ * structured errors on stderr). `cli.process` is used to parse
99
+ * argv into a populated `MigrationFileCommand` instance whose
100
+ * fields drive the orchestration directly.
101
+ */
102
+ async execute() {
103
+ return 0;
79
104
  }
80
- return {
81
- help,
82
- dryRun,
83
- configPath
84
- };
85
- }
105
+ };
86
106
  /**
87
107
  * The CLI surface invoked by an authored `migration.ts` file. Exposed as
88
108
  * a class with a static `run` method (rather than a free function) to
@@ -97,41 +117,211 @@ function parseArgs(argv) {
97
117
  */
98
118
  var MigrationCLI = class {
99
119
  /**
100
- * Orchestrates a class-flow `migration.ts` script run. Awaitable:
101
- * callers may `await MigrationCLI.run(...)` to surface async failures
102
- * from config loading, but the typical usage pattern (top-level call
103
- * after the class definition) does not require awaiting because
104
- * node's module evaluation keeps the promise alive until completion.
120
+ * Orchestrates a class-flow `migration.ts` script run.
121
+ *
122
+ * The third argument is the in-process testability surface: callers
123
+ * (and tests) may inject `argv`, `stdout`, and `stderr` instead of
124
+ * relying on `process.argv` / `process.stdout` / `process.stderr`.
125
+ * Each option defaults to its `process` global when omitted, so
126
+ * existing two-argument call sites
127
+ * (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to
128
+ * compile and behave identically.
105
129
  *
106
- * Any throwable inside this function must surface through the internal
107
- * try/catch script callers do not await, so an unhandled rejection
108
- * would silently exit 0. Treat the try/catch as load-bearing for the
109
- * no-await usage pattern.
130
+ * Returns the exit code so the caller can branch on it. Also writes
131
+ * the same code to `process.exitCode` so script-style callers that
132
+ * don't await the return value still surface a non-zero exit when
133
+ * something fails.
134
+ *
135
+ * Exit codes:
136
+ * - 0 — success, or `--help`, or imported-not-entrypoint no-op.
137
+ * - 1 — runtime/orchestration error (config not found, target
138
+ * mismatch, etc.).
139
+ * - 2 — usage error (unknown flag, malformed `--config`). Aligns
140
+ * with `docs/CLI Style Guide.md` § Exit Codes.
110
141
  */
111
- static async run(importMetaUrl, MigrationClass) {
112
- if (!importMetaUrl) return;
113
- if (!isDirectEntrypoint(importMetaUrl)) return;
114
- try {
115
- const args = parseArgs(process.argv.slice(2));
116
- if (args.help) {
117
- printMigrationHelp();
118
- return;
142
+ static async run(importMetaUrl, MigrationClass, options = {}) {
143
+ if (!importMetaUrl) return 0;
144
+ const argv = options.argv ?? process.argv;
145
+ const stdout = options.stdout ?? process.stdout;
146
+ const stderr = options.stderr ?? process.stderr;
147
+ if (!isDirectEntrypoint(importMetaUrl, argv)) return 0;
148
+ const exitCode = await orchestrate(importMetaUrl, MigrationClass, {
149
+ argv,
150
+ stdout,
151
+ stderr
152
+ });
153
+ if (exitCode !== 0 || !process.exitCode) process.exitCode = exitCode;
154
+ return exitCode;
155
+ }
156
+ };
157
+ /**
158
+ * Argv-aware variant of the entrypoint guard. The shared
159
+ * `@prisma-next/migration-tools` helper of the same name reads
160
+ * `process.argv[1]` directly, which doesn't compose with the new
161
+ * in-process testability surface (tests inject `argv` without mutating
162
+ * the process global). Inlined here so the migration-file CLI's check
163
+ * follows the injected `argv[1]` consistently.
164
+ */
165
+ function isDirectEntrypoint(importMetaUrl, argv) {
166
+ const argv1 = argv[1];
167
+ if (!argv1) return false;
168
+ try {
169
+ return realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(argv1);
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+ /**
175
+ * Argv-and-stream-driven orchestration body. Pulled out of the static
176
+ * method so the entrypoint guard / process-default plumbing stays
177
+ * separate from the parse + load + serialize steps.
178
+ */
179
+ async function orchestrate(importMetaUrl, MigrationClass, ctx) {
180
+ const cli = Cli.from([MigrationFileCommand], {
181
+ binaryName: "migration.ts",
182
+ binaryLabel: "Migration file CLI"
183
+ });
184
+ const input = ctx.argv.slice(2);
185
+ const configError = detectInvalidConfig(input);
186
+ if (configError) {
187
+ writeStructuredError(ctx.stderr, configError);
188
+ return 2;
189
+ }
190
+ let parsed;
191
+ try {
192
+ const command = cli.process({
193
+ input: [...input],
194
+ context: {
195
+ stdout: ctx.stdout,
196
+ stderr: ctx.stderr
119
197
  }
120
- const migrationDir = dirname(fileURLToPath(importMetaUrl));
121
- const config = await loadConfig(args.configPath);
122
- const probe = new MigrationClass();
123
- if (probe.targetId !== config.target.targetId) throw errorMigrationTargetMismatch({
124
- migrationTargetId: probe.targetId,
125
- configTargetId: config.target.targetId
126
- });
127
- serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, args.dryRun);
128
- } catch (err) {
129
- if (CliStructuredError.is(err) || MigrationToolsError.is(err)) process.stderr.write(`${err.message}: ${err.why}\n`);
130
- else process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
131
- process.exitCode = 1;
198
+ });
199
+ if (!(command instanceof MigrationFileCommand)) {
200
+ ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));
201
+ return 0;
132
202
  }
203
+ parsed = command;
204
+ } catch (err) {
205
+ return renderParseError(err, input, ctx.stderr);
133
206
  }
134
- };
207
+ if (parsed.help) {
208
+ ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));
209
+ return 0;
210
+ }
211
+ try {
212
+ await runMigration(importMetaUrl, MigrationClass, parsed, ctx);
213
+ return 0;
214
+ } catch (err) {
215
+ if (CliStructuredError.is(err)) writeStructuredError(ctx.stderr, err);
216
+ else if (MigrationToolsError.is(err)) {
217
+ const fix = err.fix ? `\n${err.fix}` : "";
218
+ ctx.stderr.write(`${err.code}: ${err.message}\n${err.why}${fix}\n`);
219
+ } else ctx.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
220
+ return 1;
221
+ }
222
+ }
223
+ /**
224
+ * Returns an `errorMigrationCliInvalidConfigArg` envelope when `input`
225
+ * contains a malformed `--config`:
226
+ *
227
+ * - `--config` as the last token (no value follows).
228
+ * - `--config <flag>` where `<flag>` starts with `-` (silently
229
+ * consuming the next flag would either drop the flag or serialize
230
+ * against the wrong project).
231
+ * - `--config <empty>` where the value is the empty string. Shells
232
+ * expand `--config ""` (or `--config "$UNSET_VAR"`) into a real
233
+ * empty argv token; treating that as a usage error here surfaces
234
+ * `PN-CLI-4012` instead of a less actionable loader error on an
235
+ * empty path.
236
+ * - `--config=` (the equals form with an empty value). Same shape as
237
+ * the empty-string case above; the user expressed intent to override
238
+ * the config path but the override is empty.
239
+ *
240
+ * `--config=<value>` and `--config <value>` with a non-empty value are
241
+ * both valid (and the equals form's value is allowed to start with
242
+ * `-` — the `=` makes the binding explicit).
243
+ */
244
+ function detectInvalidConfig(input) {
245
+ for (let i = 0; i < input.length; i++) {
246
+ const token = input[i];
247
+ if (token === "--config") {
248
+ const next = input[i + 1];
249
+ if (next === void 0 || next === "") return errorMigrationCliInvalidConfigArg();
250
+ if (next.startsWith("-")) return errorMigrationCliInvalidConfigArg({ nextToken: next });
251
+ continue;
252
+ }
253
+ if (token === "--config=") return errorMigrationCliInvalidConfigArg();
254
+ }
255
+ return null;
256
+ }
257
+ /**
258
+ * Translate clipanion's parse-time errors into the project's structured
259
+ * error envelopes.
260
+ *
261
+ * - `UnknownSyntaxError` covers both unknown flags (`--frobnicate`) and
262
+ * the bare-trailing `--config` case (where arity-1 needs a value but
263
+ * none was supplied). Distinguished by inspecting the input array.
264
+ * - `UsageError` covers schema/validator failures from typanion. None
265
+ * of the migration-file CLI's options have validators today, but we
266
+ * still translate it as a usage error (exit 2) for forward-compat.
267
+ * - Anything else re-throws — caller's outer catch will surface it as
268
+ * exit 1 (runtime error).
269
+ */
270
+ function renderParseError(err, input, stderr) {
271
+ if (isUnknownSyntaxError(err)) {
272
+ writeStructuredError(stderr, errorMigrationCliUnknownFlag({
273
+ flag: findOffendingFlag(input),
274
+ knownFlags: KNOWN_FLAGS
275
+ }));
276
+ return 2;
277
+ }
278
+ if (err instanceof UsageError) {
279
+ writeStructuredError(stderr, errorMigrationCliInvalidConfigArg({ nextToken: err.message }));
280
+ return 2;
281
+ }
282
+ throw err;
283
+ }
284
+ /**
285
+ * Duck-type check for clipanion's `UnknownSyntaxError`: the class is
286
+ * thrown by the parser but is not re-exported from the package's main
287
+ * entry (only `UsageError` is — see clipanion's `advanced/index.d.ts`).
288
+ * Identified by `name === 'UnknownSyntaxError'` and the
289
+ * `clipanion.type === 'none'` discriminator that clipanion's
290
+ * `ErrorWithMeta` interface guarantees.
291
+ */
292
+ function isUnknownSyntaxError(err) {
293
+ if (!(err instanceof Error) || err.name !== "UnknownSyntaxError") return false;
294
+ const meta = err.clipanion;
295
+ return typeof meta === "object" && meta !== null && meta.type === "none";
296
+ }
297
+ /**
298
+ * Best-effort: pull the first input token that doesn't match a known
299
+ * flag. Falls back to the first token when we can't pinpoint it. The
300
+ * returned name is rendered into the user-visible PN-CLI-4013 envelope
301
+ * (`Unknown flag \`<name>\``) and round-tripped via `meta.flag` so
302
+ * agent consumers can render their own "did you mean" suggestions.
303
+ */
304
+ function findOffendingFlag(input) {
305
+ for (const token of input) {
306
+ if (!token.startsWith("-")) continue;
307
+ const head = token.split("=", 1)[0] ?? token;
308
+ if (!KNOWN_FLAGS.includes(head) && head !== "-h") return head;
309
+ }
310
+ return input[0] ?? "";
311
+ }
312
+ /**
313
+ * Write a `CliStructuredError` envelope to the given stream. Format
314
+ * matches the legacy hand-rolled writer (`message: why`) so the rest of
315
+ * the project's error rendering stays consistent across surfaces. The
316
+ * full PN code (`PN-<domain>-<code>`) is included so consumers can
317
+ * grep for stable identifiers.
318
+ */
319
+ function writeStructuredError(stream, err) {
320
+ const envelope = err.toEnvelope();
321
+ const why = envelope.why ?? envelope.summary;
322
+ const fix = envelope.fix ? `\n${envelope.fix}` : "";
323
+ stream.write(`${envelope.code}: ${envelope.summary}\n${why}${fix}\n`);
324
+ }
135
325
  /**
136
326
  * Read a previously-scaffolded `migration.json` from disk, returning
137
327
  * `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`
@@ -180,18 +370,37 @@ function readExistingMetadata(metadataPath) {
180
370
  * legitimate site for combining config loading, stack assembly, and
181
371
  * filesystem persistence.
182
372
  */
183
- function serializeMigrationToDisk(instance, migrationDir, dryRun) {
373
+ function serializeMigrationToDisk(instance, migrationDir, dryRun, stdout) {
184
374
  const metadataPath = join(migrationDir, "migration.json");
185
375
  const { opsJson, metadataJson } = buildMigrationArtifacts(instance, readExistingMetadata(metadataPath));
186
376
  if (dryRun) {
187
- process.stdout.write(`--- migration.json ---\n${metadataJson}\n`);
188
- process.stdout.write("--- ops.json ---\n");
189
- process.stdout.write(`${opsJson}\n`);
377
+ stdout.write(`--- migration.json ---\n${metadataJson}\n`);
378
+ stdout.write("--- ops.json ---\n");
379
+ stdout.write(`${opsJson}\n`);
190
380
  return;
191
381
  }
192
382
  writeFileSync(join(migrationDir, "ops.json"), opsJson);
193
383
  writeFileSync(metadataPath, metadataJson);
194
- process.stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\n`);
384
+ stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\n`);
385
+ }
386
+ /**
387
+ * Inner orchestration: load config, probe-construct the migration,
388
+ * verify target, assemble the stack, construct with the stack, persist.
389
+ *
390
+ * Throws `CliStructuredError` for known failure modes (config not
391
+ * found, target mismatch); the outer `orchestrate` translates those to
392
+ * exit 1.
393
+ */
394
+ async function runMigration(importMetaUrl, MigrationClass, parsed, ctx) {
395
+ const migrationDir = dirname(fileURLToPath(importMetaUrl));
396
+ const config = await loadConfig(parsed.config);
397
+ const probe = new MigrationClass();
398
+ if (probe.targetId !== config.target.targetId) throw errorMigrationTargetMismatch({
399
+ migrationTargetId: probe.targetId,
400
+ configTargetId: config.target.targetId
401
+ });
402
+ serializeMigrationToDisk(new MigrationClass(createControlStack(config)), migrationDir, parsed.dryRun, ctx.stdout);
403
+ ctx.stderr;
195
404
  }
196
405
 
197
406
  //#endregion
@@ -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 { errorInvalidJson, MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport {\n buildMigrationArtifacts,\n isDirectEntrypoint,\n type Migration,\n printMigrationHelp,\n} from '@prisma-next/migration-tools/migration';\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) || MigrationToolsError.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 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): 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 process.stdout.write(`--- migration.json ---\\n${metadataJson}\\n`);\n process.stdout.write('--- ops.json ---\\n');\n process.stdout.write(`${opsJson}\\n`);\n return;\n }\n\n writeFileSync(join(migrationDir, 'ops.json'), opsJson);\n writeFileSync(metadataPath, metadataJson);\n\n process.stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\\n`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I,CAC3D,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;;;;;;;;;;;;;;;;;;;;;;;;;AA0BzB,SAAS,qBAAqB,cAAyD;CACrF,IAAIC;AACJ,KAAI;AACF,QAAM,aAAa,cAAc,QAAQ;SACnC;AACN,SAAO;;AAET,KAAI;AACF,SAAO,KAAK,MAAM,IAAI;UACf,GAAG;AACV,QAAM,iBAAiB,cAAc,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE,CAAC;;;;;;;;;;;;;;;;;AAkBpF,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":["KNOWN_FLAGS: readonly string[]","parsed: MigrationFileCommand","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>`) 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\n serializeMigrationToDisk(instance, migrationDir, parsed.dryRun, ctx.stdout);\n void ctx.stderr;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,MAAMA,cAAiC;CAAC;CAAU;CAAa;CAAW;;;;;;;;AAS1E,IAAM,uBAAN,cAAmC,QAAQ;CACzC,OAAgB,QAAQ,CAAC,QAAQ,QAAQ;CAEzC,OAAgB,QAAQ,QAAQ,MAAM;EACpC,aAAa;EACb,SAAS;;;;;EAKT,UAAU;GACR,CAAC,4DAA4D,KAAK;GAClE,CAAC,iCAAiC,eAAe;GACjD,CAAC,iCAAiC,iCAAiC;GACpE;EACF,CAAC;CAEF,SAAS,OAAO,QAAQ,aAAa,OAAO,EAC1C,aAAa,oDACd,CAAC;CAEF,SAAS,OAAO,OAAO,YAAY,EACjC,aAAa,iCACd,CAAC;;;;;;;;;CAUF,MAAe,UAA2B;AACxC,SAAO;;;;;;;;;;;;;;;AAiBX,IAAa,eAAb,MAA0B;;;;;;;;;;;;;;;;;;;;;;;;CAwBxB,aAAa,IACX,eACA,gBACA,UAII,EAAE,EACW;AACjB,MAAI,CAAC,cACH,QAAO;EAGT,MAAM,OAAO,QAAQ,QAAQ,QAAQ;EACrC,MAAM,SAAS,QAAQ,UAAU,QAAQ;EACzC,MAAM,SAAS,QAAQ,UAAU,QAAQ;AAEzC,MAAI,CAAC,mBAAmB,eAAe,KAAK,CAC1C,QAAO;EAGT,MAAM,WAAW,MAAM,YAAY,eAAe,gBAAgB;GAChE;GACA;GACA;GACD,CAAC;AASF,MAAI,aAAa,KAAK,CAAC,QAAQ,SAC7B,SAAQ,WAAW;AAErB,SAAO;;;;;;;;;;;AAYX,SAAS,mBAAmB,eAAuB,MAAkC;CACnF,MAAM,QAAQ,KAAK;AACnB,KAAI,C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