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

HtmlRender.ts

684 lines26.7 KB

1import type { ThreadId } from "@t3tools/contracts";
2import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
5import { isNetworkPath } from "@t3tools/shared/path";
6import {
7 clampHtmlRenderHeight,
8 HTML_RENDER_COLUMN_WIDTH,
9 HTML_RENDER_MAX_TITLE_LENGTH,
10 HTML_RENDER_MEASURE_FONTS,
11 HTML_RENDER_MEASURE_WIDTHS,
12 htmlRenderTheme,
13 htmlRenderThemeFragment,
14 injectHtmlRenderBootstrap,
15 type HtmlRenderReference,
16} from "@t3tools/shared/htmlRender";
17import {
18 T3_CODE_DARK_THEME_COLORS,
19 T3_CODE_LIGHT_THEME_COLORS,
20 type ThemeAppearance,
21} from "@t3tools/shared/themePalettes";
22import * as Context from "effect/Context";
23import * as Effect from "effect/Effect";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Path from "effect/Path";
28import * as Schema from "effect/Schema";
29import * as Semaphore from "effect/Semaphore";
30import * as Stream from "effect/Stream";
31import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
32​
33import { openMediaFile } from "../assets/MediaFile.ts";
34import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
35import { createAttachmentId } from "../attachmentStore.ts";
36import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
37import { resolveRootCliCommand } from "../cli/invocation.ts";
38import * as ServerConfig from "../config.ts";
39import { decodeHtmlAttribute } from "../project/ProjectFaviconResolver.ts";
40import * as HeadlessChrome from "./headlessChrome.ts";
41import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
42import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
43​
44const MIB = 1024 * 1024;
45const MAX_IMAGE_BYTES = 10 * MIB;
46const MAX_PAGE_BYTES = 25 * MIB;
47const HTML_FILE_EXTENSION = /\.html?$/i;
48// Like the image check, judge the bytes: a renamed .env or key does not start like a page.
49const HTML_DOCUMENT_START = /^\s*<(?:!doctype\s+html|html)[\s>]/i;
50const formatMib = (bytes: number) => `${(bytes / MIB).toFixed(1)} MiB`;
51​
52export class HtmlRenderFileError extends Schema.TaggedError<HtmlRenderFileError>()(
53 "HtmlRenderFileError",
54 { path: Schema.String, cause: Schema.optional(Schema.Defect()) },
55) {
56 override get message(): string {
57 return `${this.path} is not a readable HTML document. Pass an absolute path to a regular .html file that starts with <!doctype html> or <html>, or pass html instead.`;
58 }
60​
61export class HtmlRenderFileTooLargeError extends Schema.TaggedError<HtmlRenderFileTooLargeError>()(
62 "HtmlRenderFileTooLargeError",
63 { path: Schema.String, sizeBytes: Schema.Number },
64) {
65 override get message(): string {
66 return `${this.path} is ${formatMib(this.sizeBytes)}; a page must be at most ${formatMib(MAX_PAGE_BYTES)}.`;
67 }
69​
70export class HtmlRenderImagesNotFoundError extends Schema.TaggedError<HtmlRenderImagesNotFoundError>()(
71 "HtmlRenderImagesNotFoundError",
72 { paths: Schema.Array(Schema.String) },
73) {
74 override get message(): string {
75 return `These local images could not be read: ${this.paths.join(", ")}. Use absolute paths to existing image files, or remove them.`;
76 }
78​
79export class HtmlRenderImageTooLargeError extends Schema.TaggedError<HtmlRenderImageTooLargeError>()(
80 "HtmlRenderImageTooLargeError",
81 { path: Schema.String, sizeBytes: Schema.Number },
82) {
83 override get message(): string {
84 return `${this.path} is ${formatMib(this.sizeBytes)}; each local image must be at most ${formatMib(MAX_IMAGE_BYTES)}.`;
85 }
87​
88export class HtmlRenderPageTooLargeError extends Schema.TaggedError<HtmlRenderPageTooLargeError>()(
89 "HtmlRenderPageTooLargeError",
90 { sizeBytes: Schema.Number },
91) {
92 override get message(): string {
93 return `With its images inlined the page is ${formatMib(this.sizeBytes)}; the limit is ${formatMib(MAX_PAGE_BYTES)}. Use smaller images.`;
94 }
96​
97export class HtmlRenderViewportHeightError extends Schema.TaggedError<HtmlRenderViewportHeightError>()(
98 "HtmlRenderViewportHeightError",
99 { found: Schema.String },
100) {
101 override get message(): string {
102 return `The page uses a viewport height unit (${this.found}). The frame grows to fit the page, so a size that follows the viewport makes it grow again and again. Let content set the height, or use fixed pixel heights.`;
103 }
105​
106// Check stylesheets, style attributes, and scripts (which may write either); skip comments whole.
107// Consume unclosed comments, tags, or quotes through EOF to keep every pattern linear.
108const HTML_CSS_SOURCE =
109 /<!--[\s\S]*?(?:-->|$)|<script(?=[\s/>])((?:=\s*(?:"[^"]*(?:"|$)|'[^']*(?:'|$)|[^\s>]*)|[^>])*)(?:>|$)([\s\S]*?)(?:<\/script\s*>|$)|<style(?=[\s/>])[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|<[a-z]((?:=\s*(?:"[^"]*(?:"|$)|'[^']*(?:'|$)|[^\s>]*)|[^>])*)/gi;
110// Inside a tag, skip other attributes' quoted values, such as a title that mentions style=.
111// A quote opens a value only right after `=`; an unquoted value such as `it's` or `a="b` runs to a space.
112const TAG_STYLE =
113 /\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))|=\s*(?:"[^"]*(?:"|$)|'[^']*(?:'|$)|[^\s>]*)/gi;
114// A script is not markup, so take any style block or attribute it spells out.
115const SCRIPT_STYLE =
116 /<!--[\s\S]*?(?:-->|$)|<style(?=[\s/>])[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi;
117// vb and vmax follow the frame height too; vmin stays, as the frame width caps it.
118// The lookbehind skips base64 runs, such as an inlined image that happens to contain "1vh",
119// and identifiers such as `.h-100vmax` or `.h\+100vh`, while signed and scientific-notation lengths still count.
120const VIEWPORT_HEIGHT_UNIT =
121 /(?<![\w.+/\\-])[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?[sld]?v(?:h|b|max)(?![\w-])/i;
122// In CSS, skip comments and strings so generated text like `content:"100vh"` passes.
123// Escapes and unquoted url() bodies go first: there a quote or `/*` is plain text.
124// An unclosed string ends at a newline, as CSS ends it there.
125const CSS_VIEWPORT_HEIGHT_UNIT = new RegExp(
126 String.raw`\\[\s\S]|url\((?!\s*["'])[^)]*\)?|\/\*[\s\S]*?(?:\*\/|$)|"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n\f])*"?|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n\f])*'?|(${VIEWPORT_HEIGHT_UNIT.source})`,
127 "gi",
128);
129​
130const findInCss = (css: string) => {
131 for (const [, found] of css.matchAll(CSS_VIEWPORT_HEIGHT_UNIT)) {
132 if (found !== undefined) return found;
133 }
134 return undefined;
135};
136​
137// Generated text (`content`) only lives in stylesheets. Attribute values hold HTML character
138// references and scripts hold their own quotes, so neither is parsed as CSS strings.
139const findViewportHeight = (source: string, pattern: RegExp) => {
140 for (const [, ...captures] of source.matchAll(pattern)) {
141 for (const css of captures) {
142 const found = css === undefined ? undefined : VIEWPORT_HEIGHT_UNIT.exec(css)?.[0];
143 if (found !== undefined) return found;
144 }
145 }
146 return undefined;
147};
148​
149const rejectViewportHeight = (html: string) => {
150 for (const [, scriptTag, script, sheet, tag] of html.matchAll(HTML_CSS_SOURCE)) {
151 const found =
152 script !== undefined
153 ? (findViewportHeight(scriptTag ?? "", TAG_STYLE) ??
154 findViewportHeight(script, SCRIPT_STYLE))
155 : tag !== undefined
156 ? findViewportHeight(tag, TAG_STYLE)
157 : findInCss(sheet ?? "");
158 if (found !== undefined) return Effect.fail(new HtmlRenderViewportHeightError({ found }));
159 }
160 return Effect.void;
161};
162​
163export class HtmlRenderStoreError extends Schema.TaggedError<HtmlRenderStoreError>()(
164 "HtmlRenderStoreError",
165 { cause: Schema.Defect() },
166) {
167 override get message(): string {
168 return "The HTML render could not be saved.";
169 }
171​
172export type HtmlRenderPrepareError =
173 | HtmlRenderImagesNotFoundError
174 | HtmlRenderImageTooLargeError
175 | HtmlRenderPageTooLargeError
176 | HtmlRenderViewportHeightError;
177​
178export type HtmlRenderSource = { readonly html: string } | { readonly path: string };
179​
180export interface HtmlPreview {
181 readonly png: string;
182 readonly width: number;
183 readonly contentHeight: number;
184 readonly capturedHeight: number;
185 readonly consoleMessages: ReadonlyArray<HeadlessChrome.ConsoleMessage>;
186 readonly missingImages?: ReadonlyArray<string>;
188​
189export class HtmlRender extends Context.Service<
190 HtmlRender,
191 {
192 readonly prepare: (html: string) => Effect.Effect<string, HtmlRenderPrepareError>;
193 readonly publish: (
194 input: HtmlRenderSource & {
195 readonly threadId: ThreadId;
196 readonly title: string;
197 readonly height: number;
198 },
199 ) => Effect.Effect<
200 HtmlRenderReference,
201 | HtmlRenderFileError
202 | HtmlRenderFileTooLargeError
203 | HtmlRenderPrepareError
204 | HtmlRenderStoreError
205 >;
206 readonly preview: (
207 input: HtmlRenderSource & {
208 readonly width?: number | undefined;
209 readonly appearance?: ThemeAppearance | undefined;
210 },
211 ) => Effect.Effect<
212 HtmlPreview,
213 | HtmlRenderFileError
214 | HtmlRenderFileTooLargeError
215 | Exclude<HtmlRenderPrepareError, HtmlRenderImagesNotFoundError>
216 | PreviewBrowser.PreviewBrowserInstallError
217 | PreviewBrowser.PreviewBrowserInstallingError
218 | PreviewBrowser.PreviewBrowserUnsupportedError
219 | PreviewBrowserHost.PreviewBrowserHostError
220 | HeadlessChrome.HtmlRenderBrowserError
221 >;
222 }
223>()("t3/htmlRender/HtmlRender") {}
224​
225const IMAGE_MIME_TYPES: Record<string, string> = {
226 png: "image/png",
227 jpg: "image/jpeg",
228 jpeg: "image/jpeg",
229 gif: "image/gif",
230 webp: "image/webp",
231 avif: "image/avif",
232 svg: "image/svg+xml",
233 bmp: "image/bmp",
234 ico: "image/x-icon",
235};
236const IMAGE_EXTENSIONS = Object.keys(IMAGE_MIME_TYPES).join("|");
237const ABSOLUTE_PATH = String.raw`(?:/(?!/)|[a-z]:[\\/])`;
238const LOCAL_IMAGE_PATTERN = new RegExp(
239 String.raw`(["'\x60])(${ABSOLUTE_PATH}(?:(?!\1)[^\r\n]){0,2048}?\.(?:${IMAGE_EXTENSIONS}))(?:(?<=\.svg)#(?:(?!\1)[^\r\n]){0,2048})?\1` +
240 String.raw`|url\(\s*(${ABSOLUTE_PATH}[^\s"'\x60()]{0,2048}?\.(?:${IMAGE_EXTENSIONS}))(?:(?<=\.svg)#[^\s"'\x60()]{0,2048})?\s*\)`,
241 "gid",
242);
243const HTML_TAG_END = String.raw`(?:[^"'<>]|"[^"]*(?:"|$)|'[^']*(?:'|$))*(?:>|$)`;
244const HTML_COMMENT_CONTEXT = new RegExp(
245 String.raw`<!--(?:-?>|[\s\S]*?(?:--!?>|$))|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)(?=[\s/>])${HTML_TAG_END}[\s\S]*?(?:</\1(?=[\s/>])${HTML_TAG_END}|$)|<plaintext(?=[\s/>])[\s\S]*$|<[a-z!/]${HTML_TAG_END}`,
246 "gi",
247);
248​
249const findLocalImages = (html: string) => {
250 const tags = html
251 .matchAll(HTML_COMMENT_CONTEXT)
252 .filter(([source, rawText]) => !rawText && /^<(?!plaintext(?=[\s/>]))[a-z]/i.test(source));
253 let tag = tags.next().value;
254 return Array.from(
255 // Preserve raw text and quoted attributes; blank only comments without shifting offsets.
256 html
257 .replace(HTML_COMMENT_CONTEXT, (source) =>
258 source.startsWith("<!--")
259 ? source.replace(/[^\r\n]+/g, (run) => " ".repeat(run.length))
260 : source,
261 )
262 .matchAll(LOCAL_IMAGE_PATTERN),
263 ).flatMap((match) => {
264 const span = match.indices?.[2] ?? match.indices?.[3];
265 if (!span) return [];
266 const [start, end] = span;
267 const rawPath = html.slice(start, end);
268 while (tag && tag.index + tag[0].length <= start) tag = tags.next().value;
269 const path =
270 tag && start >= tag.index && end <= tag.index + tag[0].length
271 ? decodeHtmlAttribute(rawPath, true)
272 : rawPath;
273 return path !== rawPath && isNetworkPath(path) ? [] : [{ start, end, path }];
274 });
275};
276​
277// Inside a JS string literal a Windows path's backslashes are escaped.
278const filePathFor = (reference: string) =>
279 /^[a-z]:/i.test(reference) ? reference.replaceAll("\\\\", "\\") : reference;
280​
281// Try the literal path first so raw filesystem strings keep working, then percent-decode URL paths.
282const filePathCandidatesFor = (reference: string) => {
283 const literal = filePathFor(reference);
284 const decoded = safeDecodeURIComponent(literal);
285 return decoded !== literal && !decoded.includes("\0") && !isNetworkPath(decoded)
286 ? [literal, decoded]
287 : [literal];
288};
289​
290const dataUriPrefix = (path: string) =>
291 `data:${IMAGE_MIME_TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"};base64,`;
292​
293const latin1 = (bytes: Uint8Array, start: number, end: number) =>
294 String.fromCharCode(...bytes.subarray(start, end));
295​
296// Validate bytes, not filenames, so renamed files or symlinks cannot inline secrets.
297const isImageBytes = (bytes: Uint8Array) => {
298 const head = latin1(bytes, 0, 12);
299 if (
300 head.startsWith("\x89PNG") ||
301 head.startsWith("\xff\xd8\xff") ||
302 head.startsWith("GIF8") ||
303 head.startsWith("\0\0\x01\0") ||
304 (head.startsWith("BM") && head.slice(6, 10) === "\0\0\0\0") ||
305 (head.startsWith("RIFF") && head.slice(8, 12) === "WEBP") ||
306 /^ftyp(?:avif|avis|mif1)$/.test(head.slice(4, 12))
307 ) {
308 return true;
309 }
310 return hasSvgRoot(new TextDecoder().decode(bytes.subarray(0, 4096)));
311};
312​
313const after = (text: string, token: string, from: number) => {
314 const at = text.indexOf(token, from);
315 return at === -1 ? -1 : at + token.length;
316};
317​
318const hasSvgRoot = (text: string) => {
319 let at = 0;
320 while (at !== -1) {
321 while (/\s/.test(text.charAt(at))) at += 1;
322 if (text.startsWith("<?", at)) at = after(text, "?>", at + 2);
323 else if (text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
324 else if (text.slice(at, at + 9).toLowerCase() === "<!doctype") at = afterDoctype(text, at + 9);
325 // XML names are case-sensitive, and only these characters can end one here.
326 else return /^<svg[ \t\r\n/>]/.test(text.slice(at, at + 5));
327 }
328 return false;
329};
330​
331const afterDoctype = (text: string, from: number) => {
332 let inSubset = false;
333 let at = from;
334 while (at !== -1 && at < text.length) {
335 const char = text[at];
336 if (char === '"' || char === "'") at = after(text, char, at + 1);
337 else if (inSubset && text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
338 else if (inSubset && text.startsWith("<?", at)) at = after(text, "?>", at + 2);
339 else if (char === ">" && !inSubset) return at + 1;
340 else {
341 if (char === "[") inSubset = true;
342 else if (char === "]") inSubset = false;
343 at += 1;
344 }
345 }
346 return -1;
347};
348​
349const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (html: string) {
350 const fileSystem = yield* FileSystem.FileSystem;
351 const references = findLocalImages(html);
352 const files = yield* Effect.forEach(
353 [...new Set(references.map((reference) => reference.path))],
354 (path) =>
355 Effect.gen(function* () {
356 for (const candidate of filePathCandidatesFor(path)) {
357 const info = yield* fileSystem.stat(candidate).pipe(Effect.option);
358 if (Option.isSome(info) && info.value.type === "File") {
359 return { path, filePath: candidate, size: Number(info.value.size) };
360 }
361 }
362 return { path, filePath: undefined, size: undefined };
363 }),
364 { concurrency: 8 },
365 );
366 const oversized = files.find((file) => file.size !== undefined && file.size > MAX_IMAGE_BYTES);
367 if (oversized?.size !== undefined) {
368 return yield* new HtmlRenderImageTooLargeError({
369 path: oversized.path,
370 sizeBytes: oversized.size,
371 });
372 }
373 const sizes = new Map(files.map((file) => [file.path, file.size]));
374 const pageBytes = references.reduce((total, reference) => {
375 const size = sizes.get(reference.path);
376 return size === undefined
377 ? total
378 : total +
379 dataUriPrefix(reference.path).length +
380 Math.ceil(size / 3) * 4 -
381 Buffer.byteLength(html.slice(reference.start, reference.end));
382 }, Buffer.byteLength(html));
383 if (pageBytes > MAX_PAGE_BYTES) {
384 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: pageBytes });
385 }
386 // Files can grow after stat; bound each read and stop when accumulated images cannot fit.
387 let readBytes = 0;
388 const images = yield* Effect.forEach(
389 files.filter((file) => file.size !== undefined),
390 (file) =>
391 Effect.gen(function* () {
392 if (file.filePath === undefined) return [];
393 const read = yield* fileSystem
394 .stream(file.filePath, { bytesToRead: MAX_IMAGE_BYTES + 1 })
395 .pipe(Stream.mkUint8Array, Effect.option);
396 if (Option.isNone(read) || !isImageBytes(read.value)) return [];
397 const bytes = read.value;
398 if (bytes.byteLength > MAX_IMAGE_BYTES) {
399 return yield* new HtmlRenderImageTooLargeError({
400 path: file.path,
401 sizeBytes: bytes.byteLength,
402 });
403 }
404 readBytes += Math.ceil(bytes.byteLength / 3) * 4;
405 if (readBytes > MAX_PAGE_BYTES) {
406 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: readBytes });
407 }
408 return [{ path: file.path, bytes }];
409 }),
410 { concurrency: 4 },
411 ).pipe(Effect.map((entries) => entries.flat()));
412 const dataUris = new Map(
413 images.map(
414 (image) =>
415 [
416 image.path,
417 dataUriPrefix(image.path) + Buffer.from(image.bytes).toString("base64"),
418 ] as const,
419 ),
420 );
421 const parts: Array<string> = [];
422 let cursor = 0;
423 for (const reference of references) {
424 const dataUri = dataUris.get(reference.path);
425 if (dataUri === undefined) continue;
426 parts.push(html.slice(cursor, reference.start), dataUri);
427 cursor = reference.end;
428 }
429 parts.push(html.slice(cursor));
430 const inlined = parts.join("");
431 const inlinedBytes = Buffer.byteLength(inlined);
432 if (inlinedBytes > MAX_PAGE_BYTES) {
433 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: inlinedBytes });
434 }
435 return {
436 html: inlined,
437 missing: files.filter((file) => !dataUris.has(file.path)).map((file) => file.path),
438 };
439});
440​
441const MIN_PREVIEW_WIDTH = 240;
442const MAX_PREVIEW_WIDTH = 1_600;
443const MAX_CONCURRENT_BROWSERS = 2;
444const MEASURE_TIMEOUT = "6 seconds";
445​
446const MEASURE_FRAGMENT = htmlRenderThemeFragment(
447 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_MEASURE_FONTS),
448);
449​
450const make = Effect.gen(function* () {
451 const fileSystem = yield* FileSystem.FileSystem;
452 const path = yield* Path.Path;
453 const config = yield* ServerConfig.ServerConfig;
454 const isServerInternalPath = yield* makeIsServerInternalPath;
455 const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
456 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
457 const services = yield* Effect.context<
458 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
459 >();
460 const browsers = yield* Semaphore.make(MAX_CONCURRENT_BROWSERS);
461 // Keep Chrome sandboxed unless explicitly disabled; root must opt out to run.
462 const noSandbox = PreviewBrowserHost.sandboxDisabled(yield* HostProcess.Environment);
463 // sudo resets the environment, so the command has to name this server's home.
464 const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND, [
465 "--base-dir",
466 config.baseDir,
467 ]);
468​
469 const launching = <A>(
470 executable: string,
471 run: (noSandbox: boolean) => Effect.Effect<A, HeadlessChrome.HtmlRenderBrowserError>,
472 ) =>
473 browsers.withPermits(1)(
474 run(noSandbox).pipe(
475 Effect.catchTags({
476 HtmlRenderBrowserError: (error) =>
477 error.output === undefined
478 ? Effect.fail(error)
479 : PreviewBrowserHost.diagnoseLaunchFailure({
480 executable,
481 setupCommand,
482 output: error.output,
483 }).pipe(
484 Effect.provideContext(services),
485 Effect.flatMap((hostError) => Effect.fail(hostError ?? error)),
486 ),
487 }),
488 ),
489 );
490​
491 const measure = Effect.fn("HtmlRender.measure")(
492 function* (html: string) {
493 const executable = yield* previewBrowser.installed;
494 if (Option.isNone(executable)) return undefined;
495 const heights = yield* launching(executable.value, (noSandbox) =>
496 HeadlessChrome.measureHtmlHeights({
497 executable: executable.value,
498 noSandbox,
499 html,
500 widths: HTML_RENDER_MEASURE_WIDTHS,
501 urlFragment: MEASURE_FRAGMENT,
502 }).pipe(Effect.provideContext(services)),
503 ).pipe(
504 Effect.timeoutOrElse({
505 duration: MEASURE_TIMEOUT,
506 orElse: () =>
507 Effect.fail(
508 new HeadlessChrome.HtmlRenderBrowserError({
509 reason: `measuring took longer than ${MEASURE_TIMEOUT}`,
510 }),
511 ),
512 }),
513 );
514 return heights.toSorted(([left], [right]) => left - right);
515 },
516 Effect.catch((cause) =>
517 Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
518 cause,
519 }).pipe(Effect.as(undefined)),
520 ),
521 );
522​
523 const readPageFile = Effect.fn("HtmlRender.readPageFile")(function* (filePath: string) {
524 const unreadable = new HtmlRenderFileError({ path: filePath });
525 if (!path.isAbsolute(filePath) || isNetworkPath(filePath)) return yield* unreadable;
526 // Check the resolved file, so a symlink named .html cannot reach another file.
527 const realPath = yield* fileSystem
528 .realPath(filePath)
529 .pipe(Effect.mapError((cause) => new HtmlRenderFileError({ path: filePath, cause })));
530 if (!HTML_FILE_EXTENSION.test(realPath) || (yield* isServerInternalPath(realPath))) {
531 return yield* unreadable;
532 }
533 // Open without following links and recheck the path, so a link or FIFO swapped in is refused.
534 const html = yield* Effect.scoped(
535 Effect.gen(function* () {
536 const file = yield* openMediaFile(realPath).pipe(
537 Effect.mapError((cause) => new HtmlRenderFileError({ path: filePath, cause })),
538 );
539 // Unlike client reads, the caller may be sandboxed: a second hard link could give any
540 // file an .html name.
541 if (file === null || file.info.nlink !== 1n) return yield* unreadable;
542 if (file.info.size > BigInt(MAX_PAGE_BYTES)) {
543 return yield* new HtmlRenderFileTooLargeError({
544 path: filePath,
545 sizeBytes: Number(file.info.size),
546 });
547 }
548 // One read may return fewer bytes, so fill up to the checked size; growth past it is ignored.
549 return yield* Effect.tryPromise({
550 try: async () => {
551 const buffer = Buffer.alloc(Number(file.info.size));
552 let filled = 0;
553 while (filled < buffer.length) {
554 const { bytesRead } = await file.handle.read(buffer, filled, buffer.length - filled);
555 if (bytesRead === 0) break;
556 filled += bytesRead;
557 }
558 return buffer.toString("utf8", 0, filled);
559 },
560 catch: (cause) => new HtmlRenderFileError({ path: filePath, cause }),
561 });
562 }),
563 );
564 return HTML_DOCUMENT_START.test(html) ? html : yield* unreadable;
565 });
566​
567 const readSource = (input: HtmlRenderSource) =>
568 "path" in input ? readPageFile(input.path) : Effect.succeed(input.html);
569​
570 // The bootstrap goes in first so its head scan never runs over inlined image data.
571 const inline = (html: string) =>
572 inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
573​
574 const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
575 yield* rejectViewportHeight(html);
576 const inlined = yield* inline(html);
577 if (inlined.missing.length > 0) {
578 return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
579 }
580 return inlined.html;
581 });
582​
583 const publish = Effect.fn("HtmlRender.publish")(function* (
584 input: HtmlRenderSource & {
585 readonly threadId: ThreadId;
586 readonly title: string;
587 readonly height: number;
588 },
589 ) {
590 const source = yield* readSource(input);
591 const html = yield* prepare(source);
592 // The `-html` id suffix makes the asset route serve it as a sandboxed text/html document.
593 const attachmentId = createAttachmentId(input.threadId, "html");
594 const filePath =
595 attachmentId === null
596 ? null
597 : resolveAttachmentRelativePath({
598 attachmentsDir: config.attachmentsDir,
599 relativePath: `${attachmentId}.html`,
600 });
601 if (attachmentId === null || filePath === null) {
602 return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
603 }
604 const baseReference: HtmlRenderReference = {
605 attachmentId,
606 title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
607 height: clampHtmlRenderHeight(input.height),
608 };
609 return yield* fileSystem.writeFileString(filePath, html).pipe(
610 Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
611 Effect.uninterruptible,
612 Effect.andThen(measure(html)),
613 Effect.andThen((heights) => {
614 const reference: HtmlRenderReference = {
615 ...baseReference,
616 ...(heights === undefined ? {} : { heights }),
617 };
618 return mcpSessions
619 .recordHtmlRender(
620 input.threadId,
621 {
622 html: source,
623 path: "path" in input ? input.path : undefined,
624 title: input.title,
625 height: input.height,
626 },
627 reference,
628 )
629 .pipe(Effect.as(reference));
630 }),
631 // An interrupted publish must leave neither an attachment nor a recoverable reference.
632 Effect.onError(() =>
633 Effect.all(
634 [
635 fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore),
636 mcpSessions.takeHtmlRender(input.threadId, input, baseReference).pipe(Effect.ignore),
637 ],
638 { discard: true },
639 ),
640 ),
641 );
642 });
643​
644 const preview = Effect.fn("HtmlRender.preview")(function* (
645 input: HtmlRenderSource & {
646 readonly width?: number | undefined;
647 readonly appearance?: ThemeAppearance | undefined;
648 },
649 ) {
650 const width = Math.min(
651 MAX_PREVIEW_WIDTH,
652 Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)),
653 );
654 const appearance = input.appearance ?? "dark";
655 const source = yield* readSource(input);
656 yield* rejectViewportHeight(source);
657 const inlined = yield* inline(source);
658 const executable = yield* previewBrowser.executable;
659 const theme = htmlRenderTheme(
660 appearance === "light" ? T3_CODE_LIGHT_THEME_COLORS : T3_CODE_DARK_THEME_COLORS,
661 appearance,
662 HTML_RENDER_MEASURE_FONTS,
663 );
664 const screenshot = yield* launching(executable, (noSandbox) =>
665 HeadlessChrome.captureHtmlScreenshot({
666 executable,
667 noSandbox,
668 html: inlined.html,
669 width,
670 urlFragment: htmlRenderThemeFragment(theme),
671 appearance,
672 }).pipe(Effect.provideContext(services)),
673 );
674 return {
675 ...screenshot,
676 width,
677 ...(inlined.missing.length === 0 ? {} : { missingImages: inlined.missing }),
678 } satisfies HtmlPreview;
679 });
680​
681 return HtmlRender.of({ prepare, publish, preview });
682});
683​
684export const layer = Layer.effect(HtmlRender, make);