The best way to control Claude Code, Codex and more from any computer or phone

main
ts 386 lines 13.6 KB
Raw
1 import { exec } from "alchemy/Util/exec";
2 // Shared scaffolding for the Prisma ORM v8 deploy-time resources.
3 // NOT exported from the ORM index — service-internal only.
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import { ChildProcess } from "effect/process";
9 import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
10
11 /**
12 * A structured failure from the `prisma` CLI.
13 *
14 * In `--json` mode the CLI streams newline-delimited events and closes with
15 * a `{ kind: "result", envelope }` document. A failed envelope carries a
16 * stable `code` (e.g. `CONFIG.FILE_NOT_FOUND`, `CONTRACT.VERIFY_FAILED`)
17 * plus human guidance in `summary`/`why`/`nextActions`. Those fields are
18 * surfaced verbatim so callers can match on `code` and users get the CLI's
19 * own remediation text.
20 */
21 export class CliError extends Data.TaggedError("Prisma.CliError")<{
22 /** Stable machine code reported by the CLI (e.g. `CONTRACT.VERIFY_FAILED`). */
23 code?: string | undefined;
24 message: string;
25 /** The CLI's suggested remediation, when it reported one. */
26 fix?: string | undefined;
27 /** Extra structured detail from the CLI (e.g. host/port on connection errors). */
28 meta?: Record<string, unknown> | undefined;
29 }> {}
30
31 /**
32 * Connection-flavored failures worth retrying: a database that was
33 * provisioned earlier in the same deploy may not be accepting connections
34 * yet (eventual consistency), so `Prisma.Migrate` retries these briefly.
35 */
36 export const isTransientDbError = (error: CliError): boolean => {
37 if (error.code === "DRIVER.CONNECTION_FAILED") return true;
38 const meta = error.meta ?? {};
39 // The CLI reports the driver's errno under `sqlState` for connection
40 // failures (`ECONNREFUSED`, ...) and a real SQLSTATE for statement ones.
41 const errno = [meta.sqlState, meta.code].find((value) => typeof value === "string");
42 return (
43 ["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "ETIMEDOUT", "EAI_AGAIN"].includes(
44 errno as string,
45 ) || /connection|timeout|reachable/i.test(error.message)
46 );
47 };
48
49 const causeMessage = (cause: unknown): string =>
50 cause instanceof Error ? cause.message : String(cause);
51
52 /**
53 * Resolve the unified `prisma` CLI entrypoint (`prisma` v8 mounts the ORM
54 * commands — `contract emit`, `migration plan`, `db migrate` — that the
55 * retired `prisma-next` bin used to serve). The package is an optional peer,
56 * so it resolves out of the *user's* project and their pinned CLI version is
57 * the one that runs.
58 */
59 export const resolvePrismaCliBin = Effect.gen(function* () {
60 const fs = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const url = yield* Effect.try({
63 try: () => import.meta.resolve("prisma/package.json"),
64 catch: (cause) =>
65 new CliError({
66 message: `Failed to resolve the "prisma" CLI (is it installed? \`npm i -D prisma\`): ${causeMessage(cause)}`,
67 }),
68 });
69 const manifestPath = yield* Effect.try({
70 try: () => new URL(url),
71 catch: (cause) =>
72 new CliError({
73 message: `Failed to parse the "prisma" package URL: ${causeMessage(cause)}`,
74 }),
75 }).pipe(
76 Effect.flatMap((fileUrl) =>
77 path.fromFileUrl(fileUrl).pipe(
78 Effect.mapError(
79 (cause) =>
80 new CliError({
81 message: `Failed to convert the "prisma" package URL to a path: ${cause.message}`,
82 }),
83 ),
84 ),
85 ),
86 );
87 const manifest = yield* fs.readFileString(manifestPath).pipe(
88 Effect.flatMap((text) =>
89 Effect.try({
90 try: () => JSON.parse(text) as { bin?: Record<string, string> | string },
91 catch: (cause) =>
92 new CliError({
93 message: `Failed to parse ${manifestPath}: ${causeMessage(cause)}`,
94 }),
95 }),
96 ),
97 Effect.mapError((cause) =>
98 cause instanceof CliError
99 ? cause
100 : new CliError({ message: `Failed to read ${manifestPath}: ${cause.message}` }),
101 ),
102 );
103 const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.prisma;
104 if (bin === undefined) {
105 return yield* new CliError({
106 message: `The installed "prisma" package declares no \`prisma\` bin (${manifestPath}).`,
107 });
108 }
109 return path.resolve(path.dirname(manifestPath), bin);
110 });
111
112 /** The CLI's failure payload (`envelope.error` in `--json` mode). */
113 interface CliFailure {
114 code?: string;
115 severity?: string;
116 summary?: string;
117 why?: string;
118 nextActions?: Array<{ kind?: string; label?: string }>;
119 meta?: Record<string, unknown>;
120 docsUrl?: string;
121 }
122
123 /**
124 * The terminal `{ kind: "result" }` event the CLI closes a `--json` run
125 * with. `ok` discriminates the payload: `result` for success, `error` for
126 * failure.
127 */
128 interface CliEnvelope {
129 ok: boolean;
130 commandId?: string;
131 result?: unknown;
132 error?: CliFailure;
133 exitCode?: number;
134 nextActions?: Array<{ kind?: string; label?: string }>;
135 }
136
137 /**
138 * Scan the CLI's newline-delimited JSON stream for the terminal result
139 * envelope. Progress events (`step-started`, `step-finished`, ...) and any
140 * non-JSON banner lines are skipped.
141 */
142 const parseEnvelope = (stdout: string): CliEnvelope | undefined => {
143 let envelope: CliEnvelope | undefined;
144 for (const line of stdout.split("\n")) {
145 const text = line.trim();
146 if (!text.startsWith("{")) continue;
147 let event: { kind?: string; envelope?: CliEnvelope };
148 try {
149 event = JSON.parse(text);
150 } catch {
151 continue;
152 }
153 if (event.kind === "result" && event.envelope !== undefined) {
154 envelope = event.envelope;
155 }
156 }
157 return envelope;
158 };
159
160 /**
161 * Run a `prisma` subcommand with `--json --no-interactive` from `cwd` (the
162 * directory containing `prisma.config.ts` — all config-relative paths
163 * resolve against it, matching a user running the CLI in their project) and
164 * parse the structured result envelope.
165 */
166 export const runPrismaCli = <T>(
167 args: readonly string[],
168 options: { readonly cwd: string },
169 ): Effect.Effect<T, CliError, FileSystem.FileSystem | Path.Path | ChildProcessSpawner> =>
170 Effect.gen(function* () {
171 const bin = yield* resolvePrismaCliBin;
172 const nodeExecPath = yield* Effect.sync(() => process.execPath);
173 const result = yield* exec(
174 ChildProcess.make(nodeExecPath, [bin, ...args, "--json", "--no-interactive"], {
175 cwd: options.cwd,
176 env: { PRISMA_DISABLE_TELEMETRY: "1", DO_NOT_TRACK: "1" },
177 extendEnv: true,
178 }),
179 ).pipe(
180 // exec fully drains stdout/stderr and the exit code before returning,
181 // so the process handle's scope can close right here.
182 Effect.scoped,
183 Effect.mapError(
184 (cause) =>
185 new CliError({
186 message: `prisma ${args.slice(0, 2).join(" ")} failed to spawn: ${String(cause)}`,
187 }),
188 ),
189 );
190
191 const envelope = yield* Effect.sync(() => parseEnvelope(result.stdout));
192
193 if (envelope?.ok === true) {
194 return envelope.result as T;
195 }
196 if (envelope?.ok === false) {
197 const error = envelope.error ?? {};
198 const fix = (error.nextActions ?? envelope.nextActions ?? []).find(
199 (action) => typeof action.label === "string",
200 )?.label;
201 return yield* new CliError({
202 code: error.code,
203 message: `prisma ${args.slice(0, 2).join(" ")} failed: ${[error.summary, error.why].filter(Boolean).join(" — ") || "unknown error"}`,
204 fix,
205 meta: error.meta,
206 });
207 }
208 return yield* new CliError({
209 message: `prisma ${args.slice(0, 2).join(" ")} failed (exit ${result.exitCode}): ${result.stdout}\n${result.stderr}`,
210 });
211 });
212
213 /** `prisma contract emit --json` result. */
214 export interface EmitResult {
215 ok: true;
216 /** Canonical hash of the emitted contract's storage shape — the contract identity the migration graph and DB marker track. */
217 storageHash: string;
218 /** Only emitted for TypeScript-authored contracts. */
219 executionHash?: string;
220 profileHash: string;
221 outDir: string;
222 files: { json: string; dts: string };
223 }
224
225 /** `prisma migration plan --json` result. */
226 export interface PlanResult {
227 ok: true;
228 noOp: boolean;
229 from: string | null;
230 to: string;
231 /** cwd-relative directory of the written migration package (absent when `noOp`). */
232 dir?: string;
233 /** True when the plan wrote `placeholder(...)` sentinels that need a human decision. */
234 pendingPlaceholders?: boolean;
235 operations: Array<{ id: string; label: string; operationClass: string }>;
236 }
237
238 /** `prisma db migrate --json` result. */
239 export interface MigrateResult {
240 ok: true;
241 migrationsApplied: number;
242 migrationsTotal: number;
243 /** The DB marker's contract hash after the run. */
244 markerHash: string;
245 applied: Array<{
246 spaceId: string;
247 dirName: string;
248 migrationHash: string;
249 from: string;
250 to: string;
251 }>;
252 }
253
254 /** `prisma db migrate --show --json` result (read-only preview). */
255 export interface MigrateShowResult {
256 ok: true;
257 migrations: Array<{
258 spaceId: string;
259 dirName: string;
260 migrationHash: string;
261 from: string;
262 to: string;
263 }>;
264 }
265
266 /**
267 * Prisma ORM v8 bug workaround (through 8.0.0-rc.8): `contract emit` writes
268 * the Prisma monorepo's `@internal/*` aliases into `contract.d.ts` instead of
269 * the public `@prisma/orm-*` packages. Those packages are not published, so
270 * the emitted types would not resolve in a user project.
271 * Longest-prefix-first so `sql-contract` is not eaten by `contract`.
272 * `@internal/extension-<name>/` maps to `@prisma/orm-extension-<name>/`.
273 */
274 const INTERNAL_SPECIFIER_REWRITES: ReadonlyArray<readonly [string, string]> = [
275 ["@internal/adapter-postgres/", "@prisma/orm-postgres/adapter/"],
276 ["@internal/target-postgres/", "@prisma/orm-postgres/target/"],
277 ["@internal/sql-contract/", "@prisma/orm-postgres/family-contract/"],
278 ["@internal/contract/", "@prisma/orm-postgres/contract/"],
279 ["@internal/extension-", "@prisma/orm-extension-"],
280 ];
281
282 /**
283 * Rewrite leaked `@internal/*` specifiers in an emitted `contract.d.ts` to
284 * their public `@prisma/orm-*` equivalents. A no-op for PSL-authored emits
285 * (which never contain them); fails actionably if an unmapped `@internal/*`
286 * specifier remains.
287 */
288 export const rewriteEmittedTypes = (dtsPath: string) =>
289 Effect.gen(function* () {
290 const fs = yield* FileSystem.FileSystem;
291 const exists = yield* fs.exists(dtsPath);
292 if (!exists) return;
293 const original = yield* fs.readFileString(dtsPath);
294 if (!original.includes("@internal/")) return;
295 let rewritten = original;
296 for (const [internal, publicPrefix] of INTERNAL_SPECIFIER_REWRITES) {
297 rewritten = rewritten.replaceAll(internal, publicPrefix);
298 }
299 if (rewritten.includes("@internal/")) {
300 const leftover = rewritten.split("\n").find((line) => line.includes("@internal/"));
301 return yield* new CliError({
302 message: [
303 `Emitted ${dtsPath} references an unpublished @internal/* module this`,
304 `integration does not know how to map yet: ${leftover?.trim()}`,
305 "Please report this — the emitted types will not resolve until it is mapped.",
306 ].join("\n"),
307 });
308 }
309 yield* fs.writeFileString(dtsPath, rewritten);
310 });
311
312 /**
313 * One on-disk migration package under `{migrationsDir}/app/`.
314 *
315 * `opsEmpty` distinguishes a fully-emitted package (`ops.json` holds the
316 * rendered operations) from one still carrying unfilled `placeholder(...)`
317 * closures — `migration plan` writes `ops.json` as `[]` until the user edits
318 * `migration.ts` and self-emits it.
319 */
320 export interface MigrationPackage {
321 dirName: string;
322 from: string | null;
323 to: string;
324 migrationHash: string;
325 opsEmpty: boolean;
326 }
327
328 /**
329 * Read every migration package in the app contract space, sorted by
330 * directory name (timestamp-prefixed).
331 */
332 export const readMigrationPackages = (migrationsDirAbs: string) =>
333 Effect.gen(function* () {
334 const fs = yield* FileSystem.FileSystem;
335 const path = yield* Path.Path;
336 const appDir = path.join(migrationsDirAbs, "app");
337 const exists = yield* fs.exists(appDir);
338 if (!exists) return [] as MigrationPackage[];
339 const entries = (yield* fs.readDirectory(appDir)).sort();
340 const packages: MigrationPackage[] = [];
341 for (const dirName of entries) {
342 const metaPath = path.join(appDir, dirName, "migration.json");
343 const hasMeta = yield* fs.exists(metaPath);
344 if (!hasMeta) continue;
345 const meta = yield* fs.readFileString(metaPath).pipe(
346 Effect.flatMap((text) =>
347 Effect.try({
348 try: () =>
349 JSON.parse(text) as {
350 from: string | null;
351 to: string;
352 migrationHash: string;
353 },
354 catch: (cause) =>
355 new CliError({
356 message: `Failed to parse ${metaPath}: ${causeMessage(cause)}`,
357 }),
358 }),
359 ),
360 );
361 const opsPath = path.join(appDir, dirName, "ops.json");
362 const hasOps = yield* fs.exists(opsPath);
363 const opsText = hasOps ? yield* fs.readFileString(opsPath) : "[]";
364 packages.push({
365 dirName,
366 from: meta.from,
367 to: meta.to,
368 migrationHash: meta.migrationHash,
369 opsEmpty: opsText.trim() === "[]" || opsText.trim() === "",
370 });
371 }
372 return packages;
373 });
374
375 /**
376 * Resolve the head of the migration graph: the `to` hash no other package
377 * plans *from*. Directory-name order breaks ties (branchy graphs from
378 * merges); an empty graph has no head.
379 */
380 export const resolveGraphHead = (
381 packages: readonly MigrationPackage[],
382 ): MigrationPackage | undefined => {
383 const froms = new Set(packages.flatMap((pkg) => (pkg.from === null ? [] : [pkg.from])));
384 const heads = packages.filter((pkg) => !froms.has(pkg.to));
385 return heads.at(-1);
386 };