import { existsSync, realpathSync } from "node:fs"; import { mkdir, readdir, readFile, readlink, rm, symlink, writeFile, } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { defineCommandFamily } from "@prisma/cli-engine"; import { ok } from "@prisma/cli-engine/protocol"; import { createTestCli, mintTestJwt } from "@prisma/cli-engine/testing"; import { defineConfig as composer } from "@prisma/composer/config"; import { nodeBuild } from "@prisma/composer/node/control"; import { createComposerFamily } from "@prisma/composer-cli/family"; import { createOperationsDouble } from "@prisma/composer-cli/testing"; import { type BuiltService, ServiceBuildError, type ServiceBuildSettings, } from "@prisma/compute-sdk/service"; import { Result } from "better-result"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { cliGroups, platformCommandFamily } from "../src/cli"; import { createDeployCommand } from "../src/commands/deploy/command"; import { deployConfigSection } from "../src/commands/deploy/config"; import { inferServiceName, moduleFileText, serviceFileText, } from "../src/commands/deploy/service"; import { makeTempCwd, WORKSPACE } from "./service-testkit"; const sdk = vi.hoisted(() => ({ buildService: vi.fn() })); vi.mock("@prisma/compute-sdk/service", async (original) => ({ ...(await original()), buildService: sdk.buildService, })); const build = nodeBuild(); const COMPOSER_SECTION = composer({ extensions: [build], state: { extension: build.id, create: () => { throw new Error("no command in these tests reaches the state store"); }, }, }); const SETTINGS: ServiceBuildSettings = { packageManager: "npm", node: null, install: { value: "npm ci", from: "lockfile" }, build: { value: "npm run build", from: "package.json" }, start: { value: { kind: "command", command: "node server.js" }, from: "package.json", }, port: null, notes: [], }; const DEPLOYED = { summary: { app: "web", findings: { unset: [] }, nodes: [ { address: "web.web", entities: [ { kind: "compute-service", id: "cps_1", url: "https://web.prisma.build", }, ], }, ], }, durationMs: 1200, }; /** A build that succeeded, with the Service folder as the Artifact. */ function built(dir: string, artifactDir = dir): BuiltService { return { settings: SETTINGS, start: { value: { kind: "command", command: "node server.js" }, from: "package.json", }, steps: [ { name: "install", command: "npm ci", seconds: 4, ok: true }, { name: "build", command: "npm run build", seconds: 3, ok: true }, ], artifact: { dir: artifactDir, entrypoint: ".prisma/launcher.mjs" }, }; } interface Harness { readonly cwd: string; /** The folder that holds the generated files and the copy of the Artifact. */ readonly deployDir: string; readonly composerCalls: ReturnType["calls"]; readonly run: ( argv: readonly string[], env?: Record, ) => ReturnType["run"]>; } async function harness( options: { config?: Record } = {}, ): Promise { const cwd = await makeTempCwd("deploy-"); await writeFile( path.join(cwd, "package.json"), JSON.stringify({ name: "@acme/web", scripts: { start: "node server.js" } }), ); sdk.buildService.mockResolvedValue(Result.ok(built(cwd))); const double = createOperationsDouble({ deploy: ok(DEPLOYED) }); const deploy = createDeployCommand( createComposerFamily({ operations: double.operations }).commands.deploy, ); const cli = createTestCli({ commandFamilies: [ platformCommandFamily, defineCommandFamily({ configSection: deployConfigSection, commands: { deploy }, }), ], commands: { deploy }, groups: { deploy: cliGroups.deploy }, config: options.config, sessions: [ { workspaceId: WORKSPACE.id, workspaceName: WORKSPACE.name, credential: { token: mintTestJwt({ sub: "usr_1", workspace_id: WORKSPACE.id }), refreshToken: undefined, expiresAt: undefined, }, }, ], selectedWorkspaceId: WORKSPACE.id, now: () => new Date(0), }); return { cwd, deployDir: path.join(cwd, ".prisma", "deploy"), composerCalls: double.calls, run: (argv, env = {}) => cli.run(argv, { cwd, env: { PRISMA_CLI_STATE_DIR: path.join(cwd, ".state"), ...env }, }), }; } type Run = Awaited>; /** The envelope of a --json run: the terminal result frame. */ function envelopeOf(run: Run) { const frame = run.json.at(-1); if (frame?.kind !== "result") { throw new Error("the run wrote no result frame"); } return frame.envelope; } async function write(file: string, text = ""): Promise { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, text); } beforeEach(() => { sdk.buildService.mockReset(); }); describe("deploy: which path runs", () => { it("runs Composer's deploy unchanged when a config file declares a composer section", async () => { const h = await harness({ config: { composer: COMPOSER_SECTION } }); const result = await h.run(["deploy", "--environment", "staging"]); expect(result.exitCode).toBe(0); expect(h.composerCalls.deploy).toHaveLength(1); expect(h.composerCalls.deploy[0]).toMatchObject({ cwd: h.cwd, environment: "staging", entry: undefined, name: undefined, reportPath: undefined, }); expect(h.composerCalls.deps.deploy[0]?.credentials?.workspaceId).toBe( WORKSPACE.id, ); expect(sdk.buildService).not.toHaveBeenCalled(); expect(existsSync(h.deployDir)).toBe(false); }); it("reports an invalid composer section as Composer does, and deploys nothing", async () => { const h = await harness({ config: { composer: { extensions: "no" } } }); const result = await h.run(["deploy", "--json"]); expect(envelopeOf(result)).toMatchObject({ ok: false, error: { code: "CLI.CONFIG_SECTION_INVALID" }, }); expect(h.composerCalls.deploy).toHaveLength(0); expect(sdk.buildService).not.toHaveBeenCalled(); }); it("builds the folder as one Service when no config file declares a composer section", async () => { const h = await harness(); const result = await h.run(["deploy"]); expect(result.exitCode).toBe(0); expect(sdk.buildService).toHaveBeenCalledTimes(1); expect(sdk.buildService.mock.calls[0]?.[0]).toMatchObject({ dir: h.cwd, config: {}, }); expect(h.composerCalls.deploy).toHaveLength(1); }); it("builds the folder as one Service when --entry names no file, which the deploy action always passes", async () => { const h = await harness(); const result = await h.run(["deploy", "--entry", "module.ts"]); expect(result.exitCode).toBe(0); expect(sdk.buildService).toHaveBeenCalledTimes(1); }); it("fails with the missing composer section error when --entry names a file that exists", async () => { const h = await harness(); await write(path.join(h.cwd, "module.ts"), "export default {};\n"); const result = await h.run(["deploy", "--entry", "module.ts", "--json"]); expect(envelopeOf(result)).toMatchObject({ ok: false, error: { code: "CLI.CONFIG_SECTION_INVALID", summary: expect.stringContaining("The 'composer' section is missing"), }, diagnostics: [{ code: "CONFIG.SECTION_MISSING" }], }); expect(sdk.buildService).not.toHaveBeenCalled(); expect(h.composerCalls.deploy).toHaveLength(0); }); it("fails with the missing composer section error when a prisma-composer.config file exists", async () => { const h = await harness(); await write(path.join(h.cwd, "prisma-composer.config.ts")); const result = await h.run(["deploy", "--json"]); expect(envelopeOf(result)).toMatchObject({ ok: false, error: { code: "CLI.CONFIG_SECTION_INVALID" }, diagnostics: [{ code: "CONFIG.SECTION_MISSING" }], }); expect(sdk.buildService).not.toHaveBeenCalled(); }); }); describe("deploy: the Service config", () => { it("passes the service section to the build", async () => { const service = { build: null, start: "bun server.ts", port: 3000 }; const h = await harness({ config: { service } }); await h.run(["deploy"]); expect(sdk.buildService.mock.calls[0]?.[0]).toMatchObject({ dir: h.cwd, config: service, }); }); it.each([ [{ port: "3000" }, "port"], [{ port: 70000 }, "port"], [{ start: "" }, "start"], [{ strat: "node server.js" }, "strat"], ])("refuses the service section %j", async (service, field) => { const h = await harness({ config: { service } }); const result = await h.run(["deploy", "--json"]); expect(envelopeOf(result)).toMatchObject({ ok: false, error: { code: "CLI.CONFIG_FIELD_INVALID", meta: { section: "service", field }, }, }); expect(sdk.buildService).not.toHaveBeenCalled(); expect(h.composerCalls.deploy).toHaveLength(0); }); }); describe("deploy: a build that produces no Artifact", () => { it.each([ [ "install_failed", "DEPLOY.SERVICE_INSTALL_FAILED", { name: "install", command: "npm ci", seconds: 2, ok: false }, ], [ "build_failed", "DEPLOY.SERVICE_BUILD_FAILED", { name: "build", command: "npm run build", seconds: 5, ok: false }, ], ] as const)("stops with its own code when the build ends with %s, and shows the end of the output", async (code, cliCode, step) => { const h = await harness(); const output = "Service step failed (exit code 2):\nerror TS2304"; sdk.buildService.mockImplementation( async (options: { log: (text: string) => void }) => { options.log(`\n$ ${step.command}\n`); options.log("error TS2304\n"); return Result.err( new ServiceBuildError({ code, message: `Step failed: ${step.command}`, settings: SETTINGS, steps: [step], output, }), ); }, ); const result = await h.run(["deploy", "--json"]); expect(result.exitCode).not.toBe(0); expect(envelopeOf(result)).toMatchObject({ ok: false, error: { code: cliCode, summary: `Step failed: ${step.command}`, meta: { command: step.command, seconds: step.seconds, output }, }, }); expect(result.events).toContainEqual( expect.objectContaining({ kind: "output", source: "build", line: "error TS2304", }), ); expect(h.composerCalls.deploy).toHaveLength(0); expect(existsSync(h.deployDir)).toBe(false); }); it("stops with DEPLOY.SERVICE_NO_START when no start rule matched, and shows the notes", async () => { const h = await harness(); const note = "The start script runs a development server (vite). It is not used."; sdk.buildService.mockResolvedValue( Result.err( new ServiceBuildError({ code: "no_start", message: "No start command.", settings: { ...SETTINGS, notes: [note] }, steps: [], }), ), ); const result = await h.run(["deploy", "--json"]); expect(envelopeOf(result)).toMatchObject({ ok: false, error: { code: "DEPLOY.SERVICE_NO_START", summary: "No start command." }, }); expect(result.events).toContainEqual( expect.objectContaining({ kind: "message", severity: "warn", text: note, }), ); expect(h.composerCalls.deploy).toHaveLength(0); expect(existsSync(h.deployDir)).toBe(false); }); }); describe("deploy: the generated Composer files", () => { it("writes module.ts and service.ts into .prisma/deploy and hands that folder to Composer", async () => { const h = await harness(); await h.run(["deploy"]); const moduleFile = path.join(h.deployDir, "module.ts"); expect(await readFile(moduleFile, "utf8")).toBe( moduleFileText("web", undefined), ); expect(await readFile(path.join(h.deployDir, "service.ts"), "utf8")).toBe( serviceFileText(".prisma/launcher.mjs"), ); expect(h.composerCalls.deploy[0]).toMatchObject({ cwd: h.deployDir, config: { file: moduleFile, value: { entry: "./module.ts" } }, }); }); it("names the app, the service file and the Artifact copy in the files", () => { expect(moduleFileText("web", undefined)).toContain('appRoot("web",'); expect(moduleFileText("web", undefined)).toContain("provision(web);"); expect(serviceFileText(".prisma/launcher.mjs")).toContain( 'dir: "./artifact",\n entry: ".prisma/launcher.mjs",', ); }); it("gives the Composer service the port from the Service config", async () => { const h = await harness({ config: { service: { port: 4000 } } }); await h.run(["deploy"]); expect( await readFile(path.join(h.deployDir, "module.ts"), "utf8"), ).toContain("provision(web, { params: { port: 4000 } });"); }); it("keeps the folder out of git and reads the files as ES modules", async () => { const h = await harness(); await h.run(["deploy"]); expect(await readFile(path.join(h.deployDir, ".gitignore"), "utf8")).toBe( "*\n", ); expect( JSON.parse( await readFile(path.join(h.deployDir, "package.json"), "utf8"), ), ).toEqual({ type: "module" }); }); it("links this CLI's own Composer packages next to the files", async () => { const h = await harness(); await h.run(["deploy"]); for (const name of ["@prisma/composer", "@prisma/composer-prisma-cloud"]) { expect(realpathSync(path.join(h.deployDir, "node_modules", name))).toBe( realpathSync( path.dirname( fileURLToPath(import.meta.resolve(`${name}/package.json`)), ), ), ); } }); it("writes the same files at the same paths on a second deploy", async () => { const h = await harness(); await h.run(["deploy"]); const first = await readFile(path.join(h.deployDir, "module.ts"), "utf8"); await h.run(["deploy"]); expect(await readFile(path.join(h.deployDir, "module.ts"), "utf8")).toBe( first, ); expect(h.composerCalls.deploy[1]?.cwd).toBe(h.composerCalls.deploy[0]?.cwd); expect(h.composerCalls.deploy[1]?.config.file).toBe( h.composerCalls.deploy[0]?.config.file, ); }); }); describe("deploy: the clean copy of the Artifact", () => { it("leaves out .git and dotenv files at every depth, and the deploy folder itself", async () => { const h = await harness(); await write(path.join(h.cwd, ".git", "config"), "token"); await write(path.join(h.cwd, ".env"), "SECRET=1"); await write(path.join(h.cwd, ".env.production"), "SECRET=2"); await write(path.join(h.cwd, "packages", "api", ".env"), "SECRET=3"); await write(path.join(h.cwd, "packages", "api", ".git", "HEAD")); await write(path.join(h.cwd, "packages", "api", "index.js"), "api"); await write(path.join(h.cwd, ".prisma", "launcher.mjs"), "launcher"); await write(path.join(h.cwd, "server.js"), "server"); await h.run(["deploy"]); const copy = path.join(h.deployDir, "artifact"); const files = (await readdir(copy, { recursive: true })).sort(); expect(files).toEqual( [ ".prisma", path.join(".prisma", "launcher.mjs"), "package.json", "packages", path.join("packages", "api"), path.join("packages", "api", "index.js"), "server.js", ].sort(), ); expect(await readFile(path.join(copy, "server.js"), "utf8")).toBe("server"); }); it.skipIf(process.platform === "win32")( "copies a link as the same link", async () => { const h = await harness(); await write(path.join(h.cwd, "node_modules", "tool", "cli.js"), "tool"); await mkdir(path.join(h.cwd, "node_modules", ".bin")); await symlink( "../tool/cli.js", path.join(h.cwd, "node_modules", ".bin", "tool"), ); await h.run(["deploy"]); expect( await readlink( path.join(h.deployDir, "artifact", "node_modules", ".bin", "tool"), ), ).toBe("../tool/cli.js"); }, ); it("drops a file that the Service no longer has", async () => { const h = await harness(); await write(path.join(h.cwd, "old.js"), "old"); await h.run(["deploy"]); await rm(path.join(h.cwd, "old.js")); await h.run(["deploy"]); expect(existsSync(path.join(h.deployDir, "artifact", "old.js"))).toBe( false, ); }); it("copies only the built folder when the Artifact is a static site", async () => { const h = await harness(); await write(path.join(h.cwd, "dist", "index.html"), "

site

"); await write(path.join(h.cwd, "dist", ".env"), "SECRET=1"); sdk.buildService.mockResolvedValue( Result.ok(built(h.cwd, path.join(h.cwd, "dist"))), ); await h.run(["deploy"]); expect(await readdir(path.join(h.deployDir, "artifact"))).toEqual([ "index.html", ]); }); }); describe("deploy: the name", () => { it("uses --name when it is given", async () => { const h = await harness(); await h.run(["deploy", "--name", "api"]); expect( await readFile(path.join(h.deployDir, "module.ts"), "utf8"), ).toContain('appRoot("api",'); expect(h.composerCalls.deploy[0]?.name).toBe("api"); }); it.each([ ["@acme/web", "web"], ["my.app", "my-app"], ["_private", "private"], ["My App!", "My-App"], ["shop_api-2", "shop_api-2"], ])("makes the package.json name %j valid for Composer: %j", async (name, expected) => { const cwd = await makeTempCwd("deploy-name-"); await writeFile(path.join(cwd, "package.json"), JSON.stringify({ name })); expect(inferServiceName(cwd)).toBe(expected); }); it.each([ ["has no name", "{}"], [ "has a name with no letter or digit", JSON.stringify({ name: "@acme/..." }), ], ["is not JSON", "{"], ])("uses the folder name when package.json %s", async (_case, manifest) => { const cwd = path.join(await makeTempCwd("deploy-name-"), "my site"); await write(path.join(cwd, "package.json"), manifest); expect(inferServiceName(cwd)).toBe("my-site"); }); it("uses the folder name when there is no package.json", async () => { const cwd = path.join(await makeTempCwd("deploy-name-"), "docs"); await mkdir(cwd); expect(inferServiceName(cwd)).toBe("docs"); }); }); describe("deploy: what Composer's deploy receives and prints", () => { it("passes the environment through", async () => { const h = await harness(); await h.run(["deploy", "--environment", "pr-12"]); expect(h.composerCalls.deploy[0]?.environment).toBe("pr-12"); }); it("resolves --report against the Service folder, not the deploy folder", async () => { const h = await harness(); await h.run(["deploy", "--report", "out/report.json"]); expect(h.composerCalls.deploy[0]?.reportPath).toBe( path.join(h.cwd, "out", "report.json"), ); }); it("resolves PRISMA_COMPOSER_REPORT_FILE against the Service folder", async () => { const h = await harness(); await h.run(["deploy"], { PRISMA_COMPOSER_REPORT_FILE: "report.json" }); expect(h.composerCalls.deploy[0]?.reportPath).toBe( path.join(h.cwd, "report.json"), ); }); it("prints the result as a Composer deploy does", async () => { const service = await harness(); const composerApp = await harness({ config: { composer: COMPOSER_SECTION }, }); const fromService = await service.run(["deploy"]); const fromComposer = await composerApp.run(["deploy"]); expect(fromService.stdout).toBe( "web.web\tcompute-service\tcps_1\thttps://web.prisma.build\n", ); expect(fromService.stdout).toBe(fromComposer.stdout); }); });