@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 344 lines 14.1 KB
Raw
1 import * as Artifacts from "alchemy/Artifacts";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import type { Providers } from "../Providers.ts";
9 import {
10 type EmitResult,
11 type MigrationPackage,
12 type PlanResult,
13 CliError,
14 readMigrationPackages,
15 rewriteEmittedTypes,
16 resolveGraphHead,
17 runPrismaCli,
18 } from "./internal.ts";
19
20 export type ContractProps = {
21 /**
22 * Path to the project's `prisma.config.ts`, relative to the current
23 * working directory. The config is the single source of truth for the
24 * contract source, emit output directory, and database defaults — exactly
25 * as when running the `prisma` CLI by hand.
26 *
27 * @default "./prisma.config.ts"
28 */
29 config?: string;
30 /**
31 * Directory holding the migration graph (`app/` packages +
32 * content-addressed `snapshots/`), relative to the **config file's
33 * directory** — the same base the CLI resolves against. If you override
34 * `orm.migrations.dir` in `prisma.config.ts`, set this to the same value.
35 *
36 * @default "./migrations"
37 */
38 migrationsDir?: string;
39 /**
40 * Name slug for migration directories planned during deploy
41 * (`migrations/app/{timestamp}_{name}/`). Directory timestamps are
42 * minute-resolution, so the default slug embeds the target contract hash
43 * to keep rapid successive deploys from colliding.
44 *
45 * @default "migration-{contractHash prefix}"
46 */
47 name?: string;
48 };
49
50 export type Contract = Resource<
51 "Prisma.Contract",
52 ContractProps,
53 {
54 /**
55 * The emitted contract's storage hash — the identity the migration graph
56 * and the database marker track. Changes exactly when the contract's
57 * storage shape changes; downstream {@link Migrate} resources diff this
58 * against the database marker to decide whether to run.
59 */
60 contractHash: string;
61 /**
62 * Path to `prisma.config.ts`, relative to the current working
63 * directory. Downstream resources ({@link Migrate}) inherit it so the
64 * whole toolchain reads one config.
65 */
66 config: string;
67 /** Path to the migration graph directory, relative to the current working directory. */
68 migrationsDir: string;
69 /** Migration package directory names in the app contract space, in name order. */
70 migrations: string[];
71 /** Path to the emitted `contract.json` (runtime IR), relative to the current working directory. */
72 contractJson: string;
73 /** Path to the emitted `contract.d.ts` (types), relative to the current working directory. */
74 contractTypes: string;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A Prisma ORM v8 contract managed as an Alchemy resource.
82 *
83 * Runs `prisma contract emit` and — when the contract's storage shape
84 * has drifted from the migration graph — `prisma migration plan` as
85 * part of `alchemy deploy`, so the emitted contract artifacts
86 * (`contract.json` / `contract.d.ts`) and the migration packages under
87 * `migrations/` are always regenerated from the source contract before
88 * anything downstream deploys. Pair it with {@link Migrate} to apply the
89 * planned packages to a database in the same deploy:
90 *
91 * ```typescript
92 * const contract = yield* Prisma.Contract("contract");
93 *
94 * const migrate = yield* Prisma.Migrate("migrate", {
95 * url: branch.origin.connectionString,
96 * contract,
97 * });
98 * ```
99 *
100 * Plans that require a human decision (data backfills rendered as
101 * `placeholder(...)` closures in `migration.ts`) are never auto-answered:
102 * the deploy fails with instructions to fill the placeholder, self-emit the
103 * package (`node migrations/app/<dir>/migration.ts`), and commit — the next
104 * deploy then sees no drift and applies the committed package.
105 *
106 * The resource is delete-safe: removing it from the stack does **not** wipe
107 * the migrations directory or the emitted contract, since both are checked
108 * in and shared with other environments.
109 *
110 * ### Declaring the contract
111 * **Example:** Contract at the project root
112 * ```typescript
113 * // expects ./prisma.config.ts and writes ./migrations
114 * const contract = yield* Prisma.Contract("contract");
115 * ```
116 *
117 * **Example:** Custom config location
118 * ```typescript
119 * const contract = yield* Prisma.Contract("contract", {
120 * config: "./db/prisma.config.ts",
121 * // resolved relative to ./db (the config's directory)
122 * migrationsDir: "./migrations",
123 * });
124 * ```
125 *
126 * ### Applying migrations on deploy
127 * **Example:** Contract + Migrate against Neon
128 * ```typescript
129 * const contract = yield* Prisma.Contract("contract");
130 * const project = yield* Neon.Project("db");
131 * const branch = yield* Neon.Branch("main", { project });
132 *
133 * yield* Prisma.Migrate("migrate", {
134 * url: branch.origin.connectionString,
135 * contract,
136 * });
137 * ```
138 *
139 * @resource
140 * @category ORM
141 */
142 export const Contract = Resource<Contract>("Prisma.Contract");
143
144 const placeholderGuidance = (dir: string) =>
145 [
146 `The planned migration package ${dir} contains unfilled placeholder(s) — a data`,
147 "backfill or destructive change that Prisma cannot decide automatically",
148 "(the SQL is applied to a real database later in the same deploy).",
149 "",
150 "To resolve:",
151 ` 1. Edit ${dir}/migration.ts and replace each placeholder(...) with a typed query plan.`,
152 ` 2. Self-emit the package: node ${dir}/migration.ts`,
153 " 3. Commit the package and re-deploy (the contract will see no drift and apply it).",
154 "",
155 `Or abandon the change: delete ${dir}/ and revert the contract source.`,
156 ].join("\n");
157
158 export const ContractProvider = () =>
159 Provider.effect(
160 Contract,
161 Effect.gen(function* () {
162 const fs = yield* FileSystem.FileSystem;
163 const path = yield* Path.Path;
164
165 // Every prop is optional, so `Prisma.Contract("contract")` (no props
166 // object at all) is legal — the engine then hands lifecycle ops
167 // `undefined` rather than `{}`.
168 const resolveConfig = (p: ContractProps | undefined) =>
169 path.resolve(process.cwd(), p?.config ?? "./prisma.config.ts");
170
171 const configDir = (p: ContractProps | undefined) => path.dirname(resolveConfig(p));
172
173 const resolveMigrationsDir = (p: ContractProps | undefined) =>
174 path.resolve(configDir(p), p?.migrationsDir ?? "./migrations");
175
176 // Attributes expose paths relative to the current working directory so
177 // persisted state stays portable across machines/checkouts. Internal
178 // filesystem ops always use the absolute forms.
179 const relative = (abs: string) => path.relative(process.cwd(), abs);
180
181 const emit = (p: ContractProps | undefined, outputPath?: string) =>
182 runPrismaCli<EmitResult>(
183 [
184 "contract",
185 "emit",
186 "--config",
187 resolveConfig(p),
188 ...(outputPath ? ["--output-path", outputPath] : []),
189 ],
190 { cwd: configDir(p) },
191 );
192
193 /**
194 * Emit the contract into a temp directory (so plan-time diffs never
195 * mutate the workspace) and compare its storage hash against the
196 * migration graph head. Cached per resource for the run so plan and
197 * apply share one CLI invocation.
198 */
199 const detectDrift = (p: ContractProps | undefined) =>
200 Effect.gen(function* () {
201 const tmp = yield* fs.makeTempDirectory({
202 prefix: "alchemy-prisma-contract-",
203 });
204 const emitted = yield* emit(p, tmp).pipe(
205 Effect.ensuring(fs.remove(tmp, { recursive: true }).pipe(Effect.ignore)),
206 );
207 const packages = yield* readMigrationPackages(resolveMigrationsDir(p));
208 const head = resolveGraphHead(packages);
209 return {
210 storageHash: emitted.storageHash,
211 packages,
212 head,
213 // Drift when the graph doesn't cover the emitted contract, or the
214 // head package was planned but never self-emitted (empty ops.json
215 // means unfilled placeholders — reconcile re-raises the guidance).
216 changed: head === undefined || head.to !== emitted.storageHash || head.opsEmpty,
217 };
218 }).pipe(Artifacts.cached("Prisma.Contract.detectDrift"));
219
220 const attributes = (
221 p: ContractProps | undefined,
222 emitted: EmitResult,
223 packages: readonly MigrationPackage[],
224 ) => ({
225 contractHash: emitted.storageHash,
226 config: relative(resolveConfig(p)),
227 migrationsDir: relative(resolveMigrationsDir(p)),
228 migrations: packages.map((pkg) => pkg.dirName),
229 contractJson: relative(emitted.files.json),
230 contractTypes: relative(emitted.files.dts),
231 });
232
233 return {
234 // Non-listable: a Prisma.Contract is a local build artifact (emitted
235 // contract + migration packages under paths supplied entirely by
236 // props). There is no remote store to enumerate.
237 list: () => Effect.succeed([]),
238 diff: Effect.fn(function* ({ news, output }) {
239 if (!isResolved(news)) return undefined;
240 if (!output) return undefined;
241 const drift = yield* detectDrift(news);
242 // Emitted artifacts must exist on disk for the runtime bundle; a
243 // fresh checkout without them needs a re-emit even with no drift.
244 const emittedExists =
245 output.contractJson !== undefined &&
246 (yield* fs.exists(path.resolve(process.cwd(), output.contractJson)));
247 // Only flag an update when something would actually change —
248 // otherwise downstream resources (e.g. Prisma.Migrate) would see
249 // `contract.contractHash` as an unresolved Output during plan and
250 // cascade into spurious updates of their own. The canonical-path
251 // comparison migrates legacy state to cwd-relative form.
252 return drift.changed ||
253 !emittedExists ||
254 output.config !== relative(resolveConfig(news)) ||
255 output.migrationsDir !== relative(resolveMigrationsDir(news))
256 ? { action: "update" }
257 : undefined;
258 }),
259 read: Effect.fn(function* ({ olds, output }) {
260 if (!output) return undefined;
261 const props = olds ?? ({} as ContractProps);
262 const migrationsDir = resolveMigrationsDir(props);
263 const configExists = yield* fs.exists(resolveConfig(props));
264 if (!configExists) return undefined;
265 const packages = yield* readMigrationPackages(migrationsDir);
266 const head = resolveGraphHead(packages);
267 return {
268 ...output,
269 contractHash: head?.to ?? output.contractHash,
270 migrationsDir: relative(migrationsDir),
271 migrations: packages.map((pkg) => pkg.dirName),
272 };
273 }),
274 reconcile: Effect.fn(function* ({ news, output, session }) {
275 yield* session.note(`${output ? "Re-emitting" : "Emitting"} Prisma contract`);
276 const emitted = yield* emit(news);
277 // Emits leak unpublished @internal/* specifiers (through rc.8);
278 // rewrite them to the public @prisma/orm-* packages.
279 yield* rewriteEmittedTypes(emitted.files.dts);
280 const migrationsDir = resolveMigrationsDir(news);
281 let packages = yield* readMigrationPackages(migrationsDir);
282 const head = resolveGraphHead(packages);
283
284 if (head === undefined || head.to !== emitted.storageHash) {
285 yield* session.note(
286 `Planning Prisma migration (${head ? `${head.to.slice(0, 8)} →` : "empty →"} ${emitted.storageHash.slice(0, 8)})`,
287 );
288 const plan = yield* runPrismaCli<PlanResult>(
289 [
290 "migration",
291 "plan",
292 "--config",
293 resolveConfig(news),
294 "--name",
295 // Package directory names are minute-resolution
296 // (`{YYYYMMDDTHHmm}_{name}`), so the default slug carries the
297 // target hash to keep two plans in the same minute (e.g.
298 // rapid successive deploys) from colliding.
299 news?.name ?? `migration-${emitted.storageHash.slice(0, 8)}`,
300 ...(head ? ["--from", head.to] : []),
301 ],
302 { cwd: configDir(news) },
303 );
304 if (plan.pendingPlaceholders) {
305 const dir = plan.dir
306 ? relative(path.resolve(configDir(news), plan.dir))
307 : "the planned migration directory";
308 return yield* new CliError({ message: placeholderGuidance(dir) });
309 }
310 if (!plan.noOp && plan.dir !== undefined) {
311 // Guard against a config/props mismatch: if the CLI wrote the
312 // package outside the directory this resource watches, every
313 // deploy would re-plan a duplicate package.
314 const planDir = path.resolve(configDir(news), plan.dir);
315 if (!planDir.startsWith(migrationsDir + path.sep)) {
316 return yield* new CliError({
317 message: [
318 `prisma wrote the migration package to ${relative(planDir)},`,
319 `outside this resource's migrationsDir (${relative(migrationsDir)}).`,
320 "Set the `migrationsDir` prop to match `orm.migrations.dir` in prisma.config.ts.",
321 ].join("\n"),
322 });
323 }
324 }
325 packages = yield* readMigrationPackages(migrationsDir);
326 }
327
328 // A converged graph whose head was planned earlier but never
329 // self-emitted still blocks the deploy — Migrate would fail on it.
330 const finalHead = resolveGraphHead(packages);
331 if (finalHead?.opsEmpty) {
332 const dir = relative(path.join(migrationsDir, "app", finalHead.dirName));
333 return yield* new CliError({ message: placeholderGuidance(dir) });
334 }
335
336 return attributes(news, emitted, packages);
337 }),
338 delete: Effect.fn(function* () {
339 // Emitted contract artifacts and migration packages are checked in;
340 // do not delete on resource teardown.
341 }),
342 };
343 }),
344 );