@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, 04:45 UTC

main
ts 195 lines 6.72 KB
Raw
1 import * as browser from "@distilled.cloud/cloudflare/browser-rendering";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Effect from "effect/Effect";
4 import type * as HttpClient from "effect/http/HttpClient";
5 import * as Stream from "effect/Stream";
6 import type { Credentials } from "../Credentials.ts";
7 import {
8 type BrowserClient,
9 type BrowserContentResult,
10 BrowserError,
11 type BrowserJsonResult,
12 type BrowserLinksResult,
13 type BrowserMarkdownResult,
14 type BrowserScrapeResult,
15 type BrowserSnapshotResult,
16 } from "./Browser.ts";
17
18 // Shared HTTP scaffolding for the Browser Rendering binding. NOT re-exported
19 // from `index.ts` — only the contract and the impl layers are public. A future
20 // token-scoped `BrowserHttp` layer reuses this builder with an auth minted from
21 // an `AccountApiToken`; `BrowserLocal` builds the auth from the ambient
22 // current-credentials context.
23
24 /**
25 * Injectable auth shared by the Local (current-credentials) impl and a future
26 * Http (scoped-token) impl. `authorize` discharges the
27 * `Credentials | HttpClient` requirement of a distilled op; `accountId` is the
28 * Cloudflare account the ops run against.
29 */
30 export interface BrowserAuth {
31 authorize: <A, E>(
32 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
33 ) => Effect.Effect<A, E>;
34 accountId: string;
35 }
36
37 /** A byte stream produced by a binary {@link BrowserClient} action. */
38 type BrowserByteStream = Stream.Stream<Uint8Array, BrowserError, RuntimeContext>;
39
40 /**
41 * Build a {@link BrowserClient} over the Browser Rendering REST data-plane
42 * (`/accounts/{id}/browser-rendering/*`).
43 *
44 * The following client members `Effect.die` (or fail the stream) because they
45 * have no Cloudflare REST equivalent — use a native `BrowserBinding` inside a
46 * deployed Worker for them:
47 * - `raw` / `fetch` — the raw `BrowserRun` transport used by
48 * `@cloudflare/puppeteer` is a Worker-runtime object, not an HTTP call.
49 * - `screenshot` / `pdf` — the binary endpoints stream image/PDF bytes, which
50 * the distilled REST codec models as JSON status, not a byte stream.
51 *
52 * Because the REST data-plane only returns the action `result` (not the
53 * runtime binding's `meta` envelope), JSON actions populate `meta` with a
54 * best-effort placeholder.
55 */
56 export const makeHttpBrowserClient = (auth: BrowserAuth): BrowserClient => {
57 // Run a distilled Browser Rendering op with the injected auth and surface
58 // transport/API failures as {@link BrowserError} (matching the native
59 // binding's declared error channel).
60 const run = <A, E>(
61 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
62 ): Effect.Effect<A, BrowserError, RuntimeContext> =>
63 auth.authorize(eff).pipe(
64 Effect.mapError(
65 (cause) =>
66 new BrowserError({
67 message: "Browser Rendering request failed",
68 cause,
69 }),
70 ),
71 );
72
73 // The cf option types (`url`/`html` + puppeteer options) are structurally the
74 // REST request body; add the account id and let distilled's encoder drop any
75 // fields it doesn't model.
76 const req = (options: unknown) =>
77 ({ accountId: auth.accountId, ...(options as object) }) as never;
78
79 const content = (options: unknown) =>
80 run(browser.createContent(req(options))).pipe(
81 Effect.map((result): BrowserContentResult => ({
82 success: true,
83 result,
84 meta: { status: 200, title: "" },
85 })),
86 );
87
88 const markdown = (options: unknown) =>
89 run(browser.createMarkdown(req(options))).pipe(
90 Effect.map((result): BrowserMarkdownResult => ({
91 success: true,
92 result,
93 meta: { status: 200, title: "" },
94 })),
95 );
96
97 const links = (options: unknown) =>
98 run(browser.createLink(req(options))).pipe(
99 Effect.map((result): BrowserLinksResult => ({
100 success: true,
101 result: [...result],
102 meta: { status: 200, title: "" },
103 })),
104 );
105
106 const json = (options: unknown) =>
107 run(browser.createJson(req(options))).pipe(
108 Effect.map((result): BrowserJsonResult => ({
109 success: true,
110 result,
111 meta: { status: 200, title: "" },
112 })),
113 );
114
115 const scrape = (options: unknown) =>
116 run(browser.createScrape(req(options))).pipe(
117 Effect.map((result): BrowserScrapeResult => ({
118 success: true,
119 result: result.map((item) => ({
120 selector: item.selector,
121 // distilled models per-selector `results` as a single object; the
122 // native shape is an array of matched elements.
123 results: (Array.isArray(item.results)
124 ? item.results
125 : [item.results]) as BrowserScrapeResult["result"][number]["results"],
126 })),
127 meta: { status: 200, title: "" },
128 })),
129 );
130
131 const snapshot = (options: unknown) =>
132 run(browser.createSnapshot(req(options))).pipe(
133 Effect.map((result): BrowserSnapshotResult => ({
134 success: true,
135 result: {
136 content: result.content ?? "",
137 screenshot: result.screenshot ?? "",
138 },
139 meta: { status: 200, title: "" },
140 })),
141 );
142
143 // Binary actions have no REST byte-stream equivalent through the distilled
144 // codec — fail the stream with a defect explaining the native-binding path.
145 const binaryUnsupported = (action: string): BrowserByteStream =>
146 Stream.fromEffect(
147 Effect.die(
148 new Error(
149 `Browser over HTTP: '${action}' returns binary data and is only available inside a Worker via the native BrowserBinding; the HTTP client supports the JSON quick actions (content/markdown/scrape/links/snapshot/json).`,
150 ),
151 ),
152 ) as BrowserByteStream;
153
154 const quickAction = ((action: string, options: unknown) => {
155 switch (action) {
156 case "content":
157 return content(options);
158 case "markdown":
159 return markdown(options);
160 case "links":
161 return links(options);
162 case "json":
163 return json(options);
164 case "scrape":
165 return scrape(options);
166 case "snapshot":
167 return snapshot(options);
168 default:
169 return binaryUnsupported(action);
170 }
171 }) as BrowserClient["quickAction"];
172
173 return {
174 raw: Effect.die(
175 new Error(
176 "Browser over HTTP: `raw` (the native BrowserRun binding) is only available inside a deployed Worker — use BrowserBinding.",
177 ),
178 ),
179 fetch: () =>
180 Effect.die(
181 new Error(
182 "Browser over HTTP: `fetch` proxies the raw Browser Run transport used by @cloudflare/puppeteer and is only available inside a Worker via BrowserBinding.",
183 ),
184 ),
185 quickAction,
186 screenshot: () => binaryUnsupported("screenshot"),
187 pdf: () => binaryUnsupported("pdf"),
188 content,
189 scrape,
190 links,
191 snapshot,
192 json,
193 markdown,
194 } satisfies BrowserClient;
195 };