@prisma/orm-toolchain 8.0.0-rc.11-dev.6 → 8.0.0-rc.11-dev.8

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.
@@ -11,13 +11,14 @@ import { d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o a
11
11
  import { a as isValidSpaceId, c as spaceMigrationDirectory, l as spaceRefsDirectory, o as listContractSpaceDirectories, s as readContractSpaceHeadRef, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-CrxvgpwD-D5LLXGci.mjs";
12
12
  import { d as resolveRecordedPath, f as verifyMigration, l as planMigration, n as buildFabricatedMigrationEdge, r as collectAggregateNamespaces, s as loadContractSpaceAggregate, t as allStorageElementsExternal, u as requireHeadRef } from "./aggregate-B4HKshLQ.mjs";
13
13
  import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-BCZiAZQn.mjs";
14
- import { c as internalImportRoot, o as importRootForDependencies, r as createImportSpecifierResolver } from "./import-roots-BHOrDJbI.mjs";
14
+ import { c as internalImportRoot, o as importRootForDependencies, r as createImportSpecifierResolver, t as ImportRootError } from "./import-roots-BHOrDJbI.mjs";
15
15
  import { n as parseContractRef, r as parseMigrationRef } from "./ref-resolution-BWpwb8_b.mjs";
16
16
  import { i as writeMigrationTs } from "./migration-ts-DdVm0rws.mjs";
17
17
  import { createRequire } from "node:module";
18
18
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
19
19
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
20
20
  import { structuredError } from "@prisma/orm-framework/utils/structured-error";
21
+ import { keepInternalSpecifiers } from "@prisma/orm-framework/components/emission";
21
22
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
22
23
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
23
24
  import { CliStructuredError, CliStructuredError as CliStructuredError$1, errorConfigValidation as errorConfigValidation$1, errorContractConfigMissing, errorContractValidationFailed, errorDatabaseConnectionRequired, errorDriverRequired, errorFileNotFound, errorMigrationPlanningFailed, errorTargetMigrationNotSupported, errorUnexpected } from "@prisma/orm-framework/errors/control";
@@ -32,7 +33,7 @@ import { createHash } from "node:crypto";
32
33
  import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
33
34
  import { abortable } from "@prisma/orm-framework/utils/abortable";
34
35
  import { resolve as resolve$1 } from "node:path";
35
- //#region ../../../1-framework/3-tooling/cli/dist/ref-DcqFmceq.mjs
36
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-uqvZQnnQ.mjs
36
37
  /**
37
38
  * The typed remediation the CLI attaches to its own errors and findings.
38
39
  * Constructors live here rather than in any library the CLI calls: naming a
@@ -2542,10 +2543,7 @@ var ControlClientImpl = class {
2542
2543
  meta: void 0
2543
2544
  });
2544
2545
  }
2545
- const result = await emit(deserializedContract, this.stack, this.options.family.emission, {
2546
- serializeContract: (contract) => this.options.target.contractSerializer.serializeContract(contract),
2547
- ...ifDefined("supportsNamespaces", this.options.target.supportsNamespaces)
2548
- });
2546
+ const result = await this.emitArtifacts(deserializedContract, keepInternalSpecifiers);
2549
2547
  onProgress?.({
2550
2548
  action: "emit",
2551
2549
  kind: "spanEnd",
@@ -2574,6 +2572,39 @@ var ControlClientImpl = class {
2574
2572
  });
2575
2573
  }
2576
2574
  }
2575
+ async renderContractDts(options) {
2576
+ this.init();
2577
+ if (!this.familyInstance) throw new InternalError("Family instance was not initialized. This is a bug.");
2578
+ let contract;
2579
+ try {
2580
+ contract = this.familyInstance.deserializeContract(options.contract);
2581
+ } catch (error) {
2582
+ return notOk({
2583
+ code: "CONTRACT_VALIDATION_FAILED",
2584
+ summary: "Contract validation failed",
2585
+ why: error instanceof Error ? error.message : String(error),
2586
+ cause: error
2587
+ });
2588
+ }
2589
+ try {
2590
+ const { contractDts } = await this.emitArtifacts(contract, options.resolveImportSpecifier ?? keepInternalSpecifiers);
2591
+ return ok({ contractDts });
2592
+ } catch (error) {
2593
+ return notOk({
2594
+ code: "RENDER_FAILED",
2595
+ summary: "Failed to render contract types",
2596
+ why: error instanceof Error ? error.message : String(error),
2597
+ cause: error
2598
+ });
2599
+ }
2600
+ }
2601
+ emitArtifacts(contract, resolveImportSpecifier) {
2602
+ return emit(contract, this.stack, this.options.family.emission, {
2603
+ serializeContract: (c) => this.options.target.contractSerializer.serializeContract(c),
2604
+ resolveImportSpecifier,
2605
+ ...ifDefined("supportsNamespaces", this.options.target.supportsNamespaces)
2606
+ });
2607
+ }
2577
2608
  };
2578
2609
  /**
2579
2610
  * Per-output FIFO queue for `executeContractEmit`.
@@ -2662,7 +2693,10 @@ function nearestManifest(from) {
2662
2693
  fix: `Make \`${path}\` a JSON object with the usual manifest fields, then re-run the command. Emission reads it to decide which package names generated files should import.`,
2663
2694
  meta: { path }
2664
2695
  });
2665
- return parsed;
2696
+ return {
2697
+ manifest: parsed,
2698
+ path
2699
+ };
2666
2700
  }
2667
2701
  }
2668
2702
  function declaredDependencies(manifest) {
@@ -2680,9 +2714,19 @@ function declaredDependencies(manifest) {
2680
2714
  * project that has not moved to published names is unaffected.
2681
2715
  */
2682
2716
  function projectImportRoot(configPath) {
2683
- const manifest = nearestManifest(configPath === void 0 ? resolve(".") : dirname(resolve(configPath)));
2684
- if (manifest === void 0) return internalImportRoot;
2685
- return importRootForDependencies(declaredDependencies(manifest));
2717
+ const nearest = nearestManifest(configPath === void 0 ? resolve(".") : dirname(resolve(configPath)));
2718
+ if (nearest === void 0) return internalImportRoot;
2719
+ try {
2720
+ return importRootForDependencies(declaredDependencies(nearest.manifest));
2721
+ } catch (cause) {
2722
+ if (!(cause instanceof ImportRootError)) throw cause;
2723
+ throw errorRuntime("CLI.PROJECT_MANIFEST_INVALID", `Failed to read ${nearest.path}`, {
2724
+ why: `\`${nearest.path}\` states dependencies emission cannot import from: ${cause.message}.`,
2725
+ fix: `Keep one database facade in \`${nearest.path}\`, then re-run the command. Emission reads it to decide which package names generated files should import.`,
2726
+ meta: { path: nearest.path },
2727
+ cause
2728
+ });
2729
+ }
2686
2730
  }
2687
2731
  /** The specifier resolver emission should use for the project owning `configPath`. */
2688
2732
  function createProjectSpecifierResolver(configPath) {
@@ -2983,47 +3027,54 @@ async function executeContractEmit(options, dependencies = defaultContractEmitDe
2983
3027
  };
2984
3028
  });
2985
3029
  }
3030
+ const NO_REF_ADVANCEMENT = {
3031
+ advancedRef: null,
3032
+ plannedAdvanceRef: null
3033
+ };
2986
3034
  function computeRefAdvancementName(options) {
2987
3035
  if (options.advanceRef !== void 0) return options.advanceRef;
2988
3036
  if (options.db === void 0) return "db";
2989
3037
  return null;
2990
3038
  }
2991
- function contractDtsPathOf(contractJsonPath) {
2992
- return contractJsonPath.replace(/\.json$/i, ".d.ts");
2993
- }
2994
- async function readContractIR(contractJson, contractJsonPath) {
2995
- return {
2996
- contract: contractJson,
2997
- contractDts: await readFile(contractDtsPathOf(contractJsonPath), "utf-8")
2998
- };
2999
- }
3000
- function fsErrorCodeOf(error) {
3001
- const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
3002
- return typeof code === "string" ? code : void 0;
3003
- }
3004
- function errorUnreadableContractDts(contractJsonPath, cause) {
3005
- const contractDtsPath = contractDtsPathOf(contractJsonPath);
3006
- const code = fsErrorCodeOf(cause);
3007
- return errorFileNotFound(contractDtsPath, {
3008
- why: code === "ENOENT" ? `The contract types next to ${contractJsonPath} are missing: ${contractDtsPath}` : `The contract types next to ${contractJsonPath} could not be read${code === void 0 ? "" : ` (${code})`}: ${contractDtsPath}`,
3009
- fix: "Run {bin} contract emit to regenerate the contract artifacts, then advance the ref again.",
3010
- cause
3039
+ function errorContractDtsRenderFailed(contractJsonPath, failure) {
3040
+ const why = failure.why ?? failure.summary;
3041
+ if (failure.code === "CONTRACT_VALIDATION_FAILED") return errorContractValidationFailed(`Contract at ${contractJsonPath} failed to deserialize: ${why}`, {
3042
+ where: { path: contractJsonPath },
3043
+ ...ifDefined("cause", failure.cause)
3044
+ });
3045
+ return new CliStructuredError$1("CONTRACT.TYPES_RENDER_FAILED", "Failed to render contract types", {
3046
+ why: `The types for the contract at ${contractJsonPath} could not be rendered: ${why}`,
3047
+ fix: "Run {bin} contract emit to see why the contract does not emit, fix it, then advance the ref again.",
3048
+ where: { path: contractJsonPath },
3049
+ ...ifDefined("cause", failure.cause)
3011
3050
  });
3012
3051
  }
3013
3052
  /**
3014
- * Everything `advanceRefSafely` needs from disk, loaded before a command does
3015
- * the work that precedes the ref write: the ref name is validated and the
3016
- * sibling `.d.ts` of the contract to snapshot is read. The returned
3017
- * `ContractIR` is what the command then hands to `advanceRefSafely`, so no
3018
- * file is read after the database is signed.
3053
+ * Everything `executeRefAdvancement` needs, produced before a command does the
3054
+ * work that precedes the ref write: the ref name is validated and the
3055
+ * declarations of the contract to snapshot are rendered from its JSON, with
3056
+ * the import names the project owning `configPath` can resolve. Nothing is
3057
+ * read or rendered after the database is touched, so a contract that cannot
3058
+ * be snapshotted refuses the command before it changes anything.
3019
3059
  */
3020
3060
  async function preflightRefAdvancement(args) {
3021
3061
  if (!validateRefName(args.name)) return notOk(errorInvalidRefName(args.name));
3062
+ let resolveImportSpecifier;
3022
3063
  try {
3023
- return ok(await readContractIR(args.contractJson, args.contractJsonPath));
3064
+ resolveImportSpecifier = createProjectSpecifierResolver(args.configPath);
3024
3065
  } catch (error) {
3025
- return notOk(errorUnreadableContractDts(args.contractJsonPath, error));
3066
+ if (CliStructuredError$1.is(error)) return notOk(error);
3067
+ throw error;
3026
3068
  }
3069
+ const rendered = await args.client.renderContractDts({
3070
+ contract: args.contractJson,
3071
+ resolveImportSpecifier
3072
+ });
3073
+ if (!rendered.ok) return notOk(errorContractDtsRenderFailed(args.contractJsonPath, rendered.failure));
3074
+ return ok({
3075
+ contract: args.contractJson,
3076
+ contractDts: rendered.value.contractDts
3077
+ });
3027
3078
  }
3028
3079
  async function executeRefAdvancement(refsDir, migrationsDir, name, hash, contractIR) {
3029
3080
  if (!validateRefName(name)) throw errorInvalidRefName(name);
@@ -3040,55 +3091,31 @@ async function executeRefAdvancement(refsDir, migrationsDir, name, hash, contrac
3040
3091
  hash
3041
3092
  };
3042
3093
  }
3094
+ /**
3095
+ * The ref-advancement tail of db init / db update, run after the database
3096
+ * work with the `ContractIR` that `preflightRefAdvancement` produced before
3097
+ * it. Plan mode reports the ref that an apply would advance without writing.
3098
+ */
3043
3099
  async function buildRefAdvancementFields(options) {
3044
- const name = computeRefAdvancementName({
3045
- ...ifDefined("advanceRef", options.advanceRef),
3046
- ...ifDefined("db", options.db)
3047
- });
3048
- if (name === null) return {
3049
- advancedRef: null,
3050
- plannedAdvanceRef: null
3051
- };
3052
- if (options.mode === "plan") return {
3100
+ if (options.mode === "plan") return ok({
3053
3101
  advancedRef: null,
3054
3102
  plannedAdvanceRef: {
3055
- name,
3103
+ name: options.name,
3056
3104
  hash: options.hash
3057
3105
  }
3058
- };
3059
- return {
3060
- advancedRef: await executeRefAdvancement(options.refsDir, options.migrationsDir, name, options.hash, options.contractIR),
3061
- plannedAdvanceRef: null
3062
- };
3063
- }
3064
- /**
3065
- * Full ref-advancement phase for db init/update: ok({advancedRef:null, plannedAdvanceRef:null})
3066
- * when computeRefAdvancementName is null; else readContractIR + buildRefAdvancementFields with
3067
- * MigrationToolsError mapped, other errors rethrown.
3068
- */
3069
- async function resolveRefAdvancementFields(options) {
3070
- if (computeRefAdvancementName({
3071
- ...ifDefined("advanceRef", options.advanceRef),
3072
- ...ifDefined("db", options.db)
3073
- }) === null) return ok({
3074
- advancedRef: null,
3106
+ });
3107
+ const advanced = await advanceRefSafely({
3108
+ refsDir: options.refsDir,
3109
+ migrationsDir: options.migrationsDir,
3110
+ name: options.name,
3111
+ hash: options.hash,
3112
+ contractIR: options.contractIR
3113
+ });
3114
+ if (!advanced.ok) return advanced;
3115
+ return ok({
3116
+ advancedRef: advanced.value,
3075
3117
  plannedAdvanceRef: null
3076
3118
  });
3077
- try {
3078
- const contractIR = await readContractIR(options.contractJson, options.contractJsonPath);
3079
- return ok(await buildRefAdvancementFields({
3080
- ...ifDefined("advanceRef", options.advanceRef),
3081
- ...ifDefined("db", options.db),
3082
- refsDir: options.refsDir,
3083
- migrationsDir: options.migrationsDir,
3084
- contractIR,
3085
- mode: options.mode,
3086
- hash: options.hash
3087
- }));
3088
- } catch (error) {
3089
- if (MigrationToolsError.is(error)) return notOk(error);
3090
- throw error;
3091
- }
3092
3119
  }
3093
3120
  /**
3094
3121
  * The --advance-ref tail of migrate and db sign: executeRefAdvancement with
@@ -4784,6 +4811,6 @@ async function executeRefListCommand(options) {
4784
4811
  }
4785
4812
  }
4786
4813
  //#endregion
4787
- export { loadAggregateIntegrityViolations as $, errorMigrationPackageNotFound as A, runMigrationList as At, executeDbInit as B, errorDatabaseConnectionRequired as C, resolveFromForPlan as Ct, errorHashMismatch as D, runCommandAction as Dt, errorFileNotFound as E, resolveToForPlan as Et, errorRuntime as F, executeMigrationPlanCommand as G, executeDbVerify as H, errorTargetMigrationNotSupported as I, executeRefListCommand as J, executeRefAdvancement as K, errorTargetMismatch as L, errorNoMigrations as M, statusForMigrationHash as Mt, errorPathUnreachable as N, targetSupportsMigrations as Nt, errorLegendHumanOnly as O, runContractSpaceSeedPhase as Ot, errorRunnerFailed as P, toDeclaredExtensionsFromRaw as Pt, listRefsByContractHash as Q, errorUnexpected as R, errorContractValidationFailed as S, resolveContractRefToSnapshot as St, errorDriverRequired as T, resolveRefAdvancementFields as Tt, executeMigrateShowPlan as U, executeDbUpdate as V, executeMigrationNewCommand as W, findPackageByDirPath as X, executeRefSetCommand as Y, hasMigrationPath as Z, enumerateCheckSpaces as _, refusePackageCorruptionOnAggregate as _t, buildContractSpaceAggregate as a, mapIntegrityViolations as at, errorConsentPlanMismatch as b, resolveAppTargetPath as bt, buildRefAdvancementFields as c, originHashForStatus as ct, closeQuietly as d, readContractIR as dt, loadContractRawSafely as et, computeRefAdvancementName as f, readMigrationRefs as ft, enrichContract as g, refuseMissingInvariantPath as gt, disposeEmitQueue as h, refuseMarkerOutsideGraph as ht, appliedHashesFromLedger as i, mapContractAtError as it, errorMigrationPlanningFailed as j, sanitizeErrorMessage as jt, errorMarkerMissing as k, runMigrationCheck as kt, checkSingleTarget as l, preflightRefAdvancement as lt, deriveStatusEdgeAnnotations as m, refuseDeclaredExtensionTargetMismatch as mt, advanceRefSafely as n, looksLikePath as nt, buildMigrationSpaceGraphEntries as o, maskConnectionUrl as ot, createControlClient as p, refuseContractSpaceIntegrity as pt, executeRefDeleteCommand as q, appContractStandInFromIdentity as r, mapCaughtMigrationError as rt, buildReadAggregate as s, migrationSpaceListEntriesFromAggregate as st, CliStructuredError$1 as t, loadContractSpaceAggregateForCli as tt, chooseAction as u, readContractEnvelope as ut, errorAdvanceRefArgConflict as v, refuseUnknownInvariants as vt, errorDestructiveChanges as w, resolveMigrationRef as wt, errorContractArgConflict as x, resolveContractRef$1 as xt, errorConfigValidation$1 as y, requireLiveDatabase as yt, executeContractEmit as z };
4814
+ export { listRefsByContractHash as $, errorMarkerMissing as A, sanitizeErrorMessage as At, executeContractEmit as B, errorContractValidationFailed as C, resolveFromForPlan as Ct, errorFileNotFound as D, runContractSpaceSeedPhase as Dt, errorDriverRequired as E, runCommandAction as Et, errorRunnerFailed as F, executeMigrationNewCommand as G, executeDbUpdate as H, errorRuntime as I, executeRefDeleteCommand as J, executeMigrationPlanCommand as K, errorTargetMigrationNotSupported as L, errorMigrationPlanningFailed as M, targetSupportsMigrations as Mt, errorNoMigrations as N, toDeclaredExtensionsFromRaw as Nt, errorHashMismatch as O, runMigrationCheck as Ot, errorPathUnreachable as P, hasMigrationPath as Q, errorTargetMismatch as R, errorContractArgConflict as S, resolveContractRefToSnapshot as St, errorDestructiveChanges as T, resolveToForPlan as Tt, executeDbVerify as U, executeDbInit as V, executeMigrateShowPlan as W, executeRefSetCommand as X, executeRefListCommand as Y, findPackageByDirPath as Z, enrichContract as _, refusePackageCorruptionOnAggregate as _t, appliedHashesFromLedger as a, mapContractAtError as at, errorConfigValidation$1 as b, resolveAppTargetPath as bt, buildReadAggregate as c, migrationSpaceListEntriesFromAggregate as ct, chooseAction as d, readContractEnvelope as dt, loadAggregateIntegrityViolations as et, closeQuietly as f, readMigrationRefs as ft, disposeEmitQueue as g, refuseMissingInvariantPath as gt, deriveStatusEdgeAnnotations as h, refuseMarkerOutsideGraph as ht, appContractStandInFromIdentity as i, mapCaughtMigrationError as it, errorMigrationPackageNotFound as j, statusForMigrationHash as jt, errorLegendHumanOnly as k, runMigrationList as kt, buildRefAdvancementFields as l, originHashForStatus as lt, createControlClient as m, refuseDeclaredExtensionTargetMismatch as mt, NO_REF_ADVANCEMENT as n, loadContractSpaceAggregateForCli as nt, buildContractSpaceAggregate as o, mapIntegrityViolations as ot, computeRefAdvancementName as p, refuseContractSpaceIntegrity as pt, executeRefAdvancement as q, advanceRefSafely as r, looksLikePath as rt, buildMigrationSpaceGraphEntries as s, maskConnectionUrl as st, CliStructuredError$1 as t, loadContractRawSafely as tt, checkSingleTarget as u, preflightRefAdvancement as ut, enumerateCheckSpaces as v, refuseUnknownInvariants as vt, errorDatabaseConnectionRequired as w, resolveMigrationRef as wt, errorConsentPlanMismatch as x, resolveContractRef$1 as xt, errorAdvanceRefArgConflict as y, requireLiveDatabase as yt, errorUnexpected as z };
4788
4815
 
4789
- //# sourceMappingURL=ref-DcqFmceq-QaUjgZeM.mjs.map
4816
+ //# sourceMappingURL=ref-uqvZQnnQ-DpAQaLiM.mjs.map