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