Skip to content

Commit 1d24ff7

Browse files
fix(cli): CLI.SECOND_PACKAGE_COPY gives the bin path of the project's prisma unless it is installed in the current folder (#424)
## What the user sees `prisma` refuses an ORM or Composer command with `CLI.SECOND_PACKAGE_COPY` when the `prisma` you ran would load a different copy of the ORM packages than your project's own. The refusal is right: values made by one copy are rejected by the other. Its advice is to run the project's own `prisma` instead. In one case that advice did not work. In prisma/pdp-control-plane, a pnpm monorepo, a user ran the workspace root's `prisma contract emit` in `services/control-plane/scripts/usage-testing/`. That folder has no `package.json`. The project's own `prisma` there is `services/control-plane/node_modules/prisma`, two folders up: ```text # Before: pnpm runs the workspace root's prisma, the one that was just refused ✘ [CLI.SECOND_PACKAGE_COPY] prisma contract emit cannot run here: … → pnpm exec prisma contract emit # After: the advice names the prisma the error found ✘ [CLI.SECOND_PACKAGE_COPY] prisma contract emit cannot run here: … → ../../node_modules/.bin/prisma contract emit ``` On Windows the path is `..\..\node_modules\.bin\prisma`, which cmd.exe and PowerShell both run. ## Why The error finds the project's `prisma` the way Node does: it walks up from the current folder to the nearest `node_modules/prisma`. The advice then ran `prisma` through the package manager (`pnpm exec`, `npx --no-install`, `yarn exec`, `bunx --no-install`), and the package managers do not all look in the same place: - pnpm 10.34.9 (the incident's version) looks in the current folder's `node_modules/.bin` and then the workspace root's, skipping the folders between. So it ran the root's `prisma`. - pnpm 10.27, tried locally, fails in a folder with `node_modules` but no `package.json`. - npx and bunx walk up from the nearest folder with a `package.json`, which usually finds the right one. Yarn was not tried. A path to the bin runs the right `prisma` with every package manager. The runner form runs it with every package manager only when the project's `prisma` is installed in the current folder and that folder has a `package.json`. So the advice now uses the runner form only in that case, and the path otherwise. That gives npm and Bun users a path in some folders where their runner would also have worked. We accept that: the advice must work wherever it is given, and the error cannot tell which runner's search the user's version does. ## What changes - `packages/cli/src/second-copy.ts`: the rule above. The advice keeps any `--config` the user gave. The platform is passed in, so the tests check both path forms on any machine. - `packages/cli/src/lib/package-copies.ts`: the finder also returns the `node_modules` folder it found `prisma` in. The bin path is built from that folder as found, not from the package's real path, because under pnpm the real path is inside `node_modules/.pnpm`, which has no `.bin`. - `docs/reference/error-reference.md`: the `CLI.SECOND_PACKAGE_COPY` entry states the rule. It also corrects two runners it named wrongly (`yarn run` and `bun run`; the code uses `yarn exec` and `bunx --no-install`). ## How it was checked - New tests in `tests/second-copy.test.ts` cover the incident's layout, `--config`, a `prisma` in a folder with no `package.json`, a `package.json` with `prisma` only further up, and the Windows form. Removing either condition of the rule fails a test. - `tests/second-copy.test.ts` and `tests/package-copies.test.ts` pass. Typecheck and lint are clean. - A separate reviewer reviewed the code. Its findings are fixed. ## Alternatives considered - **Always give the bin path.** Rejected: where the runner surely works, `pnpm exec prisma` is the form users know, and it reads the same on every system. - **Point the runner at the right package** (for example `pnpm --filter <package> exec`). Rejected: the folder may belong to no package, as in the incident, and each package manager needs its own form. Agent: cobain-55 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: willbot <w.a.madden+machine@gmail.com> Signed-off-by: Will Madden <madden@prisma.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d613f48 commit 1d24ff7

5 files changed

Lines changed: 233 additions & 35 deletions

File tree

‎docs/reference/error-reference.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ A prompt with no declared default was reached where it cannot be shown — under
238238

239239
### CLI.SECOND_PACKAGE_COPY
240240

241-
An ORM or Composer command was refused because the project has its own copy of a Prisma package the command loads (`@prisma/orm-toolchain` or `@prisma/orm-framework`, and `@prisma/composer` for Composer commands), and the running `prisma` would load a different copy: another version, or the same version installed in another place, such as a global `prisma`. Values made by one copy are refused by the other, and what the command writes is read later by the project's own copy, so the run stops before the project's `prisma.config.ts` is evaluated. Refused are the commands that read the project's config, plus `orm init` (it loads the project's own ORM packages and writes files the project reads) and `lsp` (it loads the project's config itself); `emulator list` is not refused. The project's copies are looked for from one directory: the directory of the `--config` file (its real path, when it is a link) when one is given, otherwise the directory of the nearest `prisma.config.ts` at or above the current directory within the repository (the first directory with a `.git` entry), otherwise the current directory. From there, the nearest `node_modules/<package>` up to the repository root counts. Config files further up, and `parent` links, are not followed, so a copy beside a repository-wide config does not refuse a package's own command. Nor are files the config points to in another directory, most often the contract source: they load the packages from where they are, so a copy beside them is not compared. A package the project does not install, or whose copy cannot be read, is not checked. The summary names the first package that differs and both versions; `why` gives every differing package with both versions and both locations, and says so when the versions are equal. Next actions: when the project has its own `prisma`, it is not the one running, and it would not be refused, a run-command with the command path, and the `--config` the user gave, in a form that never downloads a package (`npx --no-install prisma`, `pnpm exec prisma`, `yarn run prisma`, `bun run prisma`); the user adds their other arguments, which are left out because they can hold a database URL; when that `prisma` is reachable only through `--config`, the same advice in words. When the `prisma` the user would run is refused too, the versions to change the project's packages to, or the project's versions a `prisma` release must use; for the same version installed twice, to reinstall the project's dependencies. When the project has no `prisma`, to install it in the project and run that one. Raised by the shell before the command runs; if the check itself fails, nothing is refused. `--help` is unaffected. Exits 2. Meta: `command` (the command path, such as `db migrate`), `packages` (a list of `{ name, project: { version, path }, cli: { version, path } }`).
241+
An ORM or Composer command was refused because the project has its own copy of a Prisma package the command loads (`@prisma/orm-toolchain` or `@prisma/orm-framework`, and `@prisma/composer` for Composer commands), and the running `prisma` would load a different copy: another version, or the same version installed in another place, such as a global `prisma`. Values made by one copy are refused by the other, and what the command writes is read later by the project's own copy, so the run stops before the project's `prisma.config.ts` is evaluated. Refused are the commands that read the project's config, plus `orm init` (it loads the project's own ORM packages and writes files the project reads) and `lsp` (it loads the project's config itself); `emulator list` is not refused. The project's copies are looked for from one directory: the directory of the `--config` file (its real path, when it is a link) when one is given, otherwise the directory of the nearest `prisma.config.ts` at or above the current directory within the repository (the first directory with a `.git` entry), otherwise the current directory. From there, the nearest `node_modules/<package>` up to the repository root counts. Config files further up, and `parent` links, are not followed, so a copy beside a repository-wide config does not refuse a package's own command. Nor are files the config points to in another directory, most often the contract source: they load the packages from where they are, so a copy beside them is not compared. A package the project does not install, or whose copy cannot be read, is not checked. The summary names the first package that differs and both versions; `why` gives every differing package with both versions and both locations, and says so when the versions are equal. Next actions: when the project has its own `prisma`, it is not the one running, and it would not be refused, a run-command with the command path, and the `--config` the user gave, in a form that never downloads a package: the package manager's runner (`npx --no-install prisma`, `pnpm exec prisma`, `yarn exec prisma`, `bunx --no-install prisma`) when that `prisma` is installed in the current directory and the directory has a `package.json`, otherwise the path of its bin from the current directory, such as `../../node_modules/.bin/prisma` (`..\..\node_modules\.bin\prisma` on Windows), because the runners do not search parent folders the way Node does; the user adds their other arguments, which are left out because they can hold a database URL; when that `prisma` is reachable only through `--config`, the same advice in words. When the `prisma` the user would run is refused too, the versions to change the project's packages to, or the project's versions a `prisma` release must use; for the same version installed twice, to reinstall the project's dependencies. When the project has no `prisma`, to install it in the project and run that one. Raised by the shell before the command runs; if the check itself fails, nothing is refused. `--help` is unaffected. Exits 2. Meta: `command` (the command path, such as `db migrate`), `packages` (a list of `{ name, project: { version, path }, cli: { version, path } }`).
242242

243243
### CLI.SPAWN_FAILED
244244

‎packages/cli/src/lib/package-copies.ts‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,32 @@ export async function findProjectPackage(
134134
dir: string,
135135
name: string,
136136
): Promise<Result<PackageCopy | null, PackageCopyUnreadableError>> {
137-
const packageDir = searchDirs(path.resolve(dir))
138-
.map((candidate) => path.join(candidate, "node_modules", name))
139-
.find((candidate) => existsSync(path.join(candidate, "package.json")));
140-
return packageDir === undefined ? Result.ok(null) : readCopy(packageDir);
137+
const found = await findProjectInstall(dir, name);
138+
return found.map((install) => install?.copy ?? null);
139+
}
140+
141+
export interface ProjectInstall {
142+
readonly copy: PackageCopy;
143+
/** The `node_modules` folder the package was found in, as found,
144+
* before links are followed. */
145+
readonly nodeModules: string;
146+
}
147+
148+
/** `findProjectPackage`, also saying where the package was found. */
149+
export async function findProjectInstall(
150+
dir: string,
151+
name: string,
152+
): Promise<Result<ProjectInstall | null, PackageCopyUnreadableError>> {
153+
const nodeModules = searchDirs(path.resolve(dir))
154+
.map((candidate) => path.join(candidate, "node_modules"))
155+
.find((candidate) =>
156+
existsSync(path.join(candidate, name, "package.json")),
157+
);
158+
if (nodeModules === undefined) {
159+
return Result.ok(null);
160+
}
161+
const copy = await readCopy(path.join(nodeModules, name));
162+
return copy.map((read) => ({ copy: read, nodeModules }));
141163
}
142164

143165
async function findShellPackage(

‎packages/cli/src/main.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export async function main(
2222
const refusedCommands = await refusedCommandsFor({
2323
argv: proc.argv.slice(2),
2424
cwd: proc.cwd(),
25+
platform: proc.platform,
2526
}).catch(() => []);
2627
let cli: Cli;
2728
try {

‎packages/cli/src/second-copy.ts‎

Lines changed: 65 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* writes is read later by the project's own copy, so a second copy
66
* stops the command before the project's config is evaluated.
77
*/
8+
import { existsSync } from "node:fs";
89
import path from "node:path";
910
import { fileURLToPath } from "node:url";
1011
import {
@@ -34,10 +35,10 @@ import { configPathFromArgv, flagTokens } from "./lib/argv";
3435
import {
3536
type CheckedPackage,
3637
COMPOSER_COMMAND_PACKAGES,
37-
findProjectPackage,
38+
findProjectInstall,
3839
findSecondCopies,
3940
ORM_COMMAND_PACKAGES,
40-
type PackageCopy,
41+
type ProjectInstall,
4142
projectPackageDir,
4243
type SecondCopy,
4344
} from "./lib/package-copies";
@@ -120,6 +121,8 @@ export interface SecondCopyCheckRequest {
120121
readonly cwd: string;
121122
/** The file the shell resolves its own packages from. */
122123
readonly shellModuleFile?: string;
124+
/** The platform whose shells the advice is written for. */
125+
readonly platform?: string;
123126
}
124127

125128
/**
@@ -152,6 +155,7 @@ export async function refusedCommandsFor(
152155
}
153156
const recovery = await recoveryFor({
154157
cwd: request.cwd,
158+
platform: request.platform ?? process.platform,
155159
configPath,
156160
projectDir,
157161
shellModuleFile,
@@ -201,7 +205,10 @@ export type SecondCopyRecovery =
201205
* run the command. */
202206
| {
203207
readonly kind: "run-project-prisma";
204-
readonly runner: string;
208+
/** What runs it from the current directory, ready to paste: the
209+
* package manager's runner when that finds this prisma, otherwise
210+
* the path of its bin. */
211+
readonly invocation: string;
205212
/** The `--config` the user gave, kept so the command reads the
206213
* same config. */
207214
readonly configPath: string | undefined;
@@ -226,14 +233,16 @@ export type SecondCopyRecovery =
226233

227234
async function recoveryFor(request: {
228235
readonly cwd: string;
236+
readonly platform: string;
229237
readonly configPath: string | undefined;
230238
readonly projectDir: string;
231239
readonly shellModuleFile: string;
232240
readonly packages: readonly CheckedPackage[];
233241
}): Promise<SecondCopyRecovery> {
234242
const fromCwd = await projectPrismaAt(request.cwd);
235-
const projectPrisma = fromCwd ?? (await projectPrismaAt(request.projectDir));
236-
if (projectPrisma === null) {
243+
const projectPrisma = (fromCwd ?? (await projectPrismaAt(request.projectDir)))
244+
?.copy;
245+
if (projectPrisma === undefined) {
237246
return { kind: "install-project-prisma" };
238247
}
239248
if (isInside(realpathOr(request.shellModuleFile), projectPrisma.path)) {
@@ -257,19 +266,55 @@ async function recoveryFor(request: {
257266
: path.resolve(request.cwd, request.configPath),
258267
};
259268
}
260-
const manager = Result.try(() => detectPackageManagerSync(request.cwd));
261269
return {
262270
kind: "run-project-prisma",
263-
runner: installedBinRunner(
264-
(manager.isOk() ? manager.value : null) ?? "npm",
265-
),
271+
invocation: runnerFinds(request.cwd, fromCwd.nodeModules)
272+
? `${runnerAt(request.cwd)} ${CLI_NAME}`
273+
: binPathFrom(request.cwd, fromCwd.nodeModules, request.platform),
266274
configPath: request.configPath,
267275
};
268276
}
269277

278+
/**
279+
* Whether the package manager's runner, run from `cwd`, runs the prisma
280+
* found in `nodeModules`. The runners do not search parent folders the
281+
* way Node does. Tried with pnpm 10.27: from a folder with a
282+
* `package.json` and no prisma, `pnpm exec` runs the workspace root's
283+
* prisma, and from a folder with `node_modules` but no `package.json`
284+
* it fails. So only a prisma installed in `cwd`, beside a
285+
* `package.json`, is certain.
286+
*/
287+
function runnerFinds(cwd: string, nodeModules: string): boolean {
288+
return (
289+
existsSync(path.join(cwd, "package.json")) &&
290+
nodeModules === path.join(path.resolve(cwd), "node_modules")
291+
);
292+
}
293+
294+
function runnerAt(cwd: string): string {
295+
const manager = Result.try(() => detectPackageManagerSync(cwd));
296+
return installedBinRunner((manager.isOk() ? manager.value : null) ?? "npm");
297+
}
298+
299+
/** The prisma bin in `nodeModules`, by its path from `cwd`. Its words
300+
* are only `.`, `..`, `node_modules`, `.bin` and `prisma`, so it needs
301+
* no quoting; on Windows the backslash form runs in cmd.exe and
302+
* PowerShell alike. */
303+
function binPathFrom(
304+
cwd: string,
305+
nodeModules: string,
306+
platform: string,
307+
): string {
308+
const segments = path
309+
.relative(path.resolve(cwd), path.join(nodeModules, ".bin", CLI_NAME))
310+
.split(path.sep);
311+
const fromCwd = segments[0] === ".." ? segments : [".", ...segments];
312+
return fromCwd.join(platform === "win32" ? "\\" : "/");
313+
}
314+
270315
/** The project's own prisma; an unreadable one counts as none. */
271-
async function projectPrismaAt(dir: string): Promise<PackageCopy | null> {
272-
const found = await findProjectPackage(dir, CLI_NAME);
316+
async function projectPrismaAt(dir: string): Promise<ProjectInstall | null> {
317+
const found = await findProjectInstall(dir, CLI_NAME);
273318
return found.isOk() ? found.value : null;
274319
}
275320

@@ -333,14 +378,15 @@ function nextActions(
333378
{
334379
kind: "run-command",
335380
label: `Run the project's own ${CLI_NAME} instead, adding your other arguments after the command`,
336-
command: formatShellCommand([
337-
...recovery.runner.split(" "),
338-
CLI_NAME,
339-
...commandPath.split(" "),
340-
...(recovery.configPath === undefined
341-
? []
342-
: ["--config", recovery.configPath]),
343-
]),
381+
command: [
382+
recovery.invocation,
383+
formatShellCommand([
384+
...commandPath.split(" "),
385+
...(recovery.configPath === undefined
386+
? []
387+
: ["--config", recovery.configPath]),
388+
]),
389+
].join(" "),
344390
},
345391
];
346392
case "run-project-prisma-elsewhere":

‎packages/cli/tests/second-copy.test.ts‎

Lines changed: 140 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@
66
* temporary folder.
77
*/
88
import { existsSync, readFileSync } from "node:fs";
9-
import { mkdir, mkdtemp, realpath, symlink, writeFile } from "node:fs/promises";
9+
import {
10+
mkdir,
11+
mkdtemp,
12+
realpath,
13+
rm,
14+
symlink,
15+
writeFile,
16+
} from "node:fs/promises";
1017
import { createRequire } from "node:module";
1118
import os from "node:os";
1219
import path from "node:path";
@@ -121,6 +128,16 @@ async function writePackage(
121128
);
122129
}
123130

131+
/** A package at `packageRoot` that installed its own prisma, with the
132+
* bin a package manager links for it. */
133+
async function writePackageWithPrisma(packageRoot: string): Promise<void> {
134+
await writePackage(packageRoot, path.basename(packageRoot), "1.0.0");
135+
const nodeModules = path.join(packageRoot, "node_modules");
136+
await writePackage(path.join(nodeModules, "prisma"), "prisma", "8.0.0-rc.35");
137+
await mkdir(path.join(nodeModules, ".bin"), { recursive: true });
138+
await writeFile(path.join(nodeModules, ".bin", "prisma"), "", "utf8");
139+
}
140+
124141
/** The project installed its own toolchain, at another release than
125142
* the CLI carries. */
126143
async function makeProjectWithSecondCopy(): Promise<{
@@ -635,11 +652,7 @@ describe("a product command in a project with a second copy", () => {
635652
describe("what the error says", () => {
636653
it("offers the project's own prisma, which would pass, as a command that never downloads", async () => {
637654
const { dir } = await makeProjectWithSecondCopy();
638-
await writePackage(
639-
path.join(dir, "node_modules", "prisma"),
640-
"prisma",
641-
"8.0.0-rc.35",
642-
);
655+
await writePackageWithPrisma(dir);
643656
await writeFile(path.join(dir, "pnpm-lock.yaml"), "", "utf8");
644657
const proc = makeProcess({ argv: ["db", "migrate", "--json"], cwd: dir });
645658

@@ -657,11 +670,7 @@ describe("what the error says", () => {
657670

658671
it("keeps the --config the user gave in the suggested command, and nothing else", async () => {
659672
const { dir } = await makeProjectWithSecondCopy();
660-
await writePackage(
661-
path.join(dir, "node_modules", "prisma"),
662-
"prisma",
663-
"8.0.0-rc.35",
664-
);
673+
await writePackageWithPrisma(dir);
665674
await writeFile(path.join(dir, "package-lock.json"), "{}", "utf8");
666675
const configDir = path.join(dir, "config dir");
667676
await mkdir(configDir, { recursive: true });
@@ -691,6 +700,126 @@ describe("what the error says", () => {
691700
]);
692701
});
693702

703+
describe("from a folder of a workspace package that has no package.json", () => {
704+
/** A pnpm workspace whose root and whose package each installed
705+
* prisma, and a folder inside the package holding a config. */
706+
async function makeWorkspaceFolder(): Promise<string> {
707+
const root = path.join(await makeRoot(), "monorepo");
708+
await mkdir(path.join(root, ".git"), { recursive: true });
709+
await writePackageWithPrisma(root);
710+
await writeFile(
711+
path.join(root, "pnpm-workspace.yaml"),
712+
"packages:\n - services/*\n",
713+
"utf8",
714+
);
715+
await writeFile(path.join(root, "pnpm-lock.yaml"), "", "utf8");
716+
const service = path.join(root, "services", "control-plane");
717+
await writePackageWithPrisma(service);
718+
await writePackage(
719+
path.join(service, "node_modules", TOOLCHAIN),
720+
TOOLCHAIN,
721+
"8.0.0-rc.24",
722+
);
723+
const folder = path.join(service, "scripts", "usage-testing");
724+
await mkdir(folder, { recursive: true });
725+
await writeFile(path.join(folder, "prisma.config.ts"), "", "utf8");
726+
return folder;
727+
}
728+
729+
it("gives the path of the package's prisma, which pnpm exec would not run", async () => {
730+
const cwd = await makeWorkspaceFolder();
731+
732+
const error = await refusalOf(
733+
await refusedCommandsFor({
734+
argv: ["contract", "emit"],
735+
cwd,
736+
platform: "linux",
737+
}),
738+
"contract emit",
739+
);
740+
741+
expect(error.nextActions).toEqual([
742+
{
743+
kind: "run-command",
744+
label:
745+
"Run the project's own prisma instead, adding your other arguments after the command",
746+
command: "../../node_modules/.bin/prisma contract emit",
747+
},
748+
]);
749+
});
750+
751+
it("keeps the --config the user gave after that path", async () => {
752+
const cwd = await makeWorkspaceFolder();
753+
754+
const error = await refusalOf(
755+
await refusedCommandsFor({
756+
argv: ["contract", "emit", "--config", "prisma.config.ts"],
757+
cwd,
758+
platform: "linux",
759+
}),
760+
"contract emit",
761+
);
762+
763+
expect(error.nextActions[0]?.command).toBe(
764+
"../../node_modules/.bin/prisma contract emit --config prisma.config.ts",
765+
);
766+
});
767+
768+
it("gives the path when the folder has its own package.json but no prisma", async () => {
769+
const cwd = await makeWorkspaceFolder();
770+
await writePackage(cwd, "usage-testing", "1.0.0");
771+
772+
const error = await refusalOf(
773+
await refusedCommandsFor({
774+
argv: ["contract", "emit"],
775+
cwd,
776+
platform: "linux",
777+
}),
778+
"contract emit",
779+
);
780+
781+
expect(error.nextActions[0]?.command).toBe(
782+
"../../node_modules/.bin/prisma contract emit",
783+
);
784+
});
785+
786+
it("gives the path unquoted, with backslashes, on Windows", async () => {
787+
const cwd = await makeWorkspaceFolder();
788+
789+
const error = await refusalOf(
790+
await refusedCommandsFor({
791+
argv: ["contract", "emit"],
792+
cwd,
793+
platform: "win32",
794+
}),
795+
"contract emit",
796+
);
797+
798+
expect(error.nextActions[0]?.command).toBe(
799+
"..\\..\\node_modules\\.bin\\prisma contract emit",
800+
);
801+
});
802+
});
803+
804+
it("gives the path of a prisma installed beside no package.json", async () => {
805+
const { dir } = await makeProjectWithSecondCopy();
806+
await writePackageWithPrisma(dir);
807+
await rm(path.join(dir, "package.json"));
808+
809+
const error = await refusalOf(
810+
await refusedCommandsFor({
811+
argv: ["db", "migrate"],
812+
cwd: dir,
813+
platform: "linux",
814+
}),
815+
"db migrate",
816+
);
817+
818+
expect(error.nextActions[0]?.command).toBe(
819+
"./node_modules/.bin/prisma db migrate",
820+
);
821+
});
822+
694823
it("names the versions to change when the project's own prisma would be refused too", async () => {
695824
const { dir } = await makeProjectWithSecondCopy();
696825
const projectPrisma = path.join(dir, "node_modules", "prisma");

0 commit comments

Comments
 (0)