Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

headlessChrome.ts

718 lines25.9 KB

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