@prisma/orm-toolchain 8.0.0-rc.11-dev.51 → 8.0.0-rc.11-dev.52

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,11 +5,11 @@ import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
5
5
  import { r as readRef } from "./refs-S0wu2JkI-BbFdehLe.mjs";
6
6
  import { c as spaceMigrationDirectory } from "./verify-contract-spaces-BLkC9r9l-CJIppNL8.mjs";
7
7
  import { i as createScaffoldSpecifierResolver } from "./import-roots-CYGb9VeC.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, Ft as toDeclaredExtensionsFromRaw, G as executeMigrateShowPlan, I as errorRunnerFailed, K as executeMigrationNewCommand, L as errorRuntime, M as errorMigrationPackageNotFound, Mt as snapshotVerifierFor, N as errorMigrationPlanningFailed, Nt as statusForMigrationHash, O as errorFileNotFound, P as errorNoMigrations, Pt as targetSupportsMigrations, 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-g7LrevBG-DgO9ywms.mjs";
9
- import { n as buildNextSteps, t as InitOutputSchema } from "./output-D83nTTpC-XlvN30yS.mjs";
10
- import { r as loadConfig, t as finalizeConfig } from "./exports-DJ4RhlW4.mjs";
8
+ import { $ as formatSourceDiagnostic, A as errorLegendHumanOnly, B as errorUnexpected, C as errorContractArgConflict, Ct as resolveAppTargetPath, D as errorDriverRequired, Dt as resolveMigrationRef, E as errorDestructiveChanges, F as errorPathUnreachable, Ft as statusForMigrationHash, G as executeMigrateShowPlan, I as errorRunnerFailed, It as targetSupportsMigrations, K as executeMigrationNewCommand, L as errorRuntime, Lt as toDeclaredExtensionsFromRaw, M as errorMigrationPackageNotFound, Mt as runMigrationList, N as errorMigrationPlanningFailed, Nt as sanitizeErrorMessage, O as errorFileNotFound, P as errorNoMigrations, Pt as snapshotVerifierFor, Q as findPackageByDirPath, R as errorTargetMigrationNotSupported, S as errorConsentPlanMismatch, St as requireLiveDatabase, T as errorDatabaseConnectionRequired, Tt as resolveContractRefToSnapshot, V as executeContractEmit, X as executeRefListCommand, Y as executeRefDeleteCommand, Z as executeRefSetCommand, at as loadContractSpaceAggregateForCli, b as errorAdvanceRefArgConflict, bt as refusePackageCorruptionOnAggregate, c as buildMigrationSpaceGraphEntries, ct as mapContractAtError, d as checkSingleTarget, dt as migrationSpaceListEntriesFromAggregate, et as hasMigrationPath, f as chooseAction, ft as originHashForStatus, g as deriveStatusEdgeAnnotations, gt as refuseContractSpaceIntegrity, h as createControlClient, ht as readMigrationRefs, i as advanceRefSafely, it as loadContractSource, j as errorMarkerMissing, jt as runMigrationCheck, k as errorHashMismatch, kt as runCommandAction, l as buildReadAggregate, m as computeRefAdvancementName, mt as readContractEnvelope, n as ERROR_CODE_DESTRUCTIVE_CHANGES, nt as loadAggregateIntegrityViolations, o as appliedHashesFromLedger, ot as looksLikePath, p as closeQuietly, pt as preflightRefAdvancement, q as executeMigrationPlanCommand, r as NO_REF_ADVANCEMENT, rt as loadContractRawSafely, st as mapCaughtMigrationError, t as CliStructuredError$1$1, tt as listRefsByContractHash, u as buildRefAdvancementFields, ut as maskConnectionUrl, vt as refuseMarkerOutsideGraph, w as errorContractValidationFailed, wt as resolveContractRef$1, x as errorConfigValidation$1, xt as refuseUnknownInvariants, y as enumerateCheckSpaces, yt as refuseMissingInvariantPath, z as errorTargetMismatch } from "./ref-DL4C2p9T-BVsb1HWR.mjs";
9
+ 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";
10
+ import { a as loadConfig, c as requireConfigSections, n as evaluateConfigModule, r as finalizeConfig, t as buildLoadedConfig } from "./exports-ClG6amXs.mjs";
11
11
  import { createRequire } from "node:module";
12
- import { existsSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
12
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
13
13
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
14
14
  import { DOCS_BASE, docsUrlFor, isStructuredError, isStructuredErrorCode } from "@prisma/orm-framework/utils/structured-error";
15
15
  import { keepInternalSpecifiers } from "@prisma/orm-framework/components/emission";
@@ -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-Dp-sLUaI.mjs
39
+ //#region ../../../1-framework/3-tooling/cli/dist/load-config-Dzvm7YPm.mjs
40
40
  const MISSING_CONFIG_ACTION = {
41
41
  kind: "run-command",
42
42
  label: "Create a config file",
@@ -94,7 +94,7 @@ function unreadableDiagnostic(error) {
94
94
  }]
95
95
  };
96
96
  }
97
- function isRecord$1(value) {
97
+ function isRecord$4(value) {
98
98
  return typeof value === "object" && value !== null && !Array.isArray(value);
99
99
  }
100
100
  /**
@@ -104,10 +104,10 @@ function isRecord$1(value) {
104
104
  */
105
105
  function collectArtifactCollisionIssues(raw) {
106
106
  const contract = raw["contract"];
107
- if (!isRecord$1(contract)) return [];
107
+ if (!isRecord$4(contract)) return [];
108
108
  const source = contract["source"];
109
109
  const output = contract["output"];
110
- if (!isRecord$1(source) || typeof output !== "string") return [];
110
+ if (!isRecord$4(source) || typeof output !== "string") return [];
111
111
  const inputs = source["inputs"];
112
112
  if (!Array.isArray(inputs)) return [];
113
113
  let emitted;
@@ -133,7 +133,7 @@ function validate(raw) {
133
133
  ok: false,
134
134
  diagnostics: [sectionAbsentDiagnostic()]
135
135
  };
136
- if (!isRecord$1(raw)) return {
136
+ if (!isRecord$4(raw)) return {
137
137
  ok: false,
138
138
  diagnostics: [notAnObjectDiagnostic()]
139
139
  };
@@ -253,7 +253,7 @@ function normalizeError(error) {
253
253
  * Prisma ORM rather than something the user did. Re-throwing lets the engine settle it as a bug
254
254
  * at exit 1, where converting it would report the same number as a bad connection string.
255
255
  */
256
- function isRecord(value) {
256
+ function isRecord$3(value) {
257
257
  return typeof value === "object" && value !== null && !Array.isArray(value);
258
258
  }
259
259
  /**
@@ -273,7 +273,7 @@ function isRecord(value) {
273
273
  * so a config that arrived finalized passes through unchanged.
274
274
  */
275
275
  function finalizedConfigContext(ctx) {
276
- if (!isRecord(ctx.config)) return ctx;
276
+ if (!isRecord$3(ctx.config)) return ctx;
277
277
  const config = blindCast(ctx.config);
278
278
  return {
279
279
  ...ctx,
@@ -2808,11 +2808,15 @@ function errorInitMissingFlags(options) {
2808
2808
  default: return `--${flag} <value>`;
2809
2809
  }
2810
2810
  }).join(" ");
2811
+ const prisma7 = options.prisma7SchemaPath === void 0 ? "" : ` This looks like a Prisma 7 project; to use ${options.prisma7SchemaPath} as the contract source instead, pass \`--from-prisma7-schema ${options.prisma7SchemaPath}\`.`;
2811
2812
  return new CliStructuredError$1$1("CLI.INIT_MISSING_FLAGS", "Missing required flags", {
2812
- why: `${options.why} Missing required flag(s): ${flagList}.`,
2813
+ why: `${options.why} Missing required flag(s): ${flagList}.${prisma7}`,
2813
2814
  fix: `Re-run with the missing flag(s) supplied, e.g. \`prisma orm init --yes ${fixList}\`. Use \`prisma orm init --help\` to see every flag.`,
2814
2815
  docsUrl: docsUrlFor("CLI.INIT_MISSING_FLAGS"),
2815
- meta: { missingFlags: options.missing }
2816
+ meta: {
2817
+ missingFlags: options.missing,
2818
+ prisma7SchemaPath: options.prisma7SchemaPath ?? null
2819
+ }
2816
2820
  });
2817
2821
  }
2818
2822
  /**
@@ -2958,18 +2962,353 @@ function errorInitProbeFailed(options) {
2958
2962
  * about the directory the user can fix.
2959
2963
  */
2960
2964
  function errorInitWriteFailed(options) {
2965
+ const renamed = options.filesRenamed.map((entry) => `${entry.from} → ${entry.to}`);
2966
+ const renamedNote = renamed.length === 0 ? "" : ` Before the failure this run renamed ${renamed.join(", ")}; that rename stays, and a re-run writes the missing files beside it.`;
2961
2967
  return new CliStructuredError$1$1("CLI.INIT_WRITE_FAILED", `Failed to write ${options.path}`, {
2962
- why: `\`${options.path}\` could not be written: ${options.cause}`,
2968
+ why: `\`${options.path}\` could not be written: ${options.cause}${renamedNote}`,
2963
2969
  fix: "Fix what stopped the write — a directory sitting where the file goes, permissions, a full disk — then run `prisma orm init` again. Interactive runs ask before replacing the files this run already wrote (listed in `meta.filesWritten`); non-interactive runs grant that consent with `--confirm <directory name>`.",
2964
2970
  docsUrl: docsUrlFor("CLI.INIT_WRITE_FAILED"),
2965
2971
  meta: {
2966
2972
  path: options.path,
2967
2973
  cause: options.cause,
2968
- filesWritten: options.filesWritten
2974
+ filesWritten: options.filesWritten,
2975
+ filesRenamed: options.filesRenamed
2976
+ }
2977
+ });
2978
+ }
2979
+ /**
2980
+ * Two flags were given that ask for different things: `--from-prisma7-schema`
2981
+ * names an existing schema as the contract source, while `--schema-path` and
2982
+ * `--authoring` describe a starter schema to write. Raised before anything is
2983
+ * read or written.
2984
+ */
2985
+ function errorInitFlagConflict(options) {
2986
+ const [first, second] = options.flags;
2987
+ return new CliStructuredError$1$1("CLI.INIT_FLAG_CONFLICT", "Conflicting flags", {
2988
+ why: `\`--${first}\` and \`--${second}\` cannot be combined: the first reads an existing schema as the contract source, the second describes a starter schema to write.`,
2989
+ fix: `Pass one or the other. Use \`--${first}\` to adopt an existing Prisma 7 schema, or \`--${second}\` to scaffold a new one.`,
2990
+ docsUrl: docsUrlFor("CLI.INIT_FLAG_CONFLICT"),
2991
+ meta: { flags: [first, second] }
2992
+ });
2993
+ }
2994
+ const PRISMA7_SUPPORTED_PROVIDERS = ["postgresql", "mongodb"];
2995
+ /**
2996
+ * The Prisma 7 schema's provider is one Prisma 8 has no target for, or is not
2997
+ * a string literal and no `--target` names the database instead.
2998
+ */
2999
+ function errorInitPrisma7ProviderUnsupported(options) {
3000
+ const declared = options.provider === void 0 ? "no string provider" : `\`provider = "${options.provider}"\``;
3001
+ const fix = options.provider === void 0 ? "Pass `--target` to name the database, or run `prisma orm init` without `--from-prisma7-schema` to start a fresh Prisma 8 contract." : "Run `prisma orm init` without `--from-prisma7-schema` to start a fresh Prisma 8 contract.";
3002
+ return new CliStructuredError$1$1("CLI.INIT_PRISMA7_PROVIDER_UNSUPPORTED", "Unsupported Prisma 7 datasource provider", {
3003
+ why: `\`${options.schemaPath}\` declares ${declared}. Prisma 8 supports: ${PRISMA7_SUPPORTED_PROVIDERS.join(", ")}.`,
3004
+ fix,
3005
+ docsUrl: docsUrlFor("CLI.INIT_PRISMA7_PROVIDER_UNSUPPORTED"),
3006
+ meta: {
3007
+ schemaPath: options.schemaPath,
3008
+ provider: options.provider ?? null,
3009
+ supported: [...PRISMA7_SUPPORTED_PROVIDERS]
3010
+ }
3011
+ });
3012
+ }
3013
+ /** `--target` names a different database than the Prisma 7 schema's provider. */
3014
+ function errorInitPrisma7TargetMismatch(options) {
3015
+ return new CliStructuredError$1$1("CLI.INIT_PRISMA7_TARGET_MISMATCH", "--target does not match the Prisma 7 schema", {
3016
+ why: `\`--target ${options.target}\` does not match \`${options.schemaPath}\`, which declares \`provider = "${options.provider}"\`.`,
3017
+ fix: "Drop `--target` to use the database the schema declares, or run `prisma orm init` without `--from-prisma7-schema` to start a fresh Prisma 8 contract.",
3018
+ docsUrl: docsUrlFor("CLI.INIT_PRISMA7_TARGET_MISMATCH"),
3019
+ meta: {
3020
+ schemaPath: options.schemaPath,
3021
+ provider: options.provider,
3022
+ target: options.target
3023
+ }
3024
+ });
3025
+ }
3026
+ /** The path given as a Prisma 7 schema does not exist or has no `datasource` block. */
3027
+ function errorInitPrisma7SchemaInvalid(options) {
3028
+ return new CliStructuredError$1$1("CLI.INIT_PRISMA7_SCHEMA_INVALID", "Not a Prisma 7 schema", {
3029
+ why: options.reason === "absent" ? `\`${options.schemaPath}\` does not exist.` : `\`${options.schemaPath}\` has no \`datasource\` block, so it is not a Prisma 7 schema.`,
3030
+ fix: "Point `--from-prisma7-schema` at the `schema.prisma` file (or schema directory) whose `datasource` block names your database, or run `prisma orm init` without it.",
3031
+ docsUrl: docsUrlFor("CLI.INIT_PRISMA7_SCHEMA_INVALID"),
3032
+ meta: {
3033
+ schemaPath: options.schemaPath,
3034
+ reason: options.reason
3035
+ }
3036
+ });
3037
+ }
3038
+ /**
3039
+ * A Prisma 7 `prisma.config.*` sits beside a `prisma7.config.*`, so neither can be renamed onto the
3040
+ * other.
3041
+ */
3042
+ function errorInitPrisma7ConfigCollision(options) {
3043
+ return new CliStructuredError$1$1("CLI.INIT_PRISMA7_CONFIG_COLLISION", "Two Prisma 7 config files", {
3044
+ why: `\`${options.prismaConfigPath}\` is a Prisma 7 config and \`${options.prisma7ConfigPath}\` already exists. Init renames the Prisma 7 config to \`prisma7.config.*\` so Prisma 8 can write its own, and cannot rename onto an existing file.`,
3045
+ fix: `Keep one of them: delete \`${options.prisma7ConfigPath}\` if \`${options.prismaConfigPath}\` is the config Prisma 7 should use, or delete \`${options.prismaConfigPath}\` if the move to \`${options.prisma7ConfigPath}\` is already done. Then re-run \`prisma orm init\`.`,
3046
+ docsUrl: docsUrlFor("CLI.INIT_PRISMA7_CONFIG_COLLISION"),
3047
+ meta: {
3048
+ prismaConfigPath: options.prismaConfigPath,
3049
+ prisma7ConfigPath: options.prisma7ConfigPath
2969
3050
  }
2970
3051
  });
2971
3052
  }
2972
3053
  /**
3054
+ * `prisma.config.*` exists but did not evaluate, so init cannot tell whether
3055
+ * it is Prisma 7's (to rename) or its own (to replace). Refused rather than
3056
+ * guessed: replacing a Prisma 7 config would destroy the user's file.
3057
+ */
3058
+ function errorInitPrisma7ConfigUnreadable(options) {
3059
+ const extension = options.path.slice(options.path.lastIndexOf(".") + 1);
3060
+ const versioned = options.prisma7ConfigPath;
3061
+ const why = versioned === void 0 ? `\`${options.path}\` failed to evaluate, so init cannot tell whether it is a Prisma 7 config to rename or a Prisma 8 config to replace: ${options.why}` : `\`${options.path}\` failed to evaluate: ${options.why}. \`${versioned}\` already exists, so init leaves \`${options.path}\` alone.`;
3062
+ const fix = versioned === void 0 ? `Install the project's dependencies so \`${options.path}\` can be evaluated (a Prisma 7 config imports \`prisma/config\`), or rename it to \`prisma7.config.${extension}\` by hand, then re-run \`prisma orm init\`.` : `Install the project's dependencies and fix the error in \`${options.path}\` (a missing export usually means the package it imports from needs updating), then re-run \`prisma orm init\`.`;
3063
+ return new CliStructuredError$1$1("CLI.INIT_PRISMA7_CONFIG_UNREADABLE", `Could not evaluate ${options.path}`, {
3064
+ why,
3065
+ fix,
3066
+ docsUrl: docsUrlFor("CLI.INIT_PRISMA7_CONFIG_UNREADABLE"),
3067
+ meta: {
3068
+ path: options.path,
3069
+ why: options.why,
3070
+ prisma7ConfigPath: versioned ?? null
3071
+ }
3072
+ });
3073
+ }
3074
+ /** The next action that tells the user how to undo what the Prisma 7 check installed. */
3075
+ function packagesAddedAction(added) {
3076
+ const pronoun = added.packages.length === 1 ? "it" : "them";
3077
+ return `init added ${added.packages.join(" and ")} to package.json before checking; remove ${pronoun} with \`${added.removeCommand}\`.`;
3078
+ }
3079
+ function packagesAddedNote(added) {
3080
+ return added === void 0 ? "" : `\n${packagesAddedAction(added)}`;
3081
+ }
3082
+ /**
3083
+ * The target package init loads to read the Prisma 7 schema cannot be loaded
3084
+ * from the project, or it has no Prisma 7 contract source while
3085
+ * `--from-prisma7-schema` asked for one.
3086
+ */
3087
+ function errorInitPrisma7SourceUnavailable(options) {
3088
+ const { packageName, schemaPath } = options;
3089
+ const wording = options.reason === "not-resolvable" ? {
3090
+ summary: `Could not load ${packageName} from the project`,
3091
+ why: `${packageName} was installed but could not be loaded from the project, so init cannot check that Prisma 8 reads ${schemaPath}.`,
3092
+ fix: `Check that ${packageName} is installed and resolves from this directory (Yarn Plug'n'Play hides packages from Node), then run \`prisma orm init\` again.`
3093
+ } : {
3094
+ summary: "No Prisma 7 contract source for this database",
3095
+ why: `${packageName} does not provide a Prisma 7 contract source, so it cannot read ${schemaPath}.`,
3096
+ fix: "Choose a database whose Prisma 8 package reads Prisma 7 schemas, or run `prisma orm init` without `--from-prisma7-schema`."
3097
+ };
3098
+ return new CliStructuredError$1$1("CLI.INIT_PRISMA7_SOURCE_UNAVAILABLE", wording.summary, {
3099
+ why: wording.why,
3100
+ fix: `${wording.fix}${packagesAddedNote(options.added)}`,
3101
+ docsUrl: docsUrlFor("CLI.INIT_PRISMA7_SOURCE_UNAVAILABLE"),
3102
+ meta: {
3103
+ schemaPath: options.schemaPath,
3104
+ packageName: options.packageName,
3105
+ reason: options.reason,
3106
+ packagesAdded: options.added?.packages ?? []
3107
+ }
3108
+ });
3109
+ }
3110
+ /**
3111
+ * The target package's Prisma 7 contract source refused the schema. Nothing but the check's install
3112
+ * happened.
3113
+ */
3114
+ function errorInitPrisma7SchemaRefused(options) {
3115
+ const findings = options.diagnostics.map((diagnostic) => `\n ${formatSourceDiagnostic(diagnostic)}`);
3116
+ return new CliStructuredError$1$1("CLI.INIT_PRISMA7_SCHEMA_REFUSED", `Prisma 8 cannot read ${options.schemaPath}`, {
3117
+ why: `${options.summary}${findings.join("")}`,
3118
+ fix: `Edit ${options.schemaPath} as each finding says (see the Prisma 7 contract source section of the ${options.packageName} README), or run \`prisma orm init\` without \`--from-prisma7-schema\`.${packagesAddedNote(options.added)}`,
3119
+ docsUrl: docsUrlFor("CLI.INIT_PRISMA7_SCHEMA_REFUSED"),
3120
+ meta: {
3121
+ schemaPath: options.schemaPath,
3122
+ summary: options.summary,
3123
+ diagnostics: options.diagnostics,
3124
+ packagesAdded: options.added?.packages ?? []
3125
+ }
3126
+ });
3127
+ }
3128
+ const PRISMA7_DEFAULT_SCHEMA_PATH = "prisma/schema.prisma";
3129
+ const CONFIG_EXTENSIONS = [
3130
+ "ts",
3131
+ "mts",
3132
+ "cts",
3133
+ "js",
3134
+ "mjs",
3135
+ "cjs"
3136
+ ];
3137
+ const PRISMA7_CLI_PACKAGE = "@prisma/prisma7";
3138
+ function isRecord$2(value) {
3139
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3140
+ }
3141
+ function findConfigFile(cwd, stem) {
3142
+ return CONFIG_EXTENSIONS.map((extension) => `${stem}.${extension}`).find((name) => existsSync(join(cwd, name)));
3143
+ }
3144
+ async function evaluateConfig(cwd, path) {
3145
+ const evaluated = await evaluateConfigModule(path, { cwd });
3146
+ if (!evaluated.ok) return {
3147
+ kind: "unreadable",
3148
+ why: evaluated.failure.why ?? evaluated.failure.message
3149
+ };
3150
+ const exported = evaluated.value;
3151
+ if (!isRecord$2(exported) || Object.hasOwn(exported, "__esModule")) return {
3152
+ kind: "unreadable",
3153
+ why: `${path} has no object default export`
3154
+ };
3155
+ if (exported["$prismaConfig"] !== void 0) return { kind: "prisma8" };
3156
+ const schema = exported["schema"];
3157
+ return {
3158
+ kind: "prisma7",
3159
+ schema: typeof schema === "string" ? schema : void 0
3160
+ };
3161
+ }
3162
+ async function schemaDeclaredBy(cwd, path) {
3163
+ if (path === void 0) return;
3164
+ const evaluated = await evaluateConfig(cwd, path);
3165
+ return evaluated.kind === "prisma7" ? evaluated.schema : void 0;
3166
+ }
3167
+ async function detectConfig(cwd) {
3168
+ const prismaConfigPath = findConfigFile(cwd, "prisma.config");
3169
+ const prisma7ConfigPath = findConfigFile(cwd, "prisma7.config");
3170
+ if (prismaConfigPath !== void 0) {
3171
+ const evaluated = await evaluateConfig(cwd, prismaConfigPath);
3172
+ if (evaluated.kind === "prisma7" && prisma7ConfigPath !== void 0) return {
3173
+ kind: "collision",
3174
+ prismaConfigPath,
3175
+ prisma7ConfigPath
3176
+ };
3177
+ if (evaluated.kind === "unreadable") return {
3178
+ ...evaluated,
3179
+ path: prismaConfigPath,
3180
+ prisma7ConfigPath,
3181
+ schema: await schemaDeclaredBy(cwd, prisma7ConfigPath)
3182
+ };
3183
+ if (evaluated.kind === "prisma7") return {
3184
+ ...evaluated,
3185
+ path: prismaConfigPath
3186
+ };
3187
+ if (prisma7ConfigPath === void 0) return {
3188
+ kind: "prisma8",
3189
+ path: prismaConfigPath
3190
+ };
3191
+ }
3192
+ if (prisma7ConfigPath === void 0) return { kind: "none" };
3193
+ const evaluated = await evaluateConfig(cwd, prisma7ConfigPath);
3194
+ if (evaluated.kind === "prisma8") return { kind: "none" };
3195
+ if (evaluated.kind === "unreadable") return {
3196
+ ...evaluated,
3197
+ path: prisma7ConfigPath,
3198
+ prisma7ConfigPath: void 0,
3199
+ schema: void 0
3200
+ };
3201
+ return {
3202
+ ...evaluated,
3203
+ path: prisma7ConfigPath
3204
+ };
3205
+ }
3206
+ function stripLineComments(text) {
3207
+ return text.replace(/\/\/[^\n]*/g, "");
3208
+ }
3209
+ function findProvider(text) {
3210
+ const block = /datasource\s+\w+\s*\{([^}]*)\}/.exec(stripLineComments(text));
3211
+ if (block === null) return;
3212
+ return { provider: /\bprovider\s*=\s*"([^"]*)"/.exec(block[1] ?? "")?.[1] };
3213
+ }
3214
+ function prismaFilesUnder(directory) {
3215
+ return readdirSync(directory, {
3216
+ withFileTypes: true,
3217
+ recursive: true
3218
+ }).filter((entry) => entry.isFile() && entry.name.endsWith(".prisma")).map((entry) => join(entry.parentPath, entry.name));
3219
+ }
3220
+ function detectSchema(cwd, path) {
3221
+ const absolute = resolve(cwd, path);
3222
+ if (!existsSync(absolute)) return {
3223
+ kind: "absent",
3224
+ path
3225
+ };
3226
+ const files = statSync(absolute).isDirectory() ? prismaFilesUnder(absolute) : [absolute];
3227
+ for (const file of files) {
3228
+ const found = findProvider(readFileSync(file, "utf-8"));
3229
+ if (found !== void 0) return {
3230
+ kind: "datasource",
3231
+ path,
3232
+ provider: found.provider
3233
+ };
3234
+ }
3235
+ return {
3236
+ kind: "no-datasource",
3237
+ path
3238
+ };
3239
+ }
3240
+ function readJsonRecord(path) {
3241
+ if (!existsSync(path)) return;
3242
+ try {
3243
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
3244
+ return isRecord$2(parsed) ? parsed : void 0;
3245
+ } catch {
3246
+ return;
3247
+ }
3248
+ }
3249
+ function declaredRange(manifest, name) {
3250
+ for (const field of ["devDependencies", "dependencies"]) {
3251
+ const section = manifest[field];
3252
+ const range = isRecord$2(section) ? section[name] : void 0;
3253
+ if (typeof range === "string") return range;
3254
+ }
3255
+ }
3256
+ function installedVersion(cwd, name) {
3257
+ const version = readJsonRecord(join(cwd, "node_modules", name, "package.json"))?.["version"];
3258
+ return typeof version === "string" ? version : void 0;
3259
+ }
3260
+ /** The major of a version or range (`^7.3.0`, `7.4.1`, `>=6`); `undefined` when it cannot be read. */
3261
+ function versionMajor(range) {
3262
+ const match = /^\s*[\^~>=<v]*\s*(\d+)(?:\.|$|\s|-)/.exec(range);
3263
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
3264
+ }
3265
+ function detectCli(cwd) {
3266
+ const manifest = readJsonRecord(join(cwd, "package.json"));
3267
+ if (manifest === void 0) return { kind: "none" };
3268
+ if (declaredRange(manifest, PRISMA7_CLI_PACKAGE) !== void 0) return { kind: "side-by-side" };
3269
+ const declared = declaredRange(manifest, "prisma");
3270
+ if (declared === void 0) return { kind: "none" };
3271
+ const installed = installedVersion(cwd, "prisma");
3272
+ const version = installed ?? declared;
3273
+ const major = versionMajor(version);
3274
+ if (major === void 0 || major >= 8) return { kind: "none" };
3275
+ const clientVersion = installedVersion(cwd, "@prisma/client") ?? declaredRange(manifest, "@prisma/client");
3276
+ return {
3277
+ kind: "earlier",
3278
+ version,
3279
+ major,
3280
+ source: installed === void 0 ? "declared" : "installed",
3281
+ clientVersion
3282
+ };
3283
+ }
3284
+ function warningsFor(config) {
3285
+ switch (config.kind) {
3286
+ case "unreadable": return [config.schema === void 0 ? `${config.path} could not be evaluated, so the default schema path is assumed: ${config.why}` : `${config.path} could not be evaluated, so the schema path is read from ${config.prisma7ConfigPath}: ${config.why}`];
3287
+ case "collision": return [`${config.prismaConfigPath} is a Prisma 7 config, but ${config.prisma7ConfigPath} already exists; init cannot rename one onto the other.`];
3288
+ default: return [];
3289
+ }
3290
+ }
3291
+ /**
3292
+ * Reads what `orm init` would otherwise ask for on a Prisma 7 project: the
3293
+ * schema path (the flag, else the Prisma 7 config's `schema`, else the Prisma 7
3294
+ * default), the provider of its `datasource` block, the config file an earlier
3295
+ * CLI reads, and the earlier `prisma` package the project declares. Reads text
3296
+ * and evaluates the user's config only; nothing is written and no Prisma 7
3297
+ * package is imported.
3298
+ */
3299
+ async function detectPrisma7Project(ctx) {
3300
+ const config = await detectConfig(ctx.cwd);
3301
+ const configSchema = config.kind === "prisma7" || config.kind === "unreadable" ? config.schema : void 0;
3302
+ const [path, schemaPathSource] = ctx.schemaPath !== void 0 ? [ctx.schemaPath, "flag"] : configSchema !== void 0 ? [configSchema, "config"] : [PRISMA7_DEFAULT_SCHEMA_PATH, "default"];
3303
+ return {
3304
+ config,
3305
+ schema: detectSchema(ctx.cwd, path),
3306
+ schemaPathSource,
3307
+ cli: detectCli(ctx.cwd),
3308
+ warnings: warningsFor(config)
3309
+ };
3310
+ }
3311
+ /**
2973
3312
  * Connects (when configured) to the user's database and returns a
2974
3313
  * structured outcome describing whether the server meets the declared
2975
3314
  * minimum (FR8.1). Pure with respect to its inputs: no I/O happens
@@ -3402,6 +3741,28 @@ export default definePrismaConfig({
3402
3741
  });
3403
3742
  `;
3404
3743
  }
3744
+ /**
3745
+ * The config for a project whose contract source is its Prisma 7 schema:
3746
+ * `prisma7Schema` beside `defineConfig`, from the same entrypoint, with the
3747
+ * schema path as the user gave it and the emitted artifacts under Prisma 8's
3748
+ * own directory (`output` is the directory; the facade names `contract.json`).
3749
+ */
3750
+ function prisma7ConfigFile(target, schemaPath, outputDir, resolveImportSpecifier = keepInternalSpecifiers) {
3751
+ return `import 'dotenv/config';
3752
+ import { definePrismaConfig } from '@prisma/cli-engine';
3753
+ import { defineConfig as ormConfig, prisma7Schema } from '${targetEntrypoint(target, "config", resolveImportSpecifier)}';
3754
+
3755
+ export default definePrismaConfig({
3756
+ orm: ormConfig({
3757
+ contract: prisma7Schema(${JSON.stringify(schemaPath)}),
3758
+ output: ${JSON.stringify(outputDir)},
3759
+ db: {
3760
+ connection: process.env['DATABASE_URL']!,
3761
+ },
3762
+ }),
3763
+ });
3764
+ `;
3765
+ }
3405
3766
  function dbFile(target, resolveImportSpecifier = keepInternalSpecifiers) {
3406
3767
  const runtime = targetEntrypoint(target, "runtime", resolveImportSpecifier);
3407
3768
  if (target === "postgres") return `import 'dotenv/config';
@@ -3525,18 +3886,20 @@ function initFinding(code, summary, parts) {
3525
3886
  function installFailedFinding(failure, filesWritten) {
3526
3887
  return initFinding("CLI.INIT_INSTALL_FAILED", "Failed to install dependencies", {
3527
3888
  why: failure.why ?? failure.message,
3528
- nextActions: [...failure.nextActions, runCommandAction("Emit the contract once the dependencies are installed", EMIT_COMMAND)],
3889
+ nextActions: [...failure.nextActions, filesWritten.length === 0 ? chooseAction(RERUN_AFTER_INSTALL) : runCommandAction("Emit the contract once the dependencies are installed", EMIT_COMMAND)],
3529
3890
  meta: {
3530
3891
  filesWritten,
3531
3892
  install: failure.meta ?? {}
3532
3893
  }
3533
3894
  });
3534
3895
  }
3896
+ /** Init stopped before writing anything, so the install is followed by init itself. */
3897
+ const RERUN_AFTER_INSTALL = "Run `prisma orm init` again once the dependencies install";
3535
3898
  /** The first emit failed against the freshly written scaffold. */
3536
3899
  function emitFailedFinding(cause, filesWritten) {
3537
3900
  return initFinding("CLI.INIT_EMIT_FAILED", "Failed to emit contract", {
3538
3901
  why: `\`${EMIT_COMMAND}\` failed: ${cause}`,
3539
- nextActions: [chooseAction("Fix the problem the contract source reports, then emit again"), runCommandAction("Emit the contract", EMIT_COMMAND)],
3902
+ nextActions: [chooseAction("Fix what the cause names — when the config imports something its package does not export, update that package to a version that does — then emit again"), runCommandAction("Emit the contract", EMIT_COMMAND)],
3540
3903
  meta: {
3541
3904
  filesWritten,
3542
3905
  cause
@@ -3560,15 +3923,33 @@ function scaffoldTree(document) {
3560
3923
  tone: "heading",
3561
3924
  children: fileNodes(document.filesDeleted)
3562
3925
  });
3563
- const installed = document.packagesInstalled;
3564
- if (installed.status === "installed") roots.push({
3565
- label: "installed",
3926
+ if (document.filesRenamed.length > 0) roots.push({
3927
+ label: "renamed",
3566
3928
  tone: "heading",
3567
- children: [...fileNodes(installed.deps), ...installed.devDeps.map((dep) => ({
3568
- label: `${dep} (dev)`,
3929
+ children: document.filesRenamed.map((entry) => ({
3930
+ label: `${entry.from} → ${entry.to}`,
3569
3931
  tone: "identifier"
3570
- }))]
3932
+ }))
3571
3933
  });
3934
+ const installed = document.packagesInstalled;
3935
+ if (installed.status === "installed") {
3936
+ const moved = new Set(document.prisma7?.packagesMoved ?? []);
3937
+ const suffix = (dep, dev) => {
3938
+ const notes = [...dev ? ["dev"] : [], ...moved.has(dep) ? ["Prisma 7"] : []];
3939
+ return notes.length === 0 ? dep : `${dep} (${notes.join(", ")})`;
3940
+ };
3941
+ roots.push({
3942
+ label: "installed",
3943
+ tone: "heading",
3944
+ children: [...installed.deps.map((dep) => ({
3945
+ label: suffix(dep, false),
3946
+ tone: "identifier"
3947
+ })), ...installed.devDeps.map((dep) => ({
3948
+ label: suffix(dep, true),
3949
+ tone: "identifier"
3950
+ }))]
3951
+ });
3952
+ }
3572
3953
  return {
3573
3954
  kind: "tree",
3574
3955
  roots
@@ -3582,6 +3963,18 @@ function scaffoldTree(document) {
3582
3963
  function buildInitNextActions(inputs) {
3583
3964
  const actions = [chooseAction("Set DATABASE_URL in your environment (export it or add it to .env)")];
3584
3965
  if (!inputs.contractEmitted) actions.push(runCommandAction("Emit the contract", EMIT_COMMAND));
3966
+ if (inputs.prisma7 !== null) {
3967
+ actions.push(runCommandAction(DB_SIGN_STEP, "prisma db sign"));
3968
+ actions.push({
3969
+ kind: "edit-file",
3970
+ label: "Move your routes one at a time to the Prisma 8 client in src/prisma/db.ts"
3971
+ });
3972
+ actions.push(chooseAction(PRISMA7_LOOP_STEP));
3973
+ if (inputs.prisma7.clientMoved) actions.push(runCommandAction("Regenerate the Prisma 7 client to match its CLI", "prisma7 generate"));
3974
+ actions.push(chooseAction(PRISMA7_QUICK_REFERENCE_STEP));
3975
+ actions.push(runCommandAction("Set up the Prisma agent skills for your coding agent", "prisma init"));
3976
+ return actions;
3977
+ }
3585
3978
  actions.push({
3586
3979
  kind: "edit-file",
3587
3980
  label: `Edit your schema at ${inputs.schemaPath}, then emit again`
@@ -3664,12 +4057,43 @@ async function emitScaffoldedContract(ctx, overrides = {}) {
3664
4057
  const result = await runCaptured(process.execPath, [
3665
4058
  binPath,
3666
4059
  "contract",
3667
- "emit"
4060
+ "emit",
4061
+ "--json"
3668
4062
  ], ctx.cwd);
3669
4063
  if (result.exitCode !== 0) {
3670
- const output = result.stderr.trim().length > 0 ? result.stderr : result.stdout;
3671
4064
  const cause = result.exitCode === null ? `was killed by signal ${result.signal ?? "unknown"}` : `exited with code ${result.exitCode}`;
3672
- throw new Error(`\`prisma contract emit\` ${cause}: ${redactSecrets(tail(output))}`);
4065
+ const detail = errorFromEnvelope(result.stdout) ?? tail(firstNonEmpty(result.stderr, result.stdout));
4066
+ throw new Error(`\`prisma contract emit\` ${cause}: ${redactSecrets(detail)}`);
4067
+ }
4068
+ }
4069
+ function firstNonEmpty(preferred, fallback) {
4070
+ return preferred.trim().length > 0 ? preferred : fallback;
4071
+ }
4072
+ function isRecord$1(value) {
4073
+ return typeof value === "object" && value !== null;
4074
+ }
4075
+ /**
4076
+ * The child ran with `--json`, so its settlement is a `result` event on
4077
+ * stdout whose envelope carries the structured error. That is the cause worth
4078
+ * quoting; stderr ends with whatever the child said last, which is often an
4079
+ * unrelated notice.
4080
+ */
4081
+ function errorFromEnvelope(stdout) {
4082
+ for (const line of stdout.split("\n").reverse()) {
4083
+ let event;
4084
+ try {
4085
+ event = JSON.parse(line);
4086
+ } catch {
4087
+ continue;
4088
+ }
4089
+ if (!isRecord$1(event) || event["kind"] !== "result" || !isRecord$1(event["envelope"])) continue;
4090
+ const error = event["envelope"]["error"];
4091
+ if (!isRecord$1(error)) continue;
4092
+ const code = typeof error["code"] === "string" ? error["code"] : void 0;
4093
+ const summary = typeof error["summary"] === "string" ? error["summary"] : void 0;
4094
+ const why = typeof error["why"] === "string" ? ` — ${error["why"]}` : "";
4095
+ if (code === void 0 && summary === void 0) continue;
4096
+ return `${[code, summary].filter((part) => part !== void 0).join(": ")}${why}`;
3673
4097
  }
3674
4098
  }
3675
4099
  function resolveProjectBin(cwd, overrides) {
@@ -3749,6 +4173,10 @@ function resolveTarget(value) {
3749
4173
  });
3750
4174
  return mapped;
3751
4175
  }
4176
+ /** The target a Prisma 7 `datasource` provider names; `undefined` when Prisma 8 has none for it. */
4177
+ function targetFromProviderName(provider) {
4178
+ return TARGET_ALIASES.get(provider);
4179
+ }
3752
4180
  function resolveAuthoring(value) {
3753
4181
  if (value === void 0) return void 0;
3754
4182
  const mapped = AUTHORING_VALUES.get(value.toLowerCase());
@@ -3802,94 +4230,379 @@ function formatRunScriptCommand(pm, scriptName) {
3802
4230
  default: return `npm run ${scriptName}`;
3803
4231
  }
3804
4232
  }
4233
+ function formatRemoveCommand(pm, packages) {
4234
+ return [
4235
+ pm,
4236
+ pm === "npm" ? "uninstall" : "remove",
4237
+ ...packages
4238
+ ].join(" ");
4239
+ }
3805
4240
  /**
3806
- * The `.gitattributes` entries written for a freshly initialised project
3807
- * (FR3.4). Mirrors the relevant subset of the repo-root
3808
- * [`.gitattributes`](../../../../../../../../.gitattributes):
3809
- *
3810
- * - **Today**: `contract.json`, `contract.d.ts` are emitted on every
3811
- * `prisma contract emit`. Marking them `linguist-generated`
3812
- * keeps GitHub's diff stats honest and collapses the file in code
3813
- * review by default.
3814
- * - **Forward-looking**: `ops.json`, `migration.json` are not yet emitted
3815
- * by `init` flows but will be produced by adjacent commands (lower /
3816
- * migration tooling). Adding them now matches Decision 5
3817
- * (forward-looking subset) so the file does not need to be amended
3818
- * every time a new artifact lands.
4241
+ * Recognised pnpm error signatures that justify a fallback to npm.
3819
4242
  *
3820
- * `ARTIFACT_FILENAMES` entries are written relative to the schema
3821
- * directory so a user who runs `init --schema-path db/contract.prisma`
3822
- * gets `db/contract.json linguist-generated` — not the workspace-glob
3823
- * form `<glob>/contract.json` (which would over-match any unrelated
3824
- * `contract.json` the user has elsewhere) and not the absolute
3825
- * `DEFAULT_CONTRACT_SOURCE_DIR/contract.json` (which would silently
3826
- * break for a non-default schema path).
4243
+ * These patterns indicate the published artifact itself is at fault
4244
+ * (a leaked `workspace:*` or `catalog:` specifier), not the user's
4245
+ * environment — pnpm is faithfully reporting "I cannot resolve this
4246
+ * registry version", and npm is willing to install it because npm
4247
+ * doesn't care about the protocol prefix when there's a fallback range.
3827
4248
  *
3828
- * The migration contract snapshot store (`migrations/snapshots/<hex>/`)
3829
- * is anchored to the migrations root instead, not the schema directory:
3830
- * migration package depth under `migrations/` varies (`app/<pkg>`,
3831
- * `<space>/<pkg>`, or a bare `<pkg>` in extension source repos), so no
3832
- * single schema-dir-relative pattern can reach every snapshot. See
3833
- * `STORE_GITATTRIBUTES_LINES` below.
3834
- */
3835
- const ARTIFACT_FILENAMES$1 = [
3836
- "contract.json",
3837
- "contract.d.ts",
3838
- "ops.json",
3839
- "migration.json"
3840
- ];
3841
- const ATTRIBUTE = "linguist-generated";
3842
- /**
3843
- * Full `.gitattributes` lines for the migration contract snapshot store,
3844
- * already anchored to the migrations root — unlike `ARTIFACT_FILENAMES`,
3845
- * these are not combined with the schema-relative prefix.
4249
+ * The predicate lives on its own so both shells' `init` share one list:
4250
+ * the commander command matches it against captured child stderr, the
4251
+ * engine command against the stderr the package-manager capability
4252
+ * returns on a failed install.
3846
4253
  */
3847
- const STORE_GITATTRIBUTES_LINES = [`migrations/snapshots/**/contract.json ${ATTRIBUTE}`, `migrations/snapshots/**/contract.d.ts ${ATTRIBUTE}`];
4254
+ function isRecognisedPnpmResolutionError(stderr) {
4255
+ if (!stderr) return false;
4256
+ return stderr.includes("ERR_PNPM_WORKSPACE_PKG_NOT_FOUND") || stderr.includes("ERR_PNPM_NO_MATCHING_VERSION") || /No matching version found for .* in the catalog/i.test(stderr) || /workspace:[^\s]+ is not a valid (version|spec)/i.test(stderr) || /catalog:[^\s]* is not a valid (version|spec)/i.test(stderr);
4257
+ }
4258
+ function metaString(failure, key) {
4259
+ const value = failure.meta?.[key];
4260
+ return typeof value === "string" ? value : "";
4261
+ }
3848
4262
  /**
3849
- * Computes the `.gitattributes` lines this scaffold expects to own. Each
3850
- * line has the shape `<path> linguist-generated`. The `target` parameter
3851
- * is currently unused but accepted for symmetry with the other hygiene
3852
- * helpers and to leave room for target-specific entries (e.g. a future
3853
- * family-specific artifact) without a signature break.
4263
+ * pnpm reported a specifier the published artifact leaked, which npm installs
4264
+ * happily. The engine redacts credentials out of the stderr it returns but
4265
+ * leaves error codes alone, which is what this reads.
3854
4266
  */
3855
- function requiredGitattributesLines(schemaDir, _target) {
3856
- const dir = schemaDir === "." ? "" : schemaDir.replace(/\/+$/, "");
3857
- const prefix = dir === "" ? "" : `${dir}/`;
3858
- return [...ARTIFACT_FILENAMES$1.map((file) => `${prefix}${file} ${ATTRIBUTE}`), ...STORE_GITATTRIBUTES_LINES];
4267
+ function pnpmLeakedASpecifier(failure) {
4268
+ return metaString(failure, "manager") === "pnpm" && isRecognisedPnpmResolutionError(metaString(failure, "stderrTail"));
3859
4269
  }
3860
4270
  /**
3861
- * Idempotent `.gitattributes` merge (FR3.4 / FR9.3). Returns the new file
3862
- * content given the existing content (or `undefined` if the file does
3863
- * not yet exist).
3864
- *
3865
- * Equivalence is exact-line: a user-customised line like
3866
- * `prisma/*.json linguist-generated` is *not* recognised as covering
3867
- * `DEFAULT_CONTRACT_SOURCE_DIR/contract.json linguist-generated`. We accept that
3868
- * over-specification — preserving the user's broad pattern *and*
3869
- * appending the narrow one — because the narrow lines are what the
3870
- * acceptance criteria pin (FR3.4 AC).
3871
- *
3872
- * Returns `null` when no changes are required (file already contains
3873
- * every required entry).
4271
+ * The engine redacts the stderr it hands back, and this redacts it again
4272
+ * before quoting it: what the engine strips is its own business, and registry
4273
+ * auth material is not all URL-shaped.
3874
4274
  */
3875
- function mergeGitattributes(existing, required) {
3876
- if (existing === void 0) return `${required.join("\n")}\n`;
3877
- const presentLines = new Set(existing.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#")));
3878
- const missing = required.filter((line) => !presentLines.has(line));
3879
- if (missing.length === 0) return null;
3880
- return `${existing}${existing.length === 0 || existing.endsWith("\n") ? "" : "\n"}${missing.join("\n")}\n`;
4275
+ function fallbackWarning(failure) {
4276
+ const firstLine = redactSecrets(metaString(failure, "stderrTail")).trim().split("\n")[0] ?? "";
4277
+ return [
4278
+ "pnpm could not install: a published Prisma ORM dependency leaked a `workspace:*` or `catalog:` specifier.",
4279
+ "Falling back to npm so init can complete.",
4280
+ firstLine === "" ? "" : ` pnpm error: ${firstLine}`,
4281
+ "Both installs ran under npm, which writes a package-lock.json beside the pnpm lockfile — delete whichever of the two you do not want to keep.",
4282
+ "Once the offending package republishes a clean version, re-run `pnpm install` to switch back."
4283
+ ].filter((line) => line !== "").join("\n");
4284
+ }
4285
+ /** The pnpm failure the npm retry was meant to recover from, kept alongside the npm one. */
4286
+ function retriedWarning(failure) {
4287
+ const firstLine = redactSecrets(metaString(failure, "stderrTail")).trim().split("\n")[0] ?? "";
4288
+ return ["pnpm failed first with a leaked `workspace:*` or `catalog:` specifier, so init retried with npm.", firstLine === "" ? "" : ` pnpm error: ${firstLine}`].filter((line) => line !== "").join("\n");
3881
4289
  }
3882
4290
  /**
3883
- * The minimal `.gitignore` lines a Prisma ORM scaffold needs (FR3.3).
3884
- * Order matches what Node tooling typically writes today.
3885
- *
3886
- * `node_modules/` first because it's the byte-largest miss; `dist/`
3887
- * because the scaffolded `tsconfig.json` writes there; `.env` last so
3888
- * the secret-bearing file is the one most-recently visible in any diff
3889
- * (a paranoid-correct ordering — humans skim from the top).
4291
+ * Adds the runtime and development dependencies through the engine's package
4292
+ * manager. The retry is `init`'s alone: the engine spells and runs the
4293
+ * command, and this decides — from the stderr it returned — that another
4294
+ * manager is worth a try.
3890
4295
  */
3891
- const REQUIRED_GITIGNORE_ENTRIES = [
3892
- "node_modules/",
4296
+ /**
4297
+ * The engine dependency spec a fresh scaffold installs. The scaffolded
4298
+ * `prisma.config.ts` imports `definePrismaConfig` from `@prisma/cli-engine`, and the
4299
+ * installed `prisma` names the exact engine version it runs against — so
4300
+ * the spec is read from the manifest the install just placed, never guessed
4301
+ * from a dist-tag (whose `latest` has lagged that version before and broken
4302
+ * the very next command). A CLI without a readable engine entry falls back to
4303
+ * the `next` tag, the release train the CLI itself publishes under.
4304
+ */
4305
+ function engineDevDependencySpec(cwd) {
4306
+ try {
4307
+ const manifest = JSON.parse(readFileSync(join(cwd, "node_modules", "prisma", "package.json"), "utf-8"));
4308
+ if (typeof manifest === "object" && manifest !== null) for (const field of ["dependencies", "peerDependencies"]) {
4309
+ const block = Reflect.get(manifest, field);
4310
+ if (typeof block === "object" && block !== null) {
4311
+ const engine = Reflect.get(block, "@prisma/cli-engine");
4312
+ if (typeof engine === "string" && engine.length > 0) return `@prisma/cli-engine@${engine}`;
4313
+ }
4314
+ }
4315
+ } catch {}
4316
+ return "@prisma/cli-engine@latest";
4317
+ }
4318
+ async function installProjectDependencies(ctx) {
4319
+ const pair = async (manager) => {
4320
+ for (const [packages, dev] of [[ctx.deps, false], [ctx.devDeps, true]]) {
4321
+ if (packages.length === 0) continue;
4322
+ const installed = await ctx.packages.install({
4323
+ packages,
4324
+ cwd: ctx.cwd,
4325
+ ...dev ? { dev } : {},
4326
+ ...ifDefined("manager", manager)
4327
+ });
4328
+ if (!installed.ok) return installed.failure;
4329
+ }
4330
+ };
4331
+ const failure = await pair();
4332
+ if (failure === void 0) return {
4333
+ failure: void 0,
4334
+ manager: void 0,
4335
+ warnings: ctx.catalogWarnings
4336
+ };
4337
+ if (!pnpmLeakedASpecifier(failure)) return {
4338
+ failure,
4339
+ manager: void 0,
4340
+ warnings: []
4341
+ };
4342
+ const retryFailure = await pair("npm");
4343
+ if (retryFailure !== void 0) return {
4344
+ failure: retryFailure,
4345
+ manager: void 0,
4346
+ warnings: [retriedWarning(failure)]
4347
+ };
4348
+ return {
4349
+ failure: void 0,
4350
+ manager: "npm",
4351
+ warnings: [fallbackWarning(failure)]
4352
+ };
4353
+ }
4354
+ const importFromProject = async (cwd, specifier) => {
4355
+ let resolved;
4356
+ try {
4357
+ resolved = createRequire(join(cwd, "package.json")).resolve(specifier);
4358
+ } catch {
4359
+ return;
4360
+ }
4361
+ return await import(pathToFileURL(resolved).href);
4362
+ };
4363
+ /** The install before the check failed; nothing else has happened yet. */
4364
+ var Prisma7CheckInstallFailed = class extends Error {
4365
+ failure;
4366
+ target;
4367
+ schemaPath;
4368
+ warnings;
4369
+ constructor(failure, target, schemaPath, warnings) {
4370
+ super(failure.message);
4371
+ this.failure = failure;
4372
+ this.target = target;
4373
+ this.schemaPath = schemaPath;
4374
+ this.warnings = warnings;
4375
+ this.name = "Prisma7CheckInstallFailed";
4376
+ }
4377
+ };
4378
+ /**
4379
+ * Adds the check's undo instruction to an error raised after the check installed packages, such
4380
+ * as the engine's own consent or cancellation errors, which init cannot word itself. An error with
4381
+ * no structured code becomes `CLI.UNEXPECTED`, as it would at the handler boundary.
4382
+ */
4383
+ function withPackagesAddedAction(error, added) {
4384
+ const engineError = normalizeError(error);
4385
+ return new CliStructuredError$1(engineError.code, engineError.message, {
4386
+ severity: engineError.severity,
4387
+ nextActions: [...engineError.nextActions, chooseAction(packagesAddedAction(added))],
4388
+ diagnostics: engineError.diagnostics,
4389
+ meta: {
4390
+ ...engineError.meta,
4391
+ packagesAdded: added.packages
4392
+ },
4393
+ ...ifDefined("why", engineError.why),
4394
+ ...ifDefined("where", engineError.where),
4395
+ ...ifDefined("docsUrl", engineError.docsUrl),
4396
+ cause: error
4397
+ });
4398
+ }
4399
+ /**
4400
+ * Finds out whether the chosen target package can read the Prisma 7 schema before init changes the
4401
+ * project: installs the package and `dotenv` (the packages every init installs), loads the
4402
+ * package's config entrypoint as the project resolves it, and runs its `prisma7Schema` source
4403
+ * without writing. The CLI carries no target code, so the installed package is the only one that
4404
+ * can answer.
4405
+ */
4406
+ function createPrisma7SourceCheck(ctx) {
4407
+ return async ({ target, schemaPath }) => {
4408
+ const resolveImportSpecifier = scaffoldSpecifierResolverFor(target);
4409
+ const packageName = targetPackageName(target, resolveImportSpecifier);
4410
+ const warnings = [];
4411
+ let installed = [];
4412
+ let added;
4413
+ if (ctx.install) {
4414
+ const deps = [packageName, "dotenv"];
4415
+ const declaredBefore = declaredPackages(ctx.cwd);
4416
+ const outcome = await installProjectDependencies({
4417
+ packages: ctx.packages,
4418
+ cwd: ctx.cwd,
4419
+ deps,
4420
+ devDeps: [],
4421
+ catalogWarnings: ctx.packageManager === "pnpm" ? buildCatalogWarnings(ctx.cwd, deps) : []
4422
+ });
4423
+ if (outcome.failure !== void 0) throw new Prisma7CheckInstallFailed(outcome.failure, target, schemaPath, outcome.warnings);
4424
+ warnings.push(...outcome.warnings);
4425
+ installed = deps;
4426
+ const newlyDeclared = deps.filter((dep) => !declaredBefore.has(dep));
4427
+ added = newlyDeclared.length === 0 ? void 0 : {
4428
+ packages: newlyDeclared,
4429
+ removeCommand: formatRemoveCommand(outcome.manager ?? ctx.packageManager, newlyDeclared)
4430
+ };
4431
+ }
4432
+ const undoable = async (step) => {
4433
+ try {
4434
+ return await step();
4435
+ } catch (error) {
4436
+ throw added === void 0 ? error : withPackagesAddedAction(error, added);
4437
+ }
4438
+ };
4439
+ const module = await undoable(() => ctx.importFromProject(ctx.cwd, targetEntrypoint(target, "config", resolveImportSpecifier)));
4440
+ if (module === void 0) {
4441
+ if (!ctx.install) {
4442
+ warnings.push(`Could not check that Prisma 8 can read ${schemaPath}: ${packageName} is not installed. Install the dependencies and run \`prisma contract emit\` to check it.`);
4443
+ return {
4444
+ outcome: "unchecked",
4445
+ packageName,
4446
+ installed,
4447
+ added,
4448
+ warnings
4449
+ };
4450
+ }
4451
+ throw errorInitPrisma7SourceUnavailable({
4452
+ schemaPath,
4453
+ packageName,
4454
+ reason: "not-resolvable",
4455
+ added
4456
+ });
4457
+ }
4458
+ const { defineConfig, prisma7Schema } = module;
4459
+ if (typeof defineConfig !== "function" || typeof prisma7Schema !== "function") return {
4460
+ outcome: "no-source",
4461
+ packageName,
4462
+ installed,
4463
+ added,
4464
+ warnings
4465
+ };
4466
+ const config = await undoable(() => {
4467
+ const section = defineConfig({
4468
+ contract: prisma7Schema(schemaPath),
4469
+ output: DEFAULT_CONTRACT_SOURCE_DIR
4470
+ });
4471
+ const required = requireConfigSections(buildLoadedConfig(isRecord(section) ? section : {}, ctx.cwd), [
4472
+ "family",
4473
+ "target",
4474
+ "adapter",
4475
+ "contract"
4476
+ ]);
4477
+ if (!required.ok) throw required.failure;
4478
+ return required.value;
4479
+ });
4480
+ const result = await undoable(() => loadContractSource(config));
4481
+ if (!result.ok) throw errorInitPrisma7SchemaRefused({
4482
+ schemaPath,
4483
+ packageName,
4484
+ summary: result.failure.summary,
4485
+ diagnostics: result.failure.diagnostics,
4486
+ added
4487
+ });
4488
+ return {
4489
+ outcome: "readable",
4490
+ packageName,
4491
+ installed,
4492
+ added,
4493
+ warnings
4494
+ };
4495
+ };
4496
+ }
4497
+ function declaredPackages(cwd) {
4498
+ let manifest;
4499
+ try {
4500
+ manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf-8"));
4501
+ } catch {
4502
+ return /* @__PURE__ */ new Set();
4503
+ }
4504
+ if (!isRecord(manifest)) return /* @__PURE__ */ new Set();
4505
+ const names = [
4506
+ "dependencies",
4507
+ "devDependencies",
4508
+ "optionalDependencies"
4509
+ ].flatMap((field) => {
4510
+ const section = manifest[field];
4511
+ return isRecord(section) ? Object.keys(section) : [];
4512
+ });
4513
+ return new Set(names);
4514
+ }
4515
+ function isRecord(value) {
4516
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4517
+ }
4518
+ /**
4519
+ * The `.gitattributes` entries written for a freshly initialised project
4520
+ * (FR3.4). Mirrors the relevant subset of the repo-root
4521
+ * [`.gitattributes`](../../../../../../../../.gitattributes):
4522
+ *
4523
+ * - **Today**: `contract.json`, `contract.d.ts` are emitted on every
4524
+ * `prisma contract emit`. Marking them `linguist-generated`
4525
+ * keeps GitHub's diff stats honest and collapses the file in code
4526
+ * review by default.
4527
+ * - **Forward-looking**: `ops.json`, `migration.json` are not yet emitted
4528
+ * by `init` flows but will be produced by adjacent commands (lower /
4529
+ * migration tooling). Adding them now matches Decision 5
4530
+ * (forward-looking subset) so the file does not need to be amended
4531
+ * every time a new artifact lands.
4532
+ *
4533
+ * `ARTIFACT_FILENAMES` entries are written relative to the schema
4534
+ * directory so a user who runs `init --schema-path db/contract.prisma`
4535
+ * gets `db/contract.json linguist-generated` — not the workspace-glob
4536
+ * form `<glob>/contract.json` (which would over-match any unrelated
4537
+ * `contract.json` the user has elsewhere) and not the absolute
4538
+ * `DEFAULT_CONTRACT_SOURCE_DIR/contract.json` (which would silently
4539
+ * break for a non-default schema path).
4540
+ *
4541
+ * The migration contract snapshot store (`migrations/snapshots/<hex>/`)
4542
+ * is anchored to the migrations root instead, not the schema directory:
4543
+ * migration package depth under `migrations/` varies (`app/<pkg>`,
4544
+ * `<space>/<pkg>`, or a bare `<pkg>` in extension source repos), so no
4545
+ * single schema-dir-relative pattern can reach every snapshot. See
4546
+ * `STORE_GITATTRIBUTES_LINES` below.
4547
+ */
4548
+ const ARTIFACT_FILENAMES$1 = [
4549
+ "contract.json",
4550
+ "contract.d.ts",
4551
+ "ops.json",
4552
+ "migration.json"
4553
+ ];
4554
+ const ATTRIBUTE = "linguist-generated";
4555
+ /**
4556
+ * Full `.gitattributes` lines for the migration contract snapshot store,
4557
+ * already anchored to the migrations root — unlike `ARTIFACT_FILENAMES`,
4558
+ * these are not combined with the schema-relative prefix.
4559
+ */
4560
+ const STORE_GITATTRIBUTES_LINES = [`migrations/snapshots/**/contract.json ${ATTRIBUTE}`, `migrations/snapshots/**/contract.d.ts ${ATTRIBUTE}`];
4561
+ /**
4562
+ * Computes the `.gitattributes` lines this scaffold expects to own. Each
4563
+ * line has the shape `<path> linguist-generated`. The `target` parameter
4564
+ * is currently unused but accepted for symmetry with the other hygiene
4565
+ * helpers and to leave room for target-specific entries (e.g. a future
4566
+ * family-specific artifact) without a signature break.
4567
+ */
4568
+ function requiredGitattributesLines(schemaDir, _target) {
4569
+ const dir = schemaDir === "." ? "" : schemaDir.replace(/\/+$/, "");
4570
+ const prefix = dir === "" ? "" : `${dir}/`;
4571
+ return [...ARTIFACT_FILENAMES$1.map((file) => `${prefix}${file} ${ATTRIBUTE}`), ...STORE_GITATTRIBUTES_LINES];
4572
+ }
4573
+ /**
4574
+ * Idempotent `.gitattributes` merge (FR3.4 / FR9.3). Returns the new file
4575
+ * content given the existing content (or `undefined` if the file does
4576
+ * not yet exist).
4577
+ *
4578
+ * Equivalence is exact-line: a user-customised line like
4579
+ * `prisma/*.json linguist-generated` is *not* recognised as covering
4580
+ * `DEFAULT_CONTRACT_SOURCE_DIR/contract.json linguist-generated`. We accept that
4581
+ * over-specification — preserving the user's broad pattern *and*
4582
+ * appending the narrow one — because the narrow lines are what the
4583
+ * acceptance criteria pin (FR3.4 AC).
4584
+ *
4585
+ * Returns `null` when no changes are required (file already contains
4586
+ * every required entry).
4587
+ */
4588
+ function mergeGitattributes(existing, required) {
4589
+ if (existing === void 0) return `${required.join("\n")}\n`;
4590
+ const presentLines = new Set(existing.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#")));
4591
+ const missing = required.filter((line) => !presentLines.has(line));
4592
+ if (missing.length === 0) return null;
4593
+ return `${existing}${existing.length === 0 || existing.endsWith("\n") ? "" : "\n"}${missing.join("\n")}\n`;
4594
+ }
4595
+ /**
4596
+ * The minimal `.gitignore` lines a Prisma ORM scaffold needs (FR3.3).
4597
+ * Order matches what Node tooling typically writes today.
4598
+ *
4599
+ * `node_modules/` first because it's the byte-largest miss; `dist/`
4600
+ * because the scaffolded `tsconfig.json` writes there; `.env` last so
4601
+ * the secret-bearing file is the one most-recently visible in any diff
4602
+ * (a paranoid-correct ordering — humans skim from the top).
4603
+ */
4604
+ const REQUIRED_GITIGNORE_ENTRIES = [
4605
+ "node_modules/",
3893
4606
  "dist/",
3894
4607
  ".env"
3895
4608
  ];
@@ -4019,6 +4732,169 @@ function ensureEsmModuleType(existing) {
4019
4732
  warning: null
4020
4733
  };
4021
4734
  }
4735
+ const PRISMA7_PACKAGE_CONFIG_SPECIFIER = "@prisma/prisma7/config";
4736
+ /**
4737
+ * Points a Prisma 7 config at the Prisma 7 package's config entrypoint. Both
4738
+ * quote styles are rewritten; `found` is false when the file imports neither.
4739
+ */
4740
+ function rewritePrisma7ConfigImport(content) {
4741
+ const rewritten = content.replace(/(['"])prisma\/config\1/g, (_match, quote) => `${quote}${PRISMA7_PACKAGE_CONFIG_SPECIFIER}${quote}`);
4742
+ return {
4743
+ content: rewritten,
4744
+ found: rewritten !== content
4745
+ };
4746
+ }
4747
+ /**
4748
+ * One shell token: a quoted string (to the end of the script when unterminated),
4749
+ * a backslash escape, a command operator, whitespace, or a run of other characters.
4750
+ */
4751
+ const SHELL_TOKEN = /"(?:\\[\s\S]|[^"\\])*(?:"|$)|'[^']*(?:'|$)|\\[\s\S]?|&&|\|\||[;|]|\s+|[^\s"'\\;|&]+|&/g;
4752
+ const SHELL_OPERATORS = /* @__PURE__ */ new Set([
4753
+ "&&",
4754
+ "||",
4755
+ ";",
4756
+ "|"
4757
+ ]);
4758
+ const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
4759
+ /** Wrappers whose next word, after any `NAME=value` assignments, is the command they run. */
4760
+ const PREFIX_WRAPPERS = [
4761
+ {
4762
+ words: ["pnpm", "exec"],
4763
+ flags: []
4764
+ },
4765
+ {
4766
+ words: ["pnpm", "dlx"],
4767
+ flags: []
4768
+ },
4769
+ {
4770
+ words: ["pnpm"],
4771
+ flags: []
4772
+ },
4773
+ {
4774
+ words: ["yarn", "exec"],
4775
+ flags: []
4776
+ },
4777
+ {
4778
+ words: ["yarn", "dlx"],
4779
+ flags: []
4780
+ },
4781
+ {
4782
+ words: ["yarn"],
4783
+ flags: []
4784
+ },
4785
+ {
4786
+ words: ["bun", "x"],
4787
+ flags: ["--bun"]
4788
+ },
4789
+ {
4790
+ words: ["bun"],
4791
+ flags: []
4792
+ },
4793
+ {
4794
+ words: ["bunx"],
4795
+ flags: ["--bun"]
4796
+ },
4797
+ {
4798
+ words: ["npx"],
4799
+ flags: ["-y", "--yes"]
4800
+ },
4801
+ {
4802
+ words: ["cross-env"],
4803
+ flags: []
4804
+ }
4805
+ ];
4806
+ /** Wrappers that take their own arguments and run the command after `--`. */
4807
+ const SEPARATOR_WRAPPERS = [
4808
+ ["dotenv"],
4809
+ ["dotenvx", "run"],
4810
+ ["env-cmd"]
4811
+ ];
4812
+ /**
4813
+ * Splits a script into commands at the operators outside quotes, and each
4814
+ * command into words. A quoted string belongs to the word it sits in, so no
4815
+ * word inside quotes is ever a command.
4816
+ */
4817
+ function commandsOf(script) {
4818
+ let words = [];
4819
+ const commands = [words];
4820
+ let inWord = false;
4821
+ for (const token of script.matchAll(SHELL_TOKEN)) {
4822
+ const [text] = token;
4823
+ if (SHELL_OPERATORS.has(text)) {
4824
+ words = [];
4825
+ commands.push(words);
4826
+ inWord = false;
4827
+ } else if (/^\s/.test(text)) inWord = false;
4828
+ else {
4829
+ const previous = inWord ? words.pop()?.text ?? "" : "";
4830
+ words.push({
4831
+ text: `${previous}${text}`,
4832
+ end: token.index + text.length
4833
+ });
4834
+ inWord = true;
4835
+ }
4836
+ }
4837
+ return commands;
4838
+ }
4839
+ function startsWithWords(words, at, expected) {
4840
+ return expected.every((part, offset) => words[at + offset]?.text === part);
4841
+ }
4842
+ /**
4843
+ * The `prisma` word that runs as the command starting at `at`: skips
4844
+ * `NAME=value` assignments, then either is `prisma` or unwraps a recognised
4845
+ * wrapper and looks again at the command it runs.
4846
+ */
4847
+ function prismaCommandWord(words, at) {
4848
+ let index = at;
4849
+ while (ENV_ASSIGNMENT.test(words[index]?.text ?? "")) index += 1;
4850
+ const word = words[index];
4851
+ if (word?.text === "prisma") return word;
4852
+ const prefix = PREFIX_WRAPPERS.find((wrapper) => startsWithWords(words, index, wrapper.words));
4853
+ if (prefix !== void 0) {
4854
+ let next = index + prefix.words.length;
4855
+ while (prefix.flags.includes(words[next]?.text ?? "")) next += 1;
4856
+ return prismaCommandWord(words, next);
4857
+ }
4858
+ const separated = SEPARATOR_WRAPPERS.find((wrapper) => startsWithWords(words, index, wrapper));
4859
+ if (separated === void 0) return;
4860
+ const separator = words.findIndex((candidate, position) => position >= index + separated.length && candidate.text === "--");
4861
+ return separator === -1 ? void 0 : prismaCommandWord(words, separator + 1);
4862
+ }
4863
+ /**
4864
+ * Rewrites `prisma` to `prisma7` wherever it is the command a script runs: at
4865
+ * the start of the script or after `&&`, `||`, `;`, or `|` outside quotes,
4866
+ * behind any `NAME=value` assignments and recognised wrappers. `prisma` as an
4867
+ * argument, inside quotes (`sh -c "prisma generate"`), or as the start of a
4868
+ * longer word (`prisma@7`, `prisma-erd`) is left alone.
4869
+ */
4870
+ function rewritePrismaBinary(script) {
4871
+ return commandsOf(script).map((words) => prismaCommandWord(words, 0)?.end).filter((end) => end !== void 0).reduceRight((rewritten, end) => `${rewritten.slice(0, end)}7${rewritten.slice(end)}`, script);
4872
+ }
4873
+ /**
4874
+ * Rewrites every `package.json` script that invokes the `prisma` binary to
4875
+ * invoke `prisma7`, except the scripts init itself adds, which keep the
4876
+ * Prisma 8 binary. Returns `null` when no script changes.
4877
+ */
4878
+ function rewritePrismaScripts(manifest, keepNames) {
4879
+ const parsed = blindCast(JSON.parse(manifest));
4880
+ const scripts = parsed["scripts"];
4881
+ if (typeof scripts !== "object" || scripts === null) return null;
4882
+ const kept = new Set(keepNames);
4883
+ const names = [];
4884
+ const next = {};
4885
+ for (const [name, command] of Object.entries(scripts)) {
4886
+ const rewritten = typeof command === "string" && !kept.has(name) ? rewritePrismaBinary(command) : command;
4887
+ if (rewritten !== command) names.push(name);
4888
+ next[name] = rewritten;
4889
+ }
4890
+ if (names.length === 0) return null;
4891
+ parsed["scripts"] = next;
4892
+ const trailingNewline = manifest.endsWith("\n") ? "\n" : "";
4893
+ return {
4894
+ content: `${JSON.stringify(parsed, null, 2)}${trailingNewline}`,
4895
+ names
4896
+ };
4897
+ }
4022
4898
  /**
4023
4899
  * Filenames the contract pipeline emits next to the user's schema source
4024
4900
  * (`<schemaDir>/contract.json`, `<schemaDir>/contract.d.ts`, …). Mirrors
@@ -4188,6 +5064,32 @@ function requirementsBlock(target, pkgRun) {
4188
5064
  `- The CLI never connects to your database without explicit consent. Pass \`--probe-db\` to \`${pkgRun} orm init\` if you want \`init\` to verify the server version itself.`
4189
5065
  ].join("\n");
4190
5066
  }
5067
+ const prisma7Variables = [
5068
+ "schemaPath",
5069
+ "outputDir",
5070
+ "dbImportPath",
5071
+ "pkgRun",
5072
+ "pkg",
5073
+ "configEntrypoint",
5074
+ "requirements",
5075
+ "prisma7ConfigSentence",
5076
+ "prisma7ConfigRow"
5077
+ ];
5078
+ /** The quick reference for a project whose contract source is its Prisma 7 schema. */
5079
+ function prisma7QuickReferenceMd(target, schemaPath, outputDir, pkgRun, prisma7Config, resolveImportSpecifier = keepInternalSpecifiers) {
5080
+ const vars = {
5081
+ schemaPath,
5082
+ outputDir,
5083
+ dbImportPath: `./${outputDir}/db`,
5084
+ pkgRun,
5085
+ pkg: targetPackageName(target, resolveImportSpecifier),
5086
+ configEntrypoint: targetEntrypoint(target, "config", resolveImportSpecifier),
5087
+ requirements: requirementsBlock(target, pkgRun),
5088
+ prisma7ConfigSentence: prisma7Config === void 0 ? "" : ` Prisma 7 reads its own config from \`${prisma7Config}\`.`,
5089
+ prisma7ConfigRow: prisma7Config === void 0 ? "" : `\n| [\`${prisma7Config}\`](${prisma7Config}) | Prisma 7 CLI configuration |`
5090
+ };
5091
+ return renderTemplate("quick-reference-prisma7.md", prisma7Variables, vars);
5092
+ }
4191
5093
  const sharedVariables = [
4192
5094
  "projectName",
4193
5095
  "contractPath",
@@ -4400,6 +5302,17 @@ function generatedFilesInitReplaces(schemaPath) {
4400
5302
  QUICK_REFERENCE_FILE
4401
5303
  ];
4402
5304
  }
5305
+ /**
5306
+ * The same list for the Prisma 7 path, where the schema is the user's and
5307
+ * init's files live under Prisma 8's own directory.
5308
+ */
5309
+ function generatedFilesPrisma7PathReplaces() {
5310
+ return [
5311
+ CONFIG_FILE,
5312
+ join(DEFAULT_CONTRACT_SOURCE_DIR, "db.ts"),
5313
+ QUICK_REFERENCE_FILE
5314
+ ];
5315
+ }
4403
5316
  const MANAGERS = /* @__PURE__ */ new Set([
4404
5317
  "pnpm",
4405
5318
  "npm",
@@ -4468,33 +5381,48 @@ function hasProjectManifest(cwd) {
4468
5381
  function planScaffold(ctx) {
4469
5382
  const { cwd, inputs, packageManager, resolveImportSpecifier } = ctx;
4470
5383
  const warnings = [];
4471
- const schemaDir = dirname(inputs.schemaPath);
5384
+ const source = inputs.contractSource;
5385
+ const outputDir = source.kind === "prisma7-schema" ? DEFAULT_CONTRACT_SOURCE_DIR : dirname(inputs.schemaPath);
4472
5386
  const configContractPath = isAbsolute(inputs.schemaPath) ? inputs.schemaPath : `./${inputs.schemaPath}`;
4473
5387
  const runPrefix = formatRunCommand(packageManager, "prisma", "").trimEnd();
4474
- const files = [
5388
+ const renames = planConfigRename(cwd, inputs, warnings);
5389
+ const files = source.kind === "starter" ? [
4475
5390
  {
4476
5391
  path: inputs.schemaPath,
4477
- content: starterSchema(inputs.target, inputs.authoring, resolveImportSpecifier)
5392
+ content: starterSchema(inputs.target, source.authoring, resolveImportSpecifier)
4478
5393
  },
4479
5394
  {
4480
5395
  path: CONFIG_FILE,
4481
5396
  content: configFile(inputs.target, configContractPath, resolveImportSpecifier)
4482
5397
  },
4483
5398
  {
4484
- path: join(schemaDir, "db.ts"),
5399
+ path: join(outputDir, "db.ts"),
4485
5400
  content: dbFile(inputs.target, resolveImportSpecifier)
4486
5401
  },
4487
5402
  {
4488
5403
  path: QUICK_REFERENCE_FILE,
4489
- content: quickReferenceMd(inputs.target, inputs.authoring, inputs.schemaPath, runPrefix, resolveImportSpecifier)
5404
+ content: quickReferenceMd(inputs.target, source.authoring, inputs.schemaPath, runPrefix, resolveImportSpecifier)
5405
+ }
5406
+ ] : [
5407
+ {
5408
+ path: CONFIG_FILE,
5409
+ content: prisma7ConfigFile(inputs.target, source.schemaPath, outputDir, resolveImportSpecifier)
5410
+ },
5411
+ {
5412
+ path: join(outputDir, "db.ts"),
5413
+ content: dbFile(inputs.target, resolveImportSpecifier)
4490
5414
  },
4491
5415
  {
4492
- path: ENV_EXAMPLE_FILE,
4493
- content: envExampleContent(inputs.target)
5416
+ path: QUICK_REFERENCE_FILE,
5417
+ content: prisma7QuickReferenceMd(inputs.target, source.schemaPath, outputDir, runPrefix, source.prisma7Config, resolveImportSpecifier)
4494
5418
  }
4495
5419
  ];
5420
+ files.push({
5421
+ path: ENV_EXAMPLE_FILE,
5422
+ content: envExampleContent(inputs.target)
5423
+ });
4496
5424
  if (existsSync(join(cwd, ENV_EXAMPLE_FILE))) warnings.push(`${ENV_EXAMPLE_FILE} already existed and was replaced with the Prisma ORM template.`);
4497
- const filesToDelete = inputs.reinit ? [...findStaleArtifacts(cwd, schemaDir)] : [];
5425
+ const filesToDelete = inputs.reinit ? [...findStaleArtifacts(cwd, outputDir)] : [];
4498
5426
  const dirsToDelete = legacySkillDirs().filter((rel) => existsSync(join(cwd, rel)));
4499
5427
  if (inputs.writeEnv) if (existsSync(join(cwd, ".env"))) warnings.push(".env already exists; leaving it untouched. Compare with .env.example for any new keys.");
4500
5428
  else files.push({
@@ -4530,7 +5458,7 @@ function planScaffold(ctx) {
4530
5458
  content: nextGitignore
4531
5459
  });
4532
5460
  const gitattributesPath = join(cwd, ".gitattributes");
4533
- const nextGitattributes = mergeGitattributes(existsSync(gitattributesPath) ? readFileSync(gitattributesPath, "utf-8") : void 0, requiredGitattributesLines(schemaDir, inputs.target));
5461
+ const nextGitattributes = mergeGitattributes(existsSync(gitattributesPath) ? readFileSync(gitattributesPath, "utf-8") : void 0, requiredGitattributesLines(outputDir, inputs.target));
4534
5462
  if (nextGitattributes !== null) files.push({
4535
5463
  path: ".gitattributes",
4536
5464
  content: nextGitattributes
@@ -4539,6 +5467,7 @@ function planScaffold(ctx) {
4539
5467
  const manifestExisted = existsSync(manifestPath);
4540
5468
  const synthesiseManifest = !manifestExisted && !hasProjectManifest(cwd);
4541
5469
  let parsedManifest = null;
5470
+ let scriptsRewritten = [];
4542
5471
  if (manifestExisted || synthesiseManifest) {
4543
5472
  const raw = manifestExisted ? readFileSync(manifestPath, "utf-8") : defaultPackageJsonContent(basename(cwd));
4544
5473
  try {
@@ -4559,6 +5488,14 @@ function planScaffold(ctx) {
4559
5488
  changed = true;
4560
5489
  }
4561
5490
  }
5491
+ if (inputs.sideBySide !== null) {
5492
+ const next = rewritePrismaScripts(working, REQUIRED_SCRIPTS.map((script) => script.name));
5493
+ if (next !== null) {
5494
+ working = next.content;
5495
+ scriptsRewritten = next.names;
5496
+ changed = true;
5497
+ }
5498
+ }
4562
5499
  const { content: withScripts, warnings: scriptWarnings } = mergePackageScripts(working);
4563
5500
  if (withScripts !== null) {
4564
5501
  working = withScripts;
@@ -4577,7 +5514,7 @@ function planScaffold(ctx) {
4577
5514
  if (typeWarning !== null) warnings.push(typeWarning);
4578
5515
  if (synthesiseManifest) warnings.push("No package.json found in the target directory; created a minimal one. Edit `name` / `version` to taste.");
4579
5516
  }
4580
- if (existsSync(join(cwd, "src/index.ts"))) if (existsSync(join(cwd, "README.md"))) warnings.push("README.md already exists; leaving it untouched.");
5517
+ if (source.kind === "starter" && existsSync(join(cwd, "src/index.ts"))) if (existsSync(join(cwd, "README.md"))) warnings.push("README.md already exists; leaving it untouched.");
4581
5518
  else {
4582
5519
  const declaredName = parsedManifest !== null && typeof parsedManifest["name"] === "string" ? parsedManifest["name"] : basename(cwd);
4583
5520
  files.push({
@@ -4586,6 +5523,8 @@ function planScaffold(ctx) {
4586
5523
  });
4587
5524
  }
4588
5525
  return {
5526
+ renames,
5527
+ scriptsRewritten,
4589
5528
  files,
4590
5529
  filesToDelete,
4591
5530
  dirsToDelete,
@@ -4594,6 +5533,28 @@ function planScaffold(ctx) {
4594
5533
  };
4595
5534
  }
4596
5535
  /**
5536
+ * The Prisma 7 config moves to `prisma7.config.<same extension>` with its
5537
+ * `prisma/config` import pointed at the Prisma 7 package. Planned like every
5538
+ * other write: a target that already exists fails here, before anything
5539
+ * lands on disk.
5540
+ */
5541
+ function planConfigRename(cwd, inputs, warnings) {
5542
+ const rename = inputs.sideBySide?.renameConfig ?? null;
5543
+ if (rename === null) return [];
5544
+ const to = `prisma7.config.${rename.extension}`;
5545
+ if (existsSync(join(cwd, to))) throw errorInitPrisma7ConfigCollision({
5546
+ prismaConfigPath: rename.from,
5547
+ prisma7ConfigPath: to
5548
+ });
5549
+ const rewritten = rewritePrisma7ConfigImport(readFileSync(join(cwd, rename.from), "utf-8"));
5550
+ if (!rewritten.found) warnings.push(`${rename.from} does not import 'prisma/config', so it was renamed to ${to} with its imports unchanged. If it imports the Prisma 7 config helper another way, point that import at '@prisma/prisma7/config'.`);
5551
+ return [{
5552
+ from: rename.from,
5553
+ to,
5554
+ content: rewritten.content
5555
+ }];
5556
+ }
5557
+ /**
4597
5558
  * Plans every write, then performs them. Everything that can fail on the
4598
5559
  * user's existing files fails during planning, so a failure leaves the project
4599
5560
  * as it was; after the first write, the scaffold is on disk to keep, and a
@@ -4607,7 +5568,25 @@ function scaffoldProject(ctx) {
4607
5568
  });
4608
5569
  const filesWritten = [];
4609
5570
  const filesDeleted = [];
5571
+ const filesRenamed = [];
4610
5572
  const notes = [];
5573
+ for (const rename of plan.renames) {
5574
+ try {
5575
+ writeFileSync(join(ctx.cwd, rename.to), rename.content, "utf-8");
5576
+ unlinkSync(join(ctx.cwd, rename.from));
5577
+ } catch (error) {
5578
+ throw errorInitWriteFailed({
5579
+ path: rename.to,
5580
+ cause: error instanceof Error ? error.message : String(error),
5581
+ filesWritten,
5582
+ filesRenamed
5583
+ });
5584
+ }
5585
+ filesRenamed.push({
5586
+ from: rename.from,
5587
+ to: rename.to
5588
+ });
5589
+ }
4611
5590
  for (const file of plan.files) {
4612
5591
  const target = join(ctx.cwd, file.path);
4613
5592
  try {
@@ -4617,7 +5596,8 @@ function scaffoldProject(ctx) {
4617
5596
  throw errorInitWriteFailed({
4618
5597
  path: file.path,
4619
5598
  cause: error instanceof Error ? error.message : String(error),
4620
- filesWritten
5599
+ filesWritten,
5600
+ filesRenamed
4621
5601
  });
4622
5602
  }
4623
5603
  filesWritten.push(file.path);
@@ -4643,6 +5623,8 @@ function scaffoldProject(ctx) {
4643
5623
  return {
4644
5624
  filesWritten,
4645
5625
  filesDeleted,
5626
+ filesRenamed,
5627
+ scriptsRewritten: plan.scriptsRewritten,
4646
5628
  warnings: plan.warnings,
4647
5629
  notes,
4648
5630
  hasTypesNode: plan.hasTypesNode,
@@ -4740,40 +5722,243 @@ async function resolveRemovePreviousFacade(ctx) {
4740
5722
  const otherTarget = ctx.target === "postgres" ? "mongo" : "postgres";
4741
5723
  return await ctx.prompt.confirm(`Switching from ${targetLabel(otherTarget)} to ${targetLabel(ctx.target)} — remove ${facade} from package.json dependencies?`, { default: true }) ? facade : null;
4742
5724
  }
5725
+ const PRISMA7_SCHEMA_FLAG = "from-prisma7-schema";
5726
+ const PRISMA7_CONFIG_STEM = "prisma.config.";
5727
+ const SIDE_BY_SIDE_QUESTION = "Prisma 7 is installed as `prisma`. Keep it as @prisma/prisma7 (binary prisma7) and move `prisma` to Prisma 8?";
4743
5728
  /**
4744
- * Resolves every input from the flags and, where a flag is absent, from the
4745
- * engine's prompt surface.
4746
- *
4747
- * Order matters twice. Every flag value is validated before anything is asked,
4748
- * so a typo costs a typo rather than a typed consent token. And consent comes
4749
- * as soon as the schema path is known, because that is the point at which the
4750
- * question can name the files it is about — and before any question whose
4751
- * answer only matters if the run proceeds.
5729
+ * `--from-prisma7-schema` names the contract source; `--schema-path` and
5730
+ * `--authoring` describe a starter schema to write. Both at once is a
5731
+ * contradiction, refused before anything is read.
4752
5732
  */
4753
- async function resolveInitInputs(ctx) {
4754
- const { cwd, flags, prompt } = ctx;
4755
- if (flags.strictProbe && !flags.probeDb) throw errorInitStrictProbeWithoutProbe();
4756
- const flagTarget = resolveTarget(flags.target);
4757
- const flagAuthoring = resolveAuthoring(flags.authoring);
5733
+ function rejectFlagConflict(flags) {
5734
+ if (flags.fromPrisma7Schema === void 0) return;
5735
+ if (flags.schemaPath !== void 0) throw errorInitFlagConflict({ flags: [PRISMA7_SCHEMA_FLAG, "schema-path"] });
5736
+ if (flags.authoring !== void 0) throw errorInitFlagConflict({ flags: [PRISMA7_SCHEMA_FLAG, "authoring"] });
5737
+ }
5738
+ /**
5739
+ * True only for what detection actually saw: a schema with a `datasource`
5740
+ * block is called one; otherwise the question is about the config, and the
5741
+ * path is only what it declares.
5742
+ */
5743
+ function looksLikePrisma7(detection) {
5744
+ const { config, schema } = detection;
5745
+ return config.kind === "prisma7" || config.kind === "collision" || schema.kind === "datasource";
5746
+ }
5747
+ function prisma7Question(detection) {
5748
+ const { config, schema } = detection;
5749
+ if (schema.kind === "datasource" || config.kind !== "prisma7") return `${schema.path} is a Prisma 7 schema. Use it as the Prisma 8 contract source?`;
5750
+ return `${config.path} is a Prisma 7 config. Use the schema it declares (${schema.path}) as the Prisma 8 contract source?`;
5751
+ }
5752
+ /**
5753
+ * The Prisma 7 path is entered by the flag or by an explicit yes. The question
5754
+ * declares no default on purpose: a session that cannot ask (`--yes`, no
5755
+ * terminal) must run init as today rather than have the engine answer for the
5756
+ * user, so the engine's "cannot ask" is read as a no.
5757
+ */
5758
+ async function choosePrisma7Path(ctx) {
5759
+ if (ctx.flags.fromPrisma7Schema !== void 0) return true;
5760
+ if (!looksLikePrisma7(ctx.detection)) return false;
5761
+ const { schema } = ctx.detection;
5762
+ if (schema.kind === "datasource" && !prisma7Target(schema, ctx.flagTarget, ctx.flags.target).ok) return false;
5763
+ try {
5764
+ return await ctx.prompt.confirm(prisma7Question(ctx.detection));
5765
+ } catch (error) {
5766
+ if (isPromptRequired(error)) return false;
5767
+ throw error;
5768
+ }
5769
+ }
5770
+ /**
5771
+ * The schema's provider names the target; `--target` may only agree with it,
5772
+ * or name the database when the provider is not a string literal.
5773
+ */
5774
+ function prisma7Target(schema, flagTarget, rawFlagTarget) {
5775
+ const providerTarget = schema.provider === void 0 ? void 0 : targetFromProviderName(schema.provider);
5776
+ if (schema.provider !== void 0 && providerTarget === void 0) return notOk(errorInitPrisma7ProviderUnsupported({
5777
+ schemaPath: schema.path,
5778
+ provider: schema.provider
5779
+ }));
5780
+ if (schema.provider !== void 0 && flagTarget !== void 0 && flagTarget !== providerTarget) return notOk(errorInitPrisma7TargetMismatch({
5781
+ schemaPath: schema.path,
5782
+ provider: schema.provider,
5783
+ target: rawFlagTarget ?? flagTarget
5784
+ }));
5785
+ const target = flagTarget ?? providerTarget;
5786
+ return target === void 0 ? notOk(errorInitPrisma7ProviderUnsupported({
5787
+ schemaPath: schema.path,
5788
+ provider: void 0
5789
+ })) : ok(target);
5790
+ }
5791
+ /**
5792
+ * What a fresh init does to a Prisma 7 project, said before its questions: the user answered yes
5793
+ * to adopting the schema and is about to be asked something else.
5794
+ */
5795
+ function freshInitWarning(packageName, detection) {
5796
+ const { config, schema, cli } = detection;
5797
+ const effects = [...config.kind === "prisma7" && config.path === "prisma.config.ts" ? [`asks before replacing the Prisma 7 ${CONFIG_FILE}`] : [], ...cli.kind === "earlier" ? ["installs prisma@latest, which replaces the Prisma 7 CLI"] : []];
5798
+ const consequences = effects.length === 0 ? "" : ` It ${effects.join(", and it ")}.`;
5799
+ return `${packageName} cannot read Prisma 7 schemas, so init sets up a fresh Prisma 8 project instead and leaves ${schema.path} alone.${consequences}`;
5800
+ }
5801
+ function sideBySidePlan(detection) {
5802
+ const { config, cli } = detection;
5803
+ const renameConfig = config.kind === "prisma7" && config.path.startsWith(PRISMA7_CONFIG_STEM) ? {
5804
+ from: config.path,
5805
+ extension: extname(config.path).slice(1)
5806
+ } : null;
5807
+ const movePackages = cli.kind === "earlier" ? {
5808
+ cliVersion: cli.version,
5809
+ clientVersion: cli.clientVersion
5810
+ } : null;
5811
+ if (renameConfig === null && movePackages === null) return null;
5812
+ return {
5813
+ renameConfig,
5814
+ movePackages
5815
+ };
5816
+ }
5817
+ function sideBySideQuestion(plan) {
5818
+ const { renameConfig, movePackages } = plan;
5819
+ if (movePackages === null && renameConfig !== null) return `${renameConfig.from} is a Prisma 7 config. Rename it to prisma7.config.${renameConfig.extension} so Prisma 8 can write its own?`;
5820
+ if (renameConfig === null) return SIDE_BY_SIDE_QUESTION;
5821
+ return `${SIDE_BY_SIDE_QUESTION.slice(0, -1)}, and rename ${renameConfig.from} to prisma7.config.${renameConfig.extension}?`;
5822
+ }
5823
+ async function requireReinitConsent(ctx) {
5824
+ if (ctx.replaced.length === 0) return false;
5825
+ if (!await ctx.prompt.consent(consentQuestion(ctx.replaced), { token: consentToken(ctx.cwd) })) throw errorInitUserAborted();
5826
+ return true;
5827
+ }
5828
+ async function askWriteEnv(flags, prompt) {
5829
+ return flags.writeEnv || await prompt.confirm("Also write a .env file from .env.example? (gitignored)", { default: false });
5830
+ }
5831
+ /**
5832
+ * The Prisma 7 path: every refusal comes before any consent, so a run that is
5833
+ * going to refuse never asks the user to type the consent token. That
5834
+ * includes the check that the target package can read the schema, which runs
5835
+ * as soon as the target is known. A target package without a Prisma 7
5836
+ * source makes this a fresh init, unless the flag asked for the schema.
5837
+ * `prisma.config.ts` counts as a file to replace only when it is init's own; a
5838
+ * Prisma 7 config there is renamed under the side-by-side consent, and one
5839
+ * that cannot be told apart is refused rather than overwritten.
5840
+ */
5841
+ async function resolvePrisma7Inputs(ctx) {
5842
+ const { cwd, flags, prompt, detection, flagTarget } = ctx;
5843
+ const { config, schema } = detection;
5844
+ if (config.kind === "collision") throw errorInitPrisma7ConfigCollision(config);
5845
+ if (config.kind === "unreadable" && config.path.startsWith(PRISMA7_CONFIG_STEM)) throw errorInitPrisma7ConfigUnreadable(config);
5846
+ if (schema.kind !== "datasource") throw errorInitPrisma7SchemaInvalid({
5847
+ schemaPath: schema.path,
5848
+ reason: schema.kind
5849
+ });
5850
+ const targetResult = prisma7Target(schema, flagTarget, flags.target);
5851
+ if (!targetResult.ok) throw targetResult.failure;
5852
+ const target = targetResult.value;
5853
+ const check = await ctx.checkPrisma7Source({
5854
+ target,
5855
+ schemaPath: schema.path
5856
+ });
5857
+ if (check.outcome === "no-source" && flags.fromPrisma7Schema !== void 0) throw errorInitPrisma7SourceUnavailable({
5858
+ schemaPath: schema.path,
5859
+ packageName: check.packageName,
5860
+ reason: "no-prisma7-source",
5861
+ added: check.added
5862
+ });
5863
+ try {
5864
+ if (check.outcome === "no-source") {
5865
+ ctx.warn(freshInitWarning(check.packageName, detection));
5866
+ return await resolveStarterInputs({
5867
+ cwd,
5868
+ flags,
5869
+ prompt,
5870
+ target,
5871
+ flagAuthoring: void 0,
5872
+ prisma7SchemaPath: void 0,
5873
+ warnings: [...detection.warnings, ...check.warnings],
5874
+ installed: check.installed
5875
+ });
5876
+ }
5877
+ return await confirmPrisma7Inputs({
5878
+ cwd,
5879
+ flags,
5880
+ prompt,
5881
+ detection,
5882
+ schema,
5883
+ target,
5884
+ check
5885
+ });
5886
+ } catch (error) {
5887
+ throw check.added === void 0 ? error : withPackagesAddedAction(error, check.added);
5888
+ }
5889
+ }
5890
+ function prisma7ConfigAfterInit(detection, sideBySide) {
5891
+ const rename = sideBySide?.renameConfig;
5892
+ if (rename !== void 0 && rename !== null) return `prisma7.config.${rename.extension}`;
5893
+ const { config } = detection;
5894
+ return config.kind === "prisma7" || config.kind === "unreadable" ? config.path : void 0;
5895
+ }
5896
+ /** The consents and questions of the Prisma 7 path, once the check has read the schema. */
5897
+ async function confirmPrisma7Inputs(ctx) {
5898
+ const { cwd, flags, prompt, detection, schema, target, check } = ctx;
5899
+ const { config } = detection;
5900
+ const prisma7ConfigOccupiesConfigFile = config.kind === "prisma7" && config.path === "prisma.config.ts";
5901
+ const reinit = await requireReinitConsent({
5902
+ cwd,
5903
+ prompt,
5904
+ replaced: generatedFilesPrisma7PathReplaces().filter((relative) => (relative !== "prisma.config.ts" || !prisma7ConfigOccupiesConfigFile) && existsSync(join(cwd, relative)))
5905
+ });
5906
+ const sideBySide = sideBySidePlan(detection);
5907
+ if (sideBySide !== null) {
5908
+ if (!await prompt.consent(sideBySideQuestion(sideBySide), { token: consentToken(cwd) })) throw errorInitUserAborted();
5909
+ }
5910
+ const writeEnv = await askWriteEnv(flags, prompt);
5911
+ const removePreviousFacade = await resolveRemovePreviousFacade({
5912
+ cwd,
5913
+ target,
5914
+ reinit,
5915
+ keepPreviousFacade: flags.keepPreviousFacade,
5916
+ prompt
5917
+ });
5918
+ return {
5919
+ target,
5920
+ authoring: "psl",
5921
+ schemaPath: schema.path,
5922
+ contractSource: {
5923
+ kind: "prisma7-schema",
5924
+ schemaPath: schema.path,
5925
+ provider: schema.provider,
5926
+ prisma7Config: prisma7ConfigAfterInit(detection, sideBySide)
5927
+ },
5928
+ sideBySide,
5929
+ warnings: [...detection.warnings, ...check.warnings],
5930
+ install: !flags.skipInstall,
5931
+ preinstalled: check.installed,
5932
+ writeEnv,
5933
+ probeDb: flags.probeDb,
5934
+ strictProbe: flags.strictProbe,
5935
+ reinit,
5936
+ removePreviousFacade
5937
+ };
5938
+ }
5939
+ /** A fresh init: a starter schema for the target, asked for where no flag settles it. */
5940
+ async function resolveStarterInputs(ctx) {
5941
+ const { cwd, flags, prompt, flagAuthoring } = ctx;
4758
5942
  let target;
4759
5943
  let authoring;
4760
5944
  try {
4761
- target = flagTarget ?? await askTarget(prompt);
5945
+ target = ctx.target ?? await askTarget(prompt);
4762
5946
  authoring = flagAuthoring ?? await askAuthoring(prompt);
4763
5947
  } catch (error) {
4764
5948
  if (!isPromptRequired(error)) throw error;
4765
5949
  throw errorInitMissingFlags({
4766
- missing: [...flagTarget === void 0 ? ["target"] : [], ...flagAuthoring === void 0 ? ["authoring"] : []].filter((flag) => REQUIRED_FLAG_PROMPTS.has(flag)),
4767
- why: "This session cannot prompt, so the answers have to arrive as flags."
5950
+ missing: [...ctx.target === void 0 ? ["target"] : [], ...flagAuthoring === void 0 ? ["authoring"] : []].filter((flag) => REQUIRED_FLAG_PROMPTS.has(flag)),
5951
+ why: "This session cannot prompt, so the answers have to arrive as flags.",
5952
+ prisma7SchemaPath: ctx.prisma7SchemaPath
4768
5953
  });
4769
5954
  }
4770
5955
  const schemaPath = flags.schemaPath !== void 0 ? validateSchemaPath(flags.schemaPath, authoring) : await askSchemaPath(prompt, authoring);
4771
- const replaced = generatedFilesInitReplaces(schemaPath).filter((relative) => existsSync(join(cwd, relative)));
4772
- const reinit = replaced.length > 0;
4773
- if (reinit) {
4774
- if (!await prompt.consent(consentQuestion(replaced), { token: consentToken(cwd) })) throw errorInitUserAborted();
4775
- }
4776
- const writeEnv = flags.writeEnv || await prompt.confirm("Also write a .env file from .env.example? (gitignored)", { default: false });
5956
+ const reinit = await requireReinitConsent({
5957
+ cwd,
5958
+ prompt,
5959
+ replaced: generatedFilesInitReplaces(schemaPath).filter((relative) => existsSync(join(cwd, relative)))
5960
+ });
5961
+ const writeEnv = await askWriteEnv(flags, prompt);
4777
5962
  const removePreviousFacade = await resolveRemovePreviousFacade({
4778
5963
  cwd,
4779
5964
  target,
@@ -4785,7 +5970,15 @@ async function resolveInitInputs(ctx) {
4785
5970
  target,
4786
5971
  authoring,
4787
5972
  schemaPath,
5973
+ contractSource: {
5974
+ kind: "starter",
5975
+ authoring,
5976
+ schemaPath
5977
+ },
5978
+ sideBySide: null,
5979
+ warnings: ctx.warnings,
4788
5980
  install: !flags.skipInstall,
5981
+ preinstalled: ctx.installed,
4789
5982
  writeEnv,
4790
5983
  probeDb: flags.probeDb,
4791
5984
  strictProbe: flags.strictProbe,
@@ -4794,125 +5987,58 @@ async function resolveInitInputs(ctx) {
4794
5987
  };
4795
5988
  }
4796
5989
  /**
4797
- * Recognised pnpm error signatures that justify a fallback to npm.
4798
- *
4799
- * These patterns indicate the published artifact itself is at fault
4800
- * (a leaked `workspace:*` or `catalog:` specifier), not the user's
4801
- * environment — pnpm is faithfully reporting "I cannot resolve this
4802
- * registry version", and npm is willing to install it because npm
4803
- * doesn't care about the protocol prefix when there's a fallback range.
5990
+ * Resolves every input from the flags and, where a flag is absent, from the
5991
+ * engine's prompt surface.
4804
5992
  *
4805
- * The predicate lives on its own so both shells' `init` share one list:
4806
- * the commander command matches it against captured child stderr, the
4807
- * engine command against the stderr the package-manager capability
4808
- * returns on a failed install.
4809
- */
4810
- function isRecognisedPnpmResolutionError(stderr) {
4811
- if (!stderr) return false;
4812
- return stderr.includes("ERR_PNPM_WORKSPACE_PKG_NOT_FOUND") || stderr.includes("ERR_PNPM_NO_MATCHING_VERSION") || /No matching version found for .* in the catalog/i.test(stderr) || /workspace:[^\s]+ is not a valid (version|spec)/i.test(stderr) || /catalog:[^\s]* is not a valid (version|spec)/i.test(stderr);
4813
- }
4814
- function metaString(failure, key) {
4815
- const value = failure.meta?.[key];
4816
- return typeof value === "string" ? value : "";
4817
- }
4818
- /**
4819
- * pnpm reported a specifier the published artifact leaked, which npm installs
4820
- * happily. The engine redacts credentials out of the stderr it returns but
4821
- * leaves error codes alone, which is what this reads.
4822
- */
4823
- function pnpmLeakedASpecifier(failure) {
4824
- return metaString(failure, "manager") === "pnpm" && isRecognisedPnpmResolutionError(metaString(failure, "stderrTail"));
4825
- }
4826
- /**
4827
- * The engine redacts the stderr it hands back, and this redacts it again
4828
- * before quoting it: what the engine strips is its own business, and registry
4829
- * auth material is not all URL-shaped.
4830
- */
4831
- function fallbackWarning(failure) {
4832
- const firstLine = redactSecrets(metaString(failure, "stderrTail")).trim().split("\n")[0] ?? "";
4833
- return [
4834
- "pnpm could not install: a published Prisma ORM dependency leaked a `workspace:*` or `catalog:` specifier.",
4835
- "Falling back to npm so init can complete.",
4836
- firstLine === "" ? "" : ` pnpm error: ${firstLine}`,
4837
- "Both installs ran under npm, which writes a package-lock.json beside the pnpm lockfile — delete whichever of the two you do not want to keep.",
4838
- "Once the offending package republishes a clean version, re-run `pnpm install` to switch back."
4839
- ].filter((line) => line !== "").join("\n");
4840
- }
4841
- /** The pnpm failure the npm retry was meant to recover from, kept alongside the npm one. */
4842
- function retriedWarning(failure) {
4843
- const firstLine = redactSecrets(metaString(failure, "stderrTail")).trim().split("\n")[0] ?? "";
4844
- return ["pnpm failed first with a leaked `workspace:*` or `catalog:` specifier, so init retried with npm.", firstLine === "" ? "" : ` pnpm error: ${firstLine}`].filter((line) => line !== "").join("\n");
4845
- }
4846
- /**
4847
- * Adds the runtime and development dependencies through the engine's package
4848
- * manager. The retry is `init`'s alone: the engine spells and runs the
4849
- * command, and this decides — from the stderr it returned — that another
4850
- * manager is worth a try.
4851
- */
4852
- /**
4853
- * The engine dependency spec a fresh scaffold installs. The scaffolded
4854
- * `prisma.config.ts` imports `definePrismaConfig` from `@prisma/cli-engine`, and the
4855
- * installed `prisma` names the exact engine version it runs against — so
4856
- * the spec is read from the manifest the install just placed, never guessed
4857
- * from a dist-tag (whose `latest` has lagged that version before and broken
4858
- * the very next command). A CLI without a readable engine entry falls back to
4859
- * the `next` tag, the release train the CLI itself publishes under.
5993
+ * Order matters twice. Every flag value is validated before anything is asked,
5994
+ * so a typo costs a typo rather than a typed consent token. And consent comes
5995
+ * as soon as the schema path is known, because that is the point at which the
5996
+ * question can name the files it is about — and before any question whose
5997
+ * answer only matters if the run proceeds.
4860
5998
  */
4861
- function engineDevDependencySpec(cwd) {
4862
- try {
4863
- const manifest = JSON.parse(readFileSync(join(cwd, "node_modules", "prisma", "package.json"), "utf-8"));
4864
- if (typeof manifest === "object" && manifest !== null) for (const field of ["dependencies", "peerDependencies"]) {
4865
- const block = Reflect.get(manifest, field);
4866
- if (typeof block === "object" && block !== null) {
4867
- const engine = Reflect.get(block, "@prisma/cli-engine");
4868
- if (typeof engine === "string" && engine.length > 0) return `@prisma/cli-engine@${engine}`;
4869
- }
4870
- }
4871
- } catch {}
4872
- return "@prisma/cli-engine@latest";
4873
- }
4874
- async function installProjectDependencies(ctx) {
4875
- const pair = async (manager) => {
4876
- const runtimeDeps = await ctx.packages.install({
4877
- packages: ctx.deps,
4878
- cwd: ctx.cwd,
4879
- ...ifDefined("manager", manager)
5999
+ async function resolveInitInputs(ctx) {
6000
+ const { cwd, flags, prompt } = ctx;
6001
+ if (flags.strictProbe && !flags.probeDb) throw errorInitStrictProbeWithoutProbe();
6002
+ rejectFlagConflict(flags);
6003
+ const flagTarget = resolveTarget(flags.target);
6004
+ const flagAuthoring = resolveAuthoring(flags.authoring);
6005
+ const mayAdoptPrisma7 = flags.fromPrisma7Schema !== void 0 || flagAuthoring === void 0 && flags.schemaPath === void 0;
6006
+ let prisma7SchemaPath;
6007
+ if (mayAdoptPrisma7) {
6008
+ const detection = await detectPrisma7Project({
6009
+ cwd,
6010
+ schemaPath: flags.fromPrisma7Schema
4880
6011
  });
4881
- if (!runtimeDeps.ok) return runtimeDeps.failure;
4882
- const developmentDeps = await ctx.packages.install({
4883
- packages: ctx.devDeps,
4884
- dev: true,
4885
- cwd: ctx.cwd,
4886
- ...ifDefined("manager", manager)
6012
+ if (await choosePrisma7Path({
6013
+ flags,
6014
+ prompt,
6015
+ detection,
6016
+ flagTarget
6017
+ })) return resolvePrisma7Inputs({
6018
+ cwd,
6019
+ flags,
6020
+ prompt,
6021
+ detection,
6022
+ flagTarget,
6023
+ checkPrisma7Source: ctx.checkPrisma7Source,
6024
+ warn: ctx.warn
4887
6025
  });
4888
- return developmentDeps.ok ? void 0 : developmentDeps.failure;
4889
- };
4890
- const failure = await pair();
4891
- if (failure === void 0) return {
4892
- failure: void 0,
4893
- manager: void 0,
4894
- warnings: ctx.catalogWarnings
4895
- };
4896
- if (!pnpmLeakedASpecifier(failure)) return {
4897
- failure,
4898
- manager: void 0,
4899
- warnings: []
4900
- };
4901
- const retryFailure = await pair("npm");
4902
- if (retryFailure !== void 0) return {
4903
- failure: retryFailure,
4904
- manager: void 0,
4905
- warnings: [retriedWarning(failure)]
4906
- };
4907
- return {
4908
- failure: void 0,
4909
- manager: "npm",
4910
- warnings: [fallbackWarning(failure)]
4911
- };
6026
+ prisma7SchemaPath = looksLikePrisma7(detection) ? detection.schema.path : void 0;
6027
+ }
6028
+ return resolveStarterInputs({
6029
+ cwd,
6030
+ flags,
6031
+ prompt,
6032
+ target: flagTarget,
6033
+ flagAuthoring,
6034
+ prisma7SchemaPath,
6035
+ warnings: [],
6036
+ installed: []
6037
+ });
4912
6038
  }
4913
- /** The scaffold is on disk from here on, so each of these is a finding. */
6039
+ /** Each of these is a finding on a completed run, not an error. */
4914
6040
  const INIT_EXIT_CODES = {
4915
- 4: "scaffold written; dependency install failed",
6041
+ 4: "dependency install failed",
4916
6042
  5: "scaffold written and installed; contract emit failed"
4917
6043
  };
4918
6044
  function probeWarning(outcome, strictProbe) {
@@ -4936,19 +6062,23 @@ function probeWarning(outcome, strictProbe) {
4936
6062
  };
4937
6063
  }
4938
6064
  }
6065
+ function outputTarget(target) {
6066
+ return target === "mongo" ? "mongodb" : "postgres";
6067
+ }
4939
6068
  function causeMessage(error) {
4940
6069
  return error instanceof Error ? error.message : String(error);
4941
6070
  }
4942
6071
  const createInitCommand = (injected) => defineOrmCommand({
4943
6072
  help: {
4944
6073
  summary: "Initialize a new Prisma ORM project",
4945
- description: "Scaffolds config, schema, and runtime files, installs dependencies,\nand emits the contract. Gets you from zero to typed queries in one step.\n\nRun it interactively for a guided setup, or supply --target and --authoring\nfor a fully scriptable run (CI, AI coding agents, automation).",
6074
+ description: "Scaffolds config, schema, and runtime files, installs dependencies,\nand emits the contract. Gets you from zero to typed queries in one step.\n\nRun it interactively for a guided setup, or supply --target and --authoring\nfor a fully scriptable run (CI, AI coding agents, automation).\n\nIn a Prisma 7 project, pass --from-prisma7-schema (or answer yes when asked)\nto use the existing schema.prisma as the contract source.",
4946
6075
  examples: [
4947
6076
  "orm init",
4948
6077
  "orm init --target postgres --authoring psl",
4949
6078
  "orm init --target mongodb --authoring typescript --json",
4950
6079
  "orm init --skip-install",
4951
- "orm init --target postgres --keep-previous-facade"
6080
+ "orm init --target postgres --keep-previous-facade",
6081
+ "orm init --from-prisma7-schema prisma/schema.prisma --confirm my-app"
4952
6082
  ]
4953
6083
  },
4954
6084
  args: { flags: {
@@ -4968,7 +6098,11 @@ const createInitCommand = (injected) => defineOrmCommand({
4968
6098
  probeDb: flag.boolean({ brief: "Connect to DATABASE_URL once and check the server version" }),
4969
6099
  strictProbe: flag.boolean({ brief: "Treat a failed --probe-db as fatal" }),
4970
6100
  skipInstall: flag.boolean({ brief: "Skip dependency installation and contract emission" }),
4971
- keepPreviousFacade: flag.boolean({ brief: "Keep the previous target package in package.json when switching targets" })
6101
+ keepPreviousFacade: flag.boolean({ brief: "Keep the previous target package in package.json when switching targets" }),
6102
+ fromPrisma7Schema: flag.string({
6103
+ brief: "Use an existing Prisma 7 schema.prisma as the contract source",
6104
+ placeholder: "path"
6105
+ })
4972
6106
  } },
4973
6107
  exitCodes: INIT_EXIT_CODES,
4974
6108
  installsPackages: true,
@@ -4982,15 +6116,62 @@ const createInitCommand = (injected) => defineOrmCommand({
4982
6116
  text
4983
6117
  });
4984
6118
  };
4985
- const inputs = await resolveInitInputs({
4986
- cwd: ctx.cwd,
4987
- flags: args.flags,
4988
- prompt: ctx.prompt
4989
- });
4990
6119
  const packageManager = await resolveScaffoldPackageManager({
4991
6120
  cwd: ctx.cwd,
4992
6121
  env: ctx.env
4993
6122
  });
6123
+ let inputs;
6124
+ try {
6125
+ inputs = await resolveInitInputs({
6126
+ cwd: ctx.cwd,
6127
+ flags: args.flags,
6128
+ prompt: ctx.prompt,
6129
+ checkPrisma7Source: createPrisma7SourceCheck({
6130
+ cwd: ctx.cwd,
6131
+ packages: ctx.packages,
6132
+ packageManager,
6133
+ install: !args.flags.skipInstall,
6134
+ importFromProject: injected.importFromProject
6135
+ }),
6136
+ warn
6137
+ });
6138
+ } catch (error) {
6139
+ if (!(error instanceof Prisma7CheckInstallFailed)) throw error;
6140
+ for (const warning of error.warnings) warn(warning);
6141
+ const document = {
6142
+ ok: true,
6143
+ target: outputTarget(error.target),
6144
+ authoring: "prisma7",
6145
+ schemaPath: error.schemaPath,
6146
+ filesWritten: [],
6147
+ filesDeleted: [],
6148
+ filesRenamed: [],
6149
+ packagesInstalled: {
6150
+ status: "failed",
6151
+ deps: [],
6152
+ devDeps: []
6153
+ },
6154
+ contractEmitted: false,
6155
+ prisma7: {
6156
+ schemaPath: error.schemaPath,
6157
+ configRenamedTo: null,
6158
+ scriptsRewritten: [],
6159
+ packagesMoved: []
6160
+ },
6161
+ nextSteps: [...NEXT_STEPS_BEFORE_SCAFFOLD],
6162
+ warnings
6163
+ };
6164
+ return ok$1(ctx.present({
6165
+ data: document,
6166
+ exitCode: 4,
6167
+ diagnostics: [installFailedFinding(error.failure, [])]
6168
+ }, initPresentations({
6169
+ document,
6170
+ complete: false,
6171
+ nextActions: []
6172
+ })));
6173
+ }
6174
+ for (const warning of inputs.warnings) warn(warning);
4994
6175
  const scaffold = scaffoldProject({
4995
6176
  cwd: ctx.cwd,
4996
6177
  inputs,
@@ -5002,9 +6183,23 @@ const createInitCommand = (injected) => defineOrmCommand({
5002
6183
  severity: "info",
5003
6184
  text: note
5004
6185
  });
5005
- const deps = [targetPackageName(inputs.target, scaffold.resolveImportSpecifier), "dotenv"];
6186
+ const movePackages = inputs.sideBySide?.movePackages ?? null;
6187
+ const clientMajor = movePackages?.clientVersion === void 0 ? void 0 : versionMajor(movePackages.clientVersion);
6188
+ const moveClient = movePackages !== null && clientMajor !== void 0 && clientMajor < 7;
6189
+ const deps = [
6190
+ targetPackageName(inputs.target, scaffold.resolveImportSpecifier),
6191
+ "dotenv",
6192
+ ...moveClient ? ["@prisma/client@7"] : []
6193
+ ];
6194
+ const depsToInstall = deps.filter((dep) => !inputs.preinstalled.includes(dep));
5006
6195
  const cliDevDeps = ["prisma@latest"];
5007
- const devDeps = scaffold.hasTypesNode ? cliDevDeps : [...cliDevDeps, "@types/node"];
6196
+ const devDeps = [...scaffold.hasTypesNode ? cliDevDeps : [...cliDevDeps, "@types/node"], ...movePackages !== null ? ["@prisma/prisma7@7"] : []];
6197
+ const packagesMoved = [...moveClient ? ["@prisma/client@7"] : [], ...movePackages !== null ? ["@prisma/prisma7@7"] : []];
6198
+ const adoptsPrisma7 = inputs.contractSource.kind === "prisma7-schema";
6199
+ const prisma7Steps = adoptsPrisma7 ? {
6200
+ packagesMoved,
6201
+ clientMoved: moveClient
6202
+ } : null;
5008
6203
  const findings = [];
5009
6204
  const extraActions = [];
5010
6205
  let packagesInstalled = "skipped";
@@ -5013,23 +6208,31 @@ const createInitCommand = (injected) => defineOrmCommand({
5013
6208
  const installed = packagesInstalled === "installed";
5014
6209
  const document = {
5015
6210
  ok: true,
5016
- target: inputs.target === "mongo" ? "mongodb" : "postgres",
5017
- authoring: inputs.authoring,
6211
+ target: outputTarget(inputs.target),
6212
+ authoring: adoptsPrisma7 ? "prisma7" : inputs.authoring,
5018
6213
  schemaPath: inputs.schemaPath,
5019
6214
  filesWritten: scaffold.filesWritten,
5020
6215
  filesDeleted: scaffold.filesDeleted,
6216
+ filesRenamed: scaffold.filesRenamed,
5021
6217
  packagesInstalled: {
5022
6218
  status: packagesInstalled,
5023
- deps: installed ? deps : [],
6219
+ deps: installed ? deps : [...inputs.preinstalled],
5024
6220
  devDeps: installed ? devDeps : []
5025
6221
  },
5026
6222
  contractEmitted,
6223
+ prisma7: adoptsPrisma7 ? {
6224
+ schemaPath: inputs.schemaPath,
6225
+ configRenamedTo: scaffold.filesRenamed[0]?.to ?? null,
6226
+ scriptsRewritten: [...scaffold.scriptsRewritten],
6227
+ packagesMoved
6228
+ } : null,
5027
6229
  nextSteps: buildNextSteps({
5028
- target: inputs.target === "mongo" ? "mongodb" : "postgres",
6230
+ target: outputTarget(inputs.target),
5029
6231
  packagesInstalled,
5030
6232
  contractEmitted,
5031
6233
  emitCommand: EMIT_COMMAND,
5032
- schemaPath: inputs.schemaPath
6234
+ schemaPath: inputs.schemaPath,
6235
+ prisma7: prisma7Steps
5033
6236
  }),
5034
6237
  warnings
5035
6238
  };
@@ -5048,7 +6251,8 @@ const createInitCommand = (injected) => defineOrmCommand({
5048
6251
  complete: exitCode === 0,
5049
6252
  nextActions: [...extraActions, ...buildInitNextActions({
5050
6253
  contractEmitted,
5051
- schemaPath: inputs.schemaPath
6254
+ schemaPath: inputs.schemaPath,
6255
+ prisma7: prisma7Steps
5052
6256
  })]
5053
6257
  })));
5054
6258
  };
@@ -5056,9 +6260,9 @@ const createInitCommand = (injected) => defineOrmCommand({
5056
6260
  const outcome = await installProjectDependencies({
5057
6261
  packages: ctx.packages,
5058
6262
  cwd: ctx.cwd,
5059
- deps,
6263
+ deps: depsToInstall,
5060
6264
  devDeps,
5061
- catalogWarnings: packageManager === "pnpm" ? buildCatalogWarnings(ctx.cwd, [...deps, ...devDeps]) : []
6265
+ catalogWarnings: packageManager === "pnpm" ? buildCatalogWarnings(ctx.cwd, [...depsToInstall, ...devDeps]) : []
5062
6266
  });
5063
6267
  for (const warning of outcome.warnings) warn(warning);
5064
6268
  if (outcome.failure !== void 0) {
@@ -5119,7 +6323,10 @@ const createInitCommand = (injected) => defineOrmCommand({
5119
6323
  return settle(0);
5120
6324
  }
5121
6325
  });
5122
- const initCommand = createInitCommand({ emitScaffoldedContract });
6326
+ const initCommand = createInitCommand({
6327
+ emitScaffoldedContract,
6328
+ importFromProject
6329
+ });
5123
6330
  /**
5124
6331
  * R-S5-12 asks every command to end at 143 for SIGTERM and 130 otherwise, and
5125
6332
  * a server command is the one kind the engine leaves to do it: it settles the
@@ -5147,7 +6354,7 @@ const lspCommand = defineServerCommand({
5147
6354
  } },
5148
6355
  handler: async (args, io) => {
5149
6356
  const exitCode = await withoutClientProcessIdInArgv(async () => {
5150
- const { startServer } = await import("./exports-uepvbfMs.mjs");
6357
+ const { startServer } = await import("./exports-BiGALu6k.mjs");
5151
6358
  return startServer({
5152
6359
  stdin: io.stdin,
5153
6360
  stdout: io.stdout,