Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - plain local servers stand in for LAN services.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { describe, expect, it } from "@effect/vitest";
4import { ThreadId } from "@t3tools/contracts";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import {
7 HTML_RENDER_MEASURE_FONTS,
8 HTML_RENDER_MEASURE_WIDTHS,
9 htmlRenderTheme,
10} from "@t3tools/shared/htmlRender";
11import { T3_CODE_DARK_THEME_COLORS } from "@t3tools/shared/themePalettes";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Base64 from "effect/encoding/Base64";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as NodeDgram from "node:dgram";
21import * as NodeHttp from "node:http";
22import * as NodeURL from "node:url";
23
24import { resolveAttachmentPathById } from "../attachmentStore.ts";
25import * as ServerConfig from "../config.ts";
26import * as HtmlRender from "./HtmlRender.ts";
27import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
28
29// Real-browser tests run only when this names a chrome-headless-shell, for
30// example one T3 installed under <T3 home>/tools/chrome-headless-shell.
31const TEST_BROWSER_ENV = "T3CODE_TEST_HEADLESS_SHELL";
32
33const layerHtmlRender = (
34 executable?: string,
35 installed: Effect.Effect<Option.Option<string>> = Effect.succeed(
36 Option.fromUndefinedOr(executable),
37 ),
38) =>
39 HtmlRender.layer.pipe(
40 Layer.provide(
41 Layer.succeed(
42 PreviewBrowser.PreviewBrowser,
43 PreviewBrowser.PreviewBrowser.of({
44 executable:
45 executable === undefined
46 ? Effect.die("This test has no preview browser.")
47 : Effect.succeed(executable),
48 installed,
49 }),
50 ),
51 ),
52 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-html-render-" })),
53 Layer.provideMerge(NodeServices.layer),
54 );
55const layerTest = layerHtmlRender();
56
57const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
58
59/**
60 * A stand-in browser that reads T3's first command off its debugging pipe,
61 * then runs `exit`. Reading it first keeps the pipe from resetting.
62 */
63const exitingBrowser = (exit: string) =>
64 Effect.gen(function* () {
65 const fileSystem = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-exiting-browser-" });
68 const executable = path.join(directory, "chrome-headless-shell");
69 yield* fileSystem.writeFileString(
70 executable,
71 [
72 `#!${process.execPath}`,
73 `new (process.getBuiltinModule("node:net").Socket)({ fd: 3 }).on("data", (chunk) => { if (chunk.includes(0)) { ${exit} } });`,
74 ].join("\n"),
75 );
76 yield* fileSystem.chmod(executable, 0o755);
77 return executable;
78 });
79
80const previewError = (executable: string) =>
81 Effect.gen(function* () {
82 const htmlRender = yield* HtmlRender.HtmlRender;
83 return yield* htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip);
84 }).pipe(Effect.provide(layerHtmlRender(executable)));
85
86describe("HtmlRender", () => {
87 it.effect("inlines local images by absolute path and leaves URLs and relative paths alone", () =>
88 Effect.gen(function* () {
89 const fileSystem = yield* FileSystem.FileSystem;
90 const path = yield* Path.Path;
91 const htmlRender = yield* HtmlRender.HtmlRender;
92 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
93 const png = path.join(directory, "shot.png");
94 const svg = path.join(directory, "logo.svg");
95 yield* fileSystem.writeFile(png, PNG_BYTES);
96 yield* fileSystem.writeFileString(svg, "<svg/>");
97 const kept = [
98 "https://example.com/a.png",
99 "//cdn.example.com/b.png",
100 "./c.png",
101 "data:image/png;base64,AAAA",
102 ];
103
104 const prepared = yield* htmlRender.prepare(
105 [
106 "<!doctype html><html><head><title>Shots</title></head><body>",
107 `<img src="${png}"><div style="background:url(${svg})"></div>`,
108 `<script>const shots = ['${png}', \`${svg}\`];</script>`,
109 ...kept.map((src) => `<img src="${src}">`),
110 "</body></html>",
111 ].join(""),
112 );
113
114 const pngUri = `data:image/png;base64,${Base64.encode(PNG_BYTES)}`;
115 const svgUri = `data:image/svg+xml;base64,${Base64.encode("<svg/>")}`;
116 expect(prepared).toContain(`<img src="${pngUri}">`);
117 expect(prepared).toContain(`url(${svgUri})`);
118 expect(prepared).toContain(`['${pngUri}', \`${svgUri}\`]`);
119 expect(prepared).not.toContain(directory);
120 for (const src of kept) expect(prepared).toContain(`<img src="${src}">`);
121 // The theme bootstrap opens the head, ahead of the page's own markup.
122 expect(prepared.indexOf("<head>")).toBeLessThan(prepared.indexOf('<style id="t3-theme">'));
123 expect(prepared.indexOf('<style id="t3-theme">')).toBeLessThan(prepared.indexOf("<title>"));
124 }).pipe(Effect.provide(layerTest)),
125 );
126
127 it.effect("inlines an SVG behind processing instructions and a doctype subset", () =>
128 Effect.gen(function* () {
129 const fileSystem = yield* FileSystem.FileSystem;
130 const path = yield* Path.Path;
131 const htmlRender = yield* HtmlRender.HtmlRender;
132 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
133 const svg = path.join(directory, "styled.svg");
134 const source = [
135 '<?xml version="1.0"?>',
136 '<?xml-stylesheet href="theme.css"?>',
137 '<!DOCTYPE svg [ <!ENTITY fill "red"> ]>',
138 '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>',
139 ].join("\n");
140 yield* fileSystem.writeFileString(svg, source);
141
142 const prepared = yield* htmlRender.prepare(`<img src="${svg}">`);
143
144 expect(prepared).toContain(`data:image/svg+xml;base64,${Base64.encode(source)}`);
145 }).pipe(Effect.provide(layerTest)),
146 );
147
148 it.effect("lists every local image it cannot read", () =>
149 Effect.gen(function* () {
150 const fileSystem = yield* FileSystem.FileSystem;
151 const path = yield* Path.Path;
152 const htmlRender = yield* HtmlRender.HtmlRender;
153 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
154 const folder = path.join(directory, "folder.png");
155 yield* fileSystem.makeDirectory(folder);
156 const missing = path.join(directory, "missing.jpg");
157 // Named like an image, but a symlink or renamed file must not carry other data.
158 const secret = path.join(directory, "secret.png");
159 yield* fileSystem.writeFileString(secret, "API_KEY=abc123");
160 const report = path.join(directory, "report.svg");
161 yield* fileSystem.writeFileString(report, "<!doctype html><body><svg></svg>API_KEY=abc123");
162 // An <svg> inside a quoted entity, and a prolog shaped to stall a backtracking matcher.
163 const config = path.join(directory, "config.svg");
164 yield* fileSystem.writeFileString(
165 config,
166 '<!DOCTYPE config [<!ENTITY a "a"><!ENTITY b "]><svg/>">]><config>API_KEY=abc123</config>',
167 );
168 const stalling = path.join(directory, "stalling.svg");
169 yield* fileSystem.writeFileString(stalling, `${"<?p?>".repeat(40)}<config><svg/></config>`);
170 const unclosed = path.join(directory, "unclosed.svg");
171 yield* fileSystem.writeFileString(unclosed, '<!DOCTYPE svg [<!ENTITY a "x><svg/>');
172 // Roots named SVG or svgé are other elements.
173 const upper = path.join(directory, "upper.svg");
174 yield* fileSystem.writeFileString(upper, "<SVG/>API_KEY=abc123");
175 const longer = path.join(directory, "longer.svg");
176 yield* fileSystem.writeFileString(longer, "<svg\u00e9/>API_KEY=abc123");
177
178 const error = yield* htmlRender
179 .prepare(
180 `<img src="${missing}"><img src='${folder}'><img src="C:\\nope\\shot.webp"><img src="${secret}"><img src="${report}"><img src="${config}"><img src="${stalling}"><img src="${unclosed}"><img src="${upper}"><img src="${longer}">`,
181 )
182 .pipe(Effect.flip);
183
184 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderImagesNotFoundError);
185 expect(error._tag === "HtmlRenderImagesNotFoundError" && error.paths).toEqual([
186 missing,
187 folder,
188 "C:\\nope\\shot.webp",
189 secret,
190 report,
191 config,
192 stalling,
193 unclosed,
194 upper,
195 longer,
196 ]);
197 }).pipe(Effect.provide(layerTest)),
198 );
199
200 it.effect("publishes the prepared page as an html thread attachment", () =>
201 Effect.gen(function* () {
202 const fileSystem = yield* FileSystem.FileSystem;
203 const config = yield* ServerConfig.ServerConfig;
204 const htmlRender = yield* HtmlRender.HtmlRender;
205
206 const reference = yield* htmlRender.publish({
207 threadId: ThreadId.make("thread-html-render"),
208 html: "<p>Quarterly revenue</p>",
209 title: " Revenue ",
210 height: 9_000,
211 });
212
213 // Without an installed preview browser the page publishes unmeasured.
214 expect(reference).toEqual({
215 attachmentId: expect.any(String),
216 title: "Revenue",
217 height: 2_000,
218 });
219 const stored = resolveAttachmentPathById({
220 attachmentsDir: config.attachmentsDir,
221 attachmentId: reference.attachmentId,
222 });
223 expect(stored?.endsWith(".html")).toBe(true);
224 const html = yield* fileSystem.readFileString(stored ?? "");
225 expect(html).toContain('<style id="t3-theme">');
226 expect(html).toContain("<p>Quarterly revenue</p>");
227 }).pipe(Effect.provide(layerTest)),
228 );
229
230 it.effect("removes the page when publishing is interrupted", () =>
231 Effect.gen(function* () {
232 const measuring = yield* Deferred.make<void>();
233 yield* Effect.gen(function* () {
234 const fileSystem = yield* FileSystem.FileSystem;
235 const config = yield* ServerConfig.ServerConfig;
236 const htmlRender = yield* HtmlRender.HtmlRender;
237 const storedPages = fileSystem
238 .readDirectory(config.attachmentsDir, { recursive: true })
239 .pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
240
241 const publishing = yield* htmlRender
242 .publish({
243 threadId: ThreadId.make("thread-html-cancel"),
244 html: "<p>x</p>",
245 title: "X",
246 height: 200,
247 })
248 .pipe(Effect.forkChild);
249 yield* Deferred.await(measuring);
250 expect(yield* storedPages).toHaveLength(1);
251 yield* Fiber.interrupt(publishing);
252 expect(yield* storedPages).toEqual([]);
253 }).pipe(
254 Effect.provide(
255 layerHtmlRender(
256 undefined,
257 Deferred.succeed(measuring, undefined).pipe(Effect.andThen(Effect.never)),
258 ),
259 ),
260 );
261 }),
262 );
263
264 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
265 "when the browser exits before rendering",
266 () => {
267 it.live("reports its exit code and keeps what it printed out of the message", () =>
268 Effect.gen(function* () {
269 const executable = yield* exitingBrowser(
270 `process.stderr.write("[WARNING:bus.cc] Failed to connect to the bus\\n[FATAL:shared_memory.cc] Check failed: /dev/shm is not writable\\n"); process.exit(3);`,
271 );
272
273 const error = yield* previewError(executable);
274
275 expect(error.message).toBe(
276 "Headless Chrome could not render the page: the browser exited unexpectedly (exit code 3).",
277 );
278 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
279 );
280
281 it.live("reports the signal that ended it", () =>
282 Effect.gen(function* () {
283 const executable = yield* exitingBrowser(`process.kill(process.pid, "SIGKILL");`);
284
285 const error = yield* previewError(executable);
286
287 expect(error.message).toBe(
288 "Headless Chrome could not render the page: the browser exited unexpectedly (signal SIGKILL).",
289 );
290 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
291 );
292 },
293 );
294
295 it.live(
296 "screenshots the page in headless Chrome with the requested theme and every console level",
297 (ctx) =>
298 Effect.gen(function* () {
299 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
300 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
301 yield* Effect.gen(function* () {
302 const htmlRender = yield* HtmlRender.HtmlRender;
303 const preview = yield* htmlRender.preview({
304 html: [
305 '<!doctype html><html><head></head><body><div id="page" tabindex="0" style="height:300px;background:var(--accent)"></div>',
306 '<img src="/nonexistent/t3-missing.png" hidden>',
307 "<script>",
308 "const root = getComputedStyle(document.documentElement);",
309 'const page = document.getElementById("page"); page.focus();',
310 'const focus = getComputedStyle(page); console.log("focus", focus.outlineWidth, focus.outlineOffset, page.getBoundingClientRect().width, document.documentElement.scrollWidth);',
311 'console.log("ready", 3); console.info(root.getPropertyValue("--font-sans"));',
312 'console.warn(root.getPropertyValue("--background")); console.error("boom");',
313 "</script>",
314 '<script>throw new Error("broken chart");</script>',
315 "</body></html>",
316 ].join(""),
317 width: 400,
318 appearance: "dark",
319 });
320
321 const png = Buffer.from(preview.png, "base64");
322 expect(png.readUInt32BE(0)).toBe(0x89504e47);
323 expect([png.readUInt32BE(16), png.readUInt32BE(20)]).toEqual([400, 300]);
324 expect(preview).toMatchObject({
325 width: 400,
326 contentHeight: 300,
327 capturedHeight: 300,
328 missingImages: ["/nonexistent/t3-missing.png"],
329 });
330 // Headless Chrome prefers light, so a dark background proves the theme fragment applied.
331 expect(preview.consoleMessages).toEqual(
332 expect.arrayContaining([
333 { level: "log", text: "ready 3" },
334 { level: "log", text: "focus 2px -2px 400 400" },
335 { level: "info", text: HTML_RENDER_MEASURE_FONTS.sans },
336 {
337 level: "warning",
338 text: htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark").variables["--background"],
339 },
340 { level: "error", text: "boom" },
341 {
342 level: "error",
343 text: expect.stringMatching(/^Error: broken chart\n\s+at page\.html:1:\d+$/),
344 },
345 ]),
346 );
347 }).pipe(Effect.provide(layerHtmlRender(executable)));
348 }),
349 30_000,
350 );
351
352 it.live(
353 "keeps every local file but the page itself out of the browser",
354 (ctx) =>
355 Effect.gen(function* () {
356 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
357 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
358 yield* Effect.gen(function* () {
359 const fileSystem = yield* FileSystem.FileSystem;
360 const path = yield* Path.Path;
361 const htmlRender = yield* HtmlRender.HtmlRender;
362 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" });
363 const secret = path.join(directory, "secret.js");
364 yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";');
365 const secretUrl = NodeURL.pathToFileURL(secret).href;
366
367 const preview = yield* htmlRender.preview({
368 html: [
369 `<script src="${secretUrl}"></script>`,
370 `<iframe src="${secretUrl}" onload="console.log('frame loaded')"></iframe>`,
371 '<script>addEventListener("load", () => console.log("secret:", window.secret ?? "none"));</script>',
372 ].join(""),
373 });
374
375 const texts = preview.consoleMessages.map((message) => message.text);
376 expect(texts).toContain("secret: none");
377 expect(texts.join(" ")).not.toContain("abc123");
378 }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable)));
379 }),
380 30_000,
381 );
382
383 it.live(
384 "keeps the page off this machine's local network",
385 (ctx) =>
386 Effect.gen(function* () {
387 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
388 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
389 // The page's connections go through a proxy that only reaches public
390 // addresses, and WebRTC is gone. Each line below is a way out that
391 // Chrome's own Local Network Access does not stop on its own.
392 const requests: Array<string> = [];
393 const server = yield* Effect.acquireRelease(
394 Effect.callback<NodeHttp.Server>((resume) => {
395 const listening = NodeHttp.createServer((request, response) => {
396 requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`);
397 response.end("<p>LOCAL</p>");
398 });
399 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
400 }),
401 (listening) =>
402 Effect.callback<void>((resume) => {
403 listening.close(() => resume(Effect.void));
404 }),
405 );
406 const datagrams: Array<string> = [];
407 const udp = yield* Effect.acquireRelease(
408 Effect.callback<NodeDgram.Socket>((resume) => {
409 const socket = NodeDgram.createSocket("udp4");
410 socket.on("message", (message) => datagrams.push(message.toString("hex")));
411 socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket)));
412 }),
413 (socket) =>
414 Effect.callback<void>((resume) => {
415 socket.close(() => resume(Effect.void));
416 }),
417 );
418 const address = server.address();
419 const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
420 const stun = `stun:127.0.0.1:${udp.address().port}`;
421 yield* Effect.gen(function* () {
422 const htmlRender = yield* HtmlRender.HtmlRender;
423 yield* htmlRender.preview({
424 html: [
425 `<img src="${origin}/x.png"><iframe src="${origin}/"></iframe>`,
426 `<script type="speculationrules">{"prefetch":[{"source":"list","urls":["${origin}/prefetch"]}]}</script>`,
427 `<script>fetch("${origin}/").catch(() => {}); new WebSocket("ws${origin.slice(4)}/socket");`,
428 `try { const peer = new RTCPeerConnection({ iceServers: [{ urls: "${stun}" }] });`,
429 `peer.createDataChannel("x"); peer.createOffer().then((offer) => peer.setLocalDescription(offer));`,
430 `} catch {}`,
431 `window.open("${origin}/popup"); location.href = "${origin}/navigate";</script>`,
432 ].join(""),
433 });
434 }).pipe(Effect.provide(layerHtmlRender(executable)));
435 expect(requests).toEqual([]);
436 expect(datagrams).toEqual([]);
437 }).pipe(Effect.scoped),
438 30_000,
439 );
440
441 it.live(
442 "measures a published page at every client width with a fresh load each",
443 (ctx) =>
444 Effect.gen(function* () {
445 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
446 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
447 yield* Effect.gen(function* () {
448 const htmlRender = yield* HtmlRender.HtmlRender;
449 // Like a D3 chart, the page sizes itself from the width once, at load.
450 const reference = yield* htmlRender.publish({
451 threadId: ThreadId.make("thread-html-measure"),
452 html: '<div id="chart"></div><script>document.getElementById("chart").style.height = innerWidth / 2 + "px";</script>',
453 title: "Chart",
454 height: 600,
455 });
456
457 expect(reference.heights).toEqual(
458 HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]),
459 );
460 }).pipe(Effect.provide(layerHtmlRender(executable)));
461 }),
462 30_000,
463 );
464});