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

HtmlRender.ts

476 lines17.2 KB

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