1import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1";
2import * as Cloudflare from "alchemy/Cloudflare";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as HttpRouter from "effect/http/HttpRouter";
6import { HttpServerRequest } from "effect/http/HttpServerRequest";
7import { Auth } from "./auth.ts";
8import { AuthDb } from "./database.ts";
9import { HttpLive } from "./http.ts";
10
11export default class AuthApi extends Cloudflare.Worker<AuthApi>()(
12 "AuthApi",
13 {
14 main: import.meta.url,
15 compatibility: { flags: ["nodejs_compat"] },
16 assets: { directory: "./public" },
17 },
18 Effect.gen(function* () {
19 const auth = yield* Auth;
20 const http = yield* HttpRouter.toHttpEffect(HttpLive);
21 return {
22 fetch: Effect.gen(function* () {
23 const request = yield* HttpServerRequest;
24 const pathname = new URL(request.url, "http://localhost").pathname;
25 if (pathname === "/api/auth" || pathname.startsWith("/api/auth/")) {
26 return yield* auth.fetch;
27 }
28 return yield* http;
29 }),
30 };
31 }).pipe(Effect.provide(Auth.layer.pipe(Layer.provide(CloudflareD1(AuthDb))))),
32) {}