Open History to see the last commit
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 }
48}
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 }
57}
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 }
66}
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 }
75}
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>;
92}
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.catchTags({
355 HtmlRenderSandboxUnavailableError: () =>
356 Effect.logInfo(
357 "Chrome's sandbox is unavailable on this host; launching it without one.",
358 ).pipe(
359 Effect.andThen(
360 Effect.sync(() => {
361 noSandbox = true;
362 }),
363 ),
364 Effect.andThen(run(true)),
365 ),
366 }),
367 Effect.catchTags({
368 HtmlRenderSandboxUnavailableError: (cause) =>
369 Effect.fail(
370 new HeadlessChrome.HtmlRenderBrowserError({
371 reason: "the browser has no sandbox",
372 cause,
373 }),
374 ),
375 }),
376 ),
377 );
378
379 // Never installs the browser: html_render must not depend on it.
380 const measure = (html: string) =>
381 Effect.gen(function* () {
382 const executable = yield* previewBrowser.installed;
383 if (Option.isNone(executable)) return undefined;
384 const heights = yield* launching((noSandbox) =>
385 HeadlessChrome.measureHtmlHeights({
386 executable: executable.value,
387 noSandbox,
388 html,
389 widths: HTML_RENDER_MEASURE_WIDTHS,
390 urlFragment: MEASURE_FRAGMENT,
391 }).pipe(Effect.provideContext(services)),
392 ).pipe(
393 Effect.timeoutOrElse({
394 duration: MEASURE_TIMEOUT,
395 orElse: () =>
396 Effect.fail(
397 new HeadlessChrome.HtmlRenderBrowserError({
398 reason: `measuring took longer than ${MEASURE_TIMEOUT}`,
399 }),
400 ),
401 }),
402 );
403 return heights.toSorted(([left], [right]) => left - right);
404 }).pipe(
405 Effect.catch((cause) =>
406 Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
407 cause,
408 }).pipe(Effect.as(undefined)),
409 ),
410 Effect.withSpan("HtmlRender.measure"),
411 );
412
413 // The bootstrap goes in first so its head scan never runs over inlined image data.
414 const inline = (html: string) =>
415 inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
416
417 const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
418 const inlined = yield* inline(html);
419 if (inlined.missing.length > 0) {
420 return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
421 }
422 return inlined.html;
423 });
424
425 const publish = Effect.fn("HtmlRender.publish")(function* (input: {
426 readonly threadId: ThreadId;
427 readonly html: string;
428 readonly title: string;
429 readonly height: number;
430 }) {
431 const html = yield* prepare(input.html);
432 // The `-html` id suffix makes the asset route serve it as a sandboxed text/html document.
433 const attachmentId = createAttachmentId(input.threadId, "html");
434 const filePath =
435 attachmentId === null
436 ? null
437 : resolveAttachmentRelativePath({
438 attachmentsDir: config.attachmentsDir,
439 relativePath: `${attachmentId}.html`,
440 });
441 if (attachmentId === null || filePath === null) {
442 return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
443 }
444 const heights = yield* fileSystem.writeFileString(filePath, html).pipe(
445 Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
446 Effect.andThen(measure(html)),
447 // Only the returned reference lets thread deletion find the page, so a
448 // publish that fails or is interrupted before returning removes it.
449 Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore)),
450 );
451 return {
452 attachmentId,
453 title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
454 height: clampHtmlRenderHeight(input.height),
455 ...(heights === undefined ? {} : { heights }),
456 } satisfies HtmlRenderReference;
457 });
458
459 const preview = Effect.fn("HtmlRender.preview")(function* (input: {
460 readonly html: string;
461 readonly width?: number | undefined;
462 readonly appearance?: ThemeAppearance | undefined;
463 }) {
464 const width = Math.min(
465 MAX_PREVIEW_WIDTH,
466 Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)),
467 );
468 const appearance = input.appearance ?? "dark";
469 const inlined = yield* inline(input.html);
470 const executable = yield* previewBrowser.executable;
471 const theme = htmlRenderTheme(
472 appearance === "light" ? T3_CODE_LIGHT_THEME_COLORS : T3_CODE_DARK_THEME_COLORS,
473 appearance,
474 HTML_RENDER_MEASURE_FONTS,
475 );
476 const screenshot = yield* launching((noSandbox) =>
477 HeadlessChrome.captureHtmlScreenshot({
478 executable,
479 noSandbox,
480 html: inlined.html,
481 width,
482 urlFragment: htmlRenderThemeFragment(theme),
483 }).pipe(Effect.provideContext(services)),
484 );
485 return {
486 ...screenshot,
487 width,
488 ...(inlined.missing.length === 0 ? {} : { missingImages: inlined.missing }),
489 } satisfies HtmlPreview;
490 });
491
492 return HtmlRender.of({ prepare, publish, preview });
493});
494
495export const layer = Layer.effect(HtmlRender, make);