@prisma-next/cli 0.10.0 → 0.11.0-dev.1
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.
- package/README.md +1 -1
- package/dist/{cli-errors-CF60g2cG.mjs → cli-errors-Djtz98Vm.mjs} +3 -3
- package/dist/cli-errors-Djtz98Vm.mjs.map +1 -0
- package/dist/cli.mjs +400 -13
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-Brv4qlfB.mjs → client-oXO2WCPD.mjs} +6 -5
- package/dist/client-oXO2WCPD.mjs.map +1 -0
- package/dist/{command-helpers-D3vL5yi8.mjs → command-helpers-DtavI0wJ.mjs} +109 -12
- package/dist/command-helpers-DtavI0wJ.mjs.map +1 -0
- package/dist/commands/contract-emit.mjs +1 -1
- package/dist/commands/contract-infer.mjs +1 -1
- package/dist/commands/db-init.d.mts.map +1 -1
- package/dist/commands/db-init.mjs +19 -20
- package/dist/commands/db-init.mjs.map +1 -1
- package/dist/commands/db-schema.mjs +6 -10
- package/dist/commands/db-schema.mjs.map +1 -1
- package/dist/commands/db-sign.mjs +7 -11
- package/dist/commands/db-sign.mjs.map +1 -1
- package/dist/commands/db-update.d.mts.map +1 -1
- package/dist/commands/db-update.mjs +16 -17
- package/dist/commands/db-update.mjs.map +1 -1
- package/dist/commands/db-verify.mjs +1 -1
- package/dist/commands/migrate.d.mts +1 -1
- package/dist/commands/migrate.mjs +7 -11
- package/dist/commands/migrate.mjs.map +1 -1
- package/dist/commands/migration-check.mjs +4 -7
- package/dist/commands/migration-check.mjs.map +1 -1
- package/dist/commands/migration-graph.d.mts +1 -1
- package/dist/commands/migration-graph.mjs +6 -10
- package/dist/commands/migration-graph.mjs.map +1 -1
- package/dist/commands/migration-list.mjs +5 -9
- package/dist/commands/migration-list.mjs.map +1 -1
- package/dist/commands/migration-log.d.mts.map +1 -1
- package/dist/commands/migration-log.mjs +7 -10
- package/dist/commands/migration-log.mjs.map +1 -1
- package/dist/commands/migration-new.mjs +6 -10
- package/dist/commands/migration-new.mjs.map +1 -1
- package/dist/commands/migration-plan.d.mts +1 -1
- package/dist/commands/migration-plan.mjs +1 -1
- package/dist/commands/migration-show.d.mts +1 -1
- package/dist/commands/migration-show.mjs +8 -12
- package/dist/commands/migration-show.mjs.map +1 -1
- package/dist/commands/migration-status.d.mts +1 -1
- package/dist/commands/migration-status.d.mts.map +1 -1
- package/dist/commands/migration-status.mjs +36 -14
- package/dist/commands/migration-status.mjs.map +1 -1
- package/dist/commands/ref.d.mts +1 -1
- package/dist/commands/ref.mjs +9 -19
- package/dist/commands/ref.mjs.map +1 -1
- package/dist/{contract-emit-iynA3BCA.mjs → contract-emit-bcrpT-wD.mjs} +3 -3
- package/dist/{contract-emit-iynA3BCA.mjs.map → contract-emit-bcrpT-wD.mjs.map} +1 -1
- package/dist/{contract-emit-C3STUIBg.mjs → contract-emit-uwT-Mj8-.mjs} +7 -12
- package/dist/contract-emit-uwT-Mj8-.mjs.map +1 -0
- package/dist/{contract-infer-Cnj8G1E2.mjs → contract-infer-pKkiCt7C.mjs} +9 -14
- package/dist/contract-infer-pKkiCt7C.mjs.map +1 -0
- package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs → contract-space-aggregate-loader-BmNQwlws.mjs} +2 -2
- package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs.map → contract-space-aggregate-loader-BmNQwlws.mjs.map} +1 -1
- package/dist/{db-verify-D7cyH_zz.mjs → db-verify-AoIUriL4.mjs} +9 -13
- package/dist/db-verify-AoIUriL4.mjs.map +1 -0
- package/dist/exports/control-api.d.mts +1 -1
- package/dist/exports/control-api.mjs +2 -2
- package/dist/exports/index.mjs +2 -2
- package/dist/exports/init-output.mjs +1 -1
- package/dist/{framework-components-xFLFpZUO.mjs → framework-components-65gOHkHB.mjs} +2 -2
- package/dist/{framework-components-xFLFpZUO.mjs.map → framework-components-65gOHkHB.mjs.map} +1 -1
- package/dist/{global-flags-DGmw6Kqg.d.mts → global-flags-CdE7M0d9.d.mts} +4 -1
- package/dist/global-flags-CdE7M0d9.d.mts.map +1 -0
- package/dist/{graph-render-eJDcLWny.mjs → graph-render-DJVv0_uf.mjs} +1 -1
- package/dist/{graph-render-eJDcLWny.mjs.map → graph-render-DJVv0_uf.mjs.map} +1 -1
- package/dist/{init-eh2z5Tl6.mjs → init-YX6lCJpG.mjs} +528 -627
- package/dist/init-YX6lCJpG.mjs.map +1 -0
- package/dist/{inspect-live-schema-CWLK_lgs.mjs → inspect-live-schema-LeWvkZVz.mjs} +4 -4
- package/dist/{inspect-live-schema-CWLK_lgs.mjs.map → inspect-live-schema-LeWvkZVz.mjs.map} +1 -1
- package/dist/{migration-command-scaffold-CmXXC1UZ.mjs → migration-command-scaffold-BtkunvFQ.mjs} +4 -4
- package/dist/{migration-command-scaffold-CmXXC1UZ.mjs.map → migration-command-scaffold-BtkunvFQ.mjs.map} +1 -1
- package/dist/{migration-plan-CHyUlBV0.mjs → migration-plan-C2jeH1J5.mjs} +8 -12
- package/dist/migration-plan-C2jeH1J5.mjs.map +1 -0
- package/dist/{migration-types-D2FW63pr.d.mts → migration-types-BXWvz12q.d.mts} +1 -1
- package/dist/{migration-types-D2FW63pr.d.mts.map → migration-types-BXWvz12q.d.mts.map} +1 -1
- package/dist/{migrations-DyUf5lTt.mjs → migrations-CwZMa1Ck.mjs} +2 -2
- package/dist/{migrations-DyUf5lTt.mjs.map → migrations-CwZMa1Ck.mjs.map} +1 -1
- package/dist/{output-B60Gw5fu.mjs → output-BlsrGMEF.mjs} +1 -1
- package/dist/{output-B60Gw5fu.mjs.map → output-BlsrGMEF.mjs.map} +1 -1
- package/dist/quick-reference-mongo.md +1 -1
- package/dist/quick-reference-postgres.md +1 -1
- package/dist/readme-mongo.md +35 -0
- package/dist/readme-postgres.md +34 -0
- package/dist/{terminal-ui-XtOQsqe9.mjs → terminal-ui-BiB_8KNo.mjs} +131 -24
- package/dist/terminal-ui-BiB_8KNo.mjs.map +1 -0
- package/dist/{types-0aS865QN.d.mts → types--CqjMdk0.d.mts} +2 -2
- package/dist/{types-0aS865QN.d.mts.map → types--CqjMdk0.d.mts.map} +1 -1
- package/dist/{verify-D7ypCCe6.mjs → verify-Bom75OYI.mjs} +2 -2
- package/dist/{verify-D7ypCCe6.mjs.map → verify-Bom75OYI.mjs.map} +1 -1
- package/package.json +19 -17
- package/src/cli.ts +42 -0
- package/src/commands/contract-emit.ts +4 -4
- package/src/commands/contract-infer.ts +7 -7
- package/src/commands/db-init.ts +13 -5
- package/src/commands/db-schema.ts +4 -4
- package/src/commands/db-sign.ts +4 -4
- package/src/commands/db-update.ts +13 -5
- package/src/commands/db-verify.ts +5 -5
- package/src/commands/init/detect-package-manager.ts +15 -0
- package/src/commands/init/errors.ts +33 -2
- package/src/commands/init/hygiene-gitattributes.ts +2 -2
- package/src/commands/init/index.ts +15 -6
- package/src/commands/init/init.ts +61 -32
- package/src/commands/init/inputs.ts +82 -5
- package/src/commands/init/output.ts +1 -1
- package/src/commands/init/{agent-skill-install.ts → skill-install.ts} +42 -31
- package/src/commands/init/templates/code-templates.ts +26 -24
- package/src/commands/init/templates/env.ts +8 -1
- package/src/commands/init/templates/quick-reference-mongo.md +1 -1
- package/src/commands/init/templates/quick-reference-postgres.md +1 -1
- package/src/commands/init/templates/readme-mongo.md +35 -0
- package/src/commands/init/templates/readme-postgres.md +34 -0
- package/src/commands/init/templates/readme.ts +62 -0
- package/src/commands/migrate.ts +4 -7
- package/src/commands/migration-check.ts +4 -4
- package/src/commands/migration-graph.ts +4 -4
- package/src/commands/migration-list.ts +4 -4
- package/src/commands/migration-log.ts +6 -5
- package/src/commands/migration-new.ts +4 -4
- package/src/commands/migration-plan.ts +4 -4
- package/src/commands/migration-show.ts +4 -4
- package/src/commands/migration-status.ts +49 -6
- package/src/commands/ref.ts +8 -8
- package/src/control-api/operations/apply-aggregate.ts +1 -0
- package/src/utils/cli-errors.ts +4 -0
- package/src/utils/command-helpers.ts +14 -6
- package/src/utils/global-flags.ts +105 -16
- package/src/utils/is-ci.ts +18 -0
- package/src/utils/telemetry.ts +141 -0
- package/src/utils/terminal-ui.ts +44 -23
- package/dist/cli-errors-CF60g2cG.mjs.map +0 -1
- package/dist/client-Brv4qlfB.mjs.map +0 -1
- package/dist/command-helpers-D3vL5yi8.mjs.map +0 -1
- package/dist/contract-emit-C3STUIBg.mjs.map +0 -1
- package/dist/contract-infer-Cnj8G1E2.mjs.map +0 -1
- package/dist/db-verify-D7cyH_zz.mjs.map +0 -1
- package/dist/errors-Cw6kyTyV.mjs +0 -56
- package/dist/errors-Cw6kyTyV.mjs.map +0 -1
- package/dist/global-flags-DGmw6Kqg.d.mts.map +0 -1
- package/dist/helpers-eqdN8tH6.mjs +0 -25
- package/dist/helpers-eqdN8tH6.mjs.map +0 -1
- package/dist/init-eh2z5Tl6.mjs.map +0 -1
- package/dist/migration-plan-CHyUlBV0.mjs.map +0 -1
- package/dist/result-handler-Bm_6dDYg.mjs +0 -25
- package/dist/result-handler-Bm_6dDYg.mjs.map +0 -1
- package/dist/terminal-ui-XtOQsqe9.mjs.map +0 -1
- /package/dist/{cli-errors-DdcjVLJV.d.mts → cli-errors-Czmx92Zy.d.mts} +0 -0
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-twds-ZHy.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { d as errorInvalidOutputFormat, g as errorRuntime, m as errorOutputFormatMutex, t as CliStructuredError } from "./cli-errors-Djtz98Vm.mjs";
|
|
3
|
+
import { a as isCI, i as formatErrorOutput, o as createColorFormatter, r as formatErrorJson, s as formatDim, t as createTerminalUI } from "./terminal-ui-BiB_8KNo.mjs";
|
|
3
4
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
5
|
+
import { notOk } from "@prisma-next/utils/result";
|
|
4
6
|
import { relative, resolve } from "pathe";
|
|
5
7
|
import { readFile } from "node:fs/promises";
|
|
6
8
|
import { hasMigrations } from "@prisma-next/framework-components/control";
|
|
@@ -415,15 +417,107 @@ function formatRootHelp(options) {
|
|
|
415
417
|
return `${lines.join("\n")}\n`;
|
|
416
418
|
}
|
|
417
419
|
//#endregion
|
|
420
|
+
//#region src/utils/result-handler.ts
|
|
421
|
+
/**
|
|
422
|
+
* Processes a CLI command result, handling both success and error cases.
|
|
423
|
+
* Formats output appropriately and returns the exit code.
|
|
424
|
+
* Never throws - returns exit code for commands to use with process.exit().
|
|
425
|
+
*
|
|
426
|
+
* Error output:
|
|
427
|
+
* - JSON mode: JSON error to stdout (piped) via ui.output(), human sees nothing on stderr.
|
|
428
|
+
* - Interactive: human-readable error to stderr.
|
|
429
|
+
*/
|
|
430
|
+
function handleResult(result, flags, ui, onSuccess) {
|
|
431
|
+
if (result.ok) {
|
|
432
|
+
if (onSuccess) onSuccess(result.value);
|
|
433
|
+
return 0;
|
|
434
|
+
}
|
|
435
|
+
const envelope = result.failure.toEnvelope();
|
|
436
|
+
if (flags.json) ui.output(formatErrorJson(envelope));
|
|
437
|
+
else ui.error(formatErrorOutput(envelope, flags));
|
|
438
|
+
return result.failure.domain === "CLI" ? 2 : 1;
|
|
439
|
+
}
|
|
440
|
+
//#endregion
|
|
418
441
|
//#region src/utils/global-flags.ts
|
|
442
|
+
function isJsonFlagSet(json) {
|
|
443
|
+
return json === true;
|
|
444
|
+
}
|
|
445
|
+
function resolveOutputFormat(options) {
|
|
446
|
+
const formatOption = options.format;
|
|
447
|
+
const jsonFlag = isJsonFlagSet(options.json);
|
|
448
|
+
if (formatOption !== void 0) {
|
|
449
|
+
if (formatOption !== "pretty" && formatOption !== "json") throw errorInvalidOutputFormat(formatOption);
|
|
450
|
+
if (jsonFlag && formatOption === "pretty") throw errorOutputFormatMutex();
|
|
451
|
+
return {
|
|
452
|
+
format: formatOption,
|
|
453
|
+
explicitFormat: true
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
if (jsonFlag) return {
|
|
457
|
+
format: "json",
|
|
458
|
+
explicitFormat: false
|
|
459
|
+
};
|
|
460
|
+
if (!process.stdout.isTTY) return {
|
|
461
|
+
format: "json",
|
|
462
|
+
explicitFormat: false
|
|
463
|
+
};
|
|
464
|
+
return {
|
|
465
|
+
format: "pretty",
|
|
466
|
+
explicitFormat: false
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
function inferJsonModeForParseError(options) {
|
|
470
|
+
if (options.format === "json") return true;
|
|
471
|
+
if (isJsonFlagSet(options.json) && options.format !== "pretty") return true;
|
|
472
|
+
if (options.format !== void 0) return false;
|
|
473
|
+
return !process.stdout.isTTY;
|
|
474
|
+
}
|
|
475
|
+
function emitGlobalFlagParseError(error, options) {
|
|
476
|
+
const jsonMode = inferJsonModeForParseError(options);
|
|
477
|
+
const flags = {
|
|
478
|
+
format: jsonMode ? "json" : "pretty",
|
|
479
|
+
explicitFormat: false,
|
|
480
|
+
...jsonMode ? { json: true } : {},
|
|
481
|
+
color: false,
|
|
482
|
+
verbose: 0,
|
|
483
|
+
interactive: false
|
|
484
|
+
};
|
|
485
|
+
const ui = createTerminalUI(flags);
|
|
486
|
+
const exitCode = handleResult(notOk(error), flags, ui);
|
|
487
|
+
process.exit(exitCode);
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Parses global flags from CLI options.
|
|
491
|
+
* Handles verbosity flags (-v, --trace), output format (--format, --json),
|
|
492
|
+
* quiet mode, color, interactivity (--interactive/--no-interactive), and
|
|
493
|
+
* auto-accept (-y/--yes).
|
|
494
|
+
*
|
|
495
|
+
* On invalid or conflicting format flags, prints a structured CLI error
|
|
496
|
+
* envelope and exits with code 2.
|
|
497
|
+
*/
|
|
498
|
+
function parseGlobalFlagsOrExit(options) {
|
|
499
|
+
try {
|
|
500
|
+
return parseGlobalFlags(options);
|
|
501
|
+
} catch (error) {
|
|
502
|
+
if (CliStructuredError.is(error)) emitGlobalFlagParseError(error, options);
|
|
503
|
+
throw error;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
419
506
|
/**
|
|
420
507
|
* Parses global flags from CLI options.
|
|
421
|
-
* Handles verbosity flags (-v, --trace),
|
|
422
|
-
* interactivity (--interactive/--no-interactive), and
|
|
508
|
+
* Handles verbosity flags (-v, --trace), output format (--format, --json),
|
|
509
|
+
* quiet mode, color, interactivity (--interactive/--no-interactive), and
|
|
510
|
+
* auto-accept (-y/--yes).
|
|
511
|
+
*
|
|
512
|
+
* Throws {@link CliStructuredError} for invalid or conflicting format flags.
|
|
423
513
|
*/
|
|
424
514
|
function parseGlobalFlags(options) {
|
|
425
|
-
const
|
|
426
|
-
|
|
515
|
+
const { format, explicitFormat } = resolveOutputFormat(options);
|
|
516
|
+
const flags = {
|
|
517
|
+
format,
|
|
518
|
+
explicitFormat
|
|
519
|
+
};
|
|
520
|
+
if (format === "json") flags.json = true;
|
|
427
521
|
if (options.quiet || options.q) flags.quiet = true;
|
|
428
522
|
if (options.trace || process.env["PRISMA_NEXT_TRACE"] === "1") flags.verbose = 2;
|
|
429
523
|
else if (options.verbose || options.v || process.env["PRISMA_NEXT_DEBUG"] === "1") flags.verbose = 1;
|
|
@@ -431,7 +525,7 @@ function parseGlobalFlags(options) {
|
|
|
431
525
|
if (process.env["NO_COLOR"] || flags.json) flags.color = false;
|
|
432
526
|
else if (options["no-color"]) flags.color = false;
|
|
433
527
|
else if (options.color !== void 0) flags.color = options.color;
|
|
434
|
-
else flags.color = process.stdout.isTTY && !
|
|
528
|
+
else flags.color = process.stdout.isTTY && !isCI();
|
|
435
529
|
if (options["no-interactive"]) flags.interactive = false;
|
|
436
530
|
else if (options.interactive !== void 0) flags.interactive = options.interactive;
|
|
437
531
|
else flags.interactive = !!process.stdout.isTTY;
|
|
@@ -508,10 +602,13 @@ function getCommandSeeAlso(command) {
|
|
|
508
602
|
}
|
|
509
603
|
/**
|
|
510
604
|
* Resolves the absolute path to contract.json from the config.
|
|
511
|
-
* Centralises the fallback logic shared by every command that reads the contract.
|
|
512
605
|
*/
|
|
513
606
|
function resolveContractPath(config) {
|
|
514
|
-
|
|
607
|
+
if (config.contract?.output === void 0) throw errorRuntime("config.contract.output is required to resolve the contract path", {
|
|
608
|
+
why: "CLI commands read the emitted contract from config.contract.output; the config has no value to read.",
|
|
609
|
+
fix: "Ensure your prisma-next.config.ts goes through `defineConfig()`, which normalises a default output when the provider supplies an input path, or set `contract.output` explicitly."
|
|
610
|
+
});
|
|
611
|
+
return resolve(config.contract.output);
|
|
515
612
|
}
|
|
516
613
|
/**
|
|
517
614
|
* Resolves the migrations directory and config path from CLI options.
|
|
@@ -662,7 +759,7 @@ function sanitizeErrorMessage(message, connectionUrl) {
|
|
|
662
759
|
}
|
|
663
760
|
/**
|
|
664
761
|
* Registers the global CLI options shared by every command:
|
|
665
|
-
* --json, -q/--quiet, -v/--verbose, --trace, --color, --no-color,
|
|
762
|
+
* --format, --json, -q/--quiet, -v/--verbose, --trace, --color, --no-color,
|
|
666
763
|
* --interactive, --no-interactive, -y/--yes.
|
|
667
764
|
*
|
|
668
765
|
* Also sets up the styled help formatter.
|
|
@@ -673,9 +770,9 @@ function addGlobalOptions(command) {
|
|
|
673
770
|
command: cmd,
|
|
674
771
|
flags: parseGlobalFlags({})
|
|
675
772
|
});
|
|
676
|
-
} }).option("--json", "Output as JSON").option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("--trace", "Trace output: deep internals, stack traces").option("--color", "Force color output").option("--no-color", "Disable color output").option("--interactive", "Force interactive mode").option("--no-interactive", "Disable interactive prompts").option("-y, --yes", "Auto-accept prompts");
|
|
773
|
+
} }).option("--format <pretty|json>", "Output format (default: pretty, or json when stdout is not a TTY)").option("--json", "Output as JSON (alias for --format json)").option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("--trace", "Trace output: deep internals, stack traces").option("--color", "Force color output").option("--no-color", "Disable color output").option("--interactive", "Force interactive mode").option("--no-interactive", "Disable interactive prompts").option("-y, --yes", "Auto-accept prompts");
|
|
677
774
|
}
|
|
678
775
|
//#endregion
|
|
679
|
-
export { parseGlobalFlags as _, loadMigrationPackages as a,
|
|
776
|
+
export { formatSuccessMessage as C, formatStyledHeader as S, parseGlobalFlags as _, loadMigrationPackages as a, formatCommandHelp as b, resolveContractPath as c, setCommandDescriptions as d, setCommandExamples as f, toStructuralEdge as g, toPathDecisionResult as h, getTargetMigrations as i, resolveMigrationPaths as l, targetSupportsMigrations as m, collectDeclaredInvariants as n, maskConnectionUrl as o, setCommandSeeAlso as p, command_helpers_exports as r, readContractEnvelope as s, addGlobalOptions as t, sanitizeErrorMessage as u, parseGlobalFlagsOrExit as v, formatRootHelp as x, handleResult as y };
|
|
680
777
|
|
|
681
|
-
//# sourceMappingURL=command-helpers-
|
|
778
|
+
//# sourceMappingURL=command-helpers-DtavI0wJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"command-helpers-DtavI0wJ.mjs","names":["LEFT_COLUMN_WIDTH","createPrismaNextBadge","formatHeaderLine","formatReadMoreLine","APP_SPACE_ID"],"sources":["../src/utils/formatters/styled.ts","../src/utils/formatters/help.ts","../src/utils/result-handler.ts","../src/utils/global-flags.ts","../src/utils/command-helpers.ts"],"sourcesContent":["import { blue, bold, cyan, green } from 'colorette';\nimport type { Command } from 'commander';\nimport stringWidth from 'string-width';\nimport stripAnsi from 'strip-ansi';\n\nimport type { GlobalFlags } from '../global-flags';\nimport { createColorFormatter, formatDim } from './helpers';\n\n// ============================================================================\n// Styled Output Formatters\n// ============================================================================\n\n/**\n * Fixed width for left column in help output.\n */\nconst LEFT_COLUMN_WIDTH = 20;\n\n/**\n * Creates an arrow segment badge with green background and white text.\n * Body: green background with white \"prisma-next\" text\n * Tip: dark grey arrow pointing right (Powerline separator)\n */\nfunction createPrismaNextBadge(useColor: boolean): string {\n if (!useColor) {\n return 'prisma-next';\n }\n return bold('prisma-next');\n}\n\n/**\n * Creates a padding function.\n */\nfunction createPadFunction(): (s: string, w: number) => string {\n return (s: string, w: number) => s + ' '.repeat(Math.max(0, w - s.length));\n}\n\n/**\n * Formats a header line: brand + operation + intent\n */\nfunction formatHeaderLine(options: {\n readonly brand: string;\n readonly operation: string;\n readonly intent: string;\n}): string {\n if (options.operation) {\n return `${options.brand} ${options.operation} → ${options.intent}`;\n }\n return `${options.brand} ${options.intent}`;\n}\n\n/**\n * Formats a \"Read more\" URL line.\n * The \"Read more\" label is in default color (not cyan), and the URL is blue.\n */\nfunction formatReadMoreLine(options: {\n readonly url: string;\n readonly maxLabelWidth: number;\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n}): string {\n const pad = createPadFunction();\n const labelPadded = pad('Read more', options.maxLabelWidth);\n // Label is default color (not cyan)\n const valueColored = options.useColor ? blue(options.url) : options.url;\n return `${options.formatDimText('│')} ${labelPadded} ${valueColored}`;\n}\n\n/**\n * Pads text to a fixed width, accounting for ANSI escape codes.\n * Uses string-width to measure the actual display width.\n */\nexport function padToFixedWidth(text: string, width: number): string {\n const actualWidth = stringWidth(text);\n const padding = Math.max(0, width - actualWidth);\n return text + ' '.repeat(padding);\n}\n\n/**\n * Renders a command tree structure.\n * Handles both single-level (subcommands of a command) and multi-level (top-level commands with subcommands) trees.\n */\nexport function renderCommandTree(options: {\n readonly commands: readonly Command[];\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n readonly hasItemsAfter: boolean;\n readonly continuationPrefix?: string;\n}): string[] {\n const { commands, useColor, formatDimText, hasItemsAfter, continuationPrefix } = options;\n const lines: string[] = [];\n\n if (commands.length === 0) {\n return lines;\n }\n\n // Format each command\n for (let i = 0; i < commands.length; i++) {\n const cmd = commands[i];\n if (!cmd) continue;\n\n const subcommands = cmd.commands.filter((subcmd) => !subcmd.name().startsWith('_'));\n const isLastCommand = i === commands.length - 1;\n\n if (subcommands.length > 0) {\n // Command with subcommands - show command name, then tree-structured subcommands\n const treeChar = isLastCommand && !hasItemsAfter ? formatDimText('└') : formatDimText('├');\n // For top-level command, pad name to fixed width (accounting for \"| |-- \" = 5 chars)\n const treePrefix = `${treeChar}─ `;\n const treePrefixWidth = stringWidth(stripAnsi(treePrefix));\n const remainingWidth = LEFT_COLUMN_WIDTH - treePrefixWidth;\n const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);\n const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;\n lines.push(`${formatDimText('│')} ${treePrefix}${commandNameColored}`);\n\n for (let j = 0; j < subcommands.length; j++) {\n const subcmd = subcommands[j];\n if (!subcmd) continue;\n\n const isLastSubcommand = j === subcommands.length - 1;\n const shortDescription = subcmd.description() || '';\n\n // Use tree characters: -- for last subcommand, |-- for others\n const treeChar = isLastSubcommand ? '└' : '├';\n const continuation =\n continuationPrefix ??\n (isLastCommand && isLastSubcommand && !hasItemsAfter ? ' ' : formatDimText('│'));\n // For subcommands, account for \"| | -- \" = 7 chars (or \"| -- \" = 6 chars if continuation is space)\n const continuationStr = continuation === ' ' ? ' ' : continuation;\n const subTreePrefix = `${continuationStr} ${formatDimText(treeChar)}─ `;\n const subTreePrefixWidth = stringWidth(stripAnsi(subTreePrefix));\n const subRemainingWidth = LEFT_COLUMN_WIDTH - subTreePrefixWidth;\n const subcommandNamePadded = padToFixedWidth(subcmd.name(), subRemainingWidth);\n const subcommandNameColored = useColor ? cyan(subcommandNamePadded) : subcommandNamePadded;\n lines.push(\n `${formatDimText('│')} ${subTreePrefix}${subcommandNameColored} ${shortDescription}`,\n );\n }\n } else {\n // Standalone command - show command name and description on same line\n const treeChar = isLastCommand && !hasItemsAfter ? formatDimText('└') : formatDimText('├');\n const treePrefix = `${treeChar}─ `;\n const treePrefixWidth = stringWidth(stripAnsi(treePrefix));\n const remainingWidth = LEFT_COLUMN_WIDTH - treePrefixWidth;\n const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);\n const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;\n const shortDescription = cmd.description() || '';\n lines.push(`${formatDimText('│')} ${treePrefix}${commandNameColored} ${shortDescription}`);\n }\n }\n\n return lines;\n}\n\n/**\n * Formats the header in the new experimental visual style.\n * This header appears at the start of command output, showing the operation,\n * intent, documentation link, and parameters.\n */\nexport function formatStyledHeader(options: {\n readonly command: string;\n readonly description: string;\n readonly url?: string;\n readonly details: ReadonlyArray<{ readonly label: string; readonly value: string }>;\n readonly flags: GlobalFlags;\n}): string {\n const lines: string[] = [];\n const useColor = options.flags.color !== false;\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n // Header: arrow + operation badge + intent\n const brand = createPrismaNextBadge(useColor);\n // Use full command path (e.g., \"contract emit\" not just \"emit\")\n const operation = useColor ? bold(options.command) : options.command;\n const intent = formatDimText(options.description);\n lines.push(formatHeaderLine({ brand, operation, intent }));\n lines.push(formatDimText('│')); // Vertical line separator between command and params\n\n // Format details using fixed left column width (same style as help text options)\n for (const detail of options.details) {\n // Add colon to label, then pad to fixed width using padToFixedWidth for ANSI-aware padding\n const labelWithColon = `${detail.label}:`;\n const labelPadded = padToFixedWidth(labelWithColon, LEFT_COLUMN_WIDTH);\n const labelColored = useColor ? cyan(labelPadded) : labelPadded;\n lines.push(`${formatDimText('│')} ${labelColored} ${detail.value}`);\n }\n\n // Add \"Read more\" URL if present (same style as help text)\n if (options.url) {\n lines.push(formatDimText('│')); // Separator line before \"Read more\"\n lines.push(\n formatReadMoreLine({\n url: options.url,\n maxLabelWidth: LEFT_COLUMN_WIDTH,\n useColor,\n formatDimText,\n }),\n );\n }\n\n lines.push(formatDimText('└'));\n\n return `${lines.join('\\n')}\\n`;\n}\n\n/**\n * Formats a success message in the styled output format.\n */\nexport function formatSuccessMessage(flags: GlobalFlags): string {\n const useColor = flags.color !== false;\n const formatGreen = createColorFormatter(useColor, green);\n return `${formatGreen('✔')} Success`;\n}\n","import { blue, bold, cyan, dim, green, magenta } from 'colorette';\nimport type { Command } from 'commander';\nimport wrapAnsi from 'wrap-ansi';\n\nimport { getCommandExamples, getCommandSeeAlso, getLongDescription } from '../command-helpers';\nimport type { GlobalFlags } from '../global-flags';\nimport { formatDim } from './helpers';\nimport { padToFixedWidth, renderCommandTree } from './styled';\n\n// ============================================================================\n// Help Output Formatters\n// ============================================================================\n\n/**\n * Fixed width for left column in help output.\n * Must match the value in styled.ts.\n */\nconst LEFT_COLUMN_WIDTH = 20;\n\n/**\n * Minimum width for right column wrapping in help output.\n */\nconst RIGHT_COLUMN_MIN_WIDTH = 40;\n\n/**\n * Maximum width for right column wrapping in help output (when terminal is wide enough).\n */\nconst RIGHT_COLUMN_MAX_WIDTH = 90;\n\n/**\n * Gets the terminal width, or returns a default if not available.\n */\nfunction getTerminalWidth(): number {\n // Help text goes to stderr, so prefer stderr columns. Fall back to stdout, then CLI_WIDTH env.\n const terminalWidth = process.stderr.columns || process.stdout.columns;\n const envWidth = Number.parseInt(process.env['CLI_WIDTH'] || '', 10);\n return terminalWidth || (Number.isFinite(envWidth) ? envWidth : 80);\n}\n\n/**\n * Calculates the available width for the right column based on terminal width.\n */\nfunction calculateRightColumnWidth(): number {\n const terminalWidth = getTerminalWidth();\n const availableWidth = terminalWidth - 2 - LEFT_COLUMN_WIDTH - 2;\n return Math.max(RIGHT_COLUMN_MIN_WIDTH, Math.min(availableWidth, RIGHT_COLUMN_MAX_WIDTH));\n}\n\n/**\n * Creates the CLI brand badge.\n */\nfunction createPrismaNextBadge(useColor: boolean): string {\n return useColor ? bold('prisma-next') : 'prisma-next';\n}\n\n/**\n * Formats a header line: brand + operation + intent\n */\nfunction formatHeaderLine(options: {\n readonly brand: string;\n readonly operation: string;\n readonly intent: string;\n}): string {\n if (options.operation) {\n return `${options.brand} ${options.operation} → ${options.intent}`;\n }\n return `${options.brand} ${options.intent}`;\n}\n\n/**\n * Wraps text to fit within a specified width using wrap-ansi.\n */\nfunction wrapTextAnsi(text: string, width: number): string[] {\n const wrapped = wrapAnsi(text, width, { hard: false, trim: true });\n return wrapped.split('\\n');\n}\n\n/**\n * Formats a default value as \"default: <value>\" with dimming.\n */\nfunction formatDefaultValue(value: unknown, useColor: boolean): string {\n const valueStr = String(value);\n const defaultText = `default: ${valueStr}`;\n return useColor ? dim(defaultText) : defaultText;\n}\n\n/**\n * Formats a \"Read more\" URL line.\n */\nfunction formatReadMoreLine(options: {\n readonly url: string;\n readonly maxLabelWidth: number;\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n}): string {\n const labelPadded = `Read more${' '.repeat(Math.max(0, options.maxLabelWidth - 'Read more'.length))}`;\n const valueColored = options.useColor ? blue(options.url) : options.url;\n return `${options.formatDimText('│')} ${labelPadded} ${valueColored}`;\n}\n\n/**\n * Formats multiline description with \"Prisma Next\" in green.\n */\nfunction formatMultilineDescription(options: {\n readonly descriptionLines: readonly string[];\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n}): string[] {\n const lines: string[] = [];\n const formatGreen = (text: string) => (options.useColor ? green(text) : text);\n\n const rightColumnWidth = calculateRightColumnWidth();\n const totalWidth = 2 + LEFT_COLUMN_WIDTH + 2 + rightColumnWidth;\n const wrapWidth = totalWidth - 2;\n\n for (const descLine of options.descriptionLines) {\n const formattedLine = descLine.replace(/Prisma Next/g, (match) => formatGreen(match));\n const wrappedLines = wrapTextAnsi(formattedLine, wrapWidth);\n for (const wrappedLine of wrappedLines) {\n lines.push(`${options.formatDimText('│')} ${wrappedLine}`);\n }\n }\n return lines;\n}\n\n/**\n * Maps command paths to their documentation URLs.\n */\nfunction getCommandDocsUrl(commandPath: string): string | undefined {\n const docsMap: Record<string, string> = {\n 'contract emit': 'https://pris.ly/contract-emit',\n 'contract infer': 'https://pris.ly/contract-infer',\n 'db schema': 'https://pris.ly/db-schema',\n 'db verify': 'https://pris.ly/db-verify',\n 'db update': 'https://pris.ly/db-update',\n 'migration plan': 'https://pris.ly/migration-plan',\n migrate: 'https://pris.ly/migrate',\n 'migration show': 'https://pris.ly/migration-show',\n 'migration status': 'https://pris.ly/migration-status',\n };\n return docsMap[commandPath];\n}\n\n/**\n * Builds the full command path from a command and its parents.\n */\nfunction buildCommandPath(command: Command): string {\n const parts: string[] = [];\n let current: Command | undefined = command;\n while (current && current.name() !== 'prisma-next') {\n parts.unshift(current.name());\n current = current.parent ?? undefined;\n }\n return parts.join(' ');\n}\n\n/**\n * Formats help output for a command using the styled format.\n */\nexport function formatCommandHelp(options: {\n readonly command: Command;\n readonly flags: GlobalFlags;\n}): string {\n const { command, flags } = options;\n const lines: string[] = [];\n const useColor = flags.color !== false;\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n // Build full command path (e.g., \"db verify\")\n const commandPath = buildCommandPath(command);\n const shortDescription = command.description() || '';\n const longDescription = getLongDescription(command);\n\n // Include positional arguments in the header line\n const argsSuffix = command.registeredArguments\n .map((arg) => (arg.required ? `<${arg.name()}>` : `[${arg.name()}]`))\n .join(' ');\n const brand = createPrismaNextBadge(useColor);\n const commandWithArgs = argsSuffix ? `${commandPath} ${argsSuffix}` : commandPath;\n const operation = useColor ? bold(commandWithArgs) : commandWithArgs;\n const intent = formatDimText(shortDescription);\n lines.push(formatHeaderLine({ brand, operation, intent }));\n lines.push(formatDimText('│'));\n\n // Extract options and format them\n const optionsList = command.options.map((opt) => {\n const description = opt.description || '';\n // Commander.js stores default value in defaultValue property\n const defaultValue = (opt as { defaultValue?: unknown }).defaultValue;\n return { flags: opt.flags, description, defaultValue };\n });\n\n // Extract subcommands if any\n const subcommands = command.commands.filter((cmd) => !cmd.name().startsWith('_'));\n\n // Format subcommands as a tree if present\n if (subcommands.length > 0) {\n const hasItemsAfter = optionsList.length > 0;\n const treeLines = renderCommandTree({\n commands: subcommands,\n useColor,\n formatDimText,\n hasItemsAfter,\n });\n lines.push(...treeLines);\n }\n\n // Add separator between subcommands and options if both exist\n if (subcommands.length > 0 && optionsList.length > 0) {\n lines.push(formatDimText('│'));\n }\n\n // Format options with fixed width, wrapping, and default values\n if (optionsList.length > 0) {\n for (const opt of optionsList) {\n // Format flag with fixed 30-char width\n const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);\n let flagsColored = flagsPadded;\n if (useColor) {\n // Color placeholders in magenta, then wrap in cyan\n flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match: string) => magenta(match));\n flagsColored = cyan(flagsColored);\n }\n\n // Wrap description based on terminal width\n const rightColumnWidth = calculateRightColumnWidth();\n const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);\n\n // First line: flag + first line of description\n lines.push(`${formatDimText('│')} ${flagsColored} ${wrappedDescription[0] || ''}`);\n\n // Continuation lines: empty label (30 spaces) + wrapped lines\n for (let i = 1; i < wrappedDescription.length; i++) {\n const emptyLabel = ' '.repeat(LEFT_COLUMN_WIDTH);\n lines.push(`${formatDimText('│')} ${emptyLabel} ${wrappedDescription[i] || ''}`);\n }\n\n // Default value line (if present)\n if (opt.defaultValue !== undefined) {\n const emptyLabel = ' '.repeat(LEFT_COLUMN_WIDTH);\n const defaultText = formatDefaultValue(opt.defaultValue, useColor);\n lines.push(`${formatDimText('│')} ${emptyLabel} ${defaultText}`);\n }\n }\n }\n\n // Add docs URL if available (with separator line before it)\n const docsUrl = getCommandDocsUrl(commandPath);\n if (docsUrl) {\n lines.push(formatDimText('│')); // Separator line between params and docs\n lines.push(\n formatReadMoreLine({\n url: docsUrl,\n maxLabelWidth: LEFT_COLUMN_WIDTH,\n useColor,\n formatDimText,\n }),\n );\n }\n\n // Examples (copy-pastable)\n const examples = getCommandExamples(command);\n if (examples && examples.length > 0) {\n lines.push(formatDimText('│'));\n lines.push(`${formatDimText('│')} ${formatDimText('Examples:')}`);\n for (const example of examples) {\n lines.push(`${formatDimText('│')} ${useColor ? dim('$') : '$'} ${example}`);\n }\n }\n\n // See also (cross-references to related commands)\n const seeAlso = getCommandSeeAlso(command);\n if (seeAlso && seeAlso.length > 0) {\n lines.push(formatDimText('│'));\n lines.push(`${formatDimText('│')} ${formatDimText('See also:')}`);\n for (const ref of seeAlso) {\n lines.push(`${formatDimText('│')} ${ref.verb} ${formatDimText(ref.oneLiner)}`);\n }\n }\n\n // Multi-line description (if present) - shown after all other content\n if (longDescription) {\n lines.push(formatDimText('│'));\n const descriptionLines = longDescription.split('\\n').filter((line) => line.trim().length > 0);\n lines.push(...formatMultilineDescription({ descriptionLines, useColor, formatDimText }));\n }\n\n lines.push(formatDimText('└'));\n\n return `${lines.join('\\n')}\\n`;\n}\n\n/**\n * Formats help output for the root program using the styled format.\n */\nexport function formatRootHelp(options: {\n readonly program: Command;\n readonly flags: GlobalFlags;\n}): string {\n const { program, flags } = options;\n const lines: string[] = [];\n const useColor = flags.color !== false;\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n // Header: \"prisma-next -> Manage your data layer\"\n const brand = createPrismaNextBadge(useColor);\n const shortDescription = 'Manage your data layer';\n const intent = formatDimText(shortDescription);\n lines.push(formatHeaderLine({ brand, operation: '', intent }));\n lines.push(formatDimText('│')); // Vertical line separator after header\n\n // Extract top-level commands (exclude hidden commands starting with '_' and the 'help' command)\n const topLevelCommands = program.commands.filter(\n (cmd) => !cmd.name().startsWith('_') && cmd.name() !== 'help',\n );\n\n // Extract global options (needed to determine if last command)\n const globalOptions = program.options.map((opt) => {\n const description = opt.description || '';\n // Commander.js stores default value in defaultValue property\n const defaultValue = (opt as { defaultValue?: unknown }).defaultValue;\n return { flags: opt.flags, description, defaultValue };\n });\n\n // Build command tree\n if (topLevelCommands.length > 0) {\n const hasItemsAfter = globalOptions.length > 0;\n const treeLines = renderCommandTree({\n commands: topLevelCommands,\n useColor,\n formatDimText,\n hasItemsAfter,\n });\n lines.push(...treeLines);\n }\n\n // Add separator between commands and options if both exist\n if (topLevelCommands.length > 0 && globalOptions.length > 0) {\n lines.push(formatDimText('│'));\n }\n\n // Format global options with fixed width, wrapping, and default values\n if (globalOptions.length > 0) {\n for (const opt of globalOptions) {\n // Format flag with fixed 30-char width\n const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);\n let flagsColored = flagsPadded;\n if (useColor) {\n // Color placeholders in magenta, then wrap in cyan\n flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match: string) => magenta(match));\n flagsColored = cyan(flagsColored);\n }\n\n // Wrap description based on terminal width\n const rightColumnWidth = calculateRightColumnWidth();\n const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);\n\n // First line: flag + first line of description\n lines.push(`${formatDimText('│')} ${flagsColored} ${wrappedDescription[0] || ''}`);\n\n // Continuation lines: empty label (30 spaces) + wrapped lines\n for (let i = 1; i < wrappedDescription.length; i++) {\n const emptyLabel = ' '.repeat(LEFT_COLUMN_WIDTH);\n lines.push(`${formatDimText('│')} ${emptyLabel} ${wrappedDescription[i] || ''}`);\n }\n\n // Default value line (if present)\n if (opt.defaultValue !== undefined) {\n const emptyLabel = ' '.repeat(LEFT_COLUMN_WIDTH);\n const defaultText = formatDefaultValue(opt.defaultValue, useColor);\n lines.push(`${formatDimText('│')} ${emptyLabel} ${defaultText}`);\n }\n }\n }\n\n // Multi-line description (white, not dimmed, with \"Prisma Next\" in green) - shown at bottom\n const formatGreen = (text: string) => (useColor ? green(text) : text);\n const descriptionLines = [\n `Use ${formatGreen('Prisma Next')} to define your data layer as a contract. Sign your database and application with the same contract to guarantee compatibility. Plan and apply migrations to safely evolve your schema.`,\n ];\n if (descriptionLines.length > 0) {\n lines.push(formatDimText('│')); // Separator line before description\n lines.push(...formatMultilineDescription({ descriptionLines, useColor, formatDimText }));\n }\n\n lines.push(formatDimText('└'));\n\n return `${lines.join('\\n')}\\n`;\n}\n","import type { Result } from '@prisma-next/utils/result';\nimport type { CliStructuredError } from './cli-errors';\nimport { formatErrorJson, formatErrorOutput } from './formatters/errors';\nimport type { GlobalFlags } from './global-flags';\nimport type { TerminalUI } from './terminal-ui';\n\n/**\n * Processes a CLI command result, handling both success and error cases.\n * Formats output appropriately and returns the exit code.\n * Never throws - returns exit code for commands to use with process.exit().\n *\n * Error output:\n * - JSON mode: JSON error to stdout (piped) via ui.output(), human sees nothing on stderr.\n * - Interactive: human-readable error to stderr.\n */\nexport function handleResult<T>(\n result: Result<T, CliStructuredError>,\n flags: GlobalFlags,\n ui: TerminalUI,\n onSuccess?: (value: T) => void,\n): number {\n if (result.ok) {\n if (onSuccess) {\n onSuccess(result.value);\n }\n return 0;\n }\n\n // Convert to CLI envelope\n const envelope = result.failure.toEnvelope();\n\n if (flags.json) {\n // JSON error → stdout only\n ui.output(formatErrorJson(envelope));\n } else {\n // Human-readable error → stderr\n ui.error(formatErrorOutput(envelope, flags));\n }\n\n // Infer exit code from error domain: CLI errors = 2, RUN errors = 1\n const exitCode = result.failure.domain === 'CLI' ? 2 : 1;\n return exitCode;\n}\n","import { notOk } from '@prisma-next/utils/result';\nimport { CliStructuredError, errorInvalidOutputFormat, errorOutputFormatMutex } from './cli-errors';\nimport { isCI } from './is-ci';\nimport { handleResult } from './result-handler';\nimport { createTerminalUI } from './terminal-ui';\n\nexport type OutputFormat = 'pretty' | 'json';\n\nexport interface GlobalFlags {\n readonly format: OutputFormat;\n readonly explicitFormat: boolean;\n readonly json?: boolean;\n readonly quiet?: boolean;\n readonly verbose?: number;\n readonly color?: boolean;\n readonly interactive?: boolean;\n readonly yes?: boolean;\n}\n\n/**\n * Common options parsed by Commander.js for every command.\n * Extend this for command-specific options instead of duplicating these fields.\n */\nexport interface CommonCommandOptions {\n readonly format?: string;\n readonly json?: string | boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly trace?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n readonly interactive?: boolean;\n readonly 'no-interactive'?: boolean;\n readonly yes?: boolean;\n readonly y?: boolean;\n}\n\nfunction isJsonFlagSet(json: string | boolean | undefined): boolean {\n return json === true;\n}\n\ninterface ResolvedOutputFormat {\n readonly format: OutputFormat;\n readonly explicitFormat: boolean;\n}\n\nfunction resolveOutputFormat(options: CommonCommandOptions): ResolvedOutputFormat {\n const formatOption = options.format;\n const jsonFlag = isJsonFlagSet(options.json);\n\n if (formatOption !== undefined) {\n if (formatOption !== 'pretty' && formatOption !== 'json') {\n throw errorInvalidOutputFormat(formatOption);\n }\n if (jsonFlag && formatOption === 'pretty') {\n throw errorOutputFormatMutex();\n }\n return { format: formatOption, explicitFormat: true };\n }\n\n if (jsonFlag) {\n return { format: 'json', explicitFormat: false };\n }\n\n if (!process.stdout.isTTY) {\n return { format: 'json', explicitFormat: false };\n }\n\n return { format: 'pretty', explicitFormat: false };\n}\n\nfunction inferJsonModeForParseError(options: CommonCommandOptions): boolean {\n if (options.format === 'json') {\n return true;\n }\n if (isJsonFlagSet(options.json) && options.format !== 'pretty') {\n return true;\n }\n if (options.format !== undefined) {\n return false;\n }\n return !process.stdout.isTTY;\n}\n\nfunction emitGlobalFlagParseError(error: CliStructuredError, options: CommonCommandOptions): never {\n const jsonMode = inferJsonModeForParseError(options);\n const flags: GlobalFlags = {\n format: jsonMode ? 'json' : 'pretty',\n explicitFormat: false,\n ...(jsonMode ? { json: true } : {}),\n color: false,\n verbose: 0,\n interactive: false,\n };\n const ui = createTerminalUI(flags);\n const exitCode = handleResult(notOk(error), flags, ui);\n process.exit(exitCode);\n}\n\n/**\n * Parses global flags from CLI options.\n * Handles verbosity flags (-v, --trace), output format (--format, --json),\n * quiet mode, color, interactivity (--interactive/--no-interactive), and\n * auto-accept (-y/--yes).\n *\n * On invalid or conflicting format flags, prints a structured CLI error\n * envelope and exits with code 2.\n */\nexport function parseGlobalFlagsOrExit(options: CommonCommandOptions): GlobalFlags {\n try {\n return parseGlobalFlags(options);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n emitGlobalFlagParseError(error, options);\n }\n throw error;\n }\n}\n\n/**\n * Parses global flags from CLI options.\n * Handles verbosity flags (-v, --trace), output format (--format, --json),\n * quiet mode, color, interactivity (--interactive/--no-interactive), and\n * auto-accept (-y/--yes).\n *\n * Throws {@link CliStructuredError} for invalid or conflicting format flags.\n */\nexport function parseGlobalFlags(options: CommonCommandOptions): GlobalFlags {\n const { format, explicitFormat } = resolveOutputFormat(options);\n const flags: {\n format: OutputFormat;\n explicitFormat: boolean;\n json?: boolean;\n quiet?: boolean;\n verbose?: number;\n color?: boolean;\n interactive?: boolean;\n yes?: boolean;\n } = { format, explicitFormat };\n\n if (format === 'json') {\n flags.json = true;\n }\n\n if (options.quiet || options.q) {\n flags.quiet = true;\n }\n\n if (options.trace || process.env['PRISMA_NEXT_TRACE'] === '1') {\n flags.verbose = 2;\n } else if (options.verbose || options.v || process.env['PRISMA_NEXT_DEBUG'] === '1') {\n flags.verbose = 1;\n } else {\n flags.verbose = 0;\n }\n\n if (process.env['NO_COLOR'] || flags.json) {\n flags.color = false;\n } else if (options['no-color']) {\n flags.color = false;\n } else if (options.color !== undefined) {\n flags.color = options.color;\n } else {\n flags.color = process.stdout.isTTY && !isCI();\n }\n\n if (options['no-interactive']) {\n flags.interactive = false;\n } else if (options.interactive !== undefined) {\n flags.interactive = options.interactive;\n } else {\n flags.interactive = !!process.stdout.isTTY;\n }\n\n if (options.yes || options.y) {\n flags.yes = true;\n }\n\n return flags as GlobalFlags;\n}\n","import { readFile } from 'node:fs/promises';\nimport type { ControlTargetDescriptor } from '@prisma-next/framework-components/control';\nimport { hasMigrations } from '@prisma-next/framework-components/control';\nimport type { NoInvariantPathStructuralEdge } from '@prisma-next/migration-tools/errors';\nimport type { MigrationEdge, MigrationGraph } from '@prisma-next/migration-tools/graph';\nimport { readMigrationsDir } from '@prisma-next/migration-tools/io';\nimport type { PathDecision } from '@prisma-next/migration-tools/migration-graph';\nimport { reconstructGraph } from '@prisma-next/migration-tools/migration-graph';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport { APP_SPACE_ID, spaceMigrationDirectory } from '@prisma-next/migration-tools/spaces';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Command } from 'commander';\nimport { relative, resolve } from 'pathe';\nimport { errorRuntime } from './cli-errors';\nimport { formatCommandHelp } from './formatters/help';\nimport type { CommonCommandOptions } from './global-flags';\nimport { parseGlobalFlags } from './global-flags';\n\nconst longDescriptions = new WeakMap<Command, string>();\nconst commandExamples = new WeakMap<Command, readonly string[]>();\nconst commandSeeAlso = new WeakMap<\n Command,\n readonly { readonly verb: string; readonly oneLiner: string }[]\n>();\n\n/**\n * Sets both short and long descriptions for a command.\n * The short description is used in command trees and headers.\n * The long description is shown at the bottom of help output.\n */\nexport function setCommandDescriptions(\n command: Command,\n shortDescription: string,\n longDescription?: string,\n): Command {\n command.description(shortDescription);\n if (longDescription) {\n longDescriptions.set(command, longDescription);\n }\n return command;\n}\n\n/**\n * Sets copy-pastable examples for a command, shown in help text.\n */\nexport function setCommandExamples(command: Command, examples: readonly string[]): Command {\n commandExamples.set(command, examples);\n return command;\n}\n\n/**\n * Gets the long description from a command if it was set via setCommandDescriptions.\n */\nexport function getLongDescription(command: Command): string | undefined {\n return longDescriptions.get(command);\n}\n\n/**\n * Gets examples from a command if set via setCommandExamples.\n */\nexport function getCommandExamples(command: Command): readonly string[] | undefined {\n return commandExamples.get(command);\n}\n\n/**\n * Sets cross-references to related commands, rendered in a \"See also\"\n * section below the Examples block in help output.\n */\nexport function setCommandSeeAlso(\n command: Command,\n refs: readonly { readonly verb: string; readonly oneLiner: string }[],\n): Command {\n commandSeeAlso.set(command, refs);\n return command;\n}\n\n/**\n * Gets the see-also cross-references from a command.\n */\nexport function getCommandSeeAlso(\n command: Command,\n): readonly { readonly verb: string; readonly oneLiner: string }[] | undefined {\n return commandSeeAlso.get(command);\n}\n\n/**\n * Shared CLI options interface for migration commands (db init, db update).\n * These are the Commander.js parsed options common to both commands.\n */\nexport interface MigrationCommandOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly dryRun?: boolean;\n}\n\n/**\n * Resolves the absolute path to contract.json from the config.\n */\nexport function resolveContractPath(config: { contract?: { output?: string } }): string {\n if (config.contract?.output === undefined) {\n throw errorRuntime('config.contract.output is required to resolve the contract path', {\n why: 'CLI commands read the emitted contract from config.contract.output; the config has no value to read.',\n fix: 'Ensure your prisma-next.config.ts goes through `defineConfig()`, which normalises a default output when the provider supplies an input path, or set `contract.output` explicitly.',\n });\n }\n return resolve(config.contract.output);\n}\n\n/**\n * Resolves the migrations directory and config path from CLI options.\n * Shared by migrate, migration-plan, and migration-status.\n *\n * - `migrationsDir` is the project's top-level `migrations/` directory\n * (the root that the aggregate loader walks for every contract space).\n * - `appMigrationsDir` is the app subspace directory under it\n * (`<migrationsDir>/<APP_SPACE_ID>/`). Every per-app reader / writer\n * (`migration new`, `migration plan`, `migrate`,\n * `migration status`, `migration show`, `migration ref`) operates on\n * this directory. Extensions own their own `migrations/<spaceId>/`.\n * - `refsDir` is the app's refs directory (`<appMigrationsDir>/refs/`).\n * The framework does not maintain refs at the migrations root.\n */\nexport function resolveMigrationPaths(\n configOption: string | undefined,\n config: { migrations?: { dir?: string } },\n): {\n configPath: string;\n migrationsDir: string;\n migrationsRelative: string;\n appMigrationsDir: string;\n appMigrationsRelative: string;\n refsDir: string;\n} {\n const configPath = configOption\n ? relative(process.cwd(), resolve(configOption))\n : 'prisma-next.config.ts';\n const migrationsDir = resolve(\n configOption ? resolve(configOption, '..') : process.cwd(),\n config.migrations?.dir ?? 'migrations',\n );\n const migrationsRelative = relative(process.cwd(), migrationsDir);\n const appMigrationsDir = spaceMigrationDirectory(migrationsDir, APP_SPACE_ID);\n const appMigrationsRelative = relative(process.cwd(), appMigrationsDir);\n const refsDir = resolve(appMigrationsDir, 'refs');\n return {\n configPath,\n migrationsDir,\n migrationsRelative,\n appMigrationsDir,\n appMigrationsRelative,\n refsDir,\n };\n}\n\n/**\n * Slim representation of a PathDecision for CLI JSON output.\n * Strips internal fields (createdAt, labels) from path entries.\n */\nexport interface PathDecisionResult {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly requiredInvariants: readonly string[];\n readonly satisfiedInvariants: readonly string[];\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationHash: string;\n readonly from: string;\n readonly to: string;\n readonly invariants: readonly string[];\n }[];\n}\n\nexport function collectDeclaredInvariants(graph: MigrationGraph): ReadonlySet<string> {\n const declared = new Set<string>();\n for (const edges of graph.forwardChain.values()) {\n for (const edge of edges) {\n for (const inv of edge.invariants) {\n declared.add(inv);\n }\n }\n }\n return declared;\n}\n\n/**\n * Maps a `MigrationEdge` to the structural-edge shape used in the\n * `MIGRATION.NO_INVARIANT_PATH` error envelope. Shared between\n * `migrate` and `migration status` so both commands surface\n * the same JSON wire shape when an invariant-aware route is unsatisfiable.\n */\nexport function toStructuralEdge(edge: MigrationEdge): NoInvariantPathStructuralEdge {\n return {\n dirName: edge.dirName,\n migrationHash: edge.migrationHash,\n from: edge.from,\n to: edge.to,\n invariants: edge.invariants,\n };\n}\n\n/**\n * Maps a PathDecision to the slim CLI output representation.\n */\nexport function toPathDecisionResult(decision: PathDecision): PathDecisionResult {\n return {\n fromHash: decision.fromHash,\n toHash: decision.toHash,\n alternativeCount: decision.alternativeCount,\n tieBreakReasons: decision.tieBreakReasons,\n requiredInvariants: decision.requiredInvariants ?? [],\n satisfiedInvariants: decision.satisfiedInvariants ?? [],\n ...ifDefined('refName', decision.refName),\n selectedPath: decision.selectedPath.map((entry) => ({\n dirName: entry.dirName,\n migrationHash: entry.migrationHash,\n from: entry.from,\n to: entry.to,\n invariants: entry.invariants,\n })),\n };\n}\n\nexport function targetSupportsMigrations(target: ControlTargetDescriptor<string, string>): boolean {\n return hasMigrations(target);\n}\n\nexport function getTargetMigrations(target: ControlTargetDescriptor<string, string>) {\n return hasMigrations(target) ? target.migrations : undefined;\n}\n\n/**\n * Reads the migrations directory and builds the migration graph from all\n * packages. Throws on I/O or graph errors — callers handle error mapping.\n *\n * Every on-disk package is content-addressed (`migrationHash` is always a\n * string); there is no draft state to filter out.\n */\nexport async function loadMigrationPackages(migrationsDir: string): Promise<{\n bundles: readonly OnDiskMigrationPackage[];\n graph: MigrationGraph;\n}> {\n const bundles = await readMigrationsDir(migrationsDir);\n const graph = reconstructGraph(bundles);\n return { bundles, graph };\n}\n\n/**\n * The subset of the emitted contract.json that the framework layer can\n * safely type. The emitter adds these fields on top of the family-specific\n * storage/models/relations. Other fields exist in the JSON but are opaque\n * at this layer — the index signature preserves them for downstream\n * consumers that operate at the family level (e.g., the control client).\n */\nexport interface ContractEnvelope {\n readonly storageHash: string;\n readonly schemaVersion: string;\n readonly target: string;\n readonly targetFamily: string;\n readonly profileHash?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Reads and parses contract.json, validating the framework-level envelope\n * fields (storageHash, schemaVersion, target, targetFamily).\n *\n * Family-specific validation (storage structure, codec mappings, etc.)\n * happens downstream in the control client via the family instance.\n */\nexport async function readContractEnvelope(config: {\n contract?: { output?: string };\n}): Promise<ContractEnvelope> {\n const contractPath = resolveContractPath(config);\n const content = await readFile(contractPath, 'utf-8');\n const json = JSON.parse(content) as Record<string, unknown>;\n\n const { schemaVersion, target, targetFamily, profileHash } = json;\n const storage = json['storage'] as Record<string, unknown> | undefined;\n const storageHash = storage?.['storageHash'];\n\n if (typeof storageHash !== 'string') {\n throw new Error(\n `Contract at ${relative(process.cwd(), contractPath)} is missing a valid storage.storageHash. Run \\`prisma-next contract emit\\` to regenerate.`,\n );\n }\n if (typeof schemaVersion !== 'string') {\n throw new Error(\n `Contract at ${relative(process.cwd(), contractPath)} is missing schemaVersion.`,\n );\n }\n if (typeof target !== 'string') {\n throw new Error(`Contract at ${relative(process.cwd(), contractPath)} is missing target.`);\n }\n if (typeof targetFamily !== 'string') {\n throw new Error(\n `Contract at ${relative(process.cwd(), contractPath)} is missing targetFamily.`,\n );\n }\n\n return {\n ...json,\n storageHash,\n schemaVersion,\n target,\n targetFamily,\n ...(typeof profileHash === 'string' ? { profileHash } : {}),\n };\n}\n\n/**\n * Masks credentials in a database connection URL.\n * Handles standard URLs (username + password + query params) and libpq-style key=value strings.\n */\nexport function maskConnectionUrl(url: string): string {\n try {\n const parsed = new URL(url);\n if (parsed.username) {\n parsed.username = '****';\n }\n if (parsed.password) {\n parsed.password = '****';\n }\n // Also mask password in query parameters (e.g., ?password=secret, ?sslpassword=secret)\n for (const key of [...parsed.searchParams.keys()]) {\n if (/password/i.test(key)) {\n parsed.searchParams.set(key, '****');\n }\n }\n return parsed.toString();\n } catch {\n // Fallback for libpq-style key=value connection strings (e.g., \"host=localhost password=secret user=admin\")\n return url\n .replace(/password\\s*=\\s*\\S+/gi, 'password=****')\n .replace(/user\\s*=\\s*\\S+/gi, 'user=****');\n }\n}\n\n/**\n * Strips raw connection URL fragments from an error message to prevent credential leakage.\n * Call this before surfacing driver errors to the user.\n */\nexport function sanitizeErrorMessage(message: string, connectionUrl?: string): string {\n if (!connectionUrl) {\n return message;\n }\n try {\n const parsed = new URL(connectionUrl);\n // Replace the full URL (with and without trailing slash)\n let sanitized = message;\n sanitized = sanitized.replaceAll(connectionUrl, maskConnectionUrl(connectionUrl));\n // Also replace the password and username individually if they appear\n if (parsed.password) {\n sanitized = sanitized.replaceAll(parsed.password, '****');\n }\n if (parsed.username) {\n sanitized = sanitized.replaceAll(parsed.username, '****');\n }\n return sanitized;\n } catch {\n // For libpq-style strings, mask password and user values in the message\n return message\n .replace(/password\\s*=\\s*\\S+/gi, 'password=****')\n .replace(/user\\s*=\\s*\\S+/gi, 'user=****');\n }\n}\n\n/**\n * Registers the global CLI options shared by every command:\n * --format, --json, -q/--quiet, -v/--verbose, --trace, --color, --no-color,\n * --interactive, --no-interactive, -y/--yes.\n *\n * Also sets up the styled help formatter.\n */\nexport function addGlobalOptions(command: Command): Command {\n return command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option(\n '--format <pretty|json>',\n 'Output format (default: pretty, or json when stdout is not a TTY)',\n )\n .option('--json', 'Output as JSON (alias for --format json)')\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('--trace', 'Trace output: deep internals, stack traces')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .option('--interactive', 'Force interactive mode')\n .option('--no-interactive', 'Disable interactive prompts')\n .option('-y, --yes', 'Auto-accept prompts');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAeA,MAAMA,sBAAoB;;;;;;AAO1B,SAASC,wBAAsB,UAA2B;CACxD,IAAI,CAAC,UACH,OAAO;CAET,OAAO,KAAK,cAAc;;;;;AAM5B,SAAS,oBAAsD;CAC7D,QAAQ,GAAW,MAAc,IAAI,IAAI,OAAO,KAAK,IAAI,GAAG,IAAI,EAAE,OAAO,CAAC;;;;;AAM5E,SAASC,mBAAiB,SAIf;CACT,IAAI,QAAQ,WACV,OAAO,GAAG,QAAQ,MAAM,GAAG,QAAQ,UAAU,KAAK,QAAQ;CAE5D,OAAO,GAAG,QAAQ,MAAM,GAAG,QAAQ;;;;;;AAOrC,SAASC,qBAAmB,SAKjB;CAET,MAAM,cADM,mBACW,CAAC,aAAa,QAAQ,cAAc;CAE3D,MAAM,eAAe,QAAQ,WAAW,KAAK,QAAQ,IAAI,GAAG,QAAQ;CACpE,OAAO,GAAG,QAAQ,cAAc,IAAI,CAAC,GAAG,YAAY,IAAI;;;;;;AAO1D,SAAgB,gBAAgB,MAAc,OAAuB;CACnE,MAAM,cAAc,YAAY,KAAK;CACrC,MAAM,UAAU,KAAK,IAAI,GAAG,QAAQ,YAAY;CAChD,OAAO,OAAO,IAAI,OAAO,QAAQ;;;;;;AAOnC,SAAgB,kBAAkB,SAMrB;CACX,MAAM,EAAE,UAAU,UAAU,eAAe,eAAe,uBAAuB;CACjF,MAAM,QAAkB,EAAE;CAE1B,IAAI,SAAS,WAAW,GACtB,OAAO;CAIT,KAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;EACxC,MAAM,MAAM,SAAS;EACrB,IAAI,CAAC,KAAK;EAEV,MAAM,cAAc,IAAI,SAAS,QAAQ,WAAW,CAAC,OAAO,MAAM,CAAC,WAAW,IAAI,CAAC;EACnF,MAAM,gBAAgB,MAAM,SAAS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I;EACF,MAAM,SAAS,IAAI,IAAI,cAAc;EAErC,IAAI,YAAY;EAChB,YAAY,UAAU,WAAW,eAAe,kBAAkB,cAAc,CAAC;EAEjF,IAAI,OAAO,UACT,YAAY,UAAU,WAAW,OAAO,UAAU,OAAO;EAE3D,IAAI,OAAO,UACT,YAAY,UAAU,WAAW,OAAO,UAAU,OAAO;EAE3D,OAAO;SACD;EAEN,OAAO,QACJ,QAAQ,wBAAwB,gBAAgB,CAChD,QAAQ,oBAAoB,YAAY;;;;;;;;;;AAW/C,SAAgB,iBAAiB,SAA2B;CAC1D,OAAO,QACJ,cAAc,EACb,aAAa,QAAQ;EAEnB,OAAO,kBAAkB;GAAE,SAAS;GAAK,OAD3B,iBAAiB,EAAE,CACa;GAAE,CAAC;IAEpD,CAAC,CACD,OACC,0BACA,oEACD,CACA,OAAO,UAAU,2CAA2C,CAC5D,OAAO,eAAe,0BAA0B,CAChD,OAAO,iBAAiB,sCAAsC,CAC9D,OAAO,WAAW,6CAA6C,CAC/D,OAAO,WAAW,qBAAqB,CACvC,OAAO,cAAc,uBAAuB,CAC5C,OAAO,iBAAiB,yBAAyB,CACjD,OAAO,oBAAoB,8BAA8B,CACzD,OAAO,aAAa,sBAAsB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createContractEmitCommand } from "../contract-emit-
|
|
1
|
+
import { t as createContractEmitCommand } from "../contract-emit-uwT-Mj8-.mjs";
|
|
2
2
|
export { createContractEmitCommand };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createContractInferCommand } from "../contract-infer-
|
|
1
|
+
import { t as createContractInferCommand } from "../contract-infer-pKkiCt7C.mjs";
|
|
2
2
|
export { createContractInferCommand };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db-init.d.mts","names":[],"sources":["../../src/commands/db-init.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"db-init.d.mts","names":[],"sources":["../../src/commands/db-init.ts"],"mappings":";;;iBAuNgB,mBAAA,CAAA,GAAuB,OAAA"}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { n as prepareMigrationContext, t as addMigrationCommandOptions } from "../migration-command-scaffold-CmXXC1UZ.mjs";
|
|
1
|
+
import { a as errorContractValidationFailed, g as errorRuntime, h as errorRunnerFailed, p as errorMigrationPlanningFailed, t as CliStructuredError, y as errorUnexpected } from "../cli-errors-Djtz98Vm.mjs";
|
|
2
|
+
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
3
|
+
import { d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, u as sanitizeErrorMessage, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-DtavI0wJ.mjs";
|
|
4
|
+
import { a as ContractValidationError } from "../client-oXO2WCPD.mjs";
|
|
5
|
+
import { i as formatMigrationPlanOutput, n as formatMigrationApplyOutput, r as formatMigrationJson } from "../migrations-CwZMa1Ck.mjs";
|
|
6
|
+
import { n as prepareMigrationContext, t as addMigrationCommandOptions } from "../migration-command-scaffold-BtkunvFQ.mjs";
|
|
8
7
|
import { Command } from "commander";
|
|
9
8
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
10
9
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
@@ -30,14 +29,17 @@ function mapDbInitFailure(failure) {
|
|
|
30
29
|
}
|
|
31
30
|
});
|
|
32
31
|
}
|
|
33
|
-
if (failure.code === "RUNNER_FAILED")
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
...failure.meta
|
|
39
|
-
|
|
40
|
-
|
|
32
|
+
if (failure.code === "RUNNER_FAILED") {
|
|
33
|
+
const fix = (typeof failure.meta?.["runnerErrorCode"] === "string" ? failure.meta["runnerErrorCode"] : void 0) === "LEGACY_MARKER_SHAPE" ? "Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `prisma-next db init` to recreate it with the current per-space schema." : "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`";
|
|
34
|
+
return errorRunnerFailed(failure.summary, {
|
|
35
|
+
why: failure.why ?? "Migration runner failed",
|
|
36
|
+
fix,
|
|
37
|
+
...failure.meta ? { meta: {
|
|
38
|
+
code: "RUNNER_FAILED",
|
|
39
|
+
...failure.meta
|
|
40
|
+
} } : { meta: { code: "RUNNER_FAILED" } }
|
|
41
|
+
});
|
|
42
|
+
}
|
|
41
43
|
const exhaustive = failure.code;
|
|
42
44
|
throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);
|
|
43
45
|
}
|
|
@@ -105,12 +107,9 @@ function createDbInitCommand() {
|
|
|
105
107
|
setCommandExamples(command, ["prisma-next db init --db $DATABASE_URL", "prisma-next db init --db $DATABASE_URL --dry-run"]);
|
|
106
108
|
addMigrationCommandOptions(command);
|
|
107
109
|
command.action(async (options) => {
|
|
108
|
-
const flags =
|
|
110
|
+
const flags = parseGlobalFlagsOrExit(options);
|
|
109
111
|
const startTime = Date.now();
|
|
110
|
-
const ui =
|
|
111
|
-
color: flags.color,
|
|
112
|
-
interactive: flags.interactive
|
|
113
|
-
});
|
|
112
|
+
const ui = createTerminalUI(flags);
|
|
114
113
|
const exitCode = handleResult(await executeDbInitCommand(options, flags, ui, startTime), flags, ui, (dbInitResult) => {
|
|
115
114
|
if (flags.json) ui.output(formatMigrationJson(dbInitResult));
|
|
116
115
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db-init.mjs","names":[],"sources":["../../src/commands/db-init.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { ContractValidationError } from '../control-api/errors';\nimport type { DbInitFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorMigrationPlanningFailed,\n errorRunnerFailed,\n errorRuntime,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport type { MigrationCommandOptions } from '../utils/command-helpers';\nimport {\n resolveMigrationPaths,\n sanitizeErrorMessage,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n formatMigrationApplyOutput,\n formatMigrationJson,\n formatMigrationPlanOutput,\n type MigrationCommandResult,\n} from '../utils/formatters/migrations';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n addMigrationCommandOptions,\n prepareMigrationContext,\n} from '../utils/migration-command-scaffold';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ntype DbInitOptions = MigrationCommandOptions;\n\n/**\n * Maps a DbInitFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapDbInitFailure(failure: DbInitFailure): CliStructuredError {\n if (failure.code === 'PLANNING_FAILED') {\n return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });\n }\n\n if (failure.code === 'MARKER_ORIGIN_MISMATCH') {\n const mismatchParts: string[] = [];\n if (\n failure.marker?.storageHash !== failure.destination?.storageHash &&\n failure.marker?.storageHash &&\n failure.destination?.storageHash\n ) {\n mismatchParts.push(\n `storageHash (marker: ${failure.marker.storageHash}, destination: ${failure.destination.storageHash})`,\n );\n }\n if (\n failure.marker?.profileHash !== failure.destination?.profileHash &&\n failure.marker?.profileHash &&\n failure.destination?.profileHash\n ) {\n mismatchParts.push(\n `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,\n );\n }\n\n return errorRuntime(\n `Existing database signature does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,\n {\n why: 'Database has an existing signature (marker) that does not match the target contract',\n fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',\n meta: {\n code: 'MARKER_ORIGIN_MISMATCH',\n ...ifDefined('markerStorageHash', failure.marker?.storageHash),\n ...ifDefined('destinationStorageHash', failure.destination?.storageHash),\n ...ifDefined('markerProfileHash', failure.marker?.profileHash),\n ...ifDefined('destinationProfileHash', failure.destination?.profileHash),\n },\n },\n );\n }\n\n if (failure.code === 'RUNNER_FAILED') {\n return errorRunnerFailed(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix: 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`',\n ...(failure.meta\n ? { meta: { code: 'RUNNER_FAILED', ...failure.meta } }\n : { meta: { code: 'RUNNER_FAILED' } }),\n });\n }\n\n // Exhaustive check - TypeScript will error if a new code is added but not handled\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the db init command and returns a structured Result.\n */\nasync function executeDbInitCommand(\n options: DbInitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationCommandResult, CliStructuredError>> {\n // Prepare shared migration context (config, contract, connection, client)\n const ctxResult = await prepareMigrationContext(options, flags, ui, {\n commandName: 'db init',\n description: 'Bootstrap a database to match the current contract',\n url: 'https://pris.ly/db-init',\n });\n if (!ctxResult.ok) {\n return ctxResult;\n }\n const { client, config, contractJson, dbConnection, onProgress, contractPathAbsolute } =\n ctxResult.value;\n\n // The aggregate loader (loader → planner → runner pipeline) catches\n // layout / drift / disjointness violations on its own; the legacy\n // per-space precheck + marker-check helpers are no longer needed at\n // this surface. Marker-vs-on-disk drift surfaces through the planner's\n // graph-walk strategy.\n const { migrationsDir } = resolveMigrationPaths(options.config, config);\n\n try {\n await client.connect(dbConnection);\n\n const result = await client.dbInit({\n contract: contractJson,\n mode: options.dryRun ? 'plan' : 'apply',\n migrationsDir,\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapDbInitFailure(result.failure));\n }\n\n // Convert success result to CLI output format\n const dbInitResult: MigrationCommandResult = {\n ok: true,\n mode: result.value.mode,\n plan: {\n targetId: ctxResult.value.config.target.targetId,\n destination: {\n storageHash: result.value.destination.storageHash,\n ...ifDefined('profileHash', result.value.destination.profileHash),\n },\n operations: result.value.plan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n ...ifDefined('preview', result.value.plan.preview),\n },\n ...(result.value.execution\n ? {\n execution: {\n operationsPlanned: result.value.execution.operationsPlanned,\n operationsExecuted: result.value.execution.operationsExecuted,\n },\n }\n : {}),\n ...(result.value.marker\n ? {\n marker: {\n storageHash: result.value.marker.storageHash,\n ...ifDefined('profileHash', result.value.marker.profileHash),\n },\n }\n : {}),\n ...ifDefined('perSpace', result.value.perSpace),\n summary: result.value.summary,\n timings: { total: Date.now() - startTime },\n };\n\n return ok(dbInitResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n\n const rawMessage = error instanceof Error ? error.message : String(error);\n const safeMessage = sanitizeErrorMessage(\n rawMessage,\n typeof dbConnection === 'string' ? dbConnection : undefined,\n );\n return notOk(\n errorUnexpected(safeMessage, {\n why: `Unexpected error during db init: ${safeMessage}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Bootstrap a database to match the current contract and sign it',\n 'Initializes a database to match your emitted contract using additive-only operations.\\n' +\n 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\\n' +\n 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\\n' +\n 'would be required, and signs the database to track contract state. Use --dry-run to\\n' +\n 'preview changes without applying.',\n );\n setCommandExamples(command, [\n 'prisma-next db init --db $DATABASE_URL',\n 'prisma-next db init --db $DATABASE_URL --dry-run',\n ]);\n addMigrationCommandOptions(command);\n command.action(async (options: DbInitOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n const result = await executeDbInitCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (dbInitResult) => {\n if (flags.json) {\n ui.output(formatMigrationJson(dbInitResult));\n } else {\n const output =\n dbInitResult.mode === 'plan'\n ? formatMigrationPlanOutput(dbInitResult, flags)\n : formatMigrationApplyOutput(dbInitResult, flags);\n if (output) {\n ui.log(output);\n }\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;AAuCA,SAAS,iBAAiB,SAA4C;CACpE,IAAI,QAAQ,SAAS,mBACnB,OAAO,6BAA6B,EAAE,WAAW,QAAQ,aAAa,EAAE,EAAE,CAAC;CAG7E,IAAI,QAAQ,SAAS,0BAA0B;EAC7C,MAAM,gBAA0B,EAAE;EAClC,IACE,QAAQ,QAAQ,gBAAgB,QAAQ,aAAa,eACrD,QAAQ,QAAQ,eAChB,QAAQ,aAAa,aAErB,cAAc,KACZ,wBAAwB,QAAQ,OAAO,YAAY,iBAAiB,QAAQ,YAAY,YAAY,GACrG;EAEH,IACE,QAAQ,QAAQ,gBAAgB,QAAQ,aAAa,eACrD,QAAQ,QAAQ,eAChB,QAAQ,aAAa,aAErB,cAAc,KACZ,wBAAwB,QAAQ,OAAO,YAAY,iBAAiB,QAAQ,YAAY,YAAY,GACrG;EAGH,OAAO,aACL,+DAA+D,cAAc,SAAS,IAAI,gBAAgB,cAAc,KAAK,QAAQ,CAAC,KAAK,MAC3I;GACE,KAAK;GACL,KAAK;GACL,MAAM;IACJ,MAAM;IACN,GAAG,UAAU,qBAAqB,QAAQ,QAAQ,YAAY;IAC9D,GAAG,UAAU,0BAA0B,QAAQ,aAAa,YAAY;IACxE,GAAG,UAAU,qBAAqB,QAAQ,QAAQ,YAAY;IAC9D,GAAG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,GAAG,OAAO,oBAAoB,aAAa,CAAC;QACvC;IACL,MAAM,SACJ,aAAa,SAAS,SAClB,0BAA0B,cAAc,MAAM,GAC9C,2BAA2B,cAAc,MAAM;IACrD,IAAI,QACF,GAAG,IAAI,OAAO;;IAGlB;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEF,OAAO"}
|
|
1
|
+
{"version":3,"file":"db-init.mjs","names":[],"sources":["../../src/commands/db-init.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { ContractValidationError } from '../control-api/errors';\nimport type { DbInitFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorMigrationPlanningFailed,\n errorRunnerFailed,\n errorRuntime,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport type { MigrationCommandOptions } from '../utils/command-helpers';\nimport {\n resolveMigrationPaths,\n sanitizeErrorMessage,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n formatMigrationApplyOutput,\n formatMigrationJson,\n formatMigrationPlanOutput,\n type MigrationCommandResult,\n} from '../utils/formatters/migrations';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport {\n addMigrationCommandOptions,\n prepareMigrationContext,\n} from '../utils/migration-command-scaffold';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ntype DbInitOptions = MigrationCommandOptions;\n\n/**\n * Maps a DbInitFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapDbInitFailure(failure: DbInitFailure): CliStructuredError {\n if (failure.code === 'PLANNING_FAILED') {\n return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });\n }\n\n if (failure.code === 'MARKER_ORIGIN_MISMATCH') {\n const mismatchParts: string[] = [];\n if (\n failure.marker?.storageHash !== failure.destination?.storageHash &&\n failure.marker?.storageHash &&\n failure.destination?.storageHash\n ) {\n mismatchParts.push(\n `storageHash (marker: ${failure.marker.storageHash}, destination: ${failure.destination.storageHash})`,\n );\n }\n if (\n failure.marker?.profileHash !== failure.destination?.profileHash &&\n failure.marker?.profileHash &&\n failure.destination?.profileHash\n ) {\n mismatchParts.push(\n `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,\n );\n }\n\n return errorRuntime(\n `Existing database signature does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,\n {\n why: 'Database has an existing signature (marker) that does not match the target contract',\n fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',\n meta: {\n code: 'MARKER_ORIGIN_MISMATCH',\n ...ifDefined('markerStorageHash', failure.marker?.storageHash),\n ...ifDefined('destinationStorageHash', failure.destination?.storageHash),\n ...ifDefined('markerProfileHash', failure.marker?.profileHash),\n ...ifDefined('destinationProfileHash', failure.destination?.profileHash),\n },\n },\n );\n }\n\n if (failure.code === 'RUNNER_FAILED') {\n const runnerCode =\n typeof failure.meta?.['runnerErrorCode'] === 'string'\n ? failure.meta['runnerErrorCode']\n : undefined;\n const fix =\n runnerCode === 'LEGACY_MARKER_SHAPE'\n ? 'Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `prisma-next db init` to recreate it with the current per-space schema.'\n : 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`';\n return errorRunnerFailed(failure.summary, {\n why: failure.why ?? 'Migration runner failed',\n fix,\n ...(failure.meta\n ? { meta: { code: 'RUNNER_FAILED', ...failure.meta } }\n : { meta: { code: 'RUNNER_FAILED' } }),\n });\n }\n\n // Exhaustive check - TypeScript will error if a new code is added but not handled\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the db init command and returns a structured Result.\n */\nasync function executeDbInitCommand(\n options: DbInitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationCommandResult, CliStructuredError>> {\n // Prepare shared migration context (config, contract, connection, client)\n const ctxResult = await prepareMigrationContext(options, flags, ui, {\n commandName: 'db init',\n description: 'Bootstrap a database to match the current contract',\n url: 'https://pris.ly/db-init',\n });\n if (!ctxResult.ok) {\n return ctxResult;\n }\n const { client, config, contractJson, dbConnection, onProgress, contractPathAbsolute } =\n ctxResult.value;\n\n // The aggregate loader (loader → planner → runner pipeline) catches\n // layout / drift / disjointness violations on its own; the legacy\n // per-space precheck + marker-check helpers are no longer needed at\n // this surface. Marker-vs-on-disk drift surfaces through the planner's\n // graph-walk strategy.\n const { migrationsDir } = resolveMigrationPaths(options.config, config);\n\n try {\n await client.connect(dbConnection);\n\n const result = await client.dbInit({\n contract: contractJson,\n mode: options.dryRun ? 'plan' : 'apply',\n migrationsDir,\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapDbInitFailure(result.failure));\n }\n\n // Convert success result to CLI output format\n const dbInitResult: MigrationCommandResult = {\n ok: true,\n mode: result.value.mode,\n plan: {\n targetId: ctxResult.value.config.target.targetId,\n destination: {\n storageHash: result.value.destination.storageHash,\n ...ifDefined('profileHash', result.value.destination.profileHash),\n },\n operations: result.value.plan.operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n ...ifDefined('preview', result.value.plan.preview),\n },\n ...(result.value.execution\n ? {\n execution: {\n operationsPlanned: result.value.execution.operationsPlanned,\n operationsExecuted: result.value.execution.operationsExecuted,\n },\n }\n : {}),\n ...(result.value.marker\n ? {\n marker: {\n storageHash: result.value.marker.storageHash,\n ...ifDefined('profileHash', result.value.marker.profileHash),\n },\n }\n : {}),\n ...ifDefined('perSpace', result.value.perSpace),\n summary: result.value.summary,\n timings: { total: Date.now() - startTime },\n };\n\n return ok(dbInitResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n if (error instanceof ContractValidationError) {\n return notOk(\n errorContractValidationFailed(`Contract validation failed: ${error.message}`, {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n\n const rawMessage = error instanceof Error ? error.message : String(error);\n const safeMessage = sanitizeErrorMessage(\n rawMessage,\n typeof dbConnection === 'string' ? dbConnection : undefined,\n );\n return notOk(\n errorUnexpected(safeMessage, {\n why: `Unexpected error during db init: ${safeMessage}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbInitCommand(): Command {\n const command = new Command('init');\n setCommandDescriptions(\n command,\n 'Bootstrap a database to match the current contract and sign it',\n 'Initializes a database to match your emitted contract using additive-only operations.\\n' +\n 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\\n' +\n 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\\n' +\n 'would be required, and signs the database to track contract state. Use --dry-run to\\n' +\n 'preview changes without applying.',\n );\n setCommandExamples(command, [\n 'prisma-next db init --db $DATABASE_URL',\n 'prisma-next db init --db $DATABASE_URL --dry-run',\n ]);\n addMigrationCommandOptions(command);\n command.action(async (options: DbInitOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const startTime = Date.now();\n\n const ui = createTerminalUI(flags);\n\n const result = await executeDbInitCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (dbInitResult) => {\n if (flags.json) {\n ui.output(formatMigrationJson(dbInitResult));\n } else {\n const output =\n dbInitResult.mode === 'plan'\n ? formatMigrationPlanOutput(dbInitResult, flags)\n : formatMigrationApplyOutput(dbInitResult, flags);\n if (output) {\n ui.log(output);\n }\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;AAuCA,SAAS,iBAAiB,SAA4C;CACpE,IAAI,QAAQ,SAAS,mBACnB,OAAO,6BAA6B,EAAE,WAAW,QAAQ,aAAa,EAAE,EAAE,CAAC;CAG7E,IAAI,QAAQ,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AAiB,yBACnB,OAAO,MACL,8BAA8B,+BAA+B,MAAM,WAAW,EAC5E,OAAO,EAAE,MAAM,sBAAsB,EACtC,CAAC,CACH;EAIH,MAAM,cAAc,qBADD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAGvE,OAAO,iBAAiB,WAAW,eAAe,KAAA,EACnD;EACD,OAAO,MACL,gBAAgB,aAAa,EAC3B,KAAK,oCAAoC,eAC1C,CAAC,CACH;WACO;EACR,MAAM,OAAO,OAAO;;;AAIxB,SAAgB,sBAA+B;CAC7C,MAAM,UAAU,IAAI,QAAQ,OAAO;CACnC,uBACE,SACA,kEACA,sYAKD;CACD,mBAAmB,SAAS,CAC1B,0CACA,mDACD,CAAC;CACF,2BAA2B,QAAQ;CACnC,QAAQ,OAAO,OAAO,YAA2B;EAC/C,MAAM,QAAQ,uBAAuB,QAAQ;EAC7C,MAAM,YAAY,KAAK,KAAK;EAE5B,MAAM,KAAK,iBAAiB,MAAM;EAIlC,MAAM,WAAW,aAAa,MAFT,qBAAqB,SAAS,OAAO,IAAI,UAAU,EAElC,OAAO,KAAK,iBAAiB;GACjE,IAAI,MAAM,MACR,GAAG,OAAO,oBAAoB,aAAa,CAAC;QACvC;IACL,MAAM,SACJ,aAAa,SAAS,SAClB,0BAA0B,cAAc,MAAM,GAC9C,2BAA2B,cAAc,MAAM;IACrD,IAAI,QACF,GAAG,IAAI,OAAO;;IAGlB;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEF,OAAO"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as handleResult } from "../
|
|
3
|
-
import { t as
|
|
4
|
-
import { t as
|
|
5
|
-
import { n as formatIntrospectOutput, t as formatIntrospectJson } from "../verify-D7ypCCe6.mjs";
|
|
1
|
+
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
2
|
+
import { d as setCommandDescriptions, f as setCommandExamples, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-DtavI0wJ.mjs";
|
|
3
|
+
import { t as inspectLiveSchema } from "../inspect-live-schema-LeWvkZVz.mjs";
|
|
4
|
+
import { n as formatIntrospectOutput, t as formatIntrospectJson } from "../verify-Bom75OYI.mjs";
|
|
6
5
|
import { Command } from "commander";
|
|
7
6
|
//#region src/commands/db-schema.ts
|
|
8
7
|
function toIntrospectSchemaResult(result) {
|
|
@@ -24,11 +23,8 @@ function createDbSchemaCommand() {
|
|
|
24
23
|
"prisma-next db schema --db $DATABASE_URL --json > schema.json"
|
|
25
24
|
]);
|
|
26
25
|
addGlobalOptions(command).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").action(async (options) => {
|
|
27
|
-
const flags =
|
|
28
|
-
const ui =
|
|
29
|
-
color: flags.color,
|
|
30
|
-
interactive: flags.interactive
|
|
31
|
-
});
|
|
26
|
+
const flags = parseGlobalFlagsOrExit(options);
|
|
27
|
+
const ui = createTerminalUI(flags);
|
|
32
28
|
const exitCode = handleResult(await inspectLiveSchema(options, flags, ui, Date.now(), {
|
|
33
29
|
commandName: "db schema",
|
|
34
30
|
description: "Inspect the live database schema",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db-schema.mjs","names":[],"sources":["../../src/commands/db-schema.ts"],"sourcesContent":["import type { IntrospectSchemaResult } from '@prisma-next/framework-components/control';\nimport { Command } from 'commander';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatIntrospectJson, formatIntrospectOutput } from '../utils/formatters/verify';\nimport {
|
|
1
|
+
{"version":3,"file":"db-schema.mjs","names":[],"sources":["../../src/commands/db-schema.ts"],"sourcesContent":["import type { IntrospectSchemaResult } from '@prisma-next/framework-components/control';\nimport { Command } from 'commander';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatIntrospectJson, formatIntrospectOutput } from '../utils/formatters/verify';\nimport { parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI } from '../utils/terminal-ui';\nimport {\n type InspectLiveSchemaOptions,\n type InspectLiveSchemaResult,\n inspectLiveSchema,\n} from './inspect-live-schema';\n\nfunction toIntrospectSchemaResult(\n result: InspectLiveSchemaResult,\n): IntrospectSchemaResult<unknown> {\n return {\n ok: true,\n summary: 'Schema read successfully',\n target: result.target,\n schema: result.schema,\n meta: result.meta,\n timings: result.timings,\n };\n}\n\nexport function createDbSchemaCommand(): Command {\n const command = new Command('schema');\n setCommandDescriptions(\n command,\n 'Inspect the live database schema',\n 'Reads the live database schema and prints it as a tree by default or as JSON with\\n' +\n '--json. This command is always read-only and never writes files. To save machine-\\n' +\n 'readable output, use shell redirection, for example `prisma-next db schema --json > schema.json`.',\n );\n setCommandExamples(command, [\n 'prisma-next db schema --db $DATABASE_URL',\n 'prisma-next db schema --db $DATABASE_URL --json',\n 'prisma-next db schema --db $DATABASE_URL --json > schema.json',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: InspectLiveSchemaOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const startTime = Date.now();\n\n const result = await inspectLiveSchema(options, flags, ui, startTime, {\n commandName: 'db schema',\n description: 'Inspect the live database schema',\n url: 'https://pris.ly/db-schema',\n });\n\n const exitCode = handleResult(result, flags, ui, (value) => {\n const introspectResult = toIntrospectSchemaResult(value);\n\n if (flags.json) {\n ui.output(formatIntrospectJson(introspectResult));\n return;\n }\n\n const output = formatIntrospectOutput(introspectResult, value.schemaView, flags);\n if (output) {\n ui.log(output);\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;AAiBA,SAAS,yBACP,QACiC;CACjC,OAAO;EACL,IAAI;EACJ,SAAS;EACT,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,MAAM,OAAO;EACb,SAAS,OAAO;EACjB;;AAGH,SAAgB,wBAAiC;CAC/C,MAAM,UAAU,IAAI,QAAQ,SAAS;CACrC,uBACE,SACA,oCACA,0QAGD;CACD,mBAAmB,SAAS;EAC1B;EACA;EACA;EACD,CAAC;CACF,iBAAiB,QAAQ,CACtB,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,YAAsC;EACnD,MAAM,QAAQ,uBAAuB,QAAQ;EAC7C,MAAM,KAAK,iBAAiB,MAAM;EASlC,MAAM,WAAW,aAAa,MANT,kBAAkB,SAAS,OAAO,IAFrC,KAAK,KAE6C,EAAE;GACpE,aAAa;GACb,aAAa;GACb,KAAK;GACN,CAAC,EAEoC,OAAO,KAAK,UAAU;GAC1D,MAAM,mBAAmB,yBAAyB,MAAM;GAExD,IAAI,MAAM,MAAM;IACd,GAAG,OAAO,qBAAqB,iBAAiB,CAAC;IACjD;;GAGF,MAAM,SAAS,uBAAuB,kBAAkB,MAAM,YAAY,MAAM;GAChF,IAAI,QACF,GAAG,IAAI,OAAO;IAEhB;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEJ,OAAO"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { a as errorContractValidationFailed, b as mapMigrationToolsError, c as errorDriverRequired, g as errorRuntime, l as errorFileNotFound, o as errorDatabaseConnectionRequired, t as CliStructuredError, x as mapRefResolutionError, y as errorUnexpected } from "../cli-errors-Djtz98Vm.mjs";
|
|
3
|
+
import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
|
|
4
|
+
import { S as formatStyledHeader, a as loadMigrationPackages, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, o as maskConnectionUrl, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-DtavI0wJ.mjs";
|
|
4
5
|
import { t as createProgressAdapter } from "../progress-adapter-DFfvZcYL.mjs";
|
|
5
|
-
import { t as
|
|
6
|
-
import {
|
|
7
|
-
import { a as ContractValidationError, t as createControlClient } from "../client-Brv4qlfB.mjs";
|
|
8
|
-
import { a as formatSignJson, i as formatSchemaVerifyOutput, o as formatSignOutput, r as formatSchemaVerifyJson } from "../verify-D7ypCCe6.mjs";
|
|
6
|
+
import { a as ContractValidationError, t as createControlClient } from "../client-oXO2WCPD.mjs";
|
|
7
|
+
import { a as formatSignJson, i as formatSchemaVerifyOutput, o as formatSignOutput, r as formatSchemaVerifyJson } from "../verify-Bom75OYI.mjs";
|
|
9
8
|
import { Command } from "commander";
|
|
10
9
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
11
10
|
import { join, relative, resolve } from "pathe";
|
|
@@ -139,16 +138,13 @@ function createDbSignCommand() {
|
|
|
139
138
|
"prisma-next db sign --contract production --db $DATABASE_URL"
|
|
140
139
|
]);
|
|
141
140
|
addGlobalOptions(command).argument("[contract]", "Contract reference (hash, prefix, ref name, or migration dir name)").option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--contract <contract>", "Contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)").action(async (positionalContract, options) => {
|
|
142
|
-
const flags =
|
|
141
|
+
const flags = parseGlobalFlagsOrExit(options);
|
|
143
142
|
if (positionalContract && options.contract) {
|
|
144
143
|
process.stderr.write("Cannot specify both a positional contract argument and --contract flag.\n");
|
|
145
144
|
process.exit(2);
|
|
146
145
|
return;
|
|
147
146
|
}
|
|
148
|
-
const ui =
|
|
149
|
-
color: flags.color,
|
|
150
|
-
interactive: flags.interactive
|
|
151
|
-
});
|
|
147
|
+
const ui = createTerminalUI(flags);
|
|
152
148
|
const result = await executeDbSignCommand(positionalContract, options, flags, ui);
|
|
153
149
|
if (result.ok) {
|
|
154
150
|
if (flags.json) ui.output(formatSignJson(result.value));
|