@open-pencil/html-engine 0.0.0-stage → 0.17.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Danila Poyarkov and OpenPencil contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @open-pencil/html-engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ HTML laid out as a browser lays it out, without a browser: [Blitz](https://github.com/DioxusLabs/blitz) (Stylo for style, Taffy for layout, Parley for text) compiled to WebAssembly. It captures every element's border box and computed styles (properties with a fixed initial value only when they differ from it, and always the ones whose initial value depends on the element or is inherited, such as `display`, `color`, sizes, and fonts), an inline element's boxes on each line, the text lines its text sets with their runs, and the text of every text node.
4
+
5
+ ```ts
6
+ import { loadHTMLEngine } from '@open-pencil/html-engine'
7
+
8
+ const engine = await loadHTMLEngine()
9
+ engine.addFont(await Bun.file('Inter.ttf').bytes())
10
+ engine.setGenericFamily('sans-serif', ['Inter'])
11
+
12
+ const capture = await engine.layout(html, {
13
+ baseURL: 'https://example.com/',
14
+ viewport: { width: 1440, height: 900 },
15
+ // The engine aborts `signal` when a request runs past its deadline.
16
+ fetch: async (url, signal) => {
17
+ const response = await fetch(url, { signal })
18
+ return response.ok ? { url: response.url, bytes: await response.bytes() } : null
19
+ }
20
+ })
21
+ ```
22
+
23
+ `createHTMLEngineRuntime()` is a `CSSRuntime` for `@open-pencil/dom-css`: it gives each element its computed style and, when asked, the box, inline fragments, and text lines a browser runtime records, so HTML imports headless as it does in a browser. Its `onFontFace` option receives each font the page's `@font-face` rules load, with the family, weight, and style the rule declares, so a host can draw the page's text in it.
24
+
25
+ The engine fetches nothing itself: the host answers each stylesheet, font, and image the document asks for, or declines it. Raster images are laid out at their pixel size, read from their headers. The engine has no fonts of its own, so the host registers the ones layout may use.
26
+
27
+ The module, `wasm/html-engine.wasm`, is built from the Rust crate in `crate/` by `bun run build`, which needs Rust; rustup installs the toolchain `rust-toolchain.toml` pins. A host that serves the module somewhere other than beside this package sets `setHTMLEngineLocator`. The published package carries `wasm/THIRD-PARTY-NOTICES.md`, which the release writes with the licenses and sources of the Rust crates compiled into the module.
@@ -0,0 +1,350 @@
1
+ import * as v from "valibot";
2
+ //#region src/images.ts
3
+ function ascii(bytes, at, length) {
4
+ return String.fromCharCode(...bytes.subarray(at, at + length));
5
+ }
6
+ function webpSize(bytes, view) {
7
+ const chunk = ascii(bytes, 12, 4);
8
+ if (chunk === "VP8 ") return [view.getUint16(26, true) & 16383, view.getUint16(28, true) & 16383];
9
+ if (chunk === "VP8L") {
10
+ const bits = view.getUint32(21, true);
11
+ return [(bits & 16383) + 1, (bits >> 14 & 16383) + 1];
12
+ }
13
+ if (chunk === "VP8X") return [1 + (bytes[24] | bytes[25] << 8 | bytes[26] << 16), 1 + (bytes[27] | bytes[28] << 8 | bytes[29] << 16)];
14
+ return null;
15
+ }
16
+ /** Start-of-frame markers, which carry the size; C4, C8, and CC are other segments. */
17
+ function isStartOfFrame(marker) {
18
+ return marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
19
+ }
20
+ const APP1 = 225;
21
+ const ORIENTATION_TAG = 274;
22
+ /**
23
+ * The Exif Orientation in an APP1 segment starting at `at`: 1 when the Exif data names none,
24
+ * and null when the segment is not Exif, such as XMP, which says nothing about orientation. Orientations 5
25
+ * to 8 turn the image a quarter, so browsers lay it out with width and height swapped.
26
+ */
27
+ function exifOrientation(bytes, view, at, end) {
28
+ const tiff = at + 10;
29
+ if (tiff + 8 > end || ascii(bytes, at + 4, 6) !== "Exif\0\0") return null;
30
+ const littleEndian = ascii(bytes, tiff, 2) === "II";
31
+ const firstIFD = tiff + view.getUint32(tiff + 4, littleEndian);
32
+ if (firstIFD + 2 > end) return 1;
33
+ const entries = view.getUint16(firstIFD, littleEndian);
34
+ for (let entry = 0; entry < entries; entry++) {
35
+ const offset = firstIFD + 2 + entry * 12;
36
+ if (offset + 12 > end) return 1;
37
+ if (view.getUint16(offset, littleEndian) === ORIENTATION_TAG) return view.getUint16(offset + 8, littleEndian);
38
+ }
39
+ return 1;
40
+ }
41
+ function jpegSize(bytes, view) {
42
+ let orientation = 1;
43
+ let at = 2;
44
+ while (at + 9 < bytes.length) {
45
+ if (bytes[at] !== 255) return null;
46
+ let markerAt = at + 1;
47
+ while (markerAt < bytes.length && bytes[markerAt] === 255) markerAt++;
48
+ if (markerAt + 7 >= bytes.length) return null;
49
+ const marker = bytes[markerAt];
50
+ const length = view.getUint16(markerAt + 1);
51
+ if (length < 2) return null;
52
+ const segment = markerAt - 1;
53
+ const end = Math.min(bytes.length, markerAt + 1 + length);
54
+ if (marker === APP1) orientation = exifOrientation(bytes, view, segment, end) ?? orientation;
55
+ if (isStartOfFrame(marker)) {
56
+ const size = [view.getUint16(markerAt + 6), view.getUint16(markerAt + 4)];
57
+ return orientation >= 5 && orientation <= 8 ? [size[1], size[0]] : size;
58
+ }
59
+ at = end;
60
+ }
61
+ return null;
62
+ }
63
+ const ISPE = [
64
+ 105,
65
+ 115,
66
+ 112,
67
+ 101
68
+ ];
69
+ /**
70
+ * An AVIF's size from its `ispe` box, wherever the file puts it: the box's type, then its
71
+ * version and flags, then two 32-bit sizes. A match counts only when the size the box header
72
+ * before it gives holds all of that and fits in the file.
73
+ */
74
+ function avifSize(bytes, view) {
75
+ for (let at = 4; at + 16 <= bytes.length; at++) {
76
+ if (ISPE.some((byte, index) => bytes[at + index] !== byte)) continue;
77
+ const boxSize = view.getUint32(at - 4);
78
+ if (boxSize < 20 || at - 4 + boxSize > bytes.length) continue;
79
+ return [view.getUint32(at + 8), view.getUint32(at + 12)];
80
+ }
81
+ return null;
82
+ }
83
+ /** An image file's pixel size from its header, or null for a format it does not know. */
84
+ function rasterImageSize(bytes) {
85
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
86
+ if (bytes.length > 24 && bytes[0] === 137 && ascii(bytes, 1, 3) === "PNG" && ascii(bytes, 12, 4) === "IHDR") return [view.getUint32(16), view.getUint32(20)];
87
+ if (bytes.length > 10 && ascii(bytes, 0, 3) === "GIF") return [view.getUint16(6, true), view.getUint16(8, true)];
88
+ if (bytes.length > 30 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WEBP") return webpSize(bytes, view);
89
+ if (bytes.length > 4 && bytes[0] === 255 && bytes[1] === 216) return jpegSize(bytes, view);
90
+ if (bytes.length > 32 && ascii(bytes, 4, 4) === "ftyp" && /avi[fs]/.test(ascii(bytes, 8, 4))) return avifSize(bytes, view);
91
+ return null;
92
+ }
93
+ /** An empty SVG of the image's size, which the engine lays out as the image would be. */
94
+ function imageStandIn([width, height]) {
95
+ return new TextEncoder().encode(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"/>`);
96
+ }
97
+ //#endregion
98
+ //#region src/schema.ts
99
+ const rectSchema = v.tuple([
100
+ v.number(),
101
+ v.number(),
102
+ v.number(),
103
+ v.number()
104
+ ]);
105
+ const glyphRunSchema = v.object({
106
+ /** The engine's id of the node whose text the run draws. */
107
+ node: v.number(),
108
+ x: v.number(),
109
+ width: v.number(),
110
+ text: v.string()
111
+ });
112
+ const inlineBoxRunSchema = v.object({
113
+ /** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */
114
+ box: v.number(),
115
+ x: v.number(),
116
+ width: v.number()
117
+ });
118
+ const lineSchema = v.object({
119
+ x: v.number(),
120
+ y: v.number(),
121
+ width: v.number(),
122
+ height: v.number(),
123
+ baseline: v.number(),
124
+ runs: v.array(v.union([glyphRunSchema, inlineBoxRunSchema]))
125
+ });
126
+ const capturedNodeSchema = v.object({
127
+ /** The engine's own id, which runs and inline boxes refer to. */
128
+ id: v.number(),
129
+ /** The index in `nodes` of the element holding it. */
130
+ parent: v.optional(v.number()),
131
+ /** Set on text nodes, which carry nothing else. */
132
+ text: v.optional(v.string()),
133
+ /** The element's local name, or `::before` and `::after` for generated content. */
134
+ tag: v.optional(v.string()),
135
+ /** Attributes by name, namespaced ones with their prefix, as `xlink:href`. */
136
+ attrs: v.optional(v.record(v.string(), v.string())),
137
+ /** The border box, in page pixels. */
138
+ box: v.optional(rectSchema),
139
+ /** What the image element holds, such as `raster 640x480` or `svg`. */
140
+ image: v.optional(v.string()),
141
+ /**
142
+ * Computed values: those with a fixed initial value only when they differ from it, and always
143
+ * the ones whose initial value depends on the element or is inherited, such as `display`,
144
+ * `color`, sizes, and font properties.
145
+ */
146
+ style: v.optional(v.record(v.string(), v.string())),
147
+ /** An inline element's box on each line it spans, in page pixels. */
148
+ fragments: v.optional(v.array(rectSchema)),
149
+ /** The lines of the inline formatting context the element holds, in page pixels. */
150
+ lines: v.optional(v.array(lineSchema))
151
+ });
152
+ /** The document the engine laid out: every node, parents before children. */
153
+ const captureSchema = v.object({
154
+ engine: v.literal("blitz"),
155
+ viewport: v.tuple([v.number(), v.number()]),
156
+ /** The initial values of the properties nodes leave out of `style` when they hold them. */
157
+ initial: v.record(v.string(), v.string()),
158
+ nodes: v.array(capturedNodeSchema)
159
+ });
160
+ /** The resources the document is waiting for, as `[request id, URL]` pairs. */
161
+ const requestsSchema = v.array(v.tuple([v.number(), v.string()]));
162
+ //#endregion
163
+ //#region src/engine.ts
164
+ /**
165
+ * The module's exports: strings and bytes cross as (pointer, length), and results land in one
166
+ * output buffer whose length the call returns.
167
+ */
168
+ const EXPORTS = [
169
+ "alloc",
170
+ "dealloc",
171
+ "output_ptr",
172
+ "fonts_reset",
173
+ "font_decode",
174
+ "font_add",
175
+ "font_generic",
176
+ "open",
177
+ "pump",
178
+ "provide",
179
+ "fail",
180
+ "capture"
181
+ ];
182
+ /**
183
+ * How long a request may take by default: as long as the browser runtime waits for an image, so
184
+ * one request that never ends cannot hold this layout, or the ones queued behind it, forever.
185
+ */
186
+ const REQUEST_TIMEOUT_MS = 1e4;
187
+ /** The largest viewport side the module takes, as a signed 32-bit length. */
188
+ const MAX_VIEWPORT = 2147483647;
189
+ function checkViewport({ width, height }) {
190
+ for (const side of [width, height]) if (!Number.isInteger(side) || side <= 0 || side > MAX_VIEWPORT) throw new RangeError(`The viewport needs whole positive pixel sizes, not ${width}×${height}`);
191
+ }
192
+ /** A fetch that gives up, answering null, once `signal` aborts. */
193
+ function withDeadline(request, signal) {
194
+ const expired = new Promise((resolve) => {
195
+ signal.addEventListener("abort", () => resolve(null), { once: true });
196
+ });
197
+ return Promise.race([request.catch(() => null), expired]);
198
+ }
199
+ /** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */
200
+ function unboundImports(module) {
201
+ const imports = {};
202
+ for (const { module: namespace, name } of WebAssembly.Module.imports(module)) {
203
+ imports[namespace] ??= {};
204
+ imports[namespace][name] = () => {
205
+ throw new Error(`The HTML engine called its unbound import ${namespace}.${name}`);
206
+ };
207
+ }
208
+ return imports;
209
+ }
210
+ function engineExports(exports) {
211
+ const { memory } = exports;
212
+ if (!(memory instanceof WebAssembly.Memory)) throw new Error("The HTML engine has no memory");
213
+ const functions = {};
214
+ for (const name of EXPORTS) {
215
+ const exported = exports[name];
216
+ if (typeof exported !== "function") throw new Error(`The HTML engine lacks ${name}`);
217
+ functions[name] = (...args) => Number(Reflect.apply(exported, void 0, args));
218
+ }
219
+ return {
220
+ ...functions,
221
+ memory
222
+ };
223
+ }
224
+ /** The URL an image element's `src` resolves to, or null when it does not parse. */
225
+ function imageURL(src, baseURL) {
226
+ try {
227
+ return new URL(src, baseURL).href;
228
+ } catch {
229
+ return null;
230
+ }
231
+ }
232
+ /**
233
+ * The engine lays raster images out from SVG stand-ins and reports them as SVG; `rasters` holds
234
+ * what each stood-in URL really was, which the capture reports instead.
235
+ */
236
+ function restoreImageKinds(capture, rasters, baseURL) {
237
+ for (const node of capture.nodes) {
238
+ const src = node.attrs?.src;
239
+ if (node.image !== "svg" || src === void 0) continue;
240
+ const url = imageURL(src, baseURL);
241
+ const kind = url === null ? void 0 : rasters.get(url);
242
+ if (kind) node.image = kind;
243
+ }
244
+ }
245
+ /**
246
+ * Blitz, Stylo, Taffy, and Parley compiled to WebAssembly: lays HTML out as a browser does and
247
+ * captures every element's box and computed styles, and the lines its text sets. The engine holds one document at a
248
+ * time, so layouts on one instance run one after another.
249
+ */
250
+ var HTMLEngine = class HTMLEngine {
251
+ #exports;
252
+ #encoder = new TextEncoder();
253
+ #decoder = new TextDecoder();
254
+ #queue = Promise.resolve();
255
+ constructor(exports) {
256
+ this.#exports = exports;
257
+ }
258
+ /** Instantiates the module from its bytes or a compiled `WebAssembly.Module`. */
259
+ static async instantiate(source) {
260
+ const module = source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source);
261
+ const instance = await WebAssembly.instantiate(module, unboundImports(module));
262
+ return new HTMLEngine(engineExports(instance.exports));
263
+ }
264
+ #withBytes(bytes, use) {
265
+ const pointer = this.#exports.alloc(bytes.length);
266
+ new Uint8Array(this.#exports.memory.buffer, pointer, bytes.length).set(bytes);
267
+ try {
268
+ return use(pointer, bytes.length);
269
+ } finally {
270
+ this.#exports.dealloc(pointer, bytes.length);
271
+ }
272
+ }
273
+ #withText(text, use) {
274
+ return this.#withBytes(this.#encoder.encode(text), use);
275
+ }
276
+ #output(length) {
277
+ const pointer = this.#exports.output_ptr();
278
+ return this.#decoder.decode(new Uint8Array(this.#exports.memory.buffer, pointer, length));
279
+ }
280
+ /**
281
+ * Registers a font file for layouts that start after it; `alias` also registers it under
282
+ * that family name, as browsers alias `-apple-system` to the system font. Returns the number
283
+ * of faces it holds.
284
+ */
285
+ addFont(bytes, alias) {
286
+ return this.#withBytes(bytes, (pointer, length) => this.#withText(alias ?? "", (aliasPointer, aliasLength) => this.#exports.font_add(pointer, length, aliasPointer, aliasLength)));
287
+ }
288
+ /**
289
+ * Sets the registered families a generic family such as `sans-serif` falls back to, in order.
290
+ * False when none of them is registered.
291
+ */
292
+ setGenericFamily(generic, families) {
293
+ return this.#withText(generic, (genericPointer, genericLength) => this.#withText(families.join("\n"), (pointer, length) => Boolean(this.#exports.font_generic(genericPointer, genericLength, pointer, length))));
294
+ }
295
+ /** A font file as TrueType or OpenType, with WOFF and WOFF2 decompressed; others unchanged. */
296
+ decodeFont(bytes) {
297
+ const length = this.#withBytes(bytes, (pointer, size) => this.#exports.font_decode(pointer, size));
298
+ return new Uint8Array(this.#exports.memory.buffer, this.#exports.output_ptr(), length).slice();
299
+ }
300
+ /** Forgets every registered font. */
301
+ resetFonts() {
302
+ this.#exports.fonts_reset();
303
+ }
304
+ #pump() {
305
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), requestsSchema), this.#output(this.#exports.pump()));
306
+ if (!parsed.success) throw new Error("The HTML engine reported requests in an unknown shape");
307
+ return parsed.output;
308
+ }
309
+ /**
310
+ * Answers one request, and returns what an image really was when the engine got a stand-in
311
+ * for it, keyed by the URLs it was asked for and fetched from.
312
+ */
313
+ async #answer(id, url, options) {
314
+ const signal = AbortSignal.timeout(options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS);
315
+ const { fetch } = options;
316
+ const resource = fetch ? await withDeadline((async () => fetch(url, signal))(), signal) : null;
317
+ if (!resource) {
318
+ this.#exports.fail(id);
319
+ return null;
320
+ }
321
+ const size = rasterImageSize(resource.bytes);
322
+ const bytes = size ? imageStandIn(size) : resource.bytes;
323
+ this.#withText(resource.url, (urlPointer, urlLength) => this.#withBytes(bytes, (pointer, length) => this.#exports.provide(id, urlPointer, urlLength, pointer, length)));
324
+ return size ? [[url, resource.url], `raster ${size[0]}x${size[1]}`] : null;
325
+ }
326
+ async #layout(html, options) {
327
+ checkViewport(options.viewport);
328
+ const { width, height } = options.viewport;
329
+ this.#withText(html, (htmlPointer, htmlLength) => this.#withText(options.baseURL ?? "", (urlPointer, urlLength) => this.#exports.open(htmlPointer, htmlLength, urlPointer, urlLength, width, height)));
330
+ const rasters = /* @__PURE__ */ new Map();
331
+ for (let requests = this.#pump(); requests.length > 0; requests = this.#pump()) {
332
+ const answers = await Promise.all(requests.map(([id, url]) => this.#answer(id, url, options)));
333
+ for (const [urls, kind] of answers.filter((answer) => answer !== null)) for (const key of urls) rasters.set(key, kind);
334
+ }
335
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), captureSchema), this.#output(this.#exports.capture()));
336
+ if (!parsed.success) throw new Error("The HTML engine captured a document in an unknown shape");
337
+ restoreImageKinds(parsed.output, rasters, options.baseURL);
338
+ return parsed.output;
339
+ }
340
+ /** Lays the document out once every resource it asks for is answered, and captures it. */
341
+ layout(html, options) {
342
+ const run = this.#queue.then(() => this.#layout(html, options));
343
+ this.#queue = run.catch(() => void 0);
344
+ return run;
345
+ }
346
+ };
347
+ //#endregion
348
+ export { HTMLEngine, rasterImageSize };
349
+
350
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","names":["#exports","#encoder","#decoder","#withBytes","#withText","#output","#answer","#layout","#pump","#queue"],"sources":["../../src/images.ts","../../src/schema.ts","../../src/engine.ts"],"sourcesContent":["/**\n * The engine decodes no raster images, so layout learns an image's size from a stand-in SVG of\n * the same pixel size, read from the file's header. Formats are the ones browsers lay out from\n * their headers alone: PNG, GIF, WebP, JPEG, and AVIF.\n */\n\ntype Size = [width: number, height: number]\n\nfunction ascii(bytes: Uint8Array, at: number, length: number): string {\n return String.fromCharCode(...bytes.subarray(at, at + length))\n}\n\nfunction webpSize(bytes: Uint8Array, view: DataView): Size | null {\n const chunk = ascii(bytes, 12, 4)\n if (chunk === 'VP8 ')\n return [view.getUint16(26, true) & 0x3fff, view.getUint16(28, true) & 0x3fff]\n if (chunk === 'VP8L') {\n const bits = view.getUint32(21, true)\n return [(bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1]\n }\n if (chunk === 'VP8X') {\n const width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16))\n const height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16))\n return [width, height]\n }\n return null\n}\n\n/** Start-of-frame markers, which carry the size; C4, C8, and CC are other segments. */\nfunction isStartOfFrame(marker: number): boolean {\n return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc\n}\n\nconst APP1 = 0xe1\nconst ORIENTATION_TAG = 0x0112\n\n/**\n * The Exif Orientation in an APP1 segment starting at `at`: 1 when the Exif data names none,\n * and null when the segment is not Exif, such as XMP, which says nothing about orientation. Orientations 5\n * to 8 turn the image a quarter, so browsers lay it out with width and height swapped.\n */\nfunction exifOrientation(\n bytes: Uint8Array,\n view: DataView,\n at: number,\n end: number\n): number | null {\n const tiff = at + 10\n if (tiff + 8 > end || ascii(bytes, at + 4, 6) !== 'Exif\\0\\0') return null\n const littleEndian = ascii(bytes, tiff, 2) === 'II'\n const firstIFD = tiff + view.getUint32(tiff + 4, littleEndian)\n if (firstIFD + 2 > end) return 1\n const entries = view.getUint16(firstIFD, littleEndian)\n for (let entry = 0; entry < entries; entry++) {\n const offset = firstIFD + 2 + entry * 12\n if (offset + 12 > end) return 1\n if (view.getUint16(offset, littleEndian) === ORIENTATION_TAG) {\n return view.getUint16(offset + 8, littleEndian)\n }\n }\n return 1\n}\n\nfunction jpegSize(bytes: Uint8Array, view: DataView): Size | null {\n let orientation = 1\n let at = 2\n while (at + 9 < bytes.length) {\n if (bytes[at] !== 0xff) return null\n // Any number of 0xFF fill bytes may come before a marker.\n let markerAt = at + 1\n while (markerAt < bytes.length && bytes[markerAt] === 0xff) markerAt++\n if (markerAt + 7 >= bytes.length) return null\n const marker = bytes[markerAt]\n // A segment's length counts its own two bytes, so less is a broken file.\n const length = view.getUint16(markerAt + 1)\n if (length < 2) return null\n const segment = markerAt - 1\n const end = Math.min(bytes.length, markerAt + 1 + length)\n if (marker === APP1) orientation = exifOrientation(bytes, view, segment, end) ?? orientation\n if (isStartOfFrame(marker)) {\n const size: Size = [view.getUint16(markerAt + 6), view.getUint16(markerAt + 4)]\n return orientation >= 5 && orientation <= 8 ? [size[1], size[0]] : size\n }\n at = end\n }\n return null\n}\n\nconst ISPE = [0x69, 0x73, 0x70, 0x65]\n\n/**\n * An AVIF's size from its `ispe` box, wherever the file puts it: the box's type, then its\n * version and flags, then two 32-bit sizes. A match counts only when the size the box header\n * before it gives holds all of that and fits in the file.\n */\nfunction avifSize(bytes: Uint8Array, view: DataView): Size | null {\n for (let at = 4; at + 16 <= bytes.length; at++) {\n if (ISPE.some((byte, index) => bytes[at + index] !== byte)) continue\n const boxSize = view.getUint32(at - 4)\n if (boxSize < 20 || at - 4 + boxSize > bytes.length) continue\n return [view.getUint32(at + 8), view.getUint32(at + 12)]\n }\n return null\n}\n\n/** An image file's pixel size from its header, or null for a format it does not know. */\nexport function rasterImageSize(bytes: Uint8Array): Size | null {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n // The size is in the IHDR chunk, which a PNG must start with.\n if (\n bytes.length > 24 &&\n bytes[0] === 0x89 &&\n ascii(bytes, 1, 3) === 'PNG' &&\n ascii(bytes, 12, 4) === 'IHDR'\n ) {\n return [view.getUint32(16), view.getUint32(20)]\n }\n if (bytes.length > 10 && ascii(bytes, 0, 3) === 'GIF') {\n return [view.getUint16(6, true), view.getUint16(8, true)]\n }\n if (bytes.length > 30 && ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') {\n return webpSize(bytes, view)\n }\n if (bytes.length > 4 && bytes[0] === 0xff && bytes[1] === 0xd8) return jpegSize(bytes, view)\n if (bytes.length > 32 && ascii(bytes, 4, 4) === 'ftyp' && /avi[fs]/.test(ascii(bytes, 8, 4))) {\n return avifSize(bytes, view)\n }\n return null\n}\n\n/** An empty SVG of the image's size, which the engine lays out as the image would be. */\nexport function imageStandIn([width, height]: Size): Uint8Array {\n return new TextEncoder().encode(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\"/>`\n )\n}\n","import * as v from 'valibot'\n\nconst rectSchema = v.tuple([v.number(), v.number(), v.number(), v.number()])\n\nconst glyphRunSchema = v.object({\n /** The engine's id of the node whose text the run draws. */\n node: v.number(),\n x: v.number(),\n width: v.number(),\n text: v.string()\n})\n\nconst inlineBoxRunSchema = v.object({\n /** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */\n box: v.number(),\n x: v.number(),\n width: v.number()\n})\n\nconst lineSchema = v.object({\n x: v.number(),\n y: v.number(),\n width: v.number(),\n height: v.number(),\n baseline: v.number(),\n runs: v.array(v.union([glyphRunSchema, inlineBoxRunSchema]))\n})\n\nconst capturedNodeSchema = v.object({\n /** The engine's own id, which runs and inline boxes refer to. */\n id: v.number(),\n /** The index in `nodes` of the element holding it. */\n parent: v.optional(v.number()),\n /** Set on text nodes, which carry nothing else. */\n text: v.optional(v.string()),\n /** The element's local name, or `::before` and `::after` for generated content. */\n tag: v.optional(v.string()),\n /** Attributes by name, namespaced ones with their prefix, as `xlink:href`. */\n attrs: v.optional(v.record(v.string(), v.string())),\n /** The border box, in page pixels. */\n box: v.optional(rectSchema),\n /** What the image element holds, such as `raster 640x480` or `svg`. */\n image: v.optional(v.string()),\n /**\n * Computed values: those with a fixed initial value only when they differ from it, and always\n * the ones whose initial value depends on the element or is inherited, such as `display`,\n * `color`, sizes, and font properties.\n */\n style: v.optional(v.record(v.string(), v.string())),\n /** An inline element's box on each line it spans, in page pixels. */\n fragments: v.optional(v.array(rectSchema)),\n /** The lines of the inline formatting context the element holds, in page pixels. */\n lines: v.optional(v.array(lineSchema))\n})\n\n/** The document the engine laid out: every node, parents before children. */\nexport const captureSchema = v.object({\n engine: v.literal('blitz'),\n viewport: v.tuple([v.number(), v.number()]),\n /** The initial values of the properties nodes leave out of `style` when they hold them. */\n initial: v.record(v.string(), v.string()),\n nodes: v.array(capturedNodeSchema)\n})\n\n/** The resources the document is waiting for, as `[request id, URL]` pairs. */\nexport const requestsSchema = v.array(v.tuple([v.number(), v.string()]))\n\nexport type HTMLEngineCapture = v.InferOutput<typeof captureSchema>\nexport type HTMLEngineNode = v.InferOutput<typeof capturedNodeSchema>\nexport type HTMLEngineLine = v.InferOutput<typeof lineSchema>\n","import * as v from 'valibot'\n\nimport { imageStandIn, rasterImageSize } from './images'\nimport { captureSchema, requestsSchema, type HTMLEngineCapture } from './schema'\n\n/**\n * The module's exports: strings and bytes cross as (pointer, length), and results land in one\n * output buffer whose length the call returns.\n */\nconst EXPORTS = [\n 'alloc',\n 'dealloc',\n 'output_ptr',\n 'fonts_reset',\n 'font_decode',\n 'font_add',\n 'font_generic',\n 'open',\n 'pump',\n 'provide',\n 'fail',\n 'capture'\n] as const\n\ntype EngineExports = Record<(typeof EXPORTS)[number], (...args: number[]) => number> & {\n memory: WebAssembly.Memory\n}\n\n/** A resource the document asked for, as the host fetched it: its final URL and its bytes. */\nexport interface HTMLEngineResource {\n url: string\n bytes: Uint8Array\n /** The resource's media type, such as `text/css`, when the host knows it. */\n contentType?: string\n}\n\n/**\n * Fetches a stylesheet, font, or image the document refers to; null when it cannot. `signal`\n * aborts when the request runs out of time, and the layout goes on without it.\n */\nexport type HTMLEngineFetch = (\n url: string,\n signal: AbortSignal\n) => Promise<HTMLEngineResource | null>\n\nexport interface HTMLEngineLayoutOptions {\n /** The document's URL, which relative URLs in it resolve against. */\n baseURL?: string\n /** In whole CSS pixels. */\n viewport: { width: number; height: number }\n /** Answers the document's requests; without one, every request fails. */\n fetch?: HTMLEngineFetch\n /** How long one request may take before the layout goes on without it. */\n requestTimeoutMs?: number\n}\n\n/**\n * How long a request may take by default: as long as the browser runtime waits for an image, so\n * one request that never ends cannot hold this layout, or the ones queued behind it, forever.\n */\nconst REQUEST_TIMEOUT_MS = 10_000\n\n/** The largest viewport side the module takes, as a signed 32-bit length. */\nconst MAX_VIEWPORT = 0x7fffffff\n\nfunction checkViewport({ width, height }: HTMLEngineLayoutOptions['viewport']): void {\n for (const side of [width, height]) {\n if (!Number.isInteger(side) || side <= 0 || side > MAX_VIEWPORT) {\n throw new RangeError(`The viewport needs whole positive pixel sizes, not ${width}×${height}`)\n }\n }\n}\n\n/** A fetch that gives up, answering null, once `signal` aborts. */\nfunction withDeadline<T>(request: Promise<T>, signal: AbortSignal): Promise<T | null> {\n const expired = new Promise<null>((resolve) => {\n signal.addEventListener('abort', () => resolve(null), { once: true })\n })\n return Promise.race([request.catch(() => null), expired])\n}\n\n/** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */\nfunction unboundImports(module: WebAssembly.Module): WebAssembly.Imports {\n const imports: Record<string, Record<string, () => never>> = {}\n for (const { module: namespace, name } of WebAssembly.Module.imports(module)) {\n imports[namespace] ??= {}\n imports[namespace][name] = () => {\n throw new Error(`The HTML engine called its unbound import ${namespace}.${name}`)\n }\n }\n return imports\n}\n\nfunction engineExports(exports: WebAssembly.Exports): EngineExports {\n const { memory } = exports\n if (!(memory instanceof WebAssembly.Memory)) throw new Error('The HTML engine has no memory')\n const functions: Partial<Record<(typeof EXPORTS)[number], (...args: number[]) => number>> = {}\n for (const name of EXPORTS) {\n const exported = exports[name]\n if (typeof exported !== 'function') throw new Error(`The HTML engine lacks ${name}`)\n functions[name] = (...args) => Number(Reflect.apply(exported, undefined, args))\n }\n return {\n ...(functions as Record<(typeof EXPORTS)[number], (...args: number[]) => number>),\n memory\n }\n}\n\n/** The URL an image element's `src` resolves to, or null when it does not parse. */\nfunction imageURL(src: string, baseURL: string | undefined): string | null {\n try {\n return new URL(src, baseURL).href\n } catch {\n return null\n }\n}\n\n/**\n * The engine lays raster images out from SVG stand-ins and reports them as SVG; `rasters` holds\n * what each stood-in URL really was, which the capture reports instead.\n */\nfunction restoreImageKinds(\n capture: HTMLEngineCapture,\n rasters: ReadonlyMap<string, string>,\n baseURL: string | undefined\n): void {\n for (const node of capture.nodes) {\n const src = node.attrs?.src\n if (node.image !== 'svg' || src === undefined) continue\n const url = imageURL(src, baseURL)\n const kind = url === null ? undefined : rasters.get(url)\n if (kind) node.image = kind\n }\n}\n\n/**\n * Blitz, Stylo, Taffy, and Parley compiled to WebAssembly: lays HTML out as a browser does and\n * captures every element's box and computed styles, and the lines its text sets. The engine holds one document at a\n * time, so layouts on one instance run one after another.\n */\nexport class HTMLEngine {\n readonly #exports: EngineExports\n readonly #encoder = new TextEncoder()\n readonly #decoder = new TextDecoder()\n #queue: Promise<unknown> = Promise.resolve()\n\n private constructor(exports: EngineExports) {\n this.#exports = exports\n }\n\n /** Instantiates the module from its bytes or a compiled `WebAssembly.Module`. */\n static async instantiate(source: BufferSource | WebAssembly.Module): Promise<HTMLEngine> {\n const module = source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source)\n const instance = await WebAssembly.instantiate(module, unboundImports(module))\n return new HTMLEngine(engineExports(instance.exports))\n }\n\n #withBytes<T>(bytes: Uint8Array, use: (pointer: number, length: number) => T): T {\n const pointer = this.#exports.alloc(bytes.length)\n new Uint8Array(this.#exports.memory.buffer, pointer, bytes.length).set(bytes)\n try {\n return use(pointer, bytes.length)\n } finally {\n this.#exports.dealloc(pointer, bytes.length)\n }\n }\n\n #withText<T>(text: string, use: (pointer: number, length: number) => T): T {\n return this.#withBytes(this.#encoder.encode(text), use)\n }\n\n #output(length: number): string {\n const pointer = this.#exports.output_ptr()\n return this.#decoder.decode(new Uint8Array(this.#exports.memory.buffer, pointer, length))\n }\n\n /**\n * Registers a font file for layouts that start after it; `alias` also registers it under\n * that family name, as browsers alias `-apple-system` to the system font. Returns the number\n * of faces it holds.\n */\n addFont(bytes: Uint8Array, alias?: string): number {\n return this.#withBytes(bytes, (pointer, length) =>\n this.#withText(alias ?? '', (aliasPointer, aliasLength) =>\n this.#exports.font_add(pointer, length, aliasPointer, aliasLength)\n )\n )\n }\n\n /**\n * Sets the registered families a generic family such as `sans-serif` falls back to, in order.\n * False when none of them is registered.\n */\n setGenericFamily(generic: string, families: readonly string[]): boolean {\n return this.#withText(generic, (genericPointer, genericLength) =>\n this.#withText(families.join('\\n'), (pointer, length) =>\n Boolean(this.#exports.font_generic(genericPointer, genericLength, pointer, length))\n )\n )\n }\n\n /** A font file as TrueType or OpenType, with WOFF and WOFF2 decompressed; others unchanged. */\n decodeFont(bytes: Uint8Array): Uint8Array {\n const length = this.#withBytes(bytes, (pointer, size) =>\n this.#exports.font_decode(pointer, size)\n )\n return new Uint8Array(this.#exports.memory.buffer, this.#exports.output_ptr(), length).slice()\n }\n\n /** Forgets every registered font. */\n resetFonts(): void {\n this.#exports.fonts_reset()\n }\n\n #pump(): [number, string][] {\n const parsed = v.safeParse(\n v.pipe(v.string(), v.parseJson(), requestsSchema),\n this.#output(this.#exports.pump())\n )\n if (!parsed.success) throw new Error('The HTML engine reported requests in an unknown shape')\n return parsed.output\n }\n\n /**\n * Answers one request, and returns what an image really was when the engine got a stand-in\n * for it, keyed by the URLs it was asked for and fetched from.\n */\n async #answer(\n id: number,\n url: string,\n options: HTMLEngineLayoutOptions\n ): Promise<[string[], string] | null> {\n const signal = AbortSignal.timeout(options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS)\n const { fetch } = options\n // An async wrapper turns a callback that throws before it returns into a rejection.\n const resource = fetch ? await withDeadline((async () => fetch(url, signal))(), signal) : null\n if (!resource) {\n this.#exports.fail(id)\n return null\n }\n const size = rasterImageSize(resource.bytes)\n const bytes = size ? imageStandIn(size) : resource.bytes\n this.#withText(resource.url, (urlPointer, urlLength) =>\n this.#withBytes(bytes, (pointer, length) =>\n this.#exports.provide(id, urlPointer, urlLength, pointer, length)\n )\n )\n return size ? [[url, resource.url], `raster ${size[0]}x${size[1]}`] : null\n }\n\n async #layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {\n checkViewport(options.viewport)\n const { width, height } = options.viewport\n this.#withText(html, (htmlPointer, htmlLength) =>\n this.#withText(options.baseURL ?? '', (urlPointer, urlLength) =>\n this.#exports.open(htmlPointer, htmlLength, urlPointer, urlLength, width, height)\n )\n )\n // Answers can ask for more, such as a stylesheet's fonts, so pump until nothing is waiting.\n const rasters = new Map<string, string>()\n for (let requests = this.#pump(); requests.length > 0; requests = this.#pump()) {\n const answers = await Promise.all(requests.map(([id, url]) => this.#answer(id, url, options)))\n for (const [urls, kind] of answers.filter((answer) => answer !== null)) {\n for (const key of urls) rasters.set(key, kind)\n }\n }\n const parsed = v.safeParse(\n v.pipe(v.string(), v.parseJson(), captureSchema),\n this.#output(this.#exports.capture())\n )\n if (!parsed.success) throw new Error('The HTML engine captured a document in an unknown shape')\n restoreImageKinds(parsed.output, rasters, options.baseURL)\n return parsed.output\n }\n\n /** Lays the document out once every resource it asks for is answered, and captures it. */\n layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {\n const run = this.#queue.then(() => this.#layout(html, options))\n this.#queue = run.catch(() => undefined)\n return run\n }\n}\n"],"mappings":";;AAQA,SAAS,MAAM,OAAmB,IAAY,QAAwB;CACpE,OAAO,OAAO,aAAa,GAAG,MAAM,SAAS,IAAI,KAAK,MAAM,CAAC;AAC/D;AAEA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