The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | connectionSourceDigest, |
| 3 | resolveConnectionSource, |
| 4 | staticConnectionSource, |
| 5 | type ConnectionSource, |
| 6 | type StaticConnectionSource, |
| 7 | } from "@alchemy.run/sql/ConnectionSource"; |
| 8 | import { openPostgresPool } from "@alchemy.run/sql/PostgresDriver"; |
| 9 | import type { RuntimeContext } from "alchemy"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import type * as Redacted from "effect/Redacted"; |
| 13 | import type * as Scope from "effect/Scope"; |
| 14 | import type { PoolConfig } from "pg"; |
| 15 | import { Database, type DatabaseService, type DirectDatabase } from "./Database.ts"; |
| 16 | import { BetterAuthMigrationError } from "./Errors.ts"; |
| 17 | |
| 18 | export type { ConnectionSource }; |
| 19 | /** Deploy-resolvable connection source usable for migrations. */ |
| 20 | export type MigrateSource = StaticConnectionSource; |
| 21 | |
| 22 | export interface SqlLayerOptions { |
| 23 | /** |
| 24 | * Deploy-resolvable connection source for schema migrations. Defaults to |
| 25 | * the layer's own `url` when that is deploy-resolvable (a literal or a |
| 26 | * resource Output); a runtime-only `url` (Hyperdrive) has no default — |
| 27 | * pass the origin URL here, or `false` to disable migration support. |
| 28 | */ |
| 29 | readonly migrate?: MigrateSource | false; |
| 30 | /** Extra driver pool options (`max` defaults to 1 per execution). */ |
| 31 | readonly pool?: Record<string, unknown>; |
| 32 | } |
| 33 | |
| 34 | export interface PostgresOptions extends SqlLayerOptions { |
| 35 | readonly pool?: Omit<PoolConfig, "connectionString">; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Build a `migrate` config over a scoped open-connection effect: the init |
| 40 | * half captures the connection-string Output, the apply half opens the |
| 41 | * driver against the resolved value. |
| 42 | * |
| 43 | * @internal |
| 44 | */ |
| 45 | export const makeMigrateSupport = ( |
| 46 | migrateSource: MigrateSource, |
| 47 | open: ( |
| 48 | url: Effect.Effect<Redacted.Redacted<string>>, |
| 49 | ) => Effect.Effect<DirectDatabase, never, Scope.Scope>, |
| 50 | failure: string, |
| 51 | ): NonNullable<DatabaseService["migrate"]> => ({ |
| 52 | identity: { urlDigest: connectionSourceDigest(migrateSource) } as Record<string, unknown>, |
| 53 | connect: Effect.gen(function* () { |
| 54 | // Init half — capture the connection-string Output. |
| 55 | const urlAccessor = yield* resolveConnectionSource(migrateSource); |
| 56 | // Apply half — load the driver and open the pool. |
| 57 | return open(urlAccessor).pipe( |
| 58 | Effect.catchDefect((cause: unknown) => |
| 59 | Effect.fail(new BetterAuthMigrationError({ message: failure, cause })), |
| 60 | ), |
| 61 | ); |
| 62 | }) as Effect.Effect< |
| 63 | Effect.Effect<DirectDatabase, BetterAuthMigrationError, Scope.Scope>, |
| 64 | never, |
| 65 | RuntimeContext |
| 66 | >, |
| 67 | }); |
| 68 | |
| 69 | /** |
| 70 | * Build the Postgres {@link DatabaseService}. |
| 71 | * |
| 72 | * @internal |
| 73 | */ |
| 74 | export const makePostgresService = ( |
| 75 | source: ConnectionSource, |
| 76 | options: PostgresOptions | undefined, |
| 77 | ): Effect.Effect<DatabaseService> => |
| 78 | Effect.gen(function* () { |
| 79 | const urlEffect = yield* resolveConnectionSource(source); |
| 80 | const migrateSource = staticConnectionSource(source, options?.migrate); |
| 81 | const open = (url: Effect.Effect<Redacted.Redacted<string>>) => |
| 82 | openPostgresPool(url, options?.pool) as Effect.Effect<DirectDatabase, never, Scope.Scope>; |
| 83 | |
| 84 | return { |
| 85 | provider: "postgres", |
| 86 | runtime: open(urlEffect) as DatabaseService["runtime"], |
| 87 | ...(migrateSource === undefined |
| 88 | ? {} |
| 89 | : { |
| 90 | migrate: makeMigrateSupport( |
| 91 | migrateSource, |
| 92 | open, |
| 93 | "Failed to load `pg` — install it to migrate a Postgres-backed BetterAuth", |
| 94 | ), |
| 95 | }), |
| 96 | } satisfies DatabaseService; |
| 97 | }) as Effect.Effect<DatabaseService>; |
| 98 | |
| 99 | /** |
| 100 | * Generic TCP Postgres database layer for Better Auth, from a connection |
| 101 | * string. |
| 102 | * |
| 103 | * Works with every Postgres alchemy exposes a connection string for: |
| 104 | * PlanetScale Postgres (`role.connectionUrl`), Prisma Postgres |
| 105 | * (`connection.databaseUrl`), AWS RDS inside a VPC, or any literal URL. |
| 106 | * One `pg.Pool` is opened per execution and closed when the event settles |
| 107 | * — the only legal pooling shape on workerd. Prefer `Neon`, |
| 108 | * `AuroraDataApi`, or `CloudflareHyperdrive` when they match your |
| 109 | * environment → database pair. |
| 110 | * |
| 111 | * On AWS Lambda, add `build: { install: ["pg"] }` to the Function props so |
| 112 | * the dynamically-imported driver ships in the artifact with an npm layout |
| 113 | * (its CJS require chain does not survive store-style node_modules). |
| 114 | * |
| 115 | * |
| 116 | * ### Connecting with a resource Output |
| 117 | * Resource Outputs are bound into the host environment at deploy and read |
| 118 | * back at runtime; the same source drives deploy-time migrations. |
| 119 | * **Example:** PlanetScale Postgres |
| 120 | * ```typescript |
| 121 | * import { BetterAuth } from "@alchemy.run/better-auth"; |
| 122 | * import { Postgres } from "@alchemy.run/better-auth/Postgres"; |
| 123 | * |
| 124 | * const role = yield* Planetscale.PostgresRole("auth-role", { database, branch }); |
| 125 | * |
| 126 | * Effect.gen(function* () { |
| 127 | * const auth = yield* BetterAuth({ emailAndPassword: { enabled: true } }); |
| 128 | * return { fetch: ... }; |
| 129 | * }).pipe(Effect.provide(Postgres(role.connectionUrl))) |
| 130 | * ``` |
| 131 | * |
| 132 | * ### Separate migration source |
| 133 | * When the runtime URL is not deploy-resolvable (or points at a pooler), |
| 134 | * pass a direct deploy-time URL as `migrate`. |
| 135 | * **Example:** Pooled runtime, direct migrations |
| 136 | * ```typescript |
| 137 | * Postgres(role.connectionUrlPooled, { migrate: role.connectionUrl }) |
| 138 | * ``` |
| 139 | * |
| 140 | * @layer |
| 141 | * @provides BetterAuth.Database |
| 142 | * @peer pg |
| 143 | * @product Postgres |
| 144 | */ |
| 145 | export const Postgres = (url: ConnectionSource, options?: PostgresOptions): Layer.Layer<Database> => |
| 146 | Layer.effect(Database, makePostgresService(url, options)) as Layer.Layer<Database>; |