The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import { LinkNotFound, Links, LinkStoreError, newCode, type Link } from "./Links.ts"; |
| 5 | |
| 6 | /** `Links` stored in a Cloudflare KV namespace that this Layer owns. */ |
| 7 | export const LinksKV = Layer.effect( |
| 8 | Links, |
| 9 | Effect.gen(function* () { |
| 10 | const namespace = yield* Cloudflare.KV.Namespace("Links"); |
| 11 | const kv = yield* Cloudflare.KV.ReadWriteNamespace(namespace); |
| 12 | |
| 13 | const get = Effect.fn(function* (code: string) { |
| 14 | const link = yield* kv.get<Link>(code, "json"); |
| 15 | if (!link) return yield* new LinkNotFound({ code }); |
| 16 | return link; |
| 17 | }); |
| 18 | |
| 19 | return { |
| 20 | create: Effect.fn( |
| 21 | function* (url: string) { |
| 22 | const link: Link = { code: newCode(), url, createdAt: Date.now() }; |
| 23 | yield* kv.put(link.code, JSON.stringify(link)); |
| 24 | return link; |
| 25 | }, |
| 26 | Effect.mapError((cause) => new LinkStoreError({ cause })), |
| 27 | ), |
| 28 | get: (code: string) => |
| 29 | get(code).pipe( |
| 30 | Effect.catchTag("NamespaceError", (cause) => Effect.fail(new LinkStoreError({ cause }))), |
| 31 | ), |
| 32 | list: Effect.fn( |
| 33 | function* () { |
| 34 | const { keys } = yield* kv.list(); |
| 35 | const links = yield* Effect.forEach(keys, (key) => kv.get<Link>(key.name, "json"), { |
| 36 | concurrency: 10, |
| 37 | }); |
| 38 | return links |
| 39 | .filter((link): link is Link => link !== null) |
| 40 | .sort((a, b) => b.createdAt - a.createdAt); |
| 41 | }, |
| 42 | Effect.mapError((cause) => new LinkStoreError({ cause })), |
| 43 | ), |
| 44 | setPreview: Effect.fn( |
| 45 | function* (code: string, preview: Link["preview"] & {}) { |
| 46 | const link = yield* get(code); |
| 47 | yield* kv.put(code, JSON.stringify({ ...link, preview })); |
| 48 | }, |
| 49 | Effect.catchTag("NamespaceError", (cause) => Effect.fail(new LinkStoreError({ cause }))), |
| 50 | ), |
| 51 | }; |
| 52 | }), |
| 53 | ).pipe(Layer.provide(Cloudflare.KV.ReadWriteNamespaceBinding)); |