@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 72 lines 2.22 KB
Raw
1 import * as Data from "effect/Data";
2 import * as Effect from "effect/Effect";
3 import * as Schedule from "effect/Schedule";
4
5 /** Typed failure for the fixture-driving HTTP helpers. */
6 export class AuthHttpError extends Data.TaggedError("AuthHttpError")<{
7 readonly url: string;
8 readonly status: number;
9 readonly body: string;
10 }> {
11 override get message(): string {
12 return `${this.url} -> ${this.status}: ${this.body.slice(0, 300)}`;
13 }
14 }
15
16 export interface AuthHttpResponse {
17 readonly status: number;
18 readonly body: string;
19 readonly setCookies: ReadonlyArray<string>;
20 }
21
22 const request = (url: string, init: RequestInit): Effect.Effect<AuthHttpResponse, AuthHttpError> =>
23 Effect.tryPromise({
24 try: async (signal): Promise<AuthHttpResponse> => {
25 const response = await fetch(url, { ...init, signal });
26 return {
27 status: response.status,
28 body: await response.text(),
29 setCookies: response.headers.getSetCookie(),
30 };
31 },
32 catch: (cause) => new AuthHttpError({ url, status: 0, body: String(cause) }),
33 });
34
35 export const postJson = (
36 url: string,
37 body: unknown,
38 headers?: Record<string, string>,
39 ): Effect.Effect<AuthHttpResponse, AuthHttpError> =>
40 request(url, {
41 method: "POST",
42 headers: { "content-type": "application/json", ...headers },
43 body: JSON.stringify(body),
44 });
45
46 export const getJson = <T>(
47 url: string,
48 headers?: Record<string, string>,
49 ): Effect.Effect<T, AuthHttpError> =>
50 request(url, { method: "GET", headers }).pipe(
51 Effect.filterOrFail(
52 (response) => response.status === 200,
53 (response) => new AuthHttpError({ url, ...response }),
54 ),
55 Effect.map((response) => JSON.parse(response.body) as T),
56 );
57
58 /**
59 * Retry for the first requests against a freshly-deployed workers.dev URL
60 * — the subdomain takes a few seconds to start serving.
61 */
62 export const edgeRetry = Effect.retry({
63 schedule: Schedule.exponential("1 second", 1.5),
64 times: 8,
65 });
66
67 /** Reduce set-cookie headers to a `cookie` request header value. */
68 export const toCookieHeader = (setCookies: ReadonlyArray<string>): string =>
69 setCookies
70 .map((cookie) => cookie.split(";")[0])
71 .filter((pair): pair is string => pair !== undefined && pair !== "")
72 .join("; ");