Open History to see the last commit
1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Queue from "effect/Queue";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
13import { publicProxy } from "./publicProxy.ts";
14
15export class HtmlRenderBrowserError extends Schema.TaggedError<HtmlRenderBrowserError>()(
16 "HtmlRenderBrowserError",
17 {
18 reason: Schema.String,
19 cause: Schema.optional(Schema.Defect()),
20 output: Schema.optional(Schema.String),
21 exitCode: Schema.optional(Schema.Number),
22 signal: Schema.optional(Schema.String),
23 },
24) {
25 override get message(): string {
26 const exit =
27 this.exitCode !== undefined
28 ? ` (exit code ${this.exitCode})`
29 : this.signal !== undefined
30 ? ` (signal ${this.signal})`
31 : "";
32 return `Headless Chrome could not render the page: ${this.reason}${exit}.`;
33 }
34}
35
36type BrowserFailure = HtmlRenderBrowserError;
37
38export interface ConsoleMessage {
39 readonly level: "log" | "info" | "warning" | "error";
40 readonly text: string;
41}
42
43const MAX_CONSOLE_MESSAGES = 20;
44const MAX_CONSOLE_TEXT_CHARS = 500;
45const VIEWPORT_HEIGHT = 800;
46const MAX_CAPTURE_HEIGHT = 4_000;
47const CAPTURE_TIMEOUT = "20 seconds";
48// Chrome refuses local files to every web page, frame, worker, and popup, so a
49// page cannot read files the agent's provider withholds; local images reach it
50// already inlined as data URIs. `.localhost` keeps it a secure context that may
51// still load plain-http resources, and the request never leaves the browser.
52// All of the browser's traffic goes through `publicProxy`, which only reaches
53// public addresses, so a page cannot reach this machine's local network. The
54// main frame also stays on the page and the browser opens no popups, so a
55// capture always shows the page itself.
56const PAGE_ORIGIN = "http://t3-page.localhost";
57const PAGE_URL = `${PAGE_ORIGIN}/page.html`;
58const PAGE_NAME = "page.html";
59const MEASURE_CONCURRENCY = 3;
60
61const textEncoder = new TextEncoder();
62
63/**
64 * Node's encoder, since pages run to 25 MiB.
65 */
66const pageBody = (html: string) =>
67 Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1");
68
69const CdpMessage = Schema.fromJsonString(
70 Schema.Struct({
71 id: Schema.optional(Schema.Number),
72 method: Schema.optional(Schema.String),
73 sessionId: Schema.optional(Schema.String),
74 params: Schema.optional(Schema.Unknown),
75 result: Schema.optional(Schema.Unknown),
76 error: Schema.optional(Schema.Struct({ message: Schema.String })),
77 }),
78);
79const decodeCdpMessage = Schema.decodeUnknownOption(CdpMessage);
80const encodeCdpCommand = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
81const RemoteObject = Schema.Struct({
82 type: Schema.String,
83 value: Schema.optional(Schema.Unknown),
84 description: Schema.optional(Schema.String),
85});
86const decodeConsoleApiCalled = Schema.decodeUnknownOption(
87 Schema.Struct({ type: Schema.String, args: Schema.Array(RemoteObject) }),
88);
89const decodeExceptionThrown = Schema.decodeUnknownOption(
90 Schema.Struct({
91 exceptionDetails: Schema.Struct({
92 text: Schema.String,
93 exception: Schema.optional(RemoteObject),
94 }),
95 }),
96);
97const decodeRequestPaused = Schema.decodeUnknownOption(
98 Schema.Struct({
99 requestId: Schema.String,
100 request: Schema.Struct({ url: Schema.String }),
101 frameId: Schema.optional(Schema.String),
102 resourceType: Schema.optional(Schema.String),
103 }),
104);
105const decodeLogEntryAdded = Schema.decodeUnknownOption(
106 Schema.Struct({
107 entry: Schema.Struct({
108 level: Schema.String,
109 text: Schema.String,
110 url: Schema.optional(Schema.String),
111 }),
112 }),
113);
114
115const remoteObjectText = (value: typeof RemoteObject.Type) =>
116 typeof value.value === "string"
117 ? value.value
118 : (value.description ?? (value.value === undefined ? value.type : String(value.value)));
119
120const CONSOLE_LEVELS: Readonly<Record<string, ConsoleMessage["level"]>> = {
121 log: "log",
122 debug: "log",
123 dir: "log",
124 dirxml: "log",
125 table: "log",
126 trace: "log",
127 info: "info",
128 warning: "warning",
129 error: "error",
130 assert: "error",
131};
132
133const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessage | undefined => {
134 if (method === "Runtime.consoleAPICalled") {
135 const event = Option.getOrUndefined(decodeConsoleApiCalled(params));
136 const level = event === undefined ? undefined : CONSOLE_LEVELS[event.type];
137 return event && level ? { level, text: event.args.map(remoteObjectText).join(" ") } : undefined;
138 }
139 if (method === "Runtime.exceptionThrown") {
140 const details = Option.getOrUndefined(decodeExceptionThrown(params))?.exceptionDetails;
141 return details
142 ? { level: "error", text: details.exception?.description ?? details.text }
143 : undefined;
144 }
145 if (method === "Log.entryAdded") {
146 const entry = Option.getOrUndefined(decodeLogEntryAdded(params))?.entry;
147 return entry && (entry.level === "error" || entry.level === "warning")
148 ? { level: entry.level, text: entry.url ? `${entry.text} ${entry.url}` : entry.text }
149 : undefined;
150 }
151 return undefined;
152};
153
154// Resolves after web fonts load and two frames paint, so late layout lands in the capture.
155const SETTLE_EXPRESSION =
156 "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))";
157// The root's scroll height never drops below the viewport, so a short page
158// reports its own box height instead.
159const MEASURE_EXPRESSION =
160 "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
161
162const Ignored = Schema.Unknown;
163const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
164const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
165
166// Effect's spawner names the signal that ended a child only in its error message.
167const EXIT_SIGNAL = /signal: '(SIG[A-Z0-9]+)'/;
168
169interface PageEvents {
170 readonly mainFrameId: string;
171 body: Uint8Array | undefined;
172 loaded: Deferred.Deferred<void, BrowserFailure> | undefined;
173 readonly consoleMessages: Array<ConsoleMessage>;
174 omittedConsoleMessages: number;
175}
176
177/**
178 * Starts the headless shell for the life of the scope, speaking CDP over
179 * `--remote-debugging-pipe` (fd 3 in, fd 4 out, NUL-delimited JSON).
180 */
181const launchBrowser = Effect.fnUntraced(function* (input: {
182 readonly executable: string;
183 readonly noSandbox: boolean;
184 readonly profileDirectory: string;
185}) {
186 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
187 const proxyPort = yield* publicProxy.pipe(
188 Effect.mapError(
189 (cause) => new HtmlRenderBrowserError({ reason: "the preview proxy could not start", cause }),
190 ),
191 );
192 const outgoing = yield* Queue.unbounded<Uint8Array>();
193 const child = yield* spawner
194 .spawn(
195 ChildProcess.make(
196 input.executable,
197 [
198 "--headless=new",
199 "--remote-debugging-pipe",
200 "--no-first-run",
201 "--no-default-browser-check",
202 "--disable-gpu",
203 "--hide-scrollbars",
204 "--mute-audio",
205 "--block-new-web-contents",
206 `--proxy-server=socks5://127.0.0.1:${proxyPort}`,
207 // Loopback would otherwise skip the proxy.
208 "--proxy-bypass-list=<-loopback>",
209 // WebRTC would otherwise send UDP, which no proxy carries.
210 "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
211 ...(input.noSandbox ? ["--no-sandbox"] : []),
212 `--user-data-dir=${input.profileDirectory}`,
213 "about:blank",
214 ],
215 {
216 stdin: "ignore",
217 stdout: "ignore",
218 stderr: "pipe",
219 forceKillAfter: "2 seconds",
220 additionalFds: {
221 fd3: { type: "input", stream: Stream.fromQueue(outgoing) },
222 fd4: { type: "output" },
223 },
224 },
225 ),
226 )
227 .pipe(
228 Effect.mapError(
229 (cause) =>
230 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
231 ),
232 );
233
234 let stderrTail = "";
235 const stderrReader = yield* child.stderr.pipe(
236 Stream.decodeText(),
237 Stream.runForEach((text) =>
238 Effect.sync(() => {
239 stderrTail = (stderrTail + text).slice(-2_048);
240 }),
241 ),
242 Effect.ignore,
243 Effect.forkScoped,
244 );
245
246 const pending = new Map<
247 number,
248 { readonly method: string; readonly reply: Deferred.Deferred<unknown, BrowserFailure> }
249 >();
250 const pages = new Map<string, PageEvents>();
251 let disconnected: BrowserFailure | undefined;
252 let nextId = 0;
253
254 const post = (method: string, params: Record<string, unknown>, sessionId: string) =>
255 Queue.offer(
256 outgoing,
257 new TextEncoder().encode(
258 `${encodeCdpCommand({ id: ++nextId, method, params, sessionId })}\0`,
259 ),
260 ).pipe(Effect.asVoid);
261
262 // Serves the page. Its body is shared bytes between two small JSON halves,
263 // queued together, so loading a page of up to 25 MiB at several widths never
264 // copies it on this side.
265 const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) =>
266 Queue.offerAll(outgoing, [
267 textEncoder.encode(
268 `{"id":${++nextId},"sessionId":${JSON.stringify(sessionId)},"method":"Fetch.fulfillRequest","params":{"requestId":${JSON.stringify(requestId)},"responseCode":200,"responseHeaders":[{"name":"Content-Type","value":"text/html; charset=utf-8"}],"body":"`,
269 ),
270 body,
271 textEncoder.encode('"}}\0'),
272 ]).pipe(Effect.asVoid);
273
274 const receive = (raw: string) => {
275 const message = Option.getOrUndefined(decodeCdpMessage(raw));
276 if (message?.id !== undefined) {
277 const waiter = pending.get(message.id);
278 pending.delete(message.id);
279 if (!waiter) return Effect.void;
280 return message.error
281 ? Deferred.fail(
282 waiter.reply,
283 new HtmlRenderBrowserError({
284 reason: `${waiter.method} failed`,
285 cause: message.error.message,
286 }),
287 )
288 : Deferred.succeed(waiter.reply, message.result);
289 }
290 const sessionId = message?.sessionId;
291 const page = sessionId === undefined ? undefined : pages.get(sessionId);
292 if (sessionId === undefined || !page || !message?.method) return Effect.void;
293 if (message.method === "Page.loadEventFired") {
294 return page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
295 }
296 if (message.method === "Fetch.requestPaused") {
297 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
298 if (!paused) return Effect.void;
299 const body = page.body;
300 const url = paused.request.url.split("#", 1)[0]!;
301 if (url === PAGE_URL && body !== undefined) {
302 return fulfillPage(sessionId, paused.requestId, body);
303 }
304 // A frame inside the page may show another site; Local Network Access
305 // still covers it. The main frame and T3's own origin serve nothing else.
306 const otherSiteFrame =
307 paused.resourceType === "Document" &&
308 paused.frameId !== page.mainFrameId &&
309 !url.startsWith(`${PAGE_ORIGIN}/`);
310 return otherSiteFrame
311 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
312 : post(
313 "Fetch.failRequest",
314 { requestId: paused.requestId, errorReason: "AccessDenied" },
315 sessionId,
316 );
317 }
318 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
319 if (!consoleMessage) return Effect.void;
320 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
321 page.omittedConsoleMessages += 1;
322 return Effect.void;
323 }
324 const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);
325 page.consoleMessages.push({
326 level: consoleMessage.level,
327 text:
328 text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, MAX_CONSOLE_TEXT_CHARS)}…` : text,
329 });
330 return Effect.void;
331 };
332
333 // The pipe closes when the browser exits. A startup abort, such as a missing
334 // sandbox, says why on stderr, which may still be draining, so give it a moment.
335 const disconnect = Effect.gen(function* () {
336 yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore);
337 const exit = yield* child.exitCode.pipe(
338 Effect.map((code): { exitCode?: number; signal?: string; cause?: unknown } => ({
339 exitCode: code,
340 })),
341 Effect.catch((error) => {
342 const signal = EXIT_SIGNAL.exec(String(error.cause))?.[1];
343 return Effect.succeed(signal === undefined ? { cause: error } : { signal, cause: error });
344 }),
345 Effect.timeoutOption("1 second"),
346 );
347 const error = new HtmlRenderBrowserError({
348 reason: "the browser exited unexpectedly",
349 output: stderrTail,
350 ...Option.getOrElse(exit, () => ({})),
351 });
352 disconnected = error;
353 const waiters = [...pending.values()];
354 pending.clear();
355 yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true });
356 yield* Effect.forEach(
357 pages.values(),
358 (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void),
359 { discard: true },
360 );
361 });
362
363 // Decoded text chunks may split a message anywhere, and a screenshot reply spans many.
364 let partial: Array<string> = [];
365 yield* child.getOutputFd(4).pipe(
366 Stream.decodeText(),
367 Stream.runForEach((text) => {
368 const complete: Array<string> = [];
369 let start = 0;
370 for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) {
371 partial.push(text.slice(start, end));
372 complete.push(partial.join(""));
373 partial = [];
374 start = end + 1;
375 }
376 if (start < text.length) partial.push(text.slice(start));
377 return Effect.forEach(complete, receive, { discard: true });
378 }),
379 Effect.ignore,
380 Effect.andThen(disconnect),
381 Effect.forkScoped,
382 );
383
384 const send = <A>(
385 method: string,
386 params: Record<string, unknown>,
387 result: Schema.Decoder<A>,
388 sessionId?: string,
389 ) =>
390 Effect.gen(function* () {
391 if (disconnected) return yield* disconnected;
392 const id = ++nextId;
393 const reply = yield* Deferred.make<unknown, BrowserFailure>();
394 pending.set(id, { method, reply });
395 const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
396 yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
397 return yield* Deferred.await(reply).pipe(
398 Effect.flatMap(Schema.decodeUnknownEffect(result)),
399 Effect.mapError((error) =>
400 error._tag === "HtmlRenderBrowserError"
401 ? error
402 : new HtmlRenderBrowserError({
403 reason: `${method} returned an unexpected result`,
404 cause: error,
405 }),
406 ),
407 );
408 });
409
410 const openPage = Effect.fnUntraced(function* (width: number) {
411 const { targetId } = yield* send(
412 "Target.createTarget",
413 { url: "about:blank" },
414 Schema.Struct({ targetId: Schema.String }),
415 );
416 const { sessionId } = yield* send(
417 "Target.attachToTarget",
418 { targetId, flatten: true },
419 Schema.Struct({ sessionId: Schema.String }),
420 );
421 const events: PageEvents = {
422 // A page target's id is its main frame's id.
423 mainFrameId: targetId,
424 body: undefined,
425 loaded: undefined,
426 consoleMessages: [],
427 omittedConsoleMessages: 0,
428 };
429 pages.set(sessionId, events);
430 yield* send("Page.enable", {}, Ignored, sessionId);
431 yield* send("Runtime.enable", {}, Ignored, sessionId);
432 yield* send("Log.enable", {}, Ignored, sessionId);
433 // Previews have no use for WebRTC, whose ICE servers can make the browser
434 // resolve names outside the proxy. Runs before page scripts in every frame.
435 yield* send(
436 "Page.addScriptToEvaluateOnNewDocument",
437 {
438 source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;",
439 runImmediately: true,
440 },
441 Ignored,
442 sessionId,
443 );
444 // Pauses T3's own origin, to serve the page, and every document, to keep
445 // the main frame on it.
446 yield* send(
447 "Fetch.enable",
448 {
449 patterns: [
450 { urlPattern: `${PAGE_ORIGIN}/*` },
451 { urlPattern: "*", resourceType: "Document" },
452 ],
453 },
454 Ignored,
455 sessionId,
456 );
457 yield* send(
458 "Emulation.setDeviceMetricsOverride",
459 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
460 Ignored,
461 sessionId,
462 );
463
464 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
465 const loaded = yield* Deferred.make<void, BrowserFailure>();
466 events.body = body;
467 events.loaded = loaded;
468 const navigation = yield* send(
469 "Page.navigate",
470 { url: `${PAGE_URL}${urlFragment}` },
471 Navigation,
472 sessionId,
473 );
474 if (navigation.errorText) {
475 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
476 }
477 yield* Deferred.await(loaded);
478 yield* send(
479 "Runtime.evaluate",
480 { expression: SETTLE_EXPRESSION, awaitPromise: true },
481 Ignored,
482 sessionId,
483 );
484 const measured = yield* send(
485 "Runtime.evaluate",
486 { expression: MEASURE_EXPRESSION, returnByValue: true },
487 Measured,
488 sessionId,
489 );
490 return Math.max(0, Math.ceil(measured.result.value));
491 });
492
493 const screenshot = (height: number) =>
494 send(
495 "Page.captureScreenshot",
496 {
497 format: "png",
498 captureBeyondViewport: true,
499 clip: { x: 0, y: 0, width, height, scale: 1 },
500 },
501 Schema.Struct({ data: Schema.String }),
502 sessionId,
503 ).pipe(Effect.map(({ data }) => data));
504
505 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
506 events.omittedConsoleMessages === 0
507 ? [...events.consoleMessages]
508 : [
509 ...events.consoleMessages,
510 {
511 level: "warning",
512 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
513 },
514 ];
515
516 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
517 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
518 Effect.ignore,
519 );
520
521 return { load, screenshot, consoleMessages, close };
522 });
523
524 return { openPage };
525});
526
527const scratchDirectory = Effect.gen(function* () {
528 const fileSystem = yield* FileSystem.FileSystem;
529 return yield* Effect.acquireRelease(
530 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
531 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
532 ).pipe(
533 Effect.mapError(
534 (cause) =>
535 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
536 ),
537 );
538});
539
540export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
541 function* (input: {
542 readonly executable: string;
543 readonly noSandbox: boolean;
544 readonly html: string;
545 readonly width: number;
546 readonly urlFragment: string;
547 }) {
548 const path = yield* Path.Path;
549 const directory = yield* scratchDirectory;
550 const browser = yield* launchBrowser({
551 executable: input.executable,
552 noSandbox: input.noSandbox,
553 profileDirectory: path.join(directory, "profile"),
554 });
555 const page = yield* browser.openPage(input.width);
556 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
557 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
558 const png = yield* page.screenshot(capturedHeight);
559 return { png, contentHeight, capturedHeight, consoleMessages: page.consoleMessages() };
560 },
561 Effect.scoped,
562 Effect.timeoutOrElse({
563 duration: CAPTURE_TIMEOUT,
564 orElse: () =>
565 Effect.fail(
566 new HtmlRenderBrowserError({
567 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
568 }),
569 ),
570 }),
571);
572
573/**
574 * Content heights of the page at each width, each from a fresh load, since
575 * pages often lay themselves out from the width once at load.
576 */
577export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
578 readonly executable: string;
579 readonly noSandbox: boolean;
580 readonly html: string;
581 readonly widths: ReadonlyArray<number>;
582 readonly urlFragment: string;
583}) {
584 const path = yield* Path.Path;
585 const directory = yield* scratchDirectory;
586 const browser = yield* launchBrowser({
587 executable: input.executable,
588 noSandbox: input.noSandbox,
589 profileDirectory: path.join(directory, "profile"),
590 });
591 const body = pageBody(input.html);
592 return yield* Effect.forEach(
593 input.widths,
594 (width) =>
595 browser.openPage(width).pipe(
596 Effect.flatMap((page) =>
597 page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
598 ),
599 Effect.map((height) => [width, height] as const),
600 ),
601 { concurrency: MEASURE_CONCURRENCY },
602 );
603}, Effect.scoped);