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 // Signals can miss a confined browser (AppArmor in LXC), so ask it to quit first.
378 // Runs before the spawn's release, which still signals a browser that stays up.
379 yield* Effect.addFinalizer(() =>
380 disconnected
381 ? Effect.void
382 : post("Browser.close", {}).pipe(
383 Effect.andThen(child.exitCode),
384 Effect.timeout("2 seconds"),
385 Effect.ignore,
386 ),
387 );
388
389 const send = Effect.fn("headlessChrome.send")(function* <A>(
390 method: string,
391 params: Record<string, unknown>,
392 result: Schema.Decoder<A>,
393 sessionId?: string,
394 ) {
395 if (disconnected) return yield* disconnected;
396 const id = ++nextId;
397 const reply = yield* Deferred.make<unknown, BrowserFailure>();
398 pending.set(id, { method, reply });
399 const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
400 yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
401 return yield* Deferred.await(reply).pipe(
402 Effect.flatMap(Schema.decodeUnknownEffect(result)),
403 Effect.mapError((error) =>
404 error._tag === "HtmlRenderBrowserError"
405 ? error
406 : new HtmlRenderBrowserError({
407 reason: `${method} returned an unexpected result`,
408 cause: error,
409 }),
410 ),
411 );
412 });
413
414 const openPage = Effect.fnUntraced(function* (width: number, appearance: ThemeAppearance) {
415 const { targetId } = yield* send(
416 "Target.createTarget",
417 { url: "about:blank" },
418 Schema.Struct({ targetId: Schema.String }),
419 );
420 const { sessionId } = yield* send(
421 "Target.attachToTarget",
422 { targetId, flatten: true },
423 Schema.Struct({ sessionId: Schema.String }),
424 );
425 const events: PageEvents = {
426 // A page target's id is its main frame's id.
427 mainFrameId: targetId,
428 body: undefined,
429 loaded: undefined,
430 consoleMessages: [],
431 omittedConsoleMessages: 0,
432 };
433 pages.set(sessionId, events);
434 yield* send("Page.enable", {}, Ignored, sessionId);
435 yield* send("Runtime.enable", {}, Ignored, sessionId);
436 yield* send("Log.enable", {}, Ignored, sessionId);
437 yield* send(
438 "Emulation.setEmulatedMedia",
439 { features: [{ name: "prefers-color-scheme", value: appearance }] },
440 Ignored,
441 sessionId,
442 );
443 // Previews have no use for WebRTC, whose ICE servers can make the browser
444 // resolve names outside the proxy. Runs before page scripts in every frame.
445 yield* send(
446 "Page.addScriptToEvaluateOnNewDocument",
447 {
448 source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;",
449 runImmediately: true,
450 },
451 Ignored,
452 sessionId,
453 );
454 // Intercept T3's page and all document navigations to keep the main frame on it.
455 yield* send(
456 "Fetch.enable",
457 {
458 patterns: [
459 { urlPattern: `${PAGE_ORIGIN}/*` },
460 { urlPattern: "*", resourceType: "Document" },
461 ],
462 },
463 Ignored,
464 sessionId,
465 );
466 yield* send(
467 "Emulation.setDeviceMetricsOverride",
468 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
469 Ignored,
470 sessionId,
471 );
472
473 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
474 const loaded = yield* Deferred.make<void, BrowserFailure>();
475 events.body = body;
476 events.loaded = loaded;
477 const navigation = yield* send(
478 "Page.navigate",
479 { url: `${PAGE_URL}${urlFragment}` },
480 Navigation,
481 sessionId,
482 );
483 if (navigation.errorText) {
484 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
485 }
486 yield* Deferred.await(loaded);
487 yield* send(
488 "Runtime.evaluate",
489 { expression: SETTLE_EXPRESSION, awaitPromise: true },
490 Ignored,
491 sessionId,
492 );
493 const measured = yield* send(
494 "Runtime.evaluate",
495 { expression: MEASURE_EXPRESSION, returnByValue: true },
496 Measured,
497 sessionId,
498 );
499 return Math.max(0, Math.ceil(measured.result.value));
500 });
501
502 const screenshot = (height: number) =>
503 send(
504 "Page.captureScreenshot",
505 {
506 format: "png",
507 captureBeyondViewport: true,
508 clip: { x: 0, y: 0, width, height, scale: 1 },
509 },
510 Schema.Struct({ data: Schema.String }),
511 sessionId,
512 ).pipe(Effect.map(({ data }) => data));
513
514 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
515 events.omittedConsoleMessages === 0
516 ? [...events.consoleMessages]
517 : [
518 ...events.consoleMessages,
519 {
520 level: "warning",
521 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
522 },
523 ];
524
525 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
526 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
527 Effect.ignore,
528 );
529
530 return { load, screenshot, consoleMessages, close };
531 });
532
533 return { openPage };
534});
535
536const scratchDirectory = Effect.gen(function* () {
537 const fileSystem = yield* FileSystem.FileSystem;
538 return yield* Effect.acquireRelease(
539 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
540 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
541 ).pipe(
542 Effect.mapError(
543 (cause) =>
544 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
545 ),
546 );
547});
548
549export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
550 function* (input: {
551 readonly executable: string;
552 readonly noSandbox: boolean;
553 readonly html: string;
554 readonly width: number;
555 readonly urlFragment: string;
556 readonly appearance: ThemeAppearance;
557 }) {
558 const path = yield* Path.Path;
559 const directory = yield* scratchDirectory;
560 const browser = yield* launchBrowser({
561 executable: input.executable,
562 noSandbox: input.noSandbox,
563 profileDirectory: path.join(directory, "profile"),
564 });
565 const page = yield* browser.openPage(input.width, input.appearance);
566 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
567 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
568 const png = yield* page.screenshot(capturedHeight);
569 return { png, contentHeight, capturedHeight, consoleMessages: page.consoleMessages() };
570 },
571 Effect.scoped,
572 Effect.timeoutOrElse({
573 duration: CAPTURE_TIMEOUT,
574 orElse: () =>
575 Effect.fail(
576 new HtmlRenderBrowserError({
577 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
578 }),
579 ),
580 }),
581);
582
583/** Fresh load per width, since pages may lay out only at load. */
584export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
585 readonly executable: string;
586 readonly noSandbox: boolean;
587 readonly html: string;
588 readonly widths: ReadonlyArray<number>;
589 readonly urlFragment: string;
590}) {
591 const path = yield* Path.Path;
592 const directory = yield* scratchDirectory;
593 const browser = yield* launchBrowser({
594 executable: input.executable,
595 noSandbox: input.noSandbox,
596 profileDirectory: path.join(directory, "profile"),
597 });
598 const body = pageBody(input.html);
599 return yield* Effect.forEach(
600 input.widths,
601 (width) =>
602 browser.openPage(width, "dark").pipe(
603 Effect.flatMap((page) =>
604 page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
605 ),
606 Effect.map((height) => [width, height] as const),
607 ),
608 { concurrency: MEASURE_CONCURRENCY },
609 );
610}, Effect.scoped);