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

HtmlRender.ts

493 lines18.3 KB

1import type { ThreadId } from "@t3tools/contracts";
2import { HostProcessUserId } from "@t3tools/shared/hostProcess";
3import {
4 clampHtmlRenderHeight,
5 HTML_RENDER_COLUMN_WIDTH,
6 HTML_RENDER_MAX_TITLE_LENGTH,
7 HTML_RENDER_MEASURE_FONTS,
8 HTML_RENDER_MEASURE_WIDTHS,
9 htmlRenderTheme,
10 htmlRenderThemeFragment,
11 injectHtmlRenderBootstrap,
12 type HtmlRenderReference,
13} from "@t3tools/shared/htmlRender";
14import {
15 T3_CODE_DARK_THEME_COLORS,
16 T3_CODE_LIGHT_THEME_COLORS,
17 type ThemeAppearance,
18} from "@t3tools/shared/themePalettes";
19import * as Context from "effect/Context";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import type * as Path from "effect/Path";
25import * as Schema from "effect/Schema";
26import * as Semaphore from "effect/Semaphore";
27import * as Stream from "effect/Stream";
28import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
29​
30import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
31import { createAttachmentId } from "../attachmentStore.ts";
32import * as ServerConfig from "../config.ts";
33import * as HeadlessChrome from "./headlessChrome.ts";
34import * as PreviewBrowser from "./PreviewBrowser.ts";
35​
36const MIB = 1024 * 1024;
37const MAX_IMAGE_BYTES = 10 * MIB;
38const MAX_PAGE_BYTES = 25 * MIB;
39const formatMib = (bytes: number) => `${(bytes / MIB).toFixed(1)} MiB`;
40​
41export class HtmlRenderImagesNotFoundError extends Schema.TaggedError<HtmlRenderImagesNotFoundError>()(
42 "HtmlRenderImagesNotFoundError",
43 { paths: Schema.Array(Schema.String) },
44) {
45 override get message(): string {
46 return `These local images could not be read: ${this.paths.join(", ")}. Use absolute paths to existing image files, or remove them.`;
47 }
49​
50export class HtmlRenderImageTooLargeError extends Schema.TaggedError<HtmlRenderImageTooLargeError>()(
51 "HtmlRenderImageTooLargeError",
52 { path: Schema.String, sizeBytes: Schema.Number },
53) {
54 override get message(): string {
55 return `${this.path} is ${formatMib(this.sizeBytes)}; each local image must be at most ${formatMib(MAX_IMAGE_BYTES)}.`;
56 }
58​
59export class HtmlRenderPageTooLargeError extends Schema.TaggedError<HtmlRenderPageTooLargeError>()(
60 "HtmlRenderPageTooLargeError",
61 { sizeBytes: Schema.Number },
62) {
63 override get message(): string {
64 return `With its images inlined the page is ${formatMib(this.sizeBytes)}; the limit is ${formatMib(MAX_PAGE_BYTES)}. Use smaller images.`;
65 }
67​
68export class HtmlRenderStoreError extends Schema.TaggedError<HtmlRenderStoreError>()(
69 "HtmlRenderStoreError",
70 { cause: Schema.Defect() },
71) {
72 override get message(): string {
73 return "The HTML render could not be saved.";
74 }
76​
77export type HtmlRenderPrepareError =
78 | HtmlRenderImagesNotFoundError
79 | HtmlRenderImageTooLargeError
80 | HtmlRenderPageTooLargeError;
81​
82export interface HtmlPreview {
83 /** Base64 PNG of the top `capturedHeight` pixels. */
84 readonly png: string;
85 readonly width: number;
86 /** Height the page needs to show without scrolling. */
87 readonly contentHeight: number;
88 readonly capturedHeight: number;
89 readonly consoleMessages: ReadonlyArray<HeadlessChrome.ConsoleMessage>;
90 /** Local image paths that could not be read; they show as broken images. */
91 readonly missingImages?: ReadonlyArray<string>;
93​
94export class HtmlRender extends Context.Service<
95 HtmlRender,
96 {
97 /** The self-contained page that gets stored: local images inlined, theme bootstrap injected. */
98 readonly prepare: (html: string) => Effect.Effect<string, HtmlRenderPrepareError>;
99 /**
100 * Stores a prepared page as a thread attachment for clients to show inline,
101 * measuring its height at each client width when the preview browser is
102 * already installed.
103 */
104 readonly publish: (input: {
105 readonly threadId: ThreadId;
106 readonly html: string;
107 readonly title: string;
108 readonly height: number;
109 }) => Effect.Effect<HtmlRenderReference, HtmlRenderPrepareError | HtmlRenderStoreError>;
110 /** Screenshots a page in headless Chrome, tolerating unreadable local images. */
111 readonly preview: (input: {
112 readonly html: string;
113 readonly width?: number | undefined;
114 readonly appearance?: ThemeAppearance | undefined;
115 }) => Effect.Effect<
116 HtmlPreview,
117 | Exclude<HtmlRenderPrepareError, HtmlRenderImagesNotFoundError>
118 | PreviewBrowser.PreviewBrowserInstallError
119 | PreviewBrowser.PreviewBrowserInstallingError
120 | PreviewBrowser.PreviewBrowserUnsupportedError
121 | HeadlessChrome.HtmlRenderBrowserError
122 >;
123 }
124>()("t3/htmlRender/HtmlRender") {}
125​
126const IMAGE_MIME_TYPES: Record<string, string> = {
127 png: "image/png",
128 jpg: "image/jpeg",
129 jpeg: "image/jpeg",
130 gif: "image/gif",
131 webp: "image/webp",
132 avif: "image/avif",
133 svg: "image/svg+xml",
134 bmp: "image/bmp",
135 ico: "image/x-icon",
136};
137const IMAGE_EXTENSIONS = Object.keys(IMAGE_MIME_TYPES).join("|");
138// POSIX `/…` (not protocol-relative `//…`) or Windows `C:\…` / `C:/…`.
139const ABSOLUTE_PATH = String.raw`(?:/(?!/)|[a-z]:[\\/])`;
140// An absolute image path that is a whole quoted string ("…", '…', `…`) or an
141// unquoted CSS url(…). URLs, data:, blob:, and relative paths never match.
142const LOCAL_IMAGE_PATTERN = new RegExp(
143 String.raw`(["'\x60])(${ABSOLUTE_PATH}(?:(?!\1)[^\r\n]){0,2048}?\.(?:${IMAGE_EXTENSIONS}))\1` +
144 String.raw`|url\(\s*(${ABSOLUTE_PATH}[^\s"'\x60()]{0,2048}?\.(?:${IMAGE_EXTENSIONS}))\s*\)`,
145 "gid",
146);
147​
148const findLocalImages = (html: string) =>
149 Array.from(html.matchAll(LOCAL_IMAGE_PATTERN)).flatMap((match) => {
150 const span = match.indices?.[2] ?? match.indices?.[3];
151 return span ? [{ start: span[0], end: span[1], path: html.slice(span[0], span[1]) }] : [];
152 });
153​
154// Inside a JS string literal a Windows path's backslashes are escaped.
155const filePathFor = (reference: string) =>
156 /^[a-z]:/i.test(reference) ? reference.replaceAll("\\\\", "\\") : reference;
157​
158const dataUriPrefix = (path: string) =>
159 `data:${IMAGE_MIME_TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"};base64,`;
160​
161const latin1 = (bytes: Uint8Array, start: number, end: number) =>
162 String.fromCharCode(...bytes.subarray(start, end));
163​
164/**
165 * Whether file bytes are an image, whatever the file is named, so a symlink or
166 * renamed file cannot carry other data, such as a secret, into a page.
167 */
168const isImageBytes = (bytes: Uint8Array) => {
169 const head = latin1(bytes, 0, 12);
170 if (
171 head.startsWith("\x89PNG") ||
172 head.startsWith("\xff\xd8\xff") ||
173 head.startsWith("GIF8") ||
174 head.startsWith("\0\0\x01\0") ||
175 (head.startsWith("BM") && head.slice(6, 10) === "\0\0\0\0") ||
176 (head.startsWith("RIFF") && head.slice(8, 12) === "WEBP") ||
177 /^ftyp(?:avif|avis|mif1)$/.test(head.slice(4, 12))
178 ) {
179 return true;
180 }
181 return hasSvgRoot(new TextDecoder().decode(bytes.subarray(0, 4096)));
182};
183​
184/** The index just past `token` at or after `from`, or -1 when it never appears. */
185const after = (text: string, token: string, from: number) => {
186 const at = text.indexOf(token, from);
187 return at === -1 ? -1 : at + token.length;
188};
189​
190/**
191 * Whether an XML document's root element is <svg>, after any processing
192 * instructions, comments, and a doctype. One forward pass, so no input can
193 * make it slow, and quoted text never counts as markup.
194 */
195const hasSvgRoot = (text: string) => {
196 let at = 0;
197 while (at !== -1) {
198 while (/\s/.test(text.charAt(at))) at += 1;
199 if (text.startsWith("<?", at)) at = after(text, "?>", at + 2);
200 else if (text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
201 else if (text.slice(at, at + 9).toLowerCase() === "<!doctype") at = afterDoctype(text, at + 9);
202 // XML names are case-sensitive, and only these characters can end one here.
203 else return /^<svg[ \t\r\n/>]/.test(text.slice(at, at + 5));
204 }
205 return false;
206};
207​
208/** The index just past a doctype whose body starts at `from`, honoring quotes and its internal subset. */
209const afterDoctype = (text: string, from: number) => {
210 let inSubset = false;
211 let at = from;
212 while (at !== -1 && at < text.length) {
213 const char = text[at];
214 if (char === '"' || char === "'") at = after(text, char, at + 1);
215 else if (inSubset && text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
216 else if (inSubset && text.startsWith("<?", at)) at = after(text, "?>", at + 2);
217 else if (char === ">" && !inSubset) return at + 1;
218 else {
219 if (char === "[") inSubset = true;
220 else if (char === "]") inSubset = false;
221 at += 1;
222 }
223 }
224 return -1;
225};
226​
227/** Replaces every local image reference with a data URI; unreadable paths stay as written. */
228const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (html: string) {
229 const fileSystem = yield* FileSystem.FileSystem;
230 const references = findLocalImages(html);
231 const files = yield* Effect.forEach(
232 [...new Set(references.map((reference) => reference.path))],
233 (path) =>
234 fileSystem.stat(filePathFor(path)).pipe(
235 Effect.map((info) => ({
236 path,
237 size: info.type === "File" ? Number(info.size) : undefined,
238 })),
239 Effect.orElseSucceed(() => ({ path, size: undefined })),
240 ),
241 { concurrency: 8 },
242 );
243 const oversized = files.find((file) => file.size !== undefined && file.size > MAX_IMAGE_BYTES);
244 if (oversized?.size !== undefined) {
245 return yield* new HtmlRenderImageTooLargeError({
246 path: oversized.path,
247 sizeBytes: oversized.size,
248 });
249 }
250 const sizes = new Map(files.map((file) => [file.path, file.size]));
251 const pageBytes = references.reduce((total, reference) => {
252 const size = sizes.get(reference.path);
253 return size === undefined
254 ? total
255 : total +
256 dataUriPrefix(reference.path).length +
257 Math.ceil(size / 3) * 4 -
258 Buffer.byteLength(reference.path);
259 }, Buffer.byteLength(html));
260 if (pageBytes > MAX_PAGE_BYTES) {
261 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: pageBytes });
262 }
263 // Files can grow after `stat`. Each read stops one byte past the image
264 // limit, and reading stops once the images read so far cannot fit the page.
265 let readBytes = 0;
266 const images = yield* Effect.forEach(
267 files.filter((file) => file.size !== undefined),
268 (file) =>
269 Effect.gen(function* () {
270 const read = yield* fileSystem
271 .stream(filePathFor(file.path), { bytesToRead: MAX_IMAGE_BYTES + 1 })
272 .pipe(Stream.mkUint8Array, Effect.option);
273 if (Option.isNone(read) || !isImageBytes(read.value)) return [];
274 const bytes = read.value;
275 if (bytes.byteLength > MAX_IMAGE_BYTES) {
276 return yield* new HtmlRenderImageTooLargeError({
277 path: file.path,
278 sizeBytes: bytes.byteLength,
279 });
280 }
281 readBytes += Math.ceil(bytes.byteLength / 3) * 4;
282 if (readBytes > MAX_PAGE_BYTES) {
283 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: readBytes });
284 }
285 return [{ path: file.path, bytes }];
286 }),
287 { concurrency: 4 },
288 ).pipe(Effect.map((entries) => entries.flat()));
289 const dataUris = new Map(
290 images.map(
291 (image) =>
292 // Node's encoder: images run to 10 MiB.
293 [
294 image.path,
295 dataUriPrefix(image.path) + Buffer.from(image.bytes).toString("base64"),
296 ] as const,
297 ),
298 );
299 const parts: Array<string> = [];
300 let cursor = 0;
301 for (const reference of references) {
302 const dataUri = dataUris.get(reference.path);
303 if (dataUri === undefined) continue;
304 parts.push(html.slice(cursor, reference.start), dataUri);
305 cursor = reference.end;
306 }
307 parts.push(html.slice(cursor));
308 const inlined = parts.join("");
309 const inlinedBytes = Buffer.byteLength(inlined);
310 if (inlinedBytes > MAX_PAGE_BYTES) {
311 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: inlinedBytes });
312 }
313 return {
314 html: inlined,
315 missing: files.filter((file) => !dataUris.has(file.path)).map((file) => file.path),
316 };
317});
318​
319const MIN_PREVIEW_WIDTH = 240;
320const MAX_PREVIEW_WIDTH = 1_600;
321// Each preview or measurement runs its own browser; more at once mostly costs memory.
322const MAX_CONCURRENT_BROWSERS = 2;
323// Publishing waits this long at most for heights before returning without them.
324const MEASURE_TIMEOUT = "6 seconds";
325​
326// Measured in the dark theme with Arial-metric fonts, so text wraps close to how clients show it.
327const MEASURE_FRAGMENT = htmlRenderThemeFragment(
328 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_MEASURE_FONTS),
329);
330​
331const make = Effect.gen(function* () {
332 const fileSystem = yield* FileSystem.FileSystem;
333 const config = yield* ServerConfig.ServerConfig;
334 const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
335 const services = yield* Effect.context<
336 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
337 >();
338 const browsers = yield* Semaphore.make(MAX_CONCURRENT_BROWSERS);
339 // Chrome refuses its sandbox as root. Other hosts that cannot provide one
340 // (Ubuntu 23.10+ AppArmor) are learned from the first launch and remembered.
341 let noSandbox = (yield* HostProcessUserId) === 0;
342​
343 const launching = <A>(
344 run: (
345 noSandbox: boolean,
346 ) => Effect.Effect<
347 A,
348 HeadlessChrome.HtmlRenderBrowserError | HeadlessChrome.HtmlRenderSandboxUnavailableError
349 >,
350 ) =>
351 browsers.withPermits(1)(
352 // Read once a permit is held, so a queued call sees a fallback learned meanwhile.
353 Effect.suspend(() => run(noSandbox)).pipe(
354 Effect.catchTag("HtmlRenderSandboxUnavailableError", () =>
355 Effect.logInfo(
356 "Chrome's sandbox is unavailable on this host; launching it without one.",
357 ).pipe(
358 Effect.andThen(
359 Effect.sync(() => {
360 noSandbox = true;
361 }),
362 ),
363 Effect.andThen(run(true)),
364 ),
365 ),
366 Effect.catchTag("HtmlRenderSandboxUnavailableError", (cause) =>
367 Effect.fail(
368 new HeadlessChrome.HtmlRenderBrowserError({
369 reason: "the browser has no sandbox",
370 cause,
371 }),
372 ),
373 ),
374 ),
375 );
376​
377 // Never installs the browser: html_render must not depend on it.
378 const measure = (html: string) =>
379 Effect.gen(function* () {
380 const executable = yield* previewBrowser.installed;
381 if (Option.isNone(executable)) return undefined;
382 const heights = yield* launching((noSandbox) =>
383 HeadlessChrome.measureHtmlHeights({
384 executable: executable.value,
385 noSandbox,
386 html,
387 widths: HTML_RENDER_MEASURE_WIDTHS,
388 urlFragment: MEASURE_FRAGMENT,
389 }).pipe(Effect.provideContext(services)),
390 ).pipe(
391 Effect.timeoutOrElse({
392 duration: MEASURE_TIMEOUT,
393 orElse: () =>
394 Effect.fail(
395 new HeadlessChrome.HtmlRenderBrowserError({
396 reason: `measuring took longer than ${MEASURE_TIMEOUT}`,
397 }),
398 ),
399 }),
400 );
401 return heights.toSorted(([left], [right]) => left - right);
402 }).pipe(
403 Effect.catch((cause) =>
404 Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
405 cause,
406 }).pipe(Effect.as(undefined)),
407 ),
408 Effect.withSpan("HtmlRender.measure"),
409 );
410​
411 // The bootstrap goes in first so its head scan never runs over inlined image data.
412 const inline = (html: string) =>
413 inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
414​
415 const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
416 const inlined = yield* inline(html);
417 if (inlined.missing.length > 0) {
418 return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
419 }
420 return inlined.html;
421 });
422​
423 const publish = Effect.fn("HtmlRender.publish")(function* (input: {
424 readonly threadId: ThreadId;
425 readonly html: string;
426 readonly title: string;
427 readonly height: number;
428 }) {
429 const html = yield* prepare(input.html);
430 // The `-html` id suffix makes the asset route serve it as a sandboxed text/html document.
431 const attachmentId = createAttachmentId(input.threadId, "html");
432 const filePath =
433 attachmentId === null
434 ? null
435 : resolveAttachmentRelativePath({
436 attachmentsDir: config.attachmentsDir,
437 relativePath: `${attachmentId}.html`,
438 });
439 if (attachmentId === null || filePath === null) {
440 return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
441 }
442 const heights = yield* fileSystem.writeFileString(filePath, html).pipe(
443 Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
444 Effect.andThen(measure(html)),
445 // Only the returned reference lets thread deletion find the page, so a
446 // publish that fails or is interrupted before returning removes it.
447 Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore)),
448 );
449 return {
450 attachmentId,
451 title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
452 height: clampHtmlRenderHeight(input.height),
453 ...(heights === undefined ? {} : { heights }),
454 } satisfies HtmlRenderReference;
455 });
456​
457 const preview = Effect.fn("HtmlRender.preview")(function* (input: {
458 readonly html: string;
459 readonly width?: number | undefined;
460 readonly appearance?: ThemeAppearance | undefined;
461 }) {
462 const width = Math.min(
463 MAX_PREVIEW_WIDTH,
464 Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)),
465 );
466 const appearance = input.appearance ?? "dark";
467 const inlined = yield* inline(input.html);
468 const executable = yield* previewBrowser.executable;
469 const theme = htmlRenderTheme(
470 appearance === "light" ? T3_CODE_LIGHT_THEME_COLORS : T3_CODE_DARK_THEME_COLORS,
471 appearance,
472 HTML_RENDER_MEASURE_FONTS,
473 );
474 const screenshot = yield* launching((noSandbox) =>
475 HeadlessChrome.captureHtmlScreenshot({
476 executable,
477 noSandbox,
478 html: inlined.html,
479 width,
480 urlFragment: htmlRenderThemeFragment(theme),
481 }).pipe(Effect.provideContext(services)),
482 );
483 return {
484 ...screenshot,
485 width,
486 ...(inlined.missing.length === 0 ? {} : { missingImages: inlined.missing }),
487 } satisfies HtmlPreview;
488 });
489​
490 return HtmlRender.of({ prepare, publish, preview });
491});
492​
493export const layer = Layer.effect(HtmlRender, make);