@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 266 lines 9.39 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import * as Effect from "effect/Effect";
3 import * as Exit from "effect/Exit";
4 import { proxyChain } from "@/Util/proxy-chain.ts";
5
6 const TIMEOUT = 5_000;
7
8 /**
9 * A fake drizzle-like db. `select()` and `echo()` are real methods that
10 * read `this` — so replaying them with the wrong receiver would throw,
11 * which is how we assert `this`-binding is preserved through the proxy.
12 */
13 const makeDb = () => ({
14 greeting: "hi",
15 echo(n: number) {
16 return Effect.succeed(`${this.greeting}:${n}`);
17 },
18 select() {
19 const greeting = this.greeting;
20 return {
21 from: (table: string) => Effect.succeed([`${greeting}/${table}`]),
22 };
23 },
24 });
25
26 type Db = ReturnType<typeof makeDb>;
27
28 describe("proxyChain", { tags: ["unit", "local"], timeout: 5000 }, () => {
29 it.effect("replays a property-read + call chain when yielded", () =>
30 Effect.gen(function* () {
31 const db = proxyChain<Db>(Effect.succeed(makeDb()));
32 const rows = yield* db.select().from("users");
33 expect(rows).toEqual(["hi/users"]);
34 }),
35 );
36
37 it.effect("binds `this` to the receiver for method calls", () =>
38 Effect.gen(function* () {
39 const db = proxyChain<Db>(Effect.succeed(makeDb()));
40 // `echo` reads `this.greeting`; a dropped receiver would throw.
41 const result = yield* db.echo(7);
42 expect(result).toBe("hi:7");
43 }),
44 );
45
46 it.effect("is lazy — does not resolve the underlying effect until yielded", () =>
47 Effect.gen(function* () {
48 let built = 0;
49 const db = proxyChain<Db>(
50 Effect.sync(() => {
51 built++;
52 return makeDb();
53 }),
54 );
55
56 // Building the op chain must not touch the underlying effect.
57 const query = db.select().from("users");
58 expect(built).toBe(0);
59
60 yield* query;
61 expect(built).toBe(1);
62 }),
63 );
64
65 it.effect("works as an Effect inside Effect.all (regression: used to hang)", () =>
66 Effect.gen(function* () {
67 const db = proxyChain<Db>(Effect.succeed(makeDb()));
68 const results = yield* Effect.all([db.select().from("users"), db.select().from("posts")]);
69 expect(results).toEqual([["hi/users"], ["hi/posts"]]);
70 }),
71 );
72
73 it.effect("works inside Effect.forEach", () =>
74 Effect.gen(function* () {
75 const db = proxyChain<Db>(Effect.succeed(makeDb()));
76 const results = yield* Effect.forEach(["users", "posts", "comments"], (table) =>
77 db.select().from(table),
78 );
79 expect(results).toEqual([["hi/users"], ["hi/posts"], ["hi/comments"]]);
80 }),
81 );
82
83 it.effect("supports `.pipe` on a chain (forwarded to the resolved effect)", () =>
84 Effect.gen(function* () {
85 const db = proxyChain<Db>(Effect.succeed(makeDb()));
86 const rows = yield* db
87 .select()
88 .from("users")
89 .pipe(Effect.map((rows) => rows.map((r) => r.toUpperCase())));
90 expect(rows).toEqual(["HI/USERS"]);
91 }),
92 );
93
94 it.effect("supports `.pipe` recovering a failure", () =>
95 Effect.gen(function* () {
96 const db = proxyChain<{ boom: () => Effect.Effect<string, string> }>(
97 Effect.succeed({ boom: () => Effect.fail("nope") }),
98 );
99 const result = yield* db.boom().pipe(Effect.catch((e) => Effect.succeed(`recovered:${e}`)));
100 expect(result).toBe("recovered:nope");
101 }),
102 );
103
104 it.effect("is recognized by predicate-dispatched Effect operators", () =>
105 Effect.gen(function* () {
106 const api = proxyChain(
107 Effect.succeed({
108 transaction: () => Effect.fail({ _tag: "TestError" } as const),
109 }),
110 );
111
112 const transaction = api.transaction();
113
114 expect(Effect.isEffect(transaction)).toBe(true);
115
116 const result = yield* transaction.pipe(
117 Effect.catchTag("TestError", () => Effect.succeed("recovered")),
118 );
119
120 expect(result).toBe("recovered");
121 }),
122 );
123
124 /**
125 * effect ≥ 4.0.0-rc.113's generator runner asks `value[ExitTypeId] !==
126 * undefined` to tell an Exit from an Effect. If the proxy answered that
127 * brand probe with a chain step, every `yield*` would resume with the
128 * proxy itself instead of the query result (the bug behind `users.length`
129 * serializing as `{ _id: "Effect", op: "OnSuccess" }`).
130 */
131 it.effect("does not record Effect brand probes as chain steps", () =>
132 Effect.gen(function* () {
133 const db = proxyChain<Db>(Effect.succeed(makeDb()));
134 const query = db.select().from("users") as unknown as Record<PropertyKey, unknown>;
135 expect(query["~effect/Exit"]).toBeUndefined();
136 expect(Exit.isExit(query)).toBe(false);
137 expect(Effect.isEffect(query)).toBe(true);
138 // Symbols the runtime does not define on an Effect are absent too.
139 expect(query[Symbol.for("some/unrelated/probe")]).toBeUndefined();
140 // …and the chain still resolves to the real value when yielded.
141 const rows = yield* db.select().from("users");
142 expect(Array.isArray(rows)).toBe(true);
143 expect(rows).toEqual(["hi/users"]);
144 }),
145 );
146
147 it.effect("a `.pipe`-d chain still composes inside Effect.all", () =>
148 Effect.gen(function* () {
149 const db = proxyChain<Db>(Effect.succeed(makeDb()));
150 const results = yield* Effect.all([
151 db
152 .select()
153 .from("users")
154 .pipe(Effect.map((r) => r.length)),
155 db
156 .select()
157 .from("posts")
158 .pipe(Effect.map((r) => r.length)),
159 ]);
160 expect(results).toEqual([1, 1]);
161 }),
162 );
163
164 it.effect("propagates failures from the resolved effect", () =>
165 Effect.gen(function* () {
166 const db = proxyChain<{ boom: () => Effect.Effect<never, string> }>(
167 Effect.succeed({ boom: () => Effect.fail("nope") }),
168 );
169 const error = yield* Effect.flip(db.boom());
170 expect(error).toBe("nope");
171 }),
172 );
173
174 it.effect("propagates failures from the underlying (cached) effect", () =>
175 Effect.gen(function* () {
176 const db = proxyChain<Db>(Effect.fail("connect failed"));
177 const error = yield* Effect.flip(db.select().from("users"));
178 expect(error).toBe("connect failed");
179 }),
180 );
181
182 /**
183 * A fake `@effect/sql`-like client: a tagged-template function with
184 * synchronous fragment helpers (`insert`, `and`) hanging off it — the shape
185 * that surfaced the nested-proxy bug (`sql.insert(row)` inside an outer
186 * `` sql`...` `` template was passed to the real client as a proxy, which
187 * D1 then tried to bind as a parameter).
188 */
189 const makeSql = () => {
190 const render = (v: unknown): string =>
191 typeof v === "string" && v.startsWith("frag:")
192 ? v.slice("frag:".length)
193 : typeof v === "function"
194 ? "?fn"
195 : `?${JSON.stringify(v)}`;
196 const sql = (strings: TemplateStringsArray, ...values: unknown[]) =>
197 Effect.succeed(
198 strings.reduce((acc, s, i) => acc + s + (i < values.length ? render(values[i]) : ""), ""),
199 );
200 sql.insert = (row: Record<string, unknown>) =>
201 `frag:(${Object.keys(row).join(",")}) VALUES (${Object.values(row).join(",")})`;
202 sql.and = (parts: unknown[]) => `frag:(${parts.map(render).join(" AND ")})`;
203 return sql;
204 };
205
206 type Sql = ReturnType<typeof makeSql>;
207
208 describe("nested chains as call arguments", () => {
209 it.effect("replays a nested chain argument against the same root (sql.insert)", () =>
210 Effect.gen(function* () {
211 const sql = proxyChain<Sql>(Effect.succeed(makeSql()));
212 const query = yield* sql`INSERT INTO users ${sql.insert({ id: 1, name: "'alice'" })}`;
213 expect(query).toBe("INSERT INTO users (id,name) VALUES (1,'alice')");
214 }),
215 );
216
217 it.effect("replays nested chains inside array arguments (sql.and)", () =>
218 Effect.gen(function* () {
219 const sql = proxyChain<Sql>(Effect.succeed(makeSql()));
220 const query = yield* sql`SELECT * FROM users WHERE ${sql.and([
221 sql.insert({ a: 1 }),
222 sql.insert({ b: 2 }),
223 ])}`;
224 expect(query).toBe("SELECT * FROM users WHERE ((a) VALUES (1) AND (b) VALUES (2))");
225 }),
226 );
227
228 it.effect("leaves plain values and non-chain objects untouched", () =>
229 Effect.gen(function* () {
230 const sql = proxyChain<Sql>(Effect.succeed(makeSql()));
231 const query = yield* sql`SELECT ${42} FROM ${{ obj: true }}`;
232 expect(query).toBe('SELECT ?42 FROM ?{"obj":true}');
233 }),
234 );
235
236 it.effect("resolves the underlying effect exactly once for outer + nested chains", () =>
237 Effect.gen(function* () {
238 let built = 0;
239 const sql = proxyChain<Sql>(
240 Effect.sync(() => {
241 built++;
242 return makeSql();
243 }),
244 );
245 const query = sql`INSERT INTO t ${sql.insert({ x: 9 })}`;
246 // Building the composite chain must not resolve anything…
247 expect(built).toBe(0);
248 yield* query;
249 // …and the nested chain reuses the outer chain's resolved root.
250 expect(built).toBe(1);
251 }),
252 );
253
254 it.effect("leaves a chain over a *different* underlying effect untouched", () =>
255 Effect.gen(function* () {
256 const sqlA = proxyChain<Sql>(Effect.succeed(makeSql()));
257 const other = proxyChain<Db>(Effect.succeed(makeDb()));
258 // `other.select()` is a proxy over a different cached effect — it
259 // can't be replayed synchronously, so it must pass through as-is
260 // (rendered as an opaque bind value by the fake client).
261 const query = yield* sqlA`SELECT ${other.select()}`;
262 expect(query).toBe("SELECT ?fn");
263 }),
264 );
265 });
266 });