@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 244 lines 8.62 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import * as Cause from "effect/Cause";
3 import * as Effect from "effect/Effect";
4 import * as Exit from "effect/Exit";
5 import * as Stream from "effect/Stream";
6 import * as Rpc from "@/Rpc";
7
8 const bytes = (text: string) => new TextEncoder().encode(text);
9 const jsonBytes = (b64: unknown) =>
10 bytes(JSON.stringify({ _tag: "~alchemy/rpc/bytes", b64 }) + "\n");
11 const decoders = {
12 jsonl: (input: Stream.Stream<Uint8Array>) => Rpc.decodeRpcByteStream(input, "jsonl"),
13 response: Rpc.decodeRpcResponseStream,
14 };
15
16 const expectedBase64 = (value: unknown): Uint8Array => {
17 const binary = atob(value as string);
18 return Uint8Array.from(binary, (character) => character.charCodeAt(0));
19 };
20
21 const withNativeDecoder = <A, E, R>(
22 decode: ((value: string) => Uint8Array) | undefined,
23 effect: Effect.Effect<A, E, R>,
24 ) =>
25 Effect.acquireUseRelease(
26 Effect.sync(() => {
27 const descriptor = Object.getOwnPropertyDescriptor(Uint8Array, "fromBase64");
28 Object.defineProperty(Uint8Array, "fromBase64", {
29 configurable: true,
30 writable: true,
31 value: decode,
32 });
33 return descriptor;
34 }),
35 () => effect,
36 (descriptor) =>
37 Effect.sync(() => {
38 if (descriptor === undefined) Reflect.deleteProperty(Uint8Array, "fromBase64");
39 else Object.defineProperty(Uint8Array, "fromBase64", descriptor);
40 }),
41 );
42
43 describe("RPC stream codecs", { tags: ["unit", "local"] }, () => {
44 for (const [name, decode] of Object.entries(decoders)) {
45 it.effect(`${name}: decodes split UTF-8 and frames, ignoring empty lines`, () =>
46 Effect.gen(function* () {
47 const encoded = bytes('{"text":"café 😀"}\n\n{"n":2}\n');
48 const fragments = Array.from(encoded, (_, index) => encoded.subarray(index, index + 1));
49 const result = yield* decode(Stream.fromIterable(fragments)).pipe(Stream.runCollect);
50 expect(result).toEqual([{ text: "café 😀" }, { n: 2 }]);
51 }),
52 );
53
54 it.effect(`${name}: malformed JSON stays in RpcDecodeError`, () =>
55 Effect.gen(function* () {
56 const exit = yield* decode(Stream.make(bytes("{broken}\n"))).pipe(
57 Stream.runCollect,
58 Effect.exit,
59 );
60 expect(Exit.isFailure(exit)).toBe(true);
61 if (Exit.isFailure(exit)) {
62 const reason = exit.cause.reasons.find(Cause.isFailReason);
63 expect(reason?.error).toBeInstanceOf(Rpc.RpcDecodeError);
64 }
65 }),
66 );
67
68 it.effect(`${name}: a split error marker preserves the remote failure`, () =>
69 Effect.gen(function* () {
70 const error = { _tag: "Boom", code: 7 };
71 const line = JSON.stringify({ _tag: Rpc.StreamErrorTag, error }) + "\n";
72 const result = yield* decode(
73 Stream.make(bytes(line.slice(0, 9)), bytes(line.slice(9))),
74 ).pipe(Stream.runCollect, Effect.flip);
75 expect(result).toBeInstanceOf(Rpc.RpcRemoteStreamError);
76 if (result instanceof Rpc.RpcRemoteStreamError) expect(result.error).toEqual(error);
77 }),
78 );
79
80 it.effect(`${name}: taking a prefix releases the upstream scope`, () =>
81 Effect.gen(function* () {
82 let finalized = false;
83 const source = Stream.unwrap(
84 Effect.gen(function* () {
85 yield* Effect.addFinalizer(() =>
86 Effect.sync(() => {
87 finalized = true;
88 }),
89 );
90 return Stream.iterate(0, (n) => n + 1).pipe(
91 Stream.map((n) => bytes(JSON.stringify(n) + "\n")),
92 );
93 }),
94 );
95 const result = yield* decode(source).pipe(Stream.take(3), Stream.runCollect);
96 expect(result).toEqual([0, 1, 2]);
97 expect(finalized).toBe(true);
98 }),
99 );
100 }
101
102 it.effect("raw bytes pass through without framing or copying", () =>
103 Effect.gen(function* () {
104 const value = new Uint8Array([0, 255, 10]);
105 const source = Stream.make(value);
106 const decoded = Rpc.decodeRpcByteStream(source, "bytes");
107 expect(decoded).toBe(source);
108 const result = yield* decoded.pipe(Stream.runCollect);
109 expect(result[0]).toBe(value);
110 }),
111 );
112
113 it.effect("native and fallback encoding preserve byte offsets and empty chunks", () =>
114 Effect.gen(function* () {
115 const backing = new Uint8Array([99, 98, 0, 128, 255, 10, 97]);
116 const view = backing.subarray(2, 6);
117 const fallbackView = backing.subarray(2, 6);
118 let nativeCalls = 0;
119 // Exercise both capabilities without mutating the global prototype.
120 Object.defineProperty(view, "toBase64", {
121 value: function (this: Uint8Array) {
122 expect(this).toBe(view);
123 nativeCalls++;
124 return btoa(String.fromCharCode(...this));
125 },
126 });
127 Object.defineProperty(fallbackView, "toBase64", { value: undefined });
128 const values = [
129 view,
130 fallbackView,
131 new Uint8Array(0),
132 Uint8Array.from({ length: 256 }, (_, n) => n),
133 ];
134 // The encoder erases R to any, but this fixture has no runtime services.
135 const encoded = Rpc.encodeRpcResponseStream(
136 Stream.fromIterable(values),
137 ) as Stream.Stream<Uint8Array>;
138 const result = yield* encoded.pipe(Rpc.decodeRpcResponseStream, Stream.runCollect);
139 expect(result.map((value: Uint8Array) => Array.from(value))).toEqual(
140 values.map((value) => Array.from(value)),
141 );
142 expect(nativeCalls).toBe(1);
143 }),
144 );
145
146 it.effect(
147 "uses the native decoder for strings while retaining legacy wire-value coercion",
148 () => {
149 const calls: string[] = [];
150 return withNativeDecoder(
151 function (this: Uint8ArrayConstructor, value) {
152 expect(this).toBe(Uint8Array);
153 calls.push(value);
154 return expectedBase64(value);
155 },
156 Effect.gen(function* () {
157 for (const value of ["", "AP8=", 1234, null]) {
158 const decoded = yield* Rpc.decodeRpcResponseStream(Stream.make(jsonBytes(value))).pipe(
159 Stream.runCollect,
160 );
161 expect(Array.from(decoded[0])).toEqual(Array.from(expectedBase64(value)));
162 }
163 expect(calls).toEqual(["", "AP8="]);
164 }),
165 );
166 },
167 { exclusive: true },
168 );
169
170 for (const fallback of [false, true]) {
171 it.effect(
172 `base64 ${fallback ? "fallback" : "native when available"}: matches atob acceptance`,
173 () => {
174 const program = Effect.gen(function* () {
175 // Missing padding, nonzero unused bits, ASCII whitespace, and legacy
176 // non-string wire values all retain atob's forgiving behavior.
177 for (const encoded of [
178 "",
179 "AA==",
180 "AA",
181 "AB==",
182 "AB",
183 "Zm8=",
184 "Zm8",
185 " Zm\t9v\n",
186 "Zg=\r\n=",
187 1234,
188 null,
189 ]) {
190 const decoded = yield* Rpc.decodeRpcResponseStream(
191 Stream.make(jsonBytes(encoded)),
192 ).pipe(Stream.runCollect);
193 expect(decoded).toHaveLength(1);
194 expect(Array.from(decoded[0])).toEqual(Array.from(expectedBase64(encoded)));
195 }
196 });
197 return fallback ? withNativeDecoder(undefined, program) : program;
198 },
199 { exclusive: fallback },
200 );
201
202 it.effect(
203 `base64 ${fallback ? "fallback" : "native when available"}: invalid input remains an atob defect`,
204 () => {
205 const program = Effect.gen(function* () {
206 for (const encoded of [
207 "A",
208 "=",
209 "Zg=",
210 "Zg===",
211 "Zm9v=",
212 "_w==",
213 "AA!A",
214 "AA\u000b==",
215 "AA\u00a0==",
216 ]) {
217 let expected: unknown;
218 try {
219 atob(encoded);
220 } catch (error) {
221 expected = error;
222 }
223 expect(expected).toBeInstanceOf(DOMException);
224 const exit = yield* Rpc.decodeRpcResponseStream(Stream.make(jsonBytes(encoded))).pipe(
225 Stream.runCollect,
226 Effect.exit,
227 );
228 expect(Exit.isFailure(exit)).toBe(true);
229 if (Exit.isFailure(exit)) {
230 const reason = exit.cause.reasons.find(Cause.isDieReason);
231 expect(reason?.defect).toBeInstanceOf(DOMException);
232 expect((reason?.defect as DOMException).name).toBe((expected as DOMException).name);
233 expect((reason?.defect as DOMException).message).toBe(
234 (expected as DOMException).message,
235 );
236 }
237 }
238 });
239 return fallback ? withNativeDecoder(undefined, program) : program;
240 },
241 { exclusive: fallback },
242 );
243 }
244 });