@prisma/orm-toolchain 8.0.0-rc.11-dev.39 → 8.0.0-rc.11-dev.40

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/dist/cli.mjs CHANGED
@@ -5,7 +5,7 @@ import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
5
5
  import { r as readRef } from "./refs-BpSpzdYB-BcDelHGt.mjs";
6
6
  import { c as spaceMigrationDirectory } from "./verify-contract-spaces-_vwt5LT0-BQAf8Q4T.mjs";
7
7
  import { i as createScaffoldSpecifierResolver } from "./import-roots-CCyOuQxb.mjs";
8
- import { $ as listRefsByContractHash, A as errorMarkerMissing, At as sanitizeErrorMessage, B as executeContractEmit, C as errorContractValidationFailed, D as errorFileNotFound, E as errorDriverRequired, Et as runCommandAction, F as errorRunnerFailed, G as executeMigrationNewCommand, I as errorRuntime, J as executeRefDeleteCommand, K as executeMigrationPlanCommand, L as errorTargetMigrationNotSupported, M as errorMigrationPlanningFailed, Mt as targetSupportsMigrations, N as errorNoMigrations, Nt as toDeclaredExtensionsFromRaw, O as errorHashMismatch, Ot as runMigrationCheck, P as errorPathUnreachable, Q as hasMigrationPath, R as errorTargetMismatch, S as errorContractArgConflict, St as resolveContractRefToSnapshot, T as errorDestructiveChanges, W as executeMigrateShowPlan, X as executeRefSetCommand, Y as executeRefListCommand, Z as findPackageByDirPath, _t as refusePackageCorruptionOnAggregate, a as appliedHashesFromLedger, at as mapContractAtError, b as errorConfigValidation$1, bt as resolveAppTargetPath, c as buildReadAggregate, ct as migrationSpaceListEntriesFromAggregate, d as chooseAction, dt as readContractEnvelope, et as loadAggregateIntegrityViolations, f as closeQuietly, ft as readMigrationRefs, gt as refuseMissingInvariantPath, h as deriveStatusEdgeAnnotations, ht as refuseMarkerOutsideGraph, it as mapCaughtMigrationError, j as errorMigrationPackageNotFound, jt as statusForMigrationHash, k as errorLegendHumanOnly, kt as runMigrationList, l as buildRefAdvancementFields, lt as originHashForStatus, m as createControlClient, n as NO_REF_ADVANCEMENT, nt as loadContractSpaceAggregateForCli, p as computeRefAdvancementName, pt as refuseContractSpaceIntegrity, r as advanceRefSafely, rt as looksLikePath, s as buildMigrationSpaceGraphEntries, st as maskConnectionUrl, t as CliStructuredError$1$1, tt as loadContractRawSafely, u as checkSingleTarget, ut as preflightRefAdvancement, v as enumerateCheckSpaces, vt as refuseUnknownInvariants, w as errorDatabaseConnectionRequired, wt as resolveMigrationRef, x as errorConsentPlanMismatch, xt as resolveContractRef$1, y as errorAdvanceRefArgConflict, yt as requireLiveDatabase, z as errorUnexpected } from "./ref-DlKsxbtg-B55l0TCq.mjs";
8
+ import { $ as hasMigrationPath, A as errorLegendHumanOnly, At as runMigrationList, B as errorUnexpected, C as errorContractArgConflict, Ct as resolveContractRefToSnapshot, D as errorDriverRequired, Dt as runCommandAction, E as errorDestructiveChanges, F as errorPathUnreachable, G as executeMigrateShowPlan, I as errorRunnerFailed, K as executeMigrationNewCommand, L as errorRuntime, M as errorMigrationPackageNotFound, Mt as statusForMigrationHash, N as errorMigrationPlanningFailed, Nt as targetSupportsMigrations, O as errorFileNotFound, P as errorNoMigrations, Pt as toDeclaredExtensionsFromRaw, Q as findPackageByDirPath, R as errorTargetMigrationNotSupported, S as errorConsentPlanMismatch, St as resolveContractRef$1, T as errorDatabaseConnectionRequired, Tt as resolveMigrationRef, V as executeContractEmit, X as executeRefListCommand, Y as executeRefDeleteCommand, Z as executeRefSetCommand, _t as refuseMissingInvariantPath, at as mapCaughtMigrationError, b as errorAdvanceRefArgConflict, bt as requireLiveDatabase, c as buildMigrationSpaceGraphEntries, ct as maskConnectionUrl, d as checkSingleTarget, dt as preflightRefAdvancement, et as listRefsByContractHash, f as chooseAction, ft as readContractEnvelope, g as deriveStatusEdgeAnnotations, gt as refuseMarkerOutsideGraph, h as createControlClient, i as advanceRefSafely, it as looksLikePath, j as errorMarkerMissing, jt as sanitizeErrorMessage, k as errorHashMismatch, kt as runMigrationCheck, l as buildReadAggregate, lt as migrationSpaceListEntriesFromAggregate, m as computeRefAdvancementName, mt as refuseContractSpaceIntegrity, n as ERROR_CODE_DESTRUCTIVE_CHANGES, nt as loadContractRawSafely, o as appliedHashesFromLedger, ot as mapContractAtError, p as closeQuietly, pt as readMigrationRefs, q as executeMigrationPlanCommand, r as NO_REF_ADVANCEMENT, rt as loadContractSpaceAggregateForCli, t as CliStructuredError$1$1, tt as loadAggregateIntegrityViolations, u as buildRefAdvancementFields, ut as originHashForStatus, vt as refusePackageCorruptionOnAggregate, w as errorContractValidationFailed, x as errorConfigValidation$1, xt as resolveAppTargetPath, y as enumerateCheckSpaces, yt as refuseUnknownInvariants, z as errorTargetMismatch } from "./ref-CGE8q4jD-DNPh6Yqe.mjs";
9
9
  import { n as buildNextSteps, t as InitOutputSchema } from "./output-D83nTTpC-XlvN30yS.mjs";
10
10
  import { r as loadConfig, t as finalizeConfig } from "./exports-DJ4RhlW4.mjs";
11
11
  import { createRequire } from "node:module";
@@ -36,7 +36,7 @@ import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
36
36
  import stringWidth from "string-width";
37
37
  import { bold, createColors, cyan, cyanBright, dim, green, yellow } from "colorette";
38
38
  import { build } from "esbuild";
39
- //#region ../../../1-framework/3-tooling/cli/dist/load-config-C4yTwEEc.mjs
39
+ //#region ../../../1-framework/3-tooling/cli/dist/load-config-DpSfWK8r.mjs
40
40
  const MISSING_CONFIG_ACTION = {
41
41
  kind: "run-command",
42
42
  label: "Create a config file",
@@ -1853,20 +1853,23 @@ function errorConsentTokenUnresolved(targetId) {
1853
1853
  });
1854
1854
  }
1855
1855
  /** A prompt that names nothing cannot be consented to knowingly. */
1856
- function errorConsentOperationsMissing() {
1856
+ function errorConsentOperationsMissing(options) {
1857
1857
  return new CliStructuredError$1("CLI.CONSENT_OPERATIONS_MISSING", "The plan was refused as destructive but named no operations to confirm.", {
1858
1858
  why: "The consent prompt has to list what is about to be destroyed, and the refusal carried no operations to list.",
1859
1859
  nextActions: [{
1860
1860
  kind: "run-command",
1861
1861
  label: "Preview the plan",
1862
- command: "{bin} db update --dry-run"
1862
+ command: options?.previewCommand ?? "{bin} db update --dry-run"
1863
1863
  }]
1864
1864
  });
1865
1865
  }
1866
+ /** The indented per-operation list every destructive-consent question renders. */
1867
+ function destructiveOperationList(operations) {
1868
+ return operations.map((operation) => ` - ${operation.label}`).join("\n");
1869
+ }
1866
1870
  /** The question the user answers before anything is dropped. */
1867
1871
  function destructiveConsentQuestion(operations, token) {
1868
- const listed = operations.map((operation) => ` - ${operation.label}`).join("\n");
1869
- return [`Apply ${operations.length} destructive operation(s) to ${token}? Data they remove cannot be recovered:`, listed].join("\n");
1872
+ return [`Apply ${operations.length} destructive operation(s) to ${token}? Data they remove cannot be recovered:`, destructiveOperationList(operations)].join("\n");
1870
1873
  }
1871
1874
  function updatePresentations(inputs) {
1872
1875
  const { document, database, dryRun } = inputs;
@@ -8521,21 +8524,34 @@ function outcomeFields(result, migrationsRelative) {
8521
8524
  ]
8522
8525
  };
8523
8526
  }
8524
- function operationNodes$1(result) {
8525
- return result.operations.map((operation) => operation.operationClass === "destructive" ? {
8527
+ function operationNodes$1(operations) {
8528
+ return operations.map((operation) => operation.operationClass === "destructive" ? {
8526
8529
  label: operation.label,
8527
8530
  status: "warn"
8528
8531
  } : { label: operation.label });
8529
8532
  }
8533
+ /**
8534
+ * One tree root per written package: the auto-baseline package first (when
8535
+ * this run wrote one), then the app-space package. A baseline-only run has
8536
+ * no `dir`, so the app-space root falls back to `baselineDir`.
8537
+ */
8538
+ function operationRoots(result) {
8539
+ const baselineOperations = result.baselineOperations ?? [];
8540
+ return [...baselineOperations.length > 0 && result.baselineDir !== void 0 ? [{
8541
+ label: result.baselineDir,
8542
+ children: operationNodes$1(baselineOperations)
8543
+ }] : [], ...result.operations.length > 0 ? [{
8544
+ label: result.dir ?? result.baselineDir ?? "operations",
8545
+ children: operationNodes$1(result.operations)
8546
+ }] : []];
8547
+ }
8530
8548
  function operationBlocks$1(result) {
8531
- if (result.operations.length === 0) return [];
8532
- const destructive = result.operations.some((operation) => operation.operationClass === "destructive");
8549
+ const written = [...result.baselineOperations ?? [], ...result.operations];
8550
+ if (written.length === 0) return [];
8551
+ const destructive = written.some((operation) => operation.operationClass === "destructive");
8533
8552
  return [{
8534
8553
  kind: "tree",
8535
- roots: [{
8536
- label: result.dir ?? "operations",
8537
- children: operationNodes$1(result)
8538
- }]
8554
+ roots: operationRoots(result)
8539
8555
  }, ...destructive ? [{
8540
8556
  kind: "summary",
8541
8557
  status: "warn",
@@ -8567,14 +8583,26 @@ function originNoticeBlocks(result) {
8567
8583
  text: "No db ref set — planning from an empty database. Run db init, db update, or db sign if a database already exists."
8568
8584
  }];
8569
8585
  }
8586
+ function warningBlocks(result) {
8587
+ return (result.warnings ?? []).map((text) => ({
8588
+ kind: "summary",
8589
+ status: "warn",
8590
+ text
8591
+ }));
8592
+ }
8570
8593
  function planBlocks(result, migrationsRelative) {
8571
8594
  const outcome = outcomeFields(result, migrationsRelative);
8572
- if (result.noOp) return [{
8573
- kind: "summary",
8574
- status: "ok",
8575
- text: "No changes detected"
8576
- }, outcome];
8595
+ if (result.noOp) return [
8596
+ ...warningBlocks(result),
8597
+ {
8598
+ kind: "summary",
8599
+ status: "ok",
8600
+ text: "No changes detected"
8601
+ },
8602
+ outcome
8603
+ ];
8577
8604
  if (result.pendingPlaceholders === true) return [
8605
+ ...warningBlocks(result),
8578
8606
  {
8579
8607
  kind: "summary",
8580
8608
  status: "warn",
@@ -8584,6 +8612,7 @@ function planBlocks(result, migrationsRelative) {
8584
8612
  outcome
8585
8613
  ];
8586
8614
  return [
8615
+ ...warningBlocks(result),
8587
8616
  {
8588
8617
  kind: "summary",
8589
8618
  status: "ok",
@@ -8597,10 +8626,11 @@ function planBlocks(result, migrationsRelative) {
8597
8626
  }
8598
8627
  function planNextActions(result, migrationsRelative) {
8599
8628
  if (result.pendingPlaceholders === true) {
8600
- const migrationTs = join(result.dir ?? "<dir>", "migration.ts");
8629
+ const stubFiles = [.../* @__PURE__ */ new Set([...result.baselineDir === void 0 ? [] : [join(result.baselineDir, "migration.ts")], ...result.dir === void 0 ? [] : [join(result.dir, "migration.ts")]])];
8630
+ const migrationTs = stubFiles.at(-1) ?? join("<dir>", "migration.ts");
8601
8631
  return [{
8602
8632
  kind: "edit-file",
8603
- label: `Replace each placeholder(...) call in ${migrationTs} with your query`
8633
+ label: `Replace each placeholder(...) call in ${stubFiles.join(" and ") || migrationTs} with your query`
8604
8634
  }, runCommandAction("Run it to self-emit ops.json and attest the package", `node "${migrationTs}"`)];
8605
8635
  }
8606
8636
  const written = [
@@ -8647,11 +8677,15 @@ function planPresentations(inputs) {
8647
8677
  next: () => planNextActions(inputs.document, inputs.migrationsRelative)
8648
8678
  };
8649
8679
  }
8680
+ /** The question the user answers before a destructive baseline is written. */
8681
+ function destructiveBaselineQuestion(operations) {
8682
+ return [`Write a baseline migration containing ${operations.length} destructive operation(s)? Applying it would remove data that cannot be recovered:`, destructiveOperationList(operations)].join("\n");
8683
+ }
8650
8684
  function createMigrationPlanCommand(createClient) {
8651
8685
  return defineOrmCommand({
8652
8686
  help: {
8653
8687
  summary: "Plan a migration from contract changes",
8654
- description: "Compares the emitted contract against the latest on-disk migration state\nand produces a new migration package with the required operations.\nOffline — does not consult the database.",
8688
+ description: "Compares the emitted contract against the latest on-disk migration state\nand produces a new migration package with the required operations.\nOn an empty migrations directory a baseline package is derived from the\n`db` ref first; a baseline containing destructive operations is only\nwritten with your consent: the command asks you to type the project\ndirectory name, or takes `--confirm <directory>` where there is nobody\nto ask. Offline — does not consult the database.",
8655
8689
  examples: [
8656
8690
  "migration plan",
8657
8691
  "migration plan --name add-users-table",
@@ -8675,8 +8709,13 @@ function createMigrationPlanCommand(createClient) {
8675
8709
  } },
8676
8710
  needs: { config: ormConfigSection },
8677
8711
  handler: async (args, ctx) => {
8712
+ const seededDirs = [];
8678
8713
  const seeded = (record) => {
8679
8714
  if (record.action !== "updated") return;
8715
+ for (const dirName of record.newMigrationDirs) seededDirs.push({
8716
+ spaceId: record.spaceId,
8717
+ dirName
8718
+ });
8680
8719
  const step = `Seed contract space ${record.spaceId}`;
8681
8720
  ctx.report({
8682
8721
  kind: "step-started",
@@ -8694,13 +8733,15 @@ function createMigrationPlanCommand(createClient) {
8694
8733
  }
8695
8734
  });
8696
8735
  };
8697
- const planned = await executeMigrationPlanCommand({
8736
+ const plan = (consent) => executeMigrationPlanCommand({
8698
8737
  config: ctx.config,
8699
8738
  cwd: ctx.cwd,
8700
8739
  configPath: projectConfigPathFor(ctx.cwd),
8701
8740
  ...ifDefined("name", args.flags.name),
8702
8741
  ...ifDefined("from", args.flags.from),
8703
8742
  ...ifDefined("to", args.flags.to),
8743
+ ...ifDefined("consent", consent),
8744
+ ...ifDefined("carryEmittedExtensionDirs", consent !== void 0 && seededDirs.length > 0 ? [...seededDirs] : void 0),
8704
8745
  client: createClient({
8705
8746
  family: ctx.config.family,
8706
8747
  target: ctx.config.target,
@@ -8709,6 +8750,14 @@ function createMigrationPlanCommand(createClient) {
8709
8750
  extensions: ctx.config.extensions ?? []
8710
8751
  })
8711
8752
  }, Date.now(), { onSeeded: seeded });
8753
+ let planned = await plan();
8754
+ if (!planned.ok && planned.failure.code === ERROR_CODE_DESTRUCTIVE_CHANGES) {
8755
+ const verdict = blindCast(planned.failure.meta ?? {});
8756
+ if (verdict.destructiveOperations === void 0 || verdict.destructiveOperations.length === 0 || verdict.planHash === void 0) return notOk$1(normalizeError(errorConsentOperationsMissing({ previewCommand: "{bin} migration plan" })));
8757
+ const token = consentToken(ctx.cwd);
8758
+ if (!await ctx.prompt.consent(destructiveBaselineQuestion(verdict.destructiveOperations), { token })) return notOk$1(normalizeError(planned.failure));
8759
+ planned = await plan({ planHash: verdict.planHash });
8760
+ }
8712
8761
  if (!planned.ok) return notOk$1(normalizeError(planned.failure));
8713
8762
  ctx.report({
8714
8763
  kind: "message",