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

main
ts 161 lines 5.67 KB
Raw
1 /** @effect-diagnostics anyUnknownInErrorContext:off */
2 import * as Effect from "effect/Effect";
3
4 type Op = { kind: "get"; prop: PropertyKey } | { kind: "call"; args: unknown[] };
5
6 interface ChainState {
7 readonly cached: Effect.Effect<unknown, any, any>;
8 readonly ops: ReadonlyArray<Op>;
9 }
10
11 /**
12 * Every proxy produced by {@link chain} is registered here so that a chain
13 * passed as an *argument* to another chain over the same `cached` effect
14 * (e.g. `` sql`... ${sql.insert(row)}` `` — the nested `sql.insert(row)` is
15 * itself a proxy) can be recognized and replayed against the same resolved
16 * root instead of being handed to the real client as an opaque proxy.
17 */
18 const chainStates = new WeakMap<object, ChainState>();
19
20 /**
21 * Replay an op chain against a real value. `get` reads a property,
22 * `call` invokes — bound to the previous receiver so `this` resolves
23 * to the object the method was read from (drizzle's `select()` etc.
24 * read `this._.session`, so dropping `this` would throw).
25 */
26 const replay = (
27 root: unknown,
28 ops: ReadonlyArray<Op>,
29 cached: Effect.Effect<unknown, any, any>,
30 ): unknown => {
31 let cur: any = root;
32 let receiver: any = root;
33 for (const op of ops) {
34 if (op.kind === "get") {
35 receiver = cur;
36 cur = cur[op.prop];
37 } else {
38 cur = cur.apply(receiver, replayArgs(root, op.args, cached));
39 receiver = cur;
40 }
41 }
42 return cur;
43 };
44
45 /**
46 * Resolve nested chain proxies inside a call's arguments. Only proxies over
47 * the *same* `cached` effect can be replayed synchronously (the root is
48 * already resolved); proxies over a different effect pass through untouched.
49 * Returns the original array when nothing needed resolving, so identity-
50 * sensitive values (e.g. a `TemplateStringsArray` with its `raw` property)
51 * are preserved.
52 */
53 const replayArgs = (
54 root: unknown,
55 args: ReadonlyArray<unknown>,
56 cached: Effect.Effect<unknown, any, any>,
57 ): ReadonlyArray<unknown> => {
58 let out: unknown[] | undefined;
59 for (let i = 0; i < args.length; i++) {
60 const resolved = replayArg(root, args[i], cached);
61 if (resolved !== args[i]) {
62 out ??= [...args];
63 out[i] = resolved;
64 }
65 }
66 return out ?? args;
67 };
68
69 const replayArg = (
70 root: unknown,
71 arg: unknown,
72 cached: Effect.Effect<unknown, any, any>,
73 ): unknown => {
74 if (arg === null || (typeof arg !== "object" && typeof arg !== "function")) {
75 return arg;
76 }
77 const state = chainStates.get(arg);
78 if (state?.cached === cached) {
79 return replay(root, state.ops, cached);
80 }
81 // Fragments may arrive wrapped in arrays (e.g. `sql.and([a, b])`).
82 if (Array.isArray(arg)) {
83 return replayArgs(root, arg, cached);
84 }
85 return arg;
86 };
87
88 /**
89 * Wrap a cached `Effect<T>` in a chainable Proxy so callers can use the
90 * returned value as if it were `T` itself — every property read and call
91 * records a step, and the chain is replayed against the resolved value
92 * when it's finally yielded as an Effect.
93 *
94 * Compare:
95 *
96 * ```typescript
97 * // Without proxyChain — caller has to yield the cached Effect first:
98 * const conn = yield* makeConnection(); // Effect<Db>
99 * fetch: Effect.gen(function* () {
100 * const db = yield* conn;
101 * const rows = yield* db.select().from(users);
102 * });
103 *
104 * // With proxyChain — caller treats the return as the value directly:
105 * const db = proxyChain(yield* Effect.cached(makeDb)); // T
106 * fetch: Effect.gen(function* () {
107 * const rows = yield* db.select().from(users);
108 * });
109 * ```
110 *
111 * The chain ends when the proxy is yielded as an Effect — the resolved
112 * value at that point must be a `Yieldable` (an Effect, drizzle query
113 * builder, etc). Anything before that is recorded as ops.
114 *
115 * A chain passed as an *argument* to another chain over the same effect —
116 * e.g. `` sql`INSERT INTO users ${sql.insert(row)}` ``, where `sql.insert(row)`
117 * is itself a deferred proxy — is replayed against the same resolved root
118 * before the outer call runs, so synchronous fragment helpers compose.
119 */
120 export const proxyChain = <T>(cached: Effect.Effect<T, any, any>): T => chain(cached) as T;
121
122 /**
123 * Property reads the Effect runtime uses as *brand probes* — `symbol` keys
124 * and `~effect/...` type-id strings (`~effect/Exit`, `~effect/Effect`, …).
125 * The fiber's generator runner distinguishes a yielded Effect from an Exit
126 * with `value[ExitTypeId] !== undefined` (effect ≥ 4.0.0-rc.113; earlier
127 * releases used `in`, which the `has` trap already answers). Recording such
128 * a read as a chain step would hand back a truthy proxy, so the runner
129 * would treat every chain as an already-settled Exit and resume the
130 * generator with `proxy.value` — another proxy — instead of running it.
131 * Brand probes therefore answer `undefined` when the underlying effect
132 * lacks the key; the `has` trap keeps `in`-based probes correct too.
133 */
134 const isBrandProbe = (prop: PropertyKey): boolean =>
135 typeof prop === "symbol" || (typeof prop === "string" && prop.startsWith("~effect/"));
136
137 const chain = (cached: Effect.Effect<unknown, any, any>, ops: ReadonlyArray<Op> = []): unknown => {
138 const effect = Effect.flatMap(
139 cached,
140 (root) => replay(root, ops, cached) as Effect.Effect<unknown, unknown, unknown>,
141 );
142 const proxy = new Proxy(function () {}, {
143 get(_, prop) {
144 if (Reflect.has(effect, prop)) {
145 return Reflect.get(effect, prop);
146 }
147 if (isBrandProbe(prop)) {
148 return undefined;
149 }
150 return chain(cached, [...ops, { kind: "get", prop }]);
151 },
152 has(target, prop) {
153 return Reflect.has(target, prop) || Reflect.has(effect, prop);
154 },
155 apply(_, __, args) {
156 return chain(cached, [...ops, { kind: "call", args }]);
157 },
158 });
159 chainStates.set(proxy, { cached, ops });
160 return proxy;
161 };