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

main
ts 107 lines 4.04 KB
Raw
1 import * as Effect from "effect/Effect";
2 import type { Namespace } from "./Namespace.ts";
3 import {
4 ArtifactsError,
5 type ArtifactsErrorCode,
6 type ReadWriteNamespaceClient,
7 type RepoClient,
8 type RepoHandle,
9 } from "./ReadWriteNamespace.ts";
10
11 /**
12 * Shared scaffolding for the Worker-binding implementations of the Artifacts
13 * services: maps the platform's thrown errors onto {@link ArtifactsError} and
14 * wraps the runtime binding and its repo handles in Effect-native clients.
15 */
16
17 const ARTIFACTS_ERROR_CODES: { readonly [K in ArtifactsErrorCode]: true } = {
18 ALREADY_EXISTS: true,
19 NOT_FOUND: true,
20 CREATE_IN_PROGRESS: true,
21 IMPORT_IN_PROGRESS: true,
22 FORK_IN_PROGRESS: true,
23 INVALID_INPUT: true,
24 INVALID_REPO_NAME: true,
25 INVALID_TTL: true,
26 INVALID_URL: true,
27 REMOTE_AUTH_REQUIRED: true,
28 UPSTREAM_UNAVAILABLE: true,
29 MEMORY_LIMIT: true,
30 INTERNAL_ERROR: true,
31 };
32
33 const isArtifactsErrorCode = (code: unknown): code is ArtifactsErrorCode =>
34 typeof code === "string" && Object.hasOwn(ARTIFACTS_ERROR_CODES, code);
35
36 /** The REST API's `errors[].code` for `NOT_FOUND`. */
37 const NOT_FOUND_NUMERIC_CODE = 10200;
38
39 /**
40 * Map a value thrown by the binding onto {@link ArtifactsError}, keeping the
41 * platform's `code` / `numericCode` when it attached them.
42 */
43 const toArtifactsError = (error: any): ArtifactsError =>
44 new ArtifactsError({
45 message: error?.message ?? "Unknown error",
46 code: isArtifactsErrorCode(error?.code) ? error.code : undefined,
47 numericCode: typeof error?.numericCode === "number" ? error.numericCode : undefined,
48 cause: error,
49 });
50
51 const tryPromise = <T>(fn: () => Promise<T>): Effect.Effect<T, ArtifactsError> =>
52 Effect.tryPromise({ try: fn, catch: toArtifactsError });
53
54 /** Wrap a runtime repo handle so each method returns an Effect. */
55 export const makeArtifactsRepoClient = (raw: RepoHandle): RepoClient => ({
56 raw,
57 info: () => tryPromise(() => raw.info()),
58 listTokens: () => tryPromise(() => raw.listTokens()),
59 log: (opts) => tryPromise(() => raw.log(opts)),
60 readCommit: (hash) => tryPromise(() => raw.readCommit(hash)),
61 readTree: (hash) => tryPromise(() => raw.readTree(hash)),
62 readBlob: (hash) => tryPromise(() => raw.readBlob(hash)),
63 readFile: (args) => tryPromise(() => raw.readFile(args)),
64 createToken: (scope, ttl) => tryPromise(() => raw.createToken(scope, ttl)),
65 revokeToken: (tokenOrId) => tryPromise(() => raw.revokeToken(tokenOrId)),
66 fork: (name, opts) => tryPromise(() => raw.fork(name, opts)),
67 });
68
69 /**
70 * Builds the full Artifacts client over the native worker binding. Each access
71 * level (Read / Write / ReadWrite) returns this same object typed to its subset
72 * — least-privilege by construction at the call site.
73 */
74 export const makeArtifactsNamespaceClient = (
75 env: Record<string, any>,
76 namespace: Namespace,
77 ): ReadWriteNamespaceClient => {
78 // Lazy — the WorkerEnvironment binding is not populated until runtime.
79 const raw = Effect.sync(() => (env as Record<string, Artifacts>)[namespace.name]!);
80 const use = <T>(fn: (raw: Artifacts) => Promise<T>): Effect.Effect<T, ArtifactsError> =>
81 raw.pipe(Effect.flatMap((raw) => tryPromise(() => fn(raw))));
82 // The platform throws `NOT_FOUND` for a missing repo; a `null` is mapped the
83 // same way.
84 const getRepo = (raw: Artifacts, name: string): Promise<RepoHandle | null> => raw.get(name);
85 return {
86 raw,
87 create: (name, opts) => use((raw) => raw.create(name, opts)),
88 get: (name) =>
89 use((raw) => getRepo(raw, name)).pipe(
90 Effect.flatMap((repo) =>
91 repo == null
92 ? Effect.fail(
93 new ArtifactsError({
94 message: `Artifacts repo '${name}' not found`,
95 code: "NOT_FOUND",
96 numericCode: NOT_FOUND_NUMERIC_CODE,
97 cause: new Error("not_found"),
98 }),
99 )
100 : Effect.succeed(makeArtifactsRepoClient(repo)),
101 ),
102 ),
103 list: (opts) => use((raw) => raw.list(opts)),
104 delete: (name) => use((raw) => raw.delete(name)),
105 import: (opts) => use((raw) => raw.import(opts)),
106 };
107 };