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

main
ts 157 lines 6.27 KB
Raw
1 import type { Contract } from "@prisma/orm-postgres/contract/types";
2 import type { SqlStorage } from "@prisma/orm-postgres/family-contract/types";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Option from "effect/Option";
6 import * as Path from "effect/Path";
7 import * as Schema from "effect/Schema";
8 import { effectGeneratorKey, type EffectGeneratorOptions } from "./generator.ts";
9 import { CliError, rewriteEmittedTypes, runPrismaCli, type EmitResult } from "./internal.ts";
10 import { emitSchemas, SchemaError } from "./Schema.ts";
11
12 interface GeneratorConfig {
13 readonly orm?: {
14 readonly [effectGeneratorKey]?: EffectGeneratorOptions;
15 readonly contract?: {
16 readonly output?: string;
17 readonly source?: { readonly inputs?: readonly string[] };
18 };
19 };
20 }
21
22 /** Load generation settings without running emission or migrations. */
23 export const loadGeneratorConfig = Effect.fn(function* (configFile: string) {
24 const path = yield* Path.Path;
25 const absolute = path.resolve(configFile);
26 const url = yield* path.toFileUrl(absolute);
27 const module = yield* Effect.tryPromise({
28 try: () => import(url.href),
29 catch: (cause) => new CliError({ message: `Cannot load ${absolute}: ${String(cause)}` }),
30 });
31 const config = module.default as GeneratorConfig | undefined;
32 const options = config?.orm?.[effectGeneratorKey];
33 if (!options || !config?.orm?.contract?.output) {
34 return yield* new CliError({
35 message: `Wrap the orm configuration in ${absolute} with withEffect(ormConfig(...), options) and specify output.`,
36 });
37 }
38 const directory = path.dirname(absolute);
39 return {
40 absolute,
41 directory,
42 options,
43 output: path.resolve(directory, config.orm.contract.output),
44 inputs: [
45 absolute,
46 ...(config.orm.contract.source?.inputs ?? []).map((input) => path.resolve(directory, input)),
47 ],
48 };
49 });
50
51 const header = "// Generated by alchemy prisma generate.\n";
52
53 /** Emit Prisma contracts and optional Effect bindings; never connect or migrate. */
54 export const generate = Effect.fn(function* (configFile: string) {
55 const fs = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 const config = yield* loadGeneratorConfig(configFile);
58 const temporary = yield* fs.makeTempDirectoryScoped({
59 prefix: "alchemy-prisma-generate-",
60 });
61 const emitted = yield* runPrismaCli<EmitResult>(
62 [
63 "contract",
64 "emit",
65 "--config",
66 config.absolute,
67 "--output-path",
68 path.join(temporary, path.basename(config.output)),
69 ],
70 { cwd: config.directory },
71 ).pipe(
72 Effect.catchTag("Prisma.CliError", (error) => {
73 const diagnostics = Schema.decodeUnknownOption(
74 Schema.Struct({
75 diagnostics: Schema.Array(Schema.Struct({ message: Schema.String })),
76 }),
77 )(error.meta);
78 return Effect.fail(
79 Option.isSome(diagnostics)
80 ? new CliError({
81 code: error.code,
82 fix: error.fix,
83 meta: error.meta,
84 message: [
85 error.message,
86 ...diagnostics.value.diagnostics.map((diagnostic) => diagnostic.message),
87 ].join("\n"),
88 })
89 : error,
90 );
91 }),
92 );
93 const json = path.resolve(config.directory, emitted.files.json);
94 const dts = path.resolve(config.directory, emitted.files.dts);
95 yield* rewriteEmittedTypes(dts);
96 const text = yield* fs.readFileString(json);
97 const contract = yield* Effect.try({
98 try: () => JSON.parse(text) as Contract<SqlStorage>,
99 catch: (cause) => new CliError({ message: `Invalid emitted contract: ${String(cause)}` }),
100 });
101 const directory = path.dirname(config.output);
102 const jsonName = `./${path.basename(json)}`;
103 const typeName = `./${path.basename(dts)}`;
104 const files: Record<string, string> = {};
105 if (config.options.client !== false) {
106 files["runtime.ts"] =
107 `${header}import contractJson from ${JSON.stringify(jsonName)} with { type: "json" };\nexport { contractJson };\n`;
108 files["client.ts"] =
109 `${header}import type { Contract } from ${JSON.stringify(typeName)};\nimport type * as Effect from "effect/Effect";\nimport type * as Redacted from "effect/Redacted";\nimport { Postgres, type PostgresConfig } from "@alchemy.run/prisma/ORM/Postgres";\nimport { contractJson } from "./runtime.ts";\nexport const makeDatabase = <E = never, R = never>(\n connectionString: Effect.Effect<Redacted.Redacted<string>, E, R>,\n options: Omit<PostgresConfig<Contract>, "contract" | "contractJson"> = {},\n) => Postgres<Contract, E, R>(connectionString, { ...options, contractJson });\n`;
110 }
111 if (config.options.schemas !== false) {
112 files["schemas.ts"] = yield* Effect.try({
113 try: () => emitSchemas(contract, config.options),
114 catch: (cause) =>
115 cause instanceof SchemaError
116 ? cause
117 : new CliError({ message: `Cannot emit schemas: ${String(cause)}` }),
118 });
119 }
120 files["index.ts"] =
121 header +
122 [
123 ...(config.options.client !== false ? ['export { makeDatabase } from "./client.ts";'] : []),
124 ...(config.options.schemas !== false ? ['export { schemas } from "./schemas.ts";'] : []),
125 ].join("\n") +
126 "\n";
127 const owned = ["runtime.ts", "client.ts", "schemas.ts", "index.ts"];
128 for (const name of owned) {
129 const target = path.join(directory, name);
130 if (yield* fs.exists(target)) {
131 const previous = yield* fs.readFileString(target);
132 if (!previous.startsWith(header)) {
133 return yield* new CliError({
134 message: `Refusing to overwrite non-generated file ${target}`,
135 });
136 }
137 }
138 }
139 files[path.basename(json)] = text;
140 files[path.basename(dts)] = yield* fs.readFileString(dts);
141 yield* fs.makeDirectory(directory, { recursive: true });
142 for (const name of new Set([...owned, ...Object.keys(files)])) {
143 const target = path.join(directory, name);
144 const exists = yield* fs.exists(target);
145 const previous = exists ? yield* fs.readFileString(target) : undefined;
146 const content = files[name];
147 if (content === undefined) {
148 if (exists) yield* fs.remove(target);
149 } else if (content !== previous) {
150 yield* fs.writeFileString(target, content);
151 }
152 }
153 return {
154 directory,
155 files: Object.keys(files).map((name) => path.join(directory, name)),
156 };
157 }, Effect.scoped);