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

HtmlRender.ts

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