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 const receive = (raw: string) => {
269 const message = Option.getOrUndefined(decodeCdpMessage(raw));
270 if (message?.id !== undefined) {
271 const waiter = pending.get(message.id);
272 pending.delete(message.id);
273 if (!waiter) return Effect.void;
274 return message.error
275 ? Deferred.fail(
276 waiter.reply,
277 new HtmlRenderBrowserError({
278 reason: `${waiter.method} failed`,
279 cause: message.error.message,
280 }),
281 )
282 : Deferred.succeed(waiter.reply, message.result);
283 }
284 const sessionId = message?.sessionId;
285 const page = sessionId === undefined ? undefined : pages.get(sessionId);
286 if (sessionId === undefined || !page || !message?.method) return Effect.void;
287 if (message.method === "Page.loadEventFired") {
288 return page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
289 }
290 if (message.method === "Fetch.requestPaused") {
291 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
292 if (!paused) return Effect.void;
293 const body = page.body;
294 const url = paused.request.url.split("#", 1)[0]!;
295 if (url === PAGE_URL && body !== undefined) {
296 return fulfillPage(sessionId, paused.requestId, body);
297 }
298 // Subframes may show other sites covered by Local Network Access; the main frame stays on T3's page.
299 const otherSiteFrame =
300 paused.resourceType === "Document" &&
301 paused.frameId !== page.mainFrameId &&
302 !url.startsWith(`${PAGE_ORIGIN}/`);
303 return otherSiteFrame
304 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
305 : post(
306 "Fetch.failRequest",
307 { requestId: paused.requestId, errorReason: "AccessDenied" },
308 sessionId,
309 );
310 }
311 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
312 if (!consoleMessage) return Effect.void;
313 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
314 page.omittedConsoleMessages += 1;
315 return Effect.void;
316 }
317 const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);
318 page.consoleMessages.push({
319 level: consoleMessage.level,
320 text:
321 text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, MAX_CONSOLE_TEXT_CHARS)}…` : text,
322 });
323 return Effect.void;
324 };
325
326 // Startup aborts close the pipe; let stderr drain to recover the reason.
327 const disconnect = Effect.gen(function* () {
328 yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore);
329 const exit = yield* child.exitCode.pipe(
330 Effect.map((code): { exitCode?: number; signal?: string; cause?: unknown } => ({
331 exitCode: code,
332 })),
333 Effect.catch((error) => {
334 const signal = EXIT_SIGNAL.exec(String(error.cause))?.[1];
335 return Effect.succeed(signal === undefined ? { cause: error } : { signal, cause: error });
336 }),
337 Effect.timeoutOption("1 second"),
338 );
339 const error = new HtmlRenderBrowserError({
340 reason: "the browser exited unexpectedly",
341 output: stderrTail,
342 ...Option.getOrElse(exit, () => ({})),
343 });
344 disconnected = error;
345 const waiters = [...pending.values()];
346 pending.clear();
347 yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true });
348 yield* Effect.forEach(
349 pages.values(),
350 (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void),
351 { discard: true },
352 );
353 });
354
355 // Chunks may split messages; screenshot replies span many chunks.
356 let partial: Array<string> = [];
357 yield* child.getOutputFd(4).pipe(
358 Stream.decodeText(),
359 Stream.runForEach((text) => {
360 const complete: Array<string> = [];
361 let start = 0;
362 for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) {
363 partial.push(text.slice(start, end));
364 complete.push(partial.join(""));
365 partial = [];
366 start = end + 1;
367 }
368 if (start < text.length) partial.push(text.slice(start));
369 return Effect.forEach(complete, receive, { discard: true });
370 }),
371 Effect.ignore,
372 Effect.andThen(disconnect),
373 Effect.forkScoped,
374 );
375
376 const send = Effect.fn("headlessChrome.send")(function* <A>(
377 method: string,
378 params: Record<string, unknown>,
379 result: Schema.Decoder<A>,
380 sessionId?: string,
381 ) {
382 if (disconnected) return yield* disconnected;
383 const id = ++nextId;
384 const reply = yield* Deferred.make<unknown, BrowserFailure>();
385 pending.set(id, { method, reply });
386 const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
387 yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
388 return yield* Deferred.await(reply).pipe(
389 Effect.flatMap(Schema.decodeUnknownEffect(result)),
390 Effect.mapError((error) =>
391 error._tag === "HtmlRenderBrowserError"
392 ? error
393 : new HtmlRenderBrowserError({
394 reason: `${method} returned an unexpected result`,
395 cause: error,
396 }),
397 ),
398 );
399 });
400
401 const openPage = Effect.fnUntraced(function* (width: number, appearance: ThemeAppearance) {
402 const { targetId } = yield* send(
403 "Target.createTarget",
404 { url: "about:blank" },
405 Schema.Struct({ targetId: Schema.String }),
406 );
407 const { sessionId } = yield* send(
408 "Target.attachToTarget",
409 { targetId, flatten: true },
410 Schema.Struct({ sessionId: Schema.String }),
411 );
412 const events: PageEvents = {
413 // A page target's id is its main frame's id.
414 mainFrameId: targetId,
415 body: undefined,
416 loaded: undefined,
417 consoleMessages: [],
418 omittedConsoleMessages: 0,
419 };
420 pages.set(sessionId, events);
421 yield* send("Page.enable", {}, Ignored, sessionId);
422 yield* send("Runtime.enable", {}, Ignored, sessionId);
423 yield* send("Log.enable", {}, Ignored, sessionId);
424 yield* send(
425 "Emulation.setEmulatedMedia",
426 { features: [{ name: "prefers-color-scheme", value: appearance }] },
427 Ignored,
428 sessionId,
429 );
430 // Previews have no use for WebRTC, whose ICE servers can make the browser
431 // resolve names outside the proxy. Runs before page scripts in every frame.
432 yield* send(
433 "Page.addScriptToEvaluateOnNewDocument",
434 {
435 source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;",
436 runImmediately: true,
437 },
438 Ignored,
439 sessionId,
440 );
441 // Intercept T3's page and all document navigations to keep the main frame on it.
442 yield* send(
443 "Fetch.enable",
444 {
445 patterns: [
446 { urlPattern: `${PAGE_ORIGIN}/*` },
447 { urlPattern: "*", resourceType: "Document" },
448 ],
449 },
450 Ignored,
451 sessionId,
452 );
453 yield* send(
454 "Emulation.setDeviceMetricsOverride",
455 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
456 Ignored,
457 sessionId,
458 );
459
460 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
461 const loaded = yield* Deferred.make<void, BrowserFailure>();
462 events.body = body;
463 events.loaded = loaded;
464 const navigation = yield* send(
465 "Page.navigate",
466 { url: `${PAGE_URL}${urlFragment}` },
467 Navigation,
468 sessionId,
469 );
470 if (navigation.errorText) {
471 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
472 }
473 yield* Deferred.await(loaded);
474 yield* send(
475 "Runtime.evaluate",
476 { expression: SETTLE_EXPRESSION, awaitPromise: true },
477 Ignored,
478 sessionId,
479 );
480 const measured = yield* send(
481 "Runtime.evaluate",
482 { expression: MEASURE_EXPRESSION, returnByValue: true },
483 Measured,
484 sessionId,
485 );
486 return Math.max(0, Math.ceil(measured.result.value));
487 });
488
489 const screenshot = (height: number) =>
490 send(
491 "Page.captureScreenshot",
492 {
493 format: "png",
494 captureBeyondViewport: true,
495 clip: { x: 0, y: 0, width, height, scale: 1 },
496 },
497 Schema.Struct({ data: Schema.String }),
498 sessionId,
499 ).pipe(Effect.map(({ data }) => data));
500
501 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
502 events.omittedConsoleMessages === 0
503 ? [...events.consoleMessages]
504 : [
505 ...events.consoleMessages,
506 {
507 level: "warning",
508 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
509 },
510 ];
511
512 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
513 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
514 Effect.ignore,
515 );
516
517 return { load, screenshot, consoleMessages, close };
518 });
519
520 return { openPage };
521});
522
523const scratchDirectory = Effect.gen(function* () {
524 const fileSystem = yield* FileSystem.FileSystem;
525 return yield* Effect.acquireRelease(
526 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
527 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
528 ).pipe(
529 Effect.mapError(
530 (cause) =>
531 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
532 ),
533 );
534});
535
536export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
537 function* (input: {
538 readonly executable: string;
539 readonly noSandbox: boolean;
540 readonly html: string;
541 readonly width: number;
542 readonly urlFragment: string;
543 readonly appearance: ThemeAppearance;
544 }) {
545 const path = yield* Path.Path;
546 const directory = yield* scratchDirectory;
547 const browser = yield* launchBrowser({
548 executable: input.executable,
549 noSandbox: input.noSandbox,
550 profileDirectory: path.join(directory, "profile"),
551 });
552 const page = yield* browser.openPage(input.width, input.appearance);
553 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
554 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
555 const png = yield* page.screenshot(capturedHeight);
556 return { png, contentHeight, capturedHeight, consoleMessages: page.consoleMessages() };
557 },
558 Effect.scoped,
559 Effect.timeoutOrElse({
560 duration: CAPTURE_TIMEOUT,
561 orElse: () =>
562 Effect.fail(
563 new HtmlRenderBrowserError({
564 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
565 }),
566 ),
567 }),
568);
569
570/** Fresh load per width, since pages may lay out only at load. */
571export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
572 readonly executable: string;
573 readonly noSandbox: boolean;
574 readonly html: string;
575 readonly widths: ReadonlyArray<number>;
576 readonly urlFragment: string;
577}) {
578 const path = yield* Path.Path;
579 const directory = yield* scratchDirectory;
580 const browser = yield* launchBrowser({
581 executable: input.executable,
582 noSandbox: input.noSandbox,
583 profileDirectory: path.join(directory, "profile"),
584 });
585 const body = pageBody(input.html);
586 return yield* Effect.forEach(
587 input.widths,
588 (width) =>
589 browser.openPage(width, "dark").pipe(
590 Effect.flatMap((page) =>
591 page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
592 ),
593 Effect.map((height) => [width, height] as const),
594 ),
595 { concurrency: MEASURE_CONCURRENCY },
596 );
597}, Effect.scoped);