Open History to see the last commit
1import type { ThemeAppearance } from "@t3tools/shared/themePalettes";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Queue from "effect/Queue";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
14import { publicProxy } from "./publicProxy.ts";
15
16export class HtmlRenderBrowserError extends Schema.TaggedError<HtmlRenderBrowserError>()(
17 "HtmlRenderBrowserError",
18 {
19 reason: Schema.String,
20 cause: Schema.optional(Schema.Defect()),
21 output: Schema.optional(Schema.String),
22 exitCode: Schema.optional(Schema.Number),
23 signal: Schema.optional(Schema.String),
24 },
25) {
26 override get message(): string {
27 const exit =
28 this.exitCode !== undefined
29 ? ` (exit code ${this.exitCode})`
30 : this.signal !== undefined
31 ? ` (signal ${this.signal})`
32 : "";
33 return `Headless Chrome could not render the page: ${this.reason}${exit}.`;
34 }
35}
36
37type BrowserFailure = HtmlRenderBrowserError;
38
39export interface ConsoleMessage {
40 readonly level: "log" | "info" | "warning" | "error";
41 readonly text: string;
42}
43
44const MAX_CONSOLE_MESSAGES = 20;
45const MAX_CONSOLE_TEXT_CHARS = 500;
46const VIEWPORT_HEIGHT = 800;
47const MAX_CAPTURE_HEIGHT = 4_000;
48const CAPTURE_TIMEOUT = "20 seconds";
49// Chrome blocks file access; images arrive inlined. Browser-only .localhost permits secure contexts and HTTP resources.
50// publicProxy blocks local networks; pinning the main frame and forbidding popups keeps captures on the page.
51const PAGE_ORIGIN = "http://t3-page.localhost";
52const PAGE_URL = `${PAGE_ORIGIN}/page.html`;
53const PAGE_NAME = "page.html";
54const MEASURE_CONCURRENCY = 3;
55
56const textEncoder = new TextEncoder();
57
58// Pages reach 25 MiB; use Node's encoder.
59const pageBody = (html: string) =>
60 Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1");
61
62const CdpMessage = Schema.fromJsonString(
63 Schema.Struct({
64 id: Schema.optional(Schema.Number),
65 method: Schema.optional(Schema.String),
66 sessionId: Schema.optional(Schema.String),
67 params: Schema.optional(Schema.Unknown),
68 result: Schema.optional(Schema.Unknown),
69 error: Schema.optional(Schema.Struct({ message: Schema.String })),
70 }),
71);
72const decodeCdpMessage = Schema.decodeUnknownOption(CdpMessage);
73const encodeCdpCommand = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
74const RemoteObject = Schema.Struct({
75 type: Schema.String,
76 value: Schema.optional(Schema.Unknown),
77 description: Schema.optional(Schema.String),
78});
79const decodeConsoleApiCalled = Schema.decodeUnknownOption(
80 Schema.Struct({ type: Schema.String, args: Schema.Array(RemoteObject) }),
81);
82const decodeExceptionThrown = Schema.decodeUnknownOption(
83 Schema.Struct({
84 exceptionDetails: Schema.Struct({
85 text: Schema.String,
86 exception: Schema.optional(RemoteObject),
87 }),
88 }),
89);
90const decodeRequestPaused = Schema.decodeUnknownOption(
91 Schema.Struct({
92 requestId: Schema.String,
93 request: Schema.Struct({ url: Schema.String }),
94 frameId: Schema.optional(Schema.String),
95 resourceType: Schema.optional(Schema.String),
96 }),
97);
98const decodeLogEntryAdded = Schema.decodeUnknownOption(
99 Schema.Struct({
100 entry: Schema.Struct({
101 level: Schema.String,
102 text: Schema.String,
103 url: Schema.optional(Schema.String),
104 }),
105 }),
106);
107
108const clipConsoleText = (text: string) => {
109 if (text.length <= MAX_CONSOLE_TEXT_CHARS) return text;
110 // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject.
111 const last = text.charCodeAt(MAX_CONSOLE_TEXT_CHARS - 1);
112 const end =
113 last >= 0xd800 && last <= 0xdbff ? MAX_CONSOLE_TEXT_CHARS - 1 : MAX_CONSOLE_TEXT_CHARS;
114 return `${text.slice(0, end)}…`;
115};
116
117const remoteObjectText = (value: typeof RemoteObject.Type) =>
118 typeof value.value === "string"
119 ? value.value
120 : (value.description ?? (value.value === undefined ? value.type : String(value.value)));
121
122const CONSOLE_LEVELS: Readonly<Record<string, ConsoleMessage["level"]>> = {
123 log: "log",
124 debug: "log",
125 dir: "log",
126 dirxml: "log",
127 table: "log",
128 trace: "log",
129 info: "info",
130 warning: "warning",
131 error: "error",
132 assert: "error",
133};
134
135const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessage | undefined => {
136 if (method === "Runtime.consoleAPICalled") {
137 const event = Option.getOrUndefined(decodeConsoleApiCalled(params));
138 const level = event === undefined ? undefined : CONSOLE_LEVELS[event.type];
139 return event && level ? { level, text: event.args.map(remoteObjectText).join(" ") } : undefined;
140 }
141 if (method === "Runtime.exceptionThrown") {
142 const details = Option.getOrUndefined(decodeExceptionThrown(params))?.exceptionDetails;
143 return details
144 ? { level: "error", text: details.exception?.description ?? details.text }
145 : undefined;
146 }
147 if (method === "Log.entryAdded") {
148 const entry = Option.getOrUndefined(decodeLogEntryAdded(params))?.entry;
149 return entry && (entry.level === "error" || entry.level === "warning")
150 ? { level: entry.level, text: entry.url ? `${entry.text} ${entry.url}` : entry.text }
151 : undefined;
152 }
153 return undefined;
154};
155
156// Wait for fonts and two paint frames to capture late layout.
157const SETTLE_EXPRESSION =
158 "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))";
159// scrollHeight is at least viewport height; use the root box for shorter pages.
160const MEASURE_EXPRESSION =
161 "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
162
163const Ignored = Schema.Unknown;
164const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
165const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
166
167// Effect's spawner names the signal that ended a child only in its error message.
168const EXIT_SIGNAL = /signal: '(SIG[A-Z0-9]+)'/;
169
170interface PageEvents {
171 readonly mainFrameId: string;
172 body: Uint8Array | undefined;
173 loaded: Deferred.Deferred<void, BrowserFailure> | undefined;
174 readonly consoleMessages: Array<ConsoleMessage>;
175 omittedConsoleMessages: number;
176}
177
178// CDP pipe uses fd 3 in, fd 4 out and NUL-delimited JSON.
179const launchBrowser = Effect.fnUntraced(function* (input: {
180 readonly executable: string;
181 readonly noSandbox: boolean;
182 readonly profileDirectory: string;
183}) {
184 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
185 const proxy = yield* publicProxy.pipe(
186 Effect.mapError(
187 (cause) => new HtmlRenderBrowserError({ reason: "the preview proxy could not start", cause }),
188 ),
189 );
190 const outgoing = yield* Queue.unbounded<Uint8Array>();
191 const child = yield* spawner
192 .spawn(
193 ChildProcess.make(
194 input.executable,
195 [
196 "--headless=new",
197 "--remote-debugging-pipe",
198 "--no-first-run",
199 "--no-default-browser-check",
200 "--disable-gpu",
201 "--hide-scrollbars",
202 "--mute-audio",
203 "--block-new-web-contents",
204 `--proxy-server=socks5://127.0.0.1:${proxy.port}`,
205 // Loopback would otherwise skip the proxy.
206 "--proxy-bypass-list=<-loopback>",
207 // WebRTC would otherwise send UDP, which no proxy carries.
208 "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
209 ...(input.noSandbox ? ["--no-sandbox"] : []),
210 `--user-data-dir=${input.profileDirectory}`,
211 "about:blank",
212 ],
213 {
214 stdin: "ignore",
215 stdout: "ignore",
216 stderr: "pipe",
217 forceKillAfter: "2 seconds",
218 additionalFds: {
219 fd3: { type: "input", stream: Stream.fromQueue(outgoing) },
220 fd4: { type: "output" },
221 },
222 },
223 ),
224 )
225 .pipe(
226 Effect.mapError(
227 (cause) =>
228 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
229 ),
230 // Node throws some spawn errors synchronously, such as `spawn UNKNOWN`
231 // when policy blocks the executable; `mapError` cannot catch those.
232 Effect.catchDefect((cause) =>
233 Effect.fail(
234 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
235 ),
236 ),
237 );
238
239 let stderrTail = "";
240 const stderrReader = yield* child.stderr.pipe(
241 Stream.decodeText(),
242 Stream.runForEach((text) =>
243 Effect.sync(() => {
244 stderrTail = (stderrTail + text).slice(-2_048);
245 }),
246 ),
247 Effect.ignore,
248 Effect.forkScoped,
249 );
250
251 const pending = new Map<
252 number,
253 { readonly method: string; readonly reply: Deferred.Deferred<unknown, BrowserFailure> }
254 >();
255 const pages = new Map<string, PageEvents>();
256 let disconnected: BrowserFailure | undefined;
257 let nextId = 0;
258
259 const post = (method: string, params: Record<string, unknown>, sessionId?: string) =>
260 Queue.offer(
261 outgoing,
262 new TextEncoder().encode(
263 `${encodeCdpCommand({ id: ++nextId, method, params, sessionId })}\0`,
264 ),
265 ).pipe(Effect.asVoid);
266
267 // Queue shared body bytes between JSON halves to avoid copies across capture widths.
268 const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) =>
269 Queue.offerAll(outgoing, [
270 textEncoder.encode(
271 `{"id":${++nextId},"sessionId":${JSON.stringify(sessionId)},"method":"Fetch.fulfillRequest","params":{"requestId":${JSON.stringify(requestId)},"responseCode":200,"responseHeaders":[{"name":"Content-Type","value":"text/html; charset=utf-8"}],"body":"`,
272 ),
273 body,
274 textEncoder.encode('"}}\0'),
275 ]).pipe(Effect.asVoid);
276
277 // Incoming messages share the session span; frame acknowledgements are frequent.
278 const receive = Effect.fnUntraced(function* (raw: string) {
279 const message = Option.getOrUndefined(decodeCdpMessage(raw));
280 if (message?.id !== undefined) {
281 const waiter = pending.get(message.id);
282 pending.delete(message.id);
283 if (!waiter) return yield* Effect.void;
284 return yield* message.error
285 ? Deferred.fail(
286 waiter.reply,
287 new HtmlRenderBrowserError({
288 reason: `${waiter.method} failed`,
289 cause: message.error.message,
290 }),
291 )
292 : Deferred.succeed(waiter.reply, message.result);
293 }
294 const sessionId = message?.sessionId;
295 const page = sessionId === undefined ? undefined : pages.get(sessionId);
296 if (sessionId === undefined || !page || !message?.method) return yield* Effect.void;
297 if (message.method === "Page.loadEventFired") {
298 return yield* page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
299 }
300 if (message.method === "Fetch.requestPaused") {
301 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
302 if (!paused) return yield* Effect.void;
303 const body = page.body;
304 const url = paused.request.url.split("#", 1)[0]!;
305 if (url === PAGE_URL && body !== undefined) {
306 return yield* fulfillPage(sessionId, paused.requestId, body);
307 }
308 // Subframes may show other sites covered by Local Network Access; the main frame stays on T3's page.
309 const otherSiteFrame =
310 paused.resourceType === "Document" &&
311 paused.frameId !== page.mainFrameId &&
312 !url.startsWith(`${PAGE_ORIGIN}/`);
313 return yield* otherSiteFrame
314 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
315 : post(
316 "Fetch.failRequest",
317 { requestId: paused.requestId, errorReason: "AccessDenied" },
318 sessionId,
319 );
320 }
321 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
322 if (!consoleMessage) return yield* Effect.void;
323 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
324 page.omittedConsoleMessages += 1;
325 return yield* Effect.void;
326 }
327 page.consoleMessages.push({
328 level: consoleMessage.level,
329 text: clipConsoleText(consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME)),
330 });
331 return yield* Effect.void;
332 });
333
334 // Startup aborts close the pipe; let stderr drain to recover the reason.
335 const disconnect = Effect.gen(function* () {
336 yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore);
337 const exit = yield* child.exitCode.pipe(
338 Effect.map((code): { exitCode?: number; signal?: string; cause?: unknown } => ({
339 exitCode: code,
340 })),
341 Effect.catch((error) => {
342 const signal = EXIT_SIGNAL.exec(String(error.cause))?.[1];
343 return Effect.succeed(signal === undefined ? { cause: error } : { signal, cause: error });
344 }),
345 Effect.timeoutOption("1 second"),
346 );
347 const error = new HtmlRenderBrowserError({
348 reason: "the browser exited unexpectedly",
349 output: stderrTail,
350 ...Option.getOrElse(exit, () => ({})),
351 });
352 disconnected = error;
353 const waiters = [...pending.values()];
354 pending.clear();
355 yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true });
356 yield* Effect.forEach(
357 pages.values(),
358 (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void),
359 { discard: true },
360 );
361 });
362
363 // Chunks may split messages; screenshot replies span many chunks.
364 let partial: Array<string> = [];
365 yield* child.getOutputFd(4).pipe(
366 Stream.decodeText(),
367 Stream.runForEach((text) => {
368 const complete: Array<string> = [];
369 let start = 0;
370 for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) {
371 partial.push(text.slice(start, end));
372 complete.push(partial.join(""));
373 partial = [];
374 start = end + 1;
375 }
376 if (start < text.length) partial.push(text.slice(start));
377 return Effect.forEach(complete, receive, { discard: true });
378 }),
379 Effect.ignore,
380 Effect.andThen(disconnect),
381 Effect.forkScoped,
382 );
383
384 // Signals can miss a confined browser (AppArmor in LXC), so ask it to quit first.
385 // Runs before the spawn's release, which still signals a browser that stays up.
386 yield* Effect.addFinalizer(() =>
387 disconnected
388 ? Effect.void
389 : post("Browser.close", {}).pipe(
390 Effect.andThen(child.exitCode),
391 Effect.timeout("2 seconds"),
392 Effect.ignore,
393 ),
394 );
395
396 const send = Effect.fn("headlessChrome.send")(function* <A>(
397 method: string,
398 params: Record<string, unknown>,
399 result: Schema.Decoder<A>,
400 sessionId?: string,
401 ) {
402 if (disconnected) return yield* disconnected;
403 const id = ++nextId;
404 const reply = yield* Deferred.make<unknown, BrowserFailure>();
405 pending.set(id, { method, reply });
406 const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
407 yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
408 return yield* Deferred.await(reply).pipe(
409 Effect.flatMap(Schema.decodeUnknownEffect(result)),
410 Effect.mapError((error) =>
411 error._tag === "HtmlRenderBrowserError"
412 ? error
413 : new HtmlRenderBrowserError({
414 reason: `${method} returned an unexpected result`,
415 cause: error,
416 }),
417 ),
418 );
419 });
420
421 const openPage = Effect.fnUntraced(function* (width: number, appearance: ThemeAppearance) {
422 const { targetId } = yield* send(
423 "Target.createTarget",
424 { url: "about:blank" },
425 Schema.Struct({ targetId: Schema.String }),
426 );
427 const { sessionId } = yield* send(
428 "Target.attachToTarget",
429 { targetId, flatten: true },
430 Schema.Struct({ sessionId: Schema.String }),
431 );
432 const events: PageEvents = {
433 // A page target's id is its main frame's id.
434 mainFrameId: targetId,
435 body: undefined,
436 loaded: undefined,
437 consoleMessages: [],
438 omittedConsoleMessages: 0,
439 };
440 pages.set(sessionId, events);
441 yield* send("Page.enable", {}, Ignored, sessionId);
442 yield* send("Runtime.enable", {}, Ignored, sessionId);
443 yield* send("Log.enable", {}, Ignored, sessionId);
444 yield* send(
445 "Emulation.setEmulatedMedia",
446 { features: [{ name: "prefers-color-scheme", value: appearance }] },
447 Ignored,
448 sessionId,
449 );
450 // Previews have no use for WebRTC, whose ICE servers can make the browser
451 // resolve names outside the proxy. Runs before page scripts in every frame.
452 yield* send(
453 "Page.addScriptToEvaluateOnNewDocument",
454 {
455 source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;",
456 runImmediately: true,
457 },
458 Ignored,
459 sessionId,
460 );
461 // Intercept T3's page and all document navigations to keep the main frame on it.
462 yield* send(
463 "Fetch.enable",
464 {
465 patterns: [
466 { urlPattern: `${PAGE_ORIGIN}/*` },
467 { urlPattern: "*", resourceType: "Document" },
468 ],
469 },
470 Ignored,
471 sessionId,
472 );
473 yield* send(
474 "Emulation.setDeviceMetricsOverride",
475 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
476 Ignored,
477 sessionId,
478 );
479
480 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
481 const loaded = yield* Deferred.make<void, BrowserFailure>();
482 events.body = body;
483 events.loaded = loaded;
484 const navigation = yield* send(
485 "Page.navigate",
486 { url: `${PAGE_URL}${urlFragment}` },
487 Navigation,
488 sessionId,
489 );
490 if (navigation.errorText) {
491 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
492 }
493 yield* Deferred.await(loaded);
494 yield* send(
495 "Runtime.evaluate",
496 { expression: SETTLE_EXPRESSION, awaitPromise: true },
497 Ignored,
498 sessionId,
499 );
500 const measured = yield* send(
501 "Runtime.evaluate",
502 { expression: MEASURE_EXPRESSION, returnByValue: true },
503 Measured,
504 sessionId,
505 );
506 return Math.max(0, Math.ceil(measured.result.value));
507 });
508
509 const screenshot = (height: number) =>
510 send(
511 "Page.captureScreenshot",
512 {
513 format: "png",
514 captureBeyondViewport: true,
515 clip: { x: 0, y: 0, width, height, scale: 1 },
516 },
517 Schema.Struct({ data: Schema.String }),
518 sessionId,
519 ).pipe(Effect.map(({ data }) => data));
520
521 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
522 events.omittedConsoleMessages === 0
523 ? [...events.consoleMessages]
524 : [
525 ...events.consoleMessages,
526 {
527 level: "warning",
528 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
529 },
530 ];
531
532 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
533 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
534 Effect.ignore,
535 );
536
537 return { load, screenshot, consoleMessages, close };
538 });
539
540 // Each capture opens one page per browser, so this note belongs to that page alone.
541 const fakeIpNote = (): ReadonlyArray<ConsoleMessage> =>
542 [...proxy.fakeIpHosts].map(([host, address]) => ({
543 level: "warning",
544 text: clipConsoleText(
545 `DNS returned blocked 198.18.0.0/15 addresses, which may come from Clash or Mihomo fake-IP DNS. Inline the resource, add its host to fake-ip-filter, or switch DNS to redir-host. Affected host: ${host} (${address})`,
546 ),
547 }));
548
549 return { openPage, fakeIpNote };
550});
551
552const scratchDirectory = Effect.gen(function* () {
553 const fileSystem = yield* FileSystem.FileSystem;
554 return yield* Effect.acquireRelease(
555 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
556 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
557 ).pipe(
558 Effect.mapError(
559 (cause) =>
560 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
561 ),
562 );
563});
564
565export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
566 function* (input: {
567 readonly executable: string;
568 readonly noSandbox: boolean;
569 readonly html: string;
570 readonly width: number;
571 readonly urlFragment: string;
572 readonly appearance: ThemeAppearance;
573 }) {
574 const path = yield* Path.Path;
575 const directory = yield* scratchDirectory;
576 const browser = yield* launchBrowser({
577 executable: input.executable,
578 noSandbox: input.noSandbox,
579 profileDirectory: path.join(directory, "profile"),
580 });
581 const page = yield* browser.openPage(input.width, input.appearance);
582 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
583 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
584 const png = yield* page.screenshot(capturedHeight);
585 return {
586 png,
587 contentHeight,
588 capturedHeight,
589 consoleMessages: [...page.consoleMessages(), ...browser.fakeIpNote()],
590 };
591 },
592 Effect.scoped,
593 Effect.timeoutOrElse({
594 duration: CAPTURE_TIMEOUT,
595 orElse: () =>
596 Effect.fail(
597 new HtmlRenderBrowserError({
598 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
599 }),
600 ),
601 }),
602);
603
604/** Fresh load per width, since pages may lay out only at load. */
605export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
606 readonly executable: string;
607 readonly noSandbox: boolean;
608 readonly html: string;
609 readonly widths: ReadonlyArray<number>;
610 readonly urlFragment: string;
611}) {
612 const path = yield* Path.Path;
613 const directory = yield* scratchDirectory;
614 const browser = yield* launchBrowser({
615 executable: input.executable,
616 noSandbox: input.noSandbox,
617 profileDirectory: path.join(directory, "profile"),
618 });
619 const body = pageBody(input.html);
620 return yield* Effect.forEach(
621 input.widths,
622 (width) =>
623 browser.openPage(width, "dark").pipe(
624 Effect.flatMap((page) =>
625 page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
626 ),
627 Effect.map((height) => [width, height] as const),
628 ),
629 { concurrency: MEASURE_CONCURRENCY },
630 );
631}, Effect.scoped);