/** * A product command runs only when the project's copy of each Prisma * package it loads is the copy this CLI would load. Values made by one * copy of the ORM framework are refused by another, and what a command * writes is read later by the project's own copy, so a second copy * stops the command before the project's config is evaluated. */ import path from "node:path"; import { fileURLToPath } from "node:url"; import { type AnyCommand, type CommandFamily, type MountedTree, realpathOr, } from "@prisma/cli-engine"; import { CliStructuredError, type NextAction, } from "@prisma/cli-engine/protocol"; import { Result } from "better-result"; import { composerCommandFamily, mountedCommands, ormCommandFamily, type RefusedCommands, } from "./cli"; import { CLI_NAME, DOCS_ERRORS_BASE_URL } from "./cli-name"; import { detectPackageManagerSync, installedBinRunner, } from "./lib/agent/package-manager"; import { configPathFromArgv, flagTokens } from "./lib/argv"; import { type CheckedPackage, COMPOSER_COMMAND_PACKAGES, findProjectPackage, findSecondCopies, ORM_COMMAND_PACKAGES, type PackageCopy, projectPackageDir, type SecondCopy, } from "./lib/package-copies"; import { formatShellCommand } from "./shell-command"; export const SECOND_PACKAGE_COPY_CODE = "CLI.SECOND_PACKAGE_COPY"; export interface ProductFamily { readonly family: CommandFamily; readonly packages: readonly CheckedPackage[]; } export const PRODUCT_FAMILIES: readonly ProductFamily[] = [ { family: ormCommandFamily, packages: ORM_COMMAND_PACKAGES }, { family: composerCommandFamily, packages: COMPOSER_COMMAND_PACKAGES }, ]; /** * Commands refused although they declare no config section. `orm init` * imports the project's own ORM packages into this process (each * target's init module, through the project) and writes the config and * contract the project's runtime reads; `lsp` loads the project's * config itself. */ const REFUSED_WITHOUT_CONFIG_SECTION: ReadonlySet = new Set([ "orm init", "lsp", ]); /** The mount paths of a family's commands, read from the mount table. */ export function mountedPathsOf( family: CommandFamily, commands: MountedTree = mountedCommands, ): readonly string[] { const owned = new Set(Object.values(family.commands)); return Object.keys(commands).filter((mountPath) => owned.has(commands[mountPath] as AnyCommand), ); } /** The family's commands a second copy refuses: those that read the * project's config, and those that load the project's packages or * write files its runtime reads without declaring a config section. */ export function refusedPathsOf(family: CommandFamily): readonly string[] { return mountedPathsOf(family).filter( (mountPath) => mountedCommands[mountPath]?.needs.config !== undefined || REFUSED_WITHOUT_CONFIG_SECTION.has(mountPath), ); } function firstWord(mountPath: string): string { return mountPath.split(" ")[0] as string; } /** Every product family whose commands start with a word the invocation * contains. Any token counts, not only the command path: a family * matched by an argument value only costs a check, because only that * family's commands are replaced. */ export function invokedProductFamilies( argv: readonly string[], ): readonly ProductFamily[] { const tokens = new Set(flagTokens(argv)); return PRODUCT_FAMILIES.filter((product) => refusedPathsOf(product.family).some((mountPath) => tokens.has(firstWord(mountPath)), ), ); } export interface SecondCopyCheckRequest { readonly argv: readonly string[]; readonly cwd: string; /** The file the shell resolves its own packages from. */ readonly shellModuleFile?: string; } /** * For each invoked product family with a second copy in the project, * its refused commands, replaced by stand-ins that keep their help and * arguments and fail with CLI.SECOND_PACKAGE_COPY. Empty when nothing * is refused. A package whose copy cannot be read is not compared: the * check never stops a command it cannot judge. */ export async function refusedCommandsFor( request: SecondCopyCheckRequest, ): Promise { const products = invokedProductFamilies(request.argv); if (products.length === 0) { return []; } const shellModuleFile = request.shellModuleFile ?? fileURLToPath(import.meta.url); const configPath = configPathFromArgv(request.argv) || undefined; const projectDir = projectPackageDir(request.cwd, configPath); const refused = await Promise.all( products.map(async (product) => { const { secondCopies: copies } = await findSecondCopies({ projectDir, shellModuleFile, packages: product.packages, }); if (copies.length === 0) { return []; } const recovery = await recoveryFor({ cwd: request.cwd, configPath, projectDir, shellModuleFile, packages: product.packages, }); const commands: Record = {}; for (const mountPath of refusedPathsOf(product.family)) { commands[mountPath] = refusingStandIn( mountedCommands[mountPath] as AnyCommand, () => secondPackageCopyError({ commandPath: mountPath, copies, recovery, }), ); } return [{ commands, docsBaseUrl: product.family.docsBaseUrl }]; }), ); return refused.flat(); } /** The command's help and arguments, so `--help` reads the same, with * no preconditions and a handler that only refuses. */ function refusingStandIn( def: AnyCommand, error: () => CliStructuredError, ): AnyCommand { const refuse = async (): Promise => { throw error(); }; const needs = Object.freeze({ config: undefined, credentials: false, dependencies: [], interaction: false, }); if (def.kind === "server-command") { return Object.freeze({ ...def, needs, handler: refuse }); } return Object.freeze({ ...def, needs, maySpawn: false, handler: refuse }); } export type SecondCopyRecovery = /** The project's own prisma, found from the current directory, would * run the command. */ | { readonly kind: "run-project-prisma"; readonly runner: string; /** The `--config` the user gave, kept so the command reads the * same config. */ readonly configPath: string | undefined; } /** The project's own prisma would run the command, but it is not * reachable from the current directory. */ | { readonly kind: "run-project-prisma-elsewhere"; readonly path: string; /** The absolute path of the `--config` file, which is how that * prisma is reached. */ readonly configFile: string | undefined; } | { readonly kind: "install-project-prisma" } /** The prisma the user would run is refused too: these copies differ * between it and the project. */ | { readonly kind: "align-versions"; readonly prisma: "running" | "project"; readonly copies: readonly SecondCopy[]; }; async function recoveryFor(request: { readonly cwd: string; readonly configPath: string | undefined; readonly projectDir: string; readonly shellModuleFile: string; readonly packages: readonly CheckedPackage[]; }): Promise { const fromCwd = await projectPrismaAt(request.cwd); const projectPrisma = fromCwd ?? (await projectPrismaAt(request.projectDir)); if (projectPrisma === null) { return { kind: "install-project-prisma" }; } if (isInside(realpathOr(request.shellModuleFile), projectPrisma.path)) { const { secondCopies } = await findSecondCopies(request); return { kind: "align-versions", prisma: "running", copies: secondCopies }; } const { secondCopies } = await findSecondCopies({ ...request, shellModuleFile: path.join(projectPrisma.path, "package.json"), }); if (secondCopies.length > 0) { return { kind: "align-versions", prisma: "project", copies: secondCopies }; } if (fromCwd === null) { return { kind: "run-project-prisma-elsewhere", path: projectPrisma.path, configFile: request.configPath === undefined ? undefined : path.resolve(request.cwd, request.configPath), }; } const manager = Result.try(() => detectPackageManagerSync(request.cwd)); return { kind: "run-project-prisma", runner: installedBinRunner( (manager.isOk() ? manager.value : null) ?? "npm", ), configPath: request.configPath, }; } /** The project's own prisma; an unreadable one counts as none. */ async function projectPrismaAt(dir: string): Promise { const found = await findProjectPackage(dir, CLI_NAME); return found.isOk() ? found.value : null; } function isInside(file: string, dir: string): boolean { const relative = path.relative(dir, file); return ( relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative) ); } export function secondPackageCopyError(input: { readonly commandPath: string; readonly copies: readonly SecondCopy[]; readonly recovery: SecondCopyRecovery; }): CliStructuredError { const [first] = input.copies as [SecondCopy]; const command = `${CLI_NAME} ${input.commandPath}`; const summary = first.project.version === first.cli.version ? `${command} cannot run here: the project and this ${CLI_NAME} each have their own copy of ${first.name} ${first.cli.version}.` : `${command} cannot run here: the project uses ${first.name} ${first.project.version}, and this ${CLI_NAME} uses ${first.cli.version}.`; const why = [ ...input.copies.flatMap(describeCopies), "A command can only work with the project's own copy of these packages: values made by one copy are refused by another, and the files a command writes are read later by the project's copy.", ].join("\n"); return new CliStructuredError(SECOND_PACKAGE_COPY_CODE, summary, { why, nextActions: nextActions(input.commandPath, input.recovery), meta: { command: input.commandPath, packages: input.copies.map((copy) => ({ name: copy.name, project: { version: copy.project.version, path: copy.project.path }, cli: { version: copy.cli.version, path: copy.cli.path }, })), }, docsUrl: `${DOCS_ERRORS_BASE_URL}${SECOND_PACKAGE_COPY_CODE}`, }); } function describeCopies(copy: SecondCopy): string[] { const lines = [ `The project's ${copy.name} ${copy.project.version} is at ${copy.project.path}.`, `This ${CLI_NAME}'s ${copy.name} ${copy.cli.version} is at ${copy.cli.path}.`, ]; if (copy.project.version === copy.cli.version) { lines.push( "They are the same version installed twice, and two installed copies do not work together even then.", ); } return lines; } function nextActions( commandPath: string, recovery: SecondCopyRecovery, ): readonly NextAction[] { switch (recovery.kind) { case "run-project-prisma": return [ { kind: "run-command", label: `Run the project's own ${CLI_NAME} instead, adding your other arguments after the command`, command: formatShellCommand([ ...recovery.runner.split(" "), CLI_NAME, ...commandPath.split(" "), ...(recovery.configPath === undefined ? [] : ["--config", recovery.configPath]), ]), }, ]; case "run-project-prisma-elsewhere": return [ { kind: "user-choice", label: recovery.configFile === undefined ? `From the project's directory, run the project's own ${CLI_NAME} (installed at ${recovery.path}) with the same command and arguments.` : `From the project's directory, run the project's own ${CLI_NAME} (installed at ${recovery.path}) with the same command and arguments, giving --config ${recovery.configFile}.`, }, ]; case "install-project-prisma": return [ { kind: "user-choice", label: `Install ${CLI_NAME} in the project, then run the project's own ${CLI_NAME} from the project's directory. If that one is refused too, its error names the versions to change.`, }, ]; case "align-versions": return alignActions(recovery); } } function alignActions(recovery: { readonly prisma: "running" | "project"; readonly copies: readonly SecondCopy[]; }): readonly NextAction[] { const whose = recovery.prisma === "running" ? `this ${CLI_NAME}` : `the project's own ${CLI_NAME}`; const differing = recovery.copies.filter( (copy) => copy.project.version !== copy.cli.version, ); if (differing.length === 0) { const names = recovery.copies.map((copy) => copy.name).join(" and "); return [ { kind: "user-choice", label: `Reinstall the project's dependencies so that ${whose} and the project share one copy of ${names}, then run the command again.`, }, ]; } const toCli = differing .map((copy) => `${copy.name} to ${copy.cli.version}`) .join(" and "); const projectVersions = differing .map((copy) => `${copy.name} ${copy.project.version}`) .join(" and "); return [ { kind: "user-choice", label: `Change the project's ${toCli}, the ${differing.length === 1 ? "version" : "versions"} ${whose} uses, then run the command again.`, }, { kind: "user-choice", label: `Or install a release of ${CLI_NAME} in the project that uses ${projectVersions}, the ${differing.length === 1 ? "version" : "versions"} the project has.`, }, ]; }