@prisma/orm-toolchain 8.0.0-rc.18-dev.18 → 8.0.0-rc.18-dev.19

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
@@ -11,7 +11,7 @@ import { d as writeRef, r as readRef } from "./refs-BIzM-guE-qMvITMOL.mjs";
11
11
  import { a as contractHashAtMarker } from "./aggregate-C0qscKli.mjs";
12
12
  import { i as createScaffoldSpecifierResolver } from "./import-roots-DXD7fung.mjs";
13
13
  import { o as isLiveMarkerRef } from "./ref-resolution-CCIgrFwK.mjs";
14
- import { $ as refuseMarkerOutsideGraph, B as loadAggregateIntegrityViolations, D as executeMigrateShowPlan, F as formatSourceDiagnostic, G as looksLikePath, H as loadContractSource, I as hasMigrationPath, J as migrationSpaceListEntriesFromAggregate, K as mapContractAtError, L as isStatementVerb, M as executeRefListCommand, N as executeRefSetCommand, O as executeMigrationNewCommand, P as findPackageByDirPath, R as listRefsByContractHash, S as executeContractEmit, U as loadContractSourceWithStack, V as loadContractRawSafely, W as loadContractSpaceAggregateForCli, X as readMigrationRefs, Y as preflightRefAdvancement, Z as refuseContractSpaceIntegrity, _ as createControlClient, _t as statusForMigrationHash, a as RECORDED_OR_EMPTY_CONTRACT_REF_FORMS, at as resolveContractRef$1, c as appliedHashesFromLedger, ct as resolveMigrationRef, d as buildReadAggregate, dt as retryCommandFor, et as refuseMissingInvariantPath, f as buildRefAdvancementFields, g as convertAndDelete, gt as sourceWarningDiagnostic, h as contractValidationMeta, ht as snapshotVerifierFor, i as RECORDED_CONTRACT_REF_FORMS, it as resolveAppTargetPath, j as executeRefDeleteCommand, k as executeMigrationPlanCommand, m as computeRefAdvancementName, mt as runMigrationList, n as DB_UPDATE_POLICY, nt as refuseUnknownInvariants, o as advanceRefSafely, ot as resolveContractRefToSnapshot, p as checkSingleTarget, pt as runMigrationCheck, r as NO_REF_ADVANCEMENT, rt as requireDatabaseForLiveMarkerUse, t as ALL_CONTRACT_REF_FORMS, tt as refusePackageCorruptionOnAggregate, u as buildMigrationSpaceGraphEntries, v as deriveStatusEdgeAnnotations, vt as toDeclaredExtensionsFromRaw, x as enumerateCheckSpaces, yt as validateLoadedContract, z as liveMarkerUse } from "./ref-UzwhFoEX-BdXkOZFM.mjs";
14
+ import { $ as refuseMarkerOutsideGraph, B as loadAggregateIntegrityViolations, D as executeMigrateShowPlan, F as formatSourceDiagnostic, G as looksLikePath, H as loadContractSource, I as hasMigrationPath, J as migrationSpaceListEntriesFromAggregate, K as mapContractAtError, L as isStatementVerb, M as executeRefListCommand, N as executeRefSetCommand, O as executeMigrationNewCommand, P as findPackageByDirPath, R as listRefsByContractHash, S as executeContractEmit, U as loadContractSourceWithStack, V as loadContractRawSafely, W as loadContractSpaceAggregateForCli, X as readMigrationRefs, Y as preflightRefAdvancement, Z as refuseContractSpaceIntegrity, _ as createControlClient, _t as statusForMigrationHash, a as RECORDED_OR_EMPTY_CONTRACT_REF_FORMS, at as resolveContractRef$1, c as appliedHashesFromLedger, ct as resolveMigrationRef, d as buildReadAggregate, dt as retryCommandFor, et as refuseMissingInvariantPath, f as buildRefAdvancementFields, g as convertAndDelete, gt as sourceWarningDiagnostic, h as contractValidationMeta, ht as snapshotVerifierFor, i as RECORDED_CONTRACT_REF_FORMS, it as resolveAppTargetPath, j as executeRefDeleteCommand, k as executeMigrationPlanCommand, m as computeRefAdvancementName, mt as runMigrationList, n as DB_UPDATE_POLICY, nt as refuseUnknownInvariants, o as advanceRefSafely, ot as resolveContractRefToSnapshot, p as checkSingleTarget, pt as runMigrationCheck, r as NO_REF_ADVANCEMENT, rt as requireDatabaseForLiveMarkerUse, t as ALL_CONTRACT_REF_FORMS, tt as refusePackageCorruptionOnAggregate, u as buildMigrationSpaceGraphEntries, v as deriveStatusEdgeAnnotations, vt as toDeclaredExtensionsFromRaw, x as enumerateCheckSpaces, yt as validateLoadedContract, z as liveMarkerUse } from "./ref-C4HTKAnF-CtTLsNvf.mjs";
15
15
  import { a as PRISMA7_QUICK_REFERENCE_STEP, i as PRISMA7_LOOP_STEP, n as InitOutputSchema, o as buildNextSteps, r as NEXT_STEPS_BEFORE_SCAFFOLD, t as DB_SIGN_STEP } from "./output-BcC8eB0h-C5bRd-aC.mjs";
16
16
  import { createRequire } from "node:module";
17
17
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
@@ -40,7 +40,7 @@ import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
40
40
  import stringWidth from "string-width";
41
41
  import { bold, createColors, cyan, cyanBright, dim, green, yellow } from "colorette";
42
42
  import { build } from "esbuild";
43
- //#region ../../../1-framework/3-tooling/cli/dist/load-config-D2ypzTx-.mjs
43
+ //#region ../../../1-framework/3-tooling/cli/dist/load-config-CZKX80aY.mjs
44
44
  /**
45
45
  * `isStructuredError` is the repo's own check, and it is the one that matters here: it holds the
46
46
  * regular expression for a dotted `NAMESPACE.SUBCODE`, so only a code the protocol accepts
@@ -805,6 +805,50 @@ function migrateFailedPrecheckFix(report, invocation) {
805
805
  function dbInitFailedPrecheckFix(invocation) {
806
806
  return `The database already holds part of the schema \`${cliCommand(invocation, "db init")}\` would create. If its schema already matches the contract, adopt it with \`${cliCommand(invocation, "db sign")}\` instead.`;
807
807
  }
808
+ const OUTCOME_LABEL = {
809
+ "not-found": "missing",
810
+ "not-expected": "extra",
811
+ "not-equal": "mismatch"
812
+ };
813
+ const MISMATCH_CAUSES = {
814
+ differs: true,
815
+ "possibly-equivalent": true
816
+ };
817
+ /** What a diff issue says, in the words the commander shell used. */
818
+ function issueLabel(issue) {
819
+ const label = `${OUTCOME_LABEL[issueOutcome(issue)]}: ${issue.path.join("/")}`;
820
+ return issue.explanation === void 0 ? label : `${label}. ${issue.explanation.text}`;
821
+ }
822
+ /** The issues of a failed schema check, as one sentence for a diagnostic's why, after `opening`. */
823
+ function schemaIssuesWhy(opening, issues) {
824
+ return `${opening}: ${issues.map((issue) => issueLabel(issue).replace(/\.$/, "")).join("; ")}.`;
825
+ }
826
+ /**
827
+ * The issues a runner failure of its schema check after apply carries in its meta, or `undefined`
828
+ * for another failure, or when the meta holds no issue the CLI can read.
829
+ */
830
+ function runnerSchemaIssues(meta) {
831
+ if (meta?.["runnerErrorCode"] !== "MIGRATION.SCHEMA_VERIFY_FAILED") return void 0;
832
+ const issues = meta["issues"];
833
+ return Array.isArray(issues) && issues.length > 0 && issues.every(isSchemaDiffIssue) ? issues : void 0;
834
+ }
835
+ /** The why of a runner failure of its schema check after apply, listing the issues as `db verify` does. */
836
+ function runnerSchemaCheckWhy(meta) {
837
+ const issues = runnerSchemaIssues(meta);
838
+ return issues === void 0 ? void 0 : schemaIssuesWhy("The schema check after apply found", issues);
839
+ }
840
+ function isSchemaDiffIssue(value) {
841
+ if (typeof value !== "object" || value === null) return false;
842
+ if (!("path" in value) || !Array.isArray(value.path)) return false;
843
+ if (!value.path.every((step) => typeof step === "string")) return false;
844
+ const expected = "expected" in value ? value.expected : void 0;
845
+ const actual = "actual" in value ? value.actual : void 0;
846
+ if (expected === void 0 && actual === void 0) return false;
847
+ return !("explanation" in value) || isMismatchExplanation(value.explanation);
848
+ }
849
+ function isMismatchExplanation(value) {
850
+ return typeof value === "object" && value !== null && "text" in value && typeof value.text === "string" && "cause" in value && typeof value.cause === "string" && Object.hasOwn(MISMATCH_CAUSES, value.cause);
851
+ }
808
852
  /** What a runner failure says of a type change that failed: who converted the values, and how it failed. */
809
853
  function failedTypeChangeText(change) {
810
854
  if (change.by === "cast") return change.reason === "noCast" ? `The database has no cast from the old type of field "${change.field}" to its new type.` : `A value of field "${change.field}" cannot be converted to its new type by the database's cast.`;
@@ -861,7 +905,7 @@ function failedMigrationText(failed, invocation) {
861
905
  return {
862
906
  directory: printedPath(invocation, failed.directory),
863
907
  name: dirName.slice(dirName.indexOf("_") + 1),
864
- from: failed.from,
908
+ from: failed.from === "empty" ? void 0 : failed.from,
865
909
  nodeCommand: selfEmitCommand(invocation, join(failed.directory, "migration.ts")),
866
910
  invocation
867
911
  };
@@ -929,6 +973,12 @@ function migrateRowsWithoutValueFix(reports, failedMigration, invocation) {
929
973
  function fieldList(reports) {
930
974
  return reports.map(({ field }) => field === void 0 ? void 0 : `"${field}"`).filter((field) => field !== void 0).join(", ");
931
975
  }
976
+ function migrateSchemaCheckFix(failedMigration, invocation) {
977
+ const emit = `\`${cliCommand(invocation, "contract emit")}\``;
978
+ if (failedMigration === void 0) return `The failed apply changed nothing. Change the contract source to resolve the issues listed, re-run ${emit}, delete the failed migration's directory (copy any code you wrote in its migration.ts first), plan it again with ${migrationPlanCommand$1(invocation, [], void 0)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}.`;
979
+ const plan = migrationPlanCommand$1(invocation, ["--name", failedMigration.name], failedMigration.from);
980
+ return `The failed apply changed nothing. Change the contract source to resolve the issues listed, re-run ${emit}, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${plan}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}.`;
981
+ }
932
982
  /**
933
983
  * The way out of a failed `db migrate` apply: every path and command it prints works from where the
934
984
  * CLI ran, with the `--config` it was given.
@@ -937,6 +987,7 @@ function migrateFix(failure, invocation) {
937
987
  const failedMigration = failure.failedMigration === void 0 ? void 0 : failedMigrationText(failure.failedMigration, invocation);
938
988
  if (failure.failedTypeChange !== void 0) return migrateFailedTypeChangeFix(failure.failedTypeChange, failedMigration, invocation);
939
989
  if (failure.rowsWithoutValue !== void 0) return migrateRowsWithoutValueFix(failure.rowsWithoutValue, failedMigration, invocation);
990
+ if (runnerSchemaIssues(failure.meta) !== void 0) return migrateSchemaCheckFix(failedMigration, invocation);
940
991
  if (failure.failedPrecheck !== void 0) return migrateFailedPrecheckFix(failure.failedPrecheck, invocation);
941
992
  return `Fix the issue and re-run \`${cliCommand(invocation, "db migrate", ["--to", "<contract>"])}\` — previously applied migrations are preserved.`;
942
993
  }
@@ -995,9 +1046,9 @@ function mapDbInitFailure(failure, invocation) {
995
1046
  });
996
1047
  if (failure.code === "RUNNER_FAILED") {
997
1048
  const runnerCode = typeof failure.meta?.["runnerErrorCode"] === "string" ? failure.meta["runnerErrorCode"] : void 0;
998
- const fix = failure.rowsWithoutValue !== void 0 ? dbInitRowsWithoutValueFix(failure.rowsWithoutValue, invocation) : failure.failedPrecheck !== void 0 ? dbInitFailedPrecheckFix(invocation) : runnerCode === "MIGRATION.LEGACY_MARKER_SHAPE" ? "Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `{bin} 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 `{bin} db init`";
1049
+ const fix = failure.rowsWithoutValue !== void 0 ? dbInitRowsWithoutValueFix(failure.rowsWithoutValue, invocation) : runnerSchemaIssues(failure.meta) !== void 0 ? "Change the contract source to resolve the issues listed, re-run `{bin} contract emit`, then re-run `{bin} db init`." : failure.failedPrecheck !== void 0 ? dbInitFailedPrecheckFix(invocation) : runnerCode === "MIGRATION.LEGACY_MARKER_SHAPE" ? "Legacy marker-table shape detected. Drop `prisma_contract.marker` (Postgres) or `_prisma_marker` (SQLite) and re-run `{bin} 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 `{bin} db init`";
999
1050
  return errorRunnerFailed(failure.summary, {
1000
- why: failure.why ?? (failure.failedPrecheck === void 0 ? "Migration runner failed" : failedPrecheckWhy(failure.failedPrecheck)),
1051
+ why: runnerSchemaCheckWhy(failure.meta) ?? failure.why ?? (failure.failedPrecheck === void 0 ? "Migration runner failed" : failedPrecheckWhy(failure.failedPrecheck)),
1001
1052
  fix,
1002
1053
  ...ifDefined("meta", failure.meta),
1003
1054
  ...ifDefined("cause", failure.cause)
@@ -1764,16 +1815,6 @@ function requireVerifyConnection(inputs) {
1764
1815
  function verificationThrow(inputs) {
1765
1816
  return normalizeError(errorFromCaught(inputs.error, (message) => `Unexpected error during ${inputs.commandLine}: ${message}`, { connection: inputs.connection }));
1766
1817
  }
1767
- const OUTCOME_LABEL = {
1768
- "not-found": "missing",
1769
- "not-expected": "extra",
1770
- "not-equal": "mismatch"
1771
- };
1772
- /** What a diff issue says, in the words the commander shell used. */
1773
- function issueLabel(issue) {
1774
- const label = `${OUTCOME_LABEL[issueOutcome(issue)]}: ${issue.path.join("/")}`;
1775
- return issue.explanation === void 0 ? label : `${label}. ${issue.explanation}`;
1776
- }
1777
1818
  function issueNodes(issues, status) {
1778
1819
  return issues.map((issue) => ({
1779
1820
  label: issueLabel(issue),
@@ -1829,7 +1870,7 @@ function schemaVerdictDiagnostic(inputs) {
1829
1870
  code: dotted ? code : "CONTRACT.VERIFY_FAILED",
1830
1871
  severity: "error",
1831
1872
  summary: inputs.result.summary,
1832
- ...issues.length === 0 ? {} : { why: sentence(`The live schema differs: ${issues.join("; ")}`) },
1873
+ ...issues.length === 0 ? {} : { why: schemaIssuesWhy("The live schema differs", inputs.result.schema.issues) },
1833
1874
  nextActions: inputs.nextActions,
1834
1875
  meta: {
1835
1876
  ...inputs.space === void 0 ? {} : { space: inputs.space },
@@ -1838,16 +1879,22 @@ function schemaVerdictDiagnostic(inputs) {
1838
1879
  }
1839
1880
  };
1840
1881
  }
1841
- function sentence(text) {
1842
- return text.endsWith(".") ? text : `${text}.`;
1843
- }
1844
1882
  /**
1845
- * What to do about schema drift: change the database to match the contract, or the contract to describe the database. A default the column's codec cannot read is drift of the same kind; its issue explains it.
1883
+ * What to do about schema drift, by the causes the issues name. A value the database may hold in a
1884
+ * form of its own is fixed in the contract when the two mean the same, and by `db update` when they
1885
+ * do not. `db update` is always offered; changing the contract to describe the database is offered
1886
+ * when some issue is not one the database may only have stored in its own form, or there is none.
1846
1887
  */
1847
1888
  function schemaDriftNextActions(inputs) {
1848
- const { verb, contractRef } = inputs;
1889
+ const { verb, contractRef, issues } = inputs;
1849
1890
  const retryAfterEmit = contractRef === void 0 ? `${verb} again` : `${verb} the emitted contract instead of "${contractRef}"`;
1850
- return [runCommandAction(`Change the database to match the contract, then ${verb} again`, contractRef === void 0 ? "{bin} db update" : `{bin} db update --to "${contractRef}"`), chooseAction(`Or change the contract source to describe the database as it is, re-run contract emit, then ${retryAfterEmit}`)];
1891
+ const storedForm = issues.some((issue) => issue.explanation?.cause === "possibly-equivalent");
1892
+ const other = issues.length === 0 || issues.some((issue) => issue.explanation?.cause !== "possibly-equivalent");
1893
+ return [
1894
+ ...storedForm ? [chooseAction(`If the database only stored a value in a form of its own, write it in the contract source as the database stores it, re-run contract emit, then ${retryAfterEmit}`)] : [],
1895
+ runCommandAction(`Change the database to match the contract, then ${verb} again`, contractRef === void 0 ? "{bin} db update" : `{bin} db update --to "${contractRef}"`),
1896
+ ...other ? [chooseAction(storedForm ? `Or, for the other issues, change the contract source to describe the database as it is, re-run contract emit, then ${retryAfterEmit}` : `Or change the contract source to describe the database as it is, re-run contract emit, then ${retryAfterEmit}`)] : []
1897
+ ];
1851
1898
  }
1852
1899
  /**
1853
1900
  * Verification ran and refused the signature. The command completed — it
@@ -2275,7 +2322,8 @@ function createDbSignCommand(createClient = createControlClient) {
2275
2322
  space: outcome.space,
2276
2323
  nextActions: schemaDriftNextActions({
2277
2324
  verb: "sign",
2278
- contractRef
2325
+ contractRef,
2326
+ issues: outcome.schema.schema.issues
2279
2327
  })
2280
2328
  })];
2281
2329
  case "conflict": return [markerConflictDiagnostic(outcome, rerun)];
@@ -2314,9 +2362,9 @@ function mapDbUpdateFailure(failure, invocation) {
2314
2362
  if (failure.code === "PLANNING_FAILED") return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
2315
2363
  if (failure.code === "RUNNER_FAILED") {
2316
2364
  const runnerCode = typeof failure.meta?.["runnerErrorCode"] === "string" ? failure.meta["runnerErrorCode"] : void 0;
2317
- const fix = failure.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeFix(failure.failedTypeChange, failure.databaseStorageHash, invocation) : failure.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueFix(failure.rowsWithoutValue, failure.databaseStorageHash, invocation) : runnerCode === "MIGRATION.LEGACY_MARKER_SHAPE" ? `Legacy marker-table shape detected. Drop \`prisma_contract.marker\` (Postgres) or \`_prisma_marker\` (SQLite) and re-run \`${cliCommand(invocation, "db init")}\` to recreate it with the current per-space schema.` : `Inspect the reported conflict, reconcile schema drift if needed, then re-run \`${cliCommand(invocation, "db update")}\``;
2365
+ const fix = failure.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeFix(failure.failedTypeChange, failure.databaseStorageHash, invocation) : failure.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueFix(failure.rowsWithoutValue, failure.databaseStorageHash, invocation) : runnerSchemaIssues(failure.meta) !== void 0 ? `Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${cliCommand(invocation, "db update")}\`.` : runnerCode === "MIGRATION.LEGACY_MARKER_SHAPE" ? `Legacy marker-table shape detected. Drop \`prisma_contract.marker\` (Postgres) or \`_prisma_marker\` (SQLite) and re-run \`${cliCommand(invocation, "db init")}\` to recreate it with the current per-space schema.` : `Inspect the reported conflict, reconcile schema drift if needed, then re-run \`${cliCommand(invocation, "db update")}\``;
2318
2366
  return errorRunnerFailed(failure.summary, {
2319
- why: failure.why ?? (failure.failedPrecheck === void 0 ? "Migration runner failed" : failedPrecheckWhy(failure.failedPrecheck)),
2367
+ why: runnerSchemaCheckWhy(failure.meta) ?? failure.why ?? (failure.failedPrecheck === void 0 ? "Migration runner failed" : failedPrecheckWhy(failure.failedPrecheck)),
2320
2368
  fix,
2321
2369
  meta: {
2322
2370
  ...failure.meta,
@@ -2987,7 +3035,8 @@ function driftDiagnostics(inputs) {
2987
3035
  space,
2988
3036
  nextActions: schemaDriftNextActions({
2989
3037
  verb: "verify",
2990
- contractRef: void 0
3038
+ contractRef: void 0,
3039
+ issues: result.schema.issues
2991
3040
  })
2992
3041
  }));
2993
3042
  if (perSpace.length > 0) return perSpace;
@@ -9446,7 +9495,7 @@ function migrateShowRunListRows(migrations, rendering, options) {
9446
9495
  function mapMigrateFailure(failure, invocation) {
9447
9496
  if (failure.code === "MIGRATION_PATH_NOT_FOUND") return errorPathUnreachable(failure);
9448
9497
  return errorRunnerFailed(failure.summary, {
9449
- why: failure.why ?? (failure.failedPrecheck === void 0 ? "Migration runner failed" : failedPrecheckWhy(failure.failedPrecheck)),
9498
+ why: runnerSchemaCheckWhy(failure.meta) ?? failure.why ?? (failure.failedPrecheck === void 0 ? "Migration runner failed" : failedPrecheckWhy(failure.failedPrecheck)),
9450
9499
  fix: migrateFix(failure, invocation),
9451
9500
  meta: failure.meta ?? {},
9452
9501
  ...ifDefined("cause", failure.cause)