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

main
ts 228 lines 7.99 KB
Raw
1 import { Action, Stack, type Output } from "alchemy";
2 import { CurrentRuntimeContext, sanitizeKey } from "alchemy/RuntimeContext";
3 import { sha256Object } from "alchemy/Util/sha256";
4 import type { BetterAuthOptions } from "better-auth";
5 import { getSchema } from "better-auth/db";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import type { DatabaseService } from "./Database.ts";
9 import { BetterAuthMigrationError } from "./Errors.ts";
10
11 /**
12 * Deploy-time migration machinery.
13 *
14 * This module is ONLY imported dynamically from inside
15 * `if (!globalThis.__ALCHEMY_RUNTIME__)` in `BetterAuth.ts`, so none of it
16 * (including `better-auth/db` and the Kysely-based migration engine pulled
17 * in by `better-auth/db/migration`) ever reaches a deployed runtime bundle.
18 *
19 * @internal
20 */
21
22 interface MigrateInput {
23 /** Non-secret identity of the target database (from the platform layer). */
24 identity: Record<string, unknown>;
25 /** Fingerprint of the Better Auth schema (tables + fields). */
26 schema: string;
27 /** Dialect family — part of the input so a dialect swap re-runs. */
28 provider: string;
29 }
30
31 export interface MigrateOutput {
32 tablesCreated: number;
33 tablesAltered: number;
34 indexesCreated: number;
35 }
36
37 export interface RegisterMigrationOptions {
38 readonly id: string;
39 /** The user's Better Auth options (without `database`). */
40 readonly options: BetterAuthOptions;
41 readonly db: DatabaseService;
42 /** The user's `migrate` prop — `undefined` means default-on. */
43 readonly migrate: boolean | undefined;
44 }
45
46 /**
47 * Register the schema-migration Action for a `BetterAuth` instance.
48 *
49 * Actions run only during `alchemy deploy` (apply), re-run only when their
50 * resolved input changes — here: the schema fingerprint, the database
51 * identity, or the dialect — and their body gets the ambient stack
52 * services, so `migrate.connect` can resolve resource Outputs and reach
53 * the cloud.
54 */
55 export const registerMigration = ({
56 id,
57 options,
58 db,
59 migrate,
60 }: RegisterMigrationOptions): Effect.Effect<void> =>
61 Effect.gen(function* () {
62 const support = db.migrate;
63 if (support === undefined) {
64 if (migrate === true) {
65 return yield* Effect.die(
66 new Error(
67 `BetterAuth(${id}): \`migrate: true\` was requested, but the ` +
68 `"${db.provider}" Database layer does not support automatic ` +
69 "migrations. Remove `migrate: true` (and manage the schema " +
70 "yourself, e.g. via `npx auth@1.7.5 generate`) or use a " +
71 "layer with migration support.",
72 ),
73 );
74 }
75 return;
76 }
77 if (migrate === false) {
78 return;
79 }
80 // Outside a stack evaluation (unit tests driving BetterAuth directly)
81 // there is nothing to register on — skip silently.
82 const stack = yield* Effect.serviceOption(Stack);
83 if (Option.isNone(stack)) {
84 return;
85 }
86
87 // Init-effect form: `support.connect`'s outer half runs here under the
88 // Action's capture context, so resource Outputs it yields (databaseId,
89 // connection-string attrs) become dependency captures resolved at
90 // apply. The returned runner does the actual connect + migrate.
91 const Migrate = Action(
92 "BetterAuth.Migrate",
93 Effect.gen(function* () {
94 const acquire = yield* support.connect;
95 return (_input: MigrateInput) => runMigrationWith(acquire, options);
96 }),
97 );
98 const result = yield* Migrate(`${id}Migrate`, {
99 identity: support.identity,
100 schema: yield* schemaFingerprint(options),
101 provider: db.provider,
102 }).pipe(
103 // The Action call's requirements (Stack, the runner's Req) are
104 // ambient during stack evaluation — erase them; presence of Stack
105 // was checked above.
106 (effect) => effect as unknown as Effect.Effect<Output<MigrateOutput>>,
107 );
108
109 // Bind the migration result into the host environment (when there is a
110 // host): the host's env then depends on the Action's output, giving the
111 // engine a Worker/Function → Migration dependency edge so first-deploy
112 // traffic cannot race the schema.
113 const rc = yield* CurrentRuntimeContext;
114 if (rc !== undefined) {
115 yield* rc.set(sanitizeKey(`${id}Migration`), result as never);
116 }
117 }) as Effect.Effect<void>;
118
119 /**
120 * Connect via the platform layer's `migrate.connect` and apply Better
121 * Auth's schema migrations. Additive and idempotent — re-running against
122 * an up-to-date database is a no-op.
123 */
124 export const applyMigrations = (
125 support: NonNullable<DatabaseService["migrate"]>,
126 options: BetterAuthOptions,
127 ) => Effect.flatMap(support.connect, (acquire) => runMigrationWith(acquire, options));
128
129 const runMigrationWith = (
130 acquire: Effect.Effect<
131 import("./Database.ts").DirectDatabase,
132 BetterAuthMigrationError,
133 import("effect/Scope").Scope
134 >,
135 options: BetterAuthOptions,
136 ) =>
137 Effect.scoped(
138 Effect.gen(function* () {
139 const database = yield* acquire;
140 if (typeof database === "function") {
141 return yield* Effect.die(
142 new Error(
143 "BetterAuth migration: `connect` yielded an adapter factory — " +
144 "migrations require a direct (Kysely-resolvable) database.",
145 ),
146 );
147 }
148 const { getMigrations, UnsafeMigrationError } = yield* Effect.promise(
149 () => import("better-auth/db/migration"),
150 );
151 const migrations = yield* Effect.tryPromise({
152 try: () =>
153 getMigrations({
154 ...options,
155 database,
156 // getMigrations only introspects the schema; the secret is
157 // irrelevant but required by the options type.
158 secret: "alchemy-migrate",
159 telemetry: { enabled: false },
160 }),
161 catch: (cause) =>
162 new BetterAuthMigrationError({
163 message:
164 cause instanceof UnsafeMigrationError
165 ? cause.message
166 : "Failed to compute Better Auth schema migrations",
167 cause,
168 }),
169 });
170 yield* Effect.tryPromise({
171 try: () => migrations.runMigrations(),
172 catch: (cause) =>
173 new BetterAuthMigrationError({
174 message: "Failed to apply Better Auth schema migrations",
175 cause,
176 }),
177 });
178 return {
179 tablesCreated: migrations.toBeCreated.length,
180 tablesAltered: migrations.toBeAdded.length,
181 indexesCreated: migrations.toBeAddedIndexes.length,
182 } satisfies MigrateOutput;
183 }),
184 );
185
186 /**
187 * Stable fingerprint of the Better Auth schema derived from the user's
188 * options (plugins, additionalFields, model renames, table indexes).
189 * Changing the schema changes the fingerprint, which changes the
190 * migration Action's input and re-runs it on the next deploy.
191 */
192 export const schemaFingerprint = (options: BetterAuthOptions): Effect.Effect<string> =>
193 Effect.suspend(() => {
194 const schema = getSchema(options);
195 // Reduce to the migration-relevant field and index attributes;
196 // sha256Object's stable serialization handles key ordering.
197 const reduced = Object.fromEntries(
198 Object.entries(schema).map(([table, def]) => [
199 table,
200 {
201 fields: Object.fromEntries(
202 Object.entries(def.fields).map(([name, field]) => [
203 name,
204 {
205 type: String(field.type),
206 required: field.required ?? false,
207 unique: field.unique ?? false,
208 index: field.index ?? false,
209 fieldName: field.fieldName,
210 references: field.references
211 ? {
212 model: field.references.model,
213 field: field.references.field,
214 }
215 : undefined,
216 },
217 ]),
218 ),
219 indexes: (def.indexes ?? []).map((index) => ({
220 name: index.name,
221 unique: index.unique ?? false,
222 columns: [...index.columns],
223 })),
224 },
225 ]),
226 );
227 return sha256Object(reduced);
228 });