@open-pencil/html-engine 0.17.0-beta.5 → 0.17.0-beta.7

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.
@@ -1,4 +1,6 @@
1
1
  import * as v from "valibot";
2
+ import { createMutex } from "@open-pencil/std/async";
3
+ import { DEADLINE_MS, untilAborted } from "@open-pencil/std/timing";
2
4
  //#region src/images.ts
3
5
  function ascii(bytes, at, length) {
4
6
  return Array.from(bytes.subarray(at, at + length), (code) => String.fromCharCode(code)).join("");
@@ -189,18 +191,15 @@ const EXPORTS = [
189
191
  * How long a request may take by default: as long as the browser runtime waits for an image, so
190
192
  * one request that never ends cannot hold this layout, or the ones queued behind it, forever.
191
193
  */
192
- const REQUEST_TIMEOUT_MS = 1e4;
194
+ const REQUEST_TIMEOUT_MS = DEADLINE_MS.request;
193
195
  /** The largest viewport side the module takes, as a signed 32-bit length. */
194
196
  const MAX_VIEWPORT = 2147483647;
195
197
  function checkViewport({ width, height }) {
196
198
  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}`);
197
199
  }
198
- /** A fetch that gives up, answering null, once `signal` aborts. */
200
+ /** A fetch that gives up, answering null, once it fails or `signal` aborts. */
199
201
  function withDeadline(request, signal) {
200
- const expired = new Promise((resolve) => {
201
- signal.addEventListener("abort", () => resolve(null), { once: true });
202
- });
203
- return Promise.race([request.catch(() => null), expired]);
202
+ return untilAborted(request, signal).catch(() => null);
204
203
  }
205
204
  /** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */
206
205
  function unboundImports(module) {
@@ -257,7 +256,7 @@ var HTMLEngine = class HTMLEngine {
257
256
  #exports;
258
257
  #encoder = new TextEncoder();
259
258
  #decoder = new TextDecoder();
260
- #queue = Promise.resolve();
259
+ #layouts = createMutex();
261
260
  constructor(exports) {
262
261
  this.#exports = exports;
263
262
  }
@@ -345,9 +344,7 @@ var HTMLEngine = class HTMLEngine {
345
344
  }
346
345
  /** Lays the document out once every resource it asks for is answered, and captures it. */
347
346
  layout(html, options) {
348
- const run = this.#queue.then(() => this.#layout(html, options));
349
- this.#queue = run.catch(() => void 0);
350
- return run;
347
+ return this.#layouts.run(() => this.#layout(html, options));
351
348
  }
352
349
  };
353
350
  //#endregion
@@ -1 +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 Array.from(bytes.subarray(at, at + length), (code) => String.fromCharCode(code)).join('')\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 /**\n * Computed values where `style`'s used ones lose what the page set: the sizes (`width`,\n * `height`, their minimums and maximums, and `flex-basis`) before layout resolves `auto` and\n * percentages to pixels, such as `auto`, `50%`, or `390px`, and `line-height`, such as `1.5`.\n */\n computed: 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,MAAM,KAAK,MAAM,SAAS,IAAI,KAAK,MAAM,IAAI,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE;AACjG;AAEA,SAAS,SAAS,OAAmB,MAA6B;CAChE,MAAM,QAAQ,MAAM,OAAO,IAAI,CAAC;CAChC,IAAI,UAAU,QACZ,OAAO,CAAC,KAAK,UAAU,IAAI,IAAI,IAAI,OAAQ,KAAK,UAAU,IAAI,IAAI,IAAI,KAAM;CAC9E,IAAI,UAAU,QAAQ;EACpB,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;EACpC,OAAO,EAAE,OAAO,SAAU,IAAK,QAAQ,KAAM,SAAU,CAAC;CAC1D;CACA,IAAI,UAAU,QAGZ,OAAO,CAFO,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,KACjD,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,GAC5C;CAEvB,OAAO;AACT;;AAGA,SAAS,eAAe,QAAyB;CAC/C,OAAO,UAAU,OAAQ,UAAU,OAAQ,WAAW,OAAQ,WAAW,OAAQ,WAAW;AAC9F;AAEA,MAAM,OAAO;AACb,MAAM,kBAAkB;;;;;;AAOxB,SAAS,gBACP,OACA,MACA,IACA,KACe;CACf,MAAM,OAAO,KAAK;CAClB,IAAI,OAAO,IAAI,OAAO,MA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OAAO,CAAC,CAAC;GAC7F,KAAK,MAAM,CAAC,MAAM,SAAS,QAAQ,QAAQ,WAAW,WAAW,IAAI,GACnE,KAAK,MAAM,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI;EAEjD;EACA,MAAM,SAAS,EAAE,UACf,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,GAAG,aAAa,GAC/C,KAAKD,QAAQ,KAAKL,SAAS,QAAQ,CAAC,CACtC;EACA,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,MAAM,yDAAyD;EAC9F,kBAAkB,OAAO,QAAQ,SAAS,QAAQ,OAAO;EACzD,OAAO,OAAO;CAChB;;CAGA,OAAO,MAAc,SAA8D;EACjF,MAAM,MAAM,KAAKS,OAAO,WAAW,KAAKF,QAAQ,MAAM,OAAO,CAAC;EAC9D,KAAKE,SAAS,IAAI,YAAY,KAAA,CAAS;EACvC,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"engine.js","names":["#exports","#encoder","#decoder","#withBytes","#withText","#output","#answer","#layout","#pump","#layouts"],"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 Array.from(bytes.subarray(at, at + length), (code) => String.fromCharCode(code)).join('')\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 /**\n * Computed values where `style`'s used ones lose what the page set: the sizes (`width`,\n * `height`, their minimums and maximums, and `flex-basis`) before layout resolves `auto` and\n * percentages to pixels, such as `auto`, `50%`, or `390px`, and `line-height`, such as `1.5`.\n */\n computed: 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 type { DesignResourceFetch } from '@open-pencil/dom-css'\nimport { createMutex } from '@open-pencil/std/async'\nimport { DEADLINE_MS, untilAborted } from '@open-pencil/std/timing'\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 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?: DesignResourceFetch\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 = DEADLINE_MS.request\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 it fails or `signal` aborts. */\nfunction withDeadline<T>(request: Promise<T>, signal: AbortSignal): Promise<T | null> {\n return untilAborted(request, signal).catch(() => null)\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 #layouts = createMutex()\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 return this.#layouts.run(() => this.#layout(html, options))\n }\n}\n"],"mappings":";;;;AAQA,SAAS,MAAM,OAAmB,IAAY,QAAwB;CACpE,OAAO,MAAM,KAAK,MAAM,SAAS,IAAI,KAAK,MAAM,IAAI,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE;AACjG;AAEA,SAAS,SAAS,OAAmB,MAA6B;CAChE,MAAM,QAAQ,MAAM,OAAO,IAAI,CAAC;CAChC,IAAI,UAAU,QACZ,OAAO,CAAC,KAAK,UAAU,IAAI,IAAI,IAAI,OAAQ,KAAK,UAAU,IAAI,IAAI,IAAI,KAAM;CAC9E,IAAI,UAAU,QAAQ;EACpB,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;EACpC,OAAO,EAAE,OAAO,SAAU,IAAK,QAAQ,KAAM,SAAU,CAAC;CAC1D;CACA,IAAI,UAAU,QAGZ,OAAO,CAFO,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,KACjD,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,GAC5C;CAEvB,OAAO;AACT;;AAGA,SAAS,eAAe,QAAyB;CAC/C,OAAO,UAAU,OAAQ,UAAU,OAAQ,WAAW,OAAQ,WAAW,OAAQ,WAAW;AAC9F;AAEA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,CAAC,CAAC;GAC7F,KAAK,MAAM,CAAC,MAAM,SAAS,QAAQ,QAAQ,WAAW,WAAW,IAAI,GACnE,KAAK,MAAM,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI;EAEjD;EACA,MAAM,SAAS,EAAE,UACf,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,GAAG,aAAa,GAC/C,KAAKD,QAAQ,KAAKL,SAAS,QAAQ,CAAC,CACtC;EACA,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,MAAM,yDAAyD;EAC9F,kBAAkB,OAAO,QAAQ,SAAS,QAAQ,OAAO;EACzD,OAAO,OAAO;CAChB;;CAGA,OAAO,MAAc,SAA8D;EACjF,OAAO,KAAKS,SAAS,UAAU,KAAKF,QAAQ,MAAM,OAAO,CAAC;CAC5D;AACF"}
@@ -1,8 +1,10 @@
1
1
  import { HTMLEngine } from "./engine.js";
2
+ import { DEADLINE_MS } from "@open-pencil/std/timing";
2
3
  import { parseFontFaceRules, parseHTMLDocument, parseStylesheetImports } from "@open-pencil/dom-css";
3
4
  import { serializeHTML } from "@open-pencil/dom-css/export";
4
- import { insertAll, maxOf, minOf } from "@open-pencil/scene-graph/arrays";
5
+ import { parseCSSColor } from "@open-pencil/scene-graph/css";
5
6
  import { computeBounds } from "@open-pencil/scene-graph/geometry";
7
+ import { insertAll, maxOf, minOf } from "@open-pencil/std/arrays";
6
8
  //#region src/load.ts
7
9
  let locator = () => import.meta.resolve("@open-pencil/html-engine/wasm/html-engine.wasm");
8
10
  let loading = null;
@@ -10,7 +12,7 @@ let loading = null;
10
12
  * How long a remote module may take to arrive, so a request that never settles cannot hold every
11
13
  * later load waiting on it; a failed load is retried by the next caller.
12
14
  */
13
- const MODULE_LOAD_TIMEOUT_MS = 6e4;
15
+ const MODULE_LOAD_TIMEOUT_MS = DEADLINE_MS.transfer;
14
16
  /** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */
15
17
  function setHTMLEngineLocator(locate) {
16
18
  locator = locate;
@@ -208,6 +210,85 @@ function documentHTML(body, cssText) {
208
210
  * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
209
211
  * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
210
212
  */
213
+ /** The `::before` and `::after` nodes of each captured element, by the element's index. */
214
+ function generatedChildren(capture) {
215
+ const generated = /* @__PURE__ */ new Map();
216
+ for (const [index, node] of capture.nodes.entries()) {
217
+ if (node.parent === void 0 || !node.tag?.startsWith("::")) continue;
218
+ generated.set(node.parent, [...generated.get(node.parent) ?? [], index]);
219
+ }
220
+ return generated;
221
+ }
222
+ /** The text a captured node holds directly, as a pseudo-element's generated content. */
223
+ /** Each captured node's own text, its text children's joined in order, by the node's index. */
224
+ function ownTexts(capture) {
225
+ const texts = /* @__PURE__ */ new Map();
226
+ for (const node of capture.nodes) {
227
+ if (node.text === void 0 || node.parent === void 0) continue;
228
+ texts.set(node.parent, (texts.get(node.parent) ?? "") + node.text);
229
+ }
230
+ return texts;
231
+ }
232
+ /**
233
+ * Shows each element's `::before` and `::after` as elements of their own, first and last among its
234
+ * children, with the style, box, and text the engine generated for them, so they are imported as
235
+ * any element is.
236
+ */
237
+ function showGeneratedContent(capture, pairs, layout) {
238
+ const indexes = new Map(capture.nodes.map((node, index) => [node, index]));
239
+ const generated = generatedChildren(capture);
240
+ const texts = ownTexts(capture);
241
+ for (const [element, node] of pairs) {
242
+ const index = indexes.get(node);
243
+ for (const pseudo of (index === void 0 ? void 0 : generated.get(index)) ?? []) {
244
+ const captured = capture.nodes[pseudo];
245
+ const text = texts.get(pseudo) ?? "";
246
+ const child = {
247
+ type: "element",
248
+ tagName: captured.tag ?? "::before",
249
+ attrs: {},
250
+ children: text ? [{
251
+ type: "text",
252
+ text
253
+ }] : [],
254
+ computedStyle: withShorthands({
255
+ ...capture.initial,
256
+ ...captured.style,
257
+ ...captured.computed
258
+ })
259
+ };
260
+ if (layout) child.layout = layoutOf(captured);
261
+ if (captured.tag === "::after") element.children.push(child);
262
+ else element.children.unshift(child);
263
+ }
264
+ }
265
+ }
266
+ /**
267
+ * The color the page's canvas is painted, as CSS takes it: the root element's background, or the
268
+ * body's when the root has none.
269
+ */
270
+ function canvasBackground(capture) {
271
+ const background = (tag) => {
272
+ const color = capture.nodes.find((candidate) => candidate.tag === tag)?.style?.["background-color"];
273
+ return color && parseCSSColor(color) ? color : void 0;
274
+ };
275
+ return background("html") ?? background("body");
276
+ }
277
+ /** A fetch that also keeps what it answered, by the URL asked for and the one it came from. */
278
+ function keepingFetch(fetch, answered) {
279
+ if (!fetch) return void 0;
280
+ return async (url, signal) => {
281
+ const resource = await fetch(url, signal);
282
+ if (resource) answered.set(url, resource).set(resource.url, resource);
283
+ return resource;
284
+ };
285
+ }
286
+ /** What an `<img>` loaded, by its `src` resolved against the page's address. */
287
+ function imageOf(element, answered, baseURL) {
288
+ const { src } = element.attrs;
289
+ if (element.tagName.toLowerCase() !== "img" || !src || !URL.canParse(src, baseURL)) return;
290
+ return answered.get(new URL(src, baseURL).href);
291
+ }
211
292
  function createHTMLEngineRuntime(options = {}) {
212
293
  const engine = options.engine ?? loadHTMLEngine;
213
294
  return {
@@ -216,20 +297,30 @@ function createHTMLEngineRuntime(options = {}) {
216
297
  serializeHTML,
217
298
  async computeStyles(document, cssText = "", compute = {}) {
218
299
  const laidOut = await engine();
300
+ const answered = /* @__PURE__ */ new Map();
301
+ const fetch = keepingFetch(options.fetch, answered);
219
302
  const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {
220
303
  baseURL: options.baseURL,
221
304
  viewport: compute.viewport ?? DEFAULT_VIEWPORT,
222
- fetch: fontFaceFetch(laidOut, cssText, options)
305
+ fetch: fontFaceFetch(laidOut, cssText, {
306
+ ...options,
307
+ fetch
308
+ })
223
309
  });
224
310
  const styled = structuredClone(document);
225
- for (const [element, node] of pairElements(styled, capture)) {
311
+ const pairs = pairElements(styled, capture);
312
+ for (const [element, node] of pairs) {
226
313
  element.computedStyle = withShorthands({
227
314
  ...capture.initial,
228
315
  ...node.style,
229
316
  ...node.computed
230
317
  });
231
318
  if (compute.layout) element.layout = layoutOf(node);
319
+ const image = imageOf(element, answered, options.baseURL);
320
+ if (image) element.image = image;
232
321
  }
322
+ showGeneratedContent(capture, pairs, compute.layout === true);
323
+ styled.background = canvasBackground(capture);
233
324
  return styled;
234
325
  }
235
326
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/load.ts","../../src/runtime.ts"],"sourcesContent":["import { HTMLEngine } from './engine'\n\n/**\n * Where the engine's module (`html-engine.wasm`) loads from. By default it is read beside this\n * package, as Node and Bun resolve it; a host that serves it elsewhere, such as a bundled app,\n * points here instead.\n */\nexport type HTMLEngineLocator = () => string\n\nlet locator: HTMLEngineLocator = () =>\n import.meta.resolve('@open-pencil/html-engine/wasm/html-engine.wasm')\n\nlet loading: Promise<HTMLEngine> | null = null\n\n/**\n * How long a remote module may take to arrive, so a request that never settles cannot hold every\n * later load waiting on it; a failed load is retried by the next caller.\n */\nconst MODULE_LOAD_TIMEOUT_MS = 60_000\n\n/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */\nexport function setHTMLEngineLocator(locate: HTMLEngineLocator): void {\n locator = locate\n loading = null\n}\n\nasync function readModule(url: string): Promise<ArrayBuffer> {\n if (!url.startsWith('file:')) {\n const response = await fetch(url, { signal: AbortSignal.timeout(MODULE_LOAD_TIMEOUT_MS) })\n if (!response.ok)\n throw new Error(`html-engine.wasm failed to load from ${url}: ${response.status}`)\n return response.arrayBuffer()\n }\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n const file = await readFile(new URL(url)).catch((error: unknown) => {\n throw new Error(\n `html-engine.wasm is missing at ${url}; build it with bun run build in packages/html-engine`,\n { cause: error }\n )\n })\n return file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength)\n}\n\n/** The engine, loaded once; a failed load is retried by the next caller. */\nexport function loadHTMLEngine(): Promise<HTMLEngine> {\n if (loading) return loading\n const load = readModule(locator()).then((bytes) => HTMLEngine.instantiate(bytes))\n loading = load\n load.catch(() => {\n if (loading === load) loading = null\n })\n return load\n}\n","import {\n parseFontFaceRules,\n parseHTMLDocument,\n parseStylesheetImports,\n type CSSFontFaceRule,\n type CSSComputeOptions,\n type CSSRuntime,\n type DesignDocument,\n type DesignElement,\n type DesignLayout,\n type DesignStyleDeclaration,\n type DesignViewport\n} from '@open-pencil/dom-css'\nimport { serializeHTML } from '@open-pencil/dom-css/export'\nimport { insertAll, maxOf, minOf } from '@open-pencil/scene-graph/arrays'\nimport { computeBounds } from '@open-pencil/scene-graph/geometry'\nimport type { Rect } from '@open-pencil/scene-graph/primitives'\n\nimport type { HTMLEngine, HTMLEngineFetch, HTMLEngineResource } from './engine'\nimport { loadHTMLEngine } from './load'\nimport type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'\n\n/** The viewport a document is laid out in when the caller names none, as HTML import uses. */\nconst DEFAULT_VIEWPORT: DesignViewport = { width: 1440, height: 900 }\n\n/** A font a page's `@font-face` rule loads: the face the rule declares, and the file as TrueType or OpenType. */\nexport interface HTMLEngineFontFace {\n family: string\n weight: number\n italic: boolean\n url: string\n bytes: Uint8Array\n}\n\nexport interface HTMLEngineRuntimeOptions {\n /** The engine to lay documents out with, with the fonts they may use registered. */\n engine?: () => Promise<HTMLEngine>\n /** The document's URL, which its relative URLs resolve against. */\n baseURL?: string\n /**\n * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for\n * its `@font-face` rules when it comes with a CSS content type.\n */\n fetch?: HTMLEngineFetch\n /**\n * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so\n * a host can draw that text in the same font. The layout waits for it.\n */\n onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>\n}\n\nfunction isStylesheet(resource: HTMLEngineResource): boolean {\n return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'\n}\n\n/**\n * A fetch that also reads the page's `@font-face` rules, from its own CSS and every stylesheet it\n * fetches, and passes each font they load to `onFontFace` as the engine receives it.\n */\nfunction fontFaceFetch(\n engine: HTMLEngine,\n cssText: string,\n options: HTMLEngineRuntimeOptions\n): HTMLEngineFetch | undefined {\n const { fetch, onFontFace } = options\n if (!fetch || !onFontFace) return fetch\n const rules = new Map<string, CSSFontFaceRule[]>()\n // What CSS imports is a stylesheet whatever its name or the type it is served as.\n const stylesheets = new Set<string>()\n // The engine fetches a file once per rule that names it; each face is passed on once.\n const delivered = new Set<string>()\n const learn = (css: string, base: string | undefined) => {\n for (const rule of parseFontFaceRules(css, base)) {\n for (const source of rule.sources) rules.set(source, [...(rules.get(source) ?? []), rule])\n }\n for (const url of parseStylesheetImports(css, base)) stylesheets.add(url)\n }\n learn(cssText, options.baseURL)\n return async (url, signal) => {\n const resource = await fetch(url, signal)\n if (!resource) return null\n if (isStylesheet(resource) || stylesheets.has(url) || stylesheets.has(resource.url)) {\n learn(new TextDecoder().decode(resource.bytes), resource.url)\n }\n // One file can serve several rules, such as a family and an alias of it.\n const served = rules.get(url) ?? rules.get(resource.url) ?? []\n const bytes = served.length > 0 ? engine.decodeFont(resource.bytes) : null\n for (const rule of served) {\n const face = `${url}|${rule.family}|${rule.weight}|${rule.italic}`\n if (!bytes || delivered.has(face)) continue\n delivered.add(face)\n await onFontFace({\n family: rule.family,\n weight: rule.weight,\n italic: rule.italic,\n url,\n bytes\n })\n }\n return resource\n }\n}\n\ntype Box = HTMLEngineCapture['nodes'][number]['box']\n\nfunction rect(box: NonNullable<Box>): Rect {\n const [x, y, width, height] = box\n return { x, y, width, height }\n}\n\nfunction hasArea(box: NonNullable<Box>): boolean {\n return box[2] > 0 && box[3] > 0\n}\n\n/** Children of each captured node that are elements, by the node's index; generated content left out. */\nfunction elementChildren(capture: HTMLEngineCapture): Map<number, number[]> {\n const children = new Map<number, number[]>()\n for (const [index, node] of capture.nodes.entries()) {\n if (node.parent === undefined || node.tag === undefined || node.tag.startsWith('::')) continue\n const siblings = children.get(node.parent) ?? []\n siblings.push(index)\n children.set(node.parent, siblings)\n }\n return children\n}\n\n/**\n * Elements the HTML parser inserts around others where the markup leaves them out, such as the\n * `tbody` around a table's rows; a serialized document need not hold them.\n */\nconst IMPLIED_WRAPPERS = new Set(['tbody'])\n\n/**\n * Each element of the document with the captured element it was laid out as: matched in order\n * and by tag, looking through wrappers the parser inserted. A mismatch ends the matching among\n * those siblings, so it never pairs an element with another's box.\n */\nfunction pairElements(\n document: DesignDocument,\n capture: HTMLEngineCapture\n): [DesignElement, HTMLEngineNode][] {\n const children = elementChildren(capture)\n const body = capture.nodes.findIndex((node) => node.tag === 'body')\n const pairs: [DesignElement, HTMLEngineNode][] = []\n const pair = (elements: readonly DesignElement[], parent: number, shaderFrame = false) => {\n const queue = [...(children.get(parent) ?? [])]\n // The serializer writes a shader's still frame as an image ahead of its layer's children.\n const first = queue.at(0)\n if (shaderFrame && first !== undefined && capture.nodes[first].tag === 'img') queue.shift()\n for (const element of elements) {\n let node = queue.shift()\n // The HTML parser keeps SVG's mixed-case names, such as `linearGradient`; the document may not.\n while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {\n const tag = capture.nodes[node].tag\n if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return\n insertAll(queue, 0, children.get(node) ?? [])\n node = queue.shift()\n }\n if (node === undefined) return\n pairs.push([element, capture.nodes[node]])\n pair(designElements(element.children), node, element.shader?.frame !== undefined)\n }\n }\n if (body !== -1) pair(designElements(document.children), body)\n return pairs\n}\n\nfunction sameTag(captured: string | undefined, tagName: string): boolean {\n return captured?.toLowerCase() === tagName.toLowerCase()\n}\n\nfunction designElements(nodes: DesignDocument['children']): DesignElement[] {\n return nodes.filter((node): node is DesignElement => node.type === 'element')\n}\n\n/** Shorthands a browser runtime reports, `overflow` and `gap`, built from their captured longhands. */\nfunction withShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n // Captures leave initial values out.\n const value = (property: string, initial: string) =>\n Object.hasOwn(style, property) ? style[property] : initial\n const pair = (first: string, second: string) => (first === second ? first : `${first} ${second}`)\n const shorthands: DesignStyleDeclaration = {}\n if (Object.hasOwn(style, 'overflow-x') || Object.hasOwn(style, 'overflow-y')) {\n shorthands.overflow = pair(value('overflow-x', 'visible'), value('overflow-y', 'visible'))\n }\n if (Object.hasOwn(style, 'row-gap') || Object.hasOwn(style, 'column-gap')) {\n shorthands.gap = pair(value('row-gap', 'normal'), value('column-gap', 'normal'))\n }\n return { ...style, ...shorthands }\n}\n\n/** White space values that keep spaces, so a line of them takes room as a line of words does. */\nconst PRESERVED_WHITE_SPACE = new Set(['pre', 'pre-wrap', 'break-spaces'])\n\n/**\n * A line as a browser's text rects make it: across its words, leaving out inline boxes, and\n * nothing for a line without text. Where white space is kept, a line of spaces counts too.\n */\nfunction textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {\n const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)\n const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')\n if (words.length === 0) return null\n const left = minOf(words.map((run) => run.x))\n const right = maxOf(words.map((run) => run.x + run.width))\n return { x: left, y: line.y, width: right - left, height: line.height }\n}\n\nfunction layoutOf(node: HTMLEngineNode): DesignLayout | undefined {\n if (!node.box) return undefined\n const layout: DesignLayout = { box: rect(node.box) }\n const fragments = node.fragments?.filter(hasArea)\n if (fragments && fragments.length > 0) {\n layout.fragments = fragments.map(rect)\n // An inline element's box is the one around its fragments, as getBoundingClientRect gives.\n layout.box = computeBounds(layout.fragments)\n return layout\n }\n const whiteSpace = node.style?.['white-space']\n const keepsSpaces = whiteSpace !== undefined && PRESERVED_WHITE_SPACE.has(whiteSpace)\n const lines = (node.lines ?? [])\n .map((line) => textLine(line, keepsSpaces))\n .filter((line) => line !== null)\n if (lines.length > 0) layout.lines = lines\n return layout\n}\n\nfunction documentHTML(body: string, cssText: string): string {\n // `</style` would end the stylesheet early.\n const css = cssText.replaceAll(/<\\/style/gi, '<\\\\/style')\n return `<!doctype html><html><head><style>${css}</style></head><body>${body}</body></html>`\n}\n\n/**\n * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,\n * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a\n * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.\n */\nexport function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {\n const engine = options.engine ?? loadHTMLEngine\n return {\n kind: 'headless',\n parseHTML: parseHTMLDocument,\n serializeHTML,\n async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {\n const laidOut = await engine()\n const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {\n baseURL: options.baseURL,\n viewport: compute.viewport ?? DEFAULT_VIEWPORT,\n fetch: fontFaceFetch(laidOut, cssText, options)\n })\n const styled = structuredClone(document)\n for (const [element, node] of pairElements(styled, capture)) {\n // Every captured property's computed value, so none falls back to a stale inline one, with\n // sizes and line heights as the page set them rather than as layout resolved them, so the\n // importer tells a size the page fixed from one that fills or hugs and keeps a line height\n // that scales with the font; the boxes layout gave stay in `layout`.\n element.computedStyle = withShorthands({\n ...capture.initial,\n ...node.style,\n ...node.computed\n })\n if (compute.layout) element.layout = layoutOf(node)\n }\n return styled\n }\n }\n}\n"],"mappings":";;;;;;AASA,IAAI,gBACF,YAAY,QAAQ,gDAAgD;AAEtE,IAAI,UAAsC;;;;;AAM1C,MAAM,yBAAyB;;AAG/B,SAAgB,qBAAqB,QAAiC;CACpE,UAAU;CACV,UAAU;AACZ;AAEA,eAAe,WAAW,KAAmC;CAC3D,IAAI,CAAC,IAAI,WAAW,OAAO,GAAG;EAC5B,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,QAAQ,YAAY,QAAQ,sBAAsB,EAAE,CAAC;EACzF,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,wCAAwC,IAAI,IAAI,SAAS,QAAQ;EACnF,OAAO,SAAS,YAAY;CAC9B;CACA,MAAM,EAAE,aAAa,MAAM;;EAA0B;;CACrD,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AI;EAErC,OAAO,MAAM,cAAc,OAAO,SAAS;EAC3C,OAAO;CACT;CACA,MAAM,aAAa,KAAK,QAAQ;CAChC,MAAM,cAAc,eAAe,KAAA,KAAa,sBAAsB,IAAI,UAAU;CACpF,MAAM,SAAS,KAAK,SAAS,CAAC,EAAA,CAC3B,KAAK,SAAS,SAAS,MAAM,WAAW,CAAC,CAAC,CAC1C,QAAQ,SAAS,SAAS,IAAI;CACjC,IAAI,MAAM,SAAS,GAAG,OAAO,QAAQ;CACrC,OAAO;AACT;AAEA,SAAS,aAAa,MAAc,SAAyB;CAG3D,OAAO,qCADK,QAAQ,WAAW,cAAc,WACC,EAAE,uBAAuB,KAAK;AAC9E;;;;;;AAOA,SAAgB,wBAAwB,UAAoC,CAAC,GAAe;CAC1F,MAAM,SAAS,QAAQ,UAAU;CACjC,OAAO;EACL,MAAM;EACN,WAAW;EACX;EACA,MAAM,cAAc,UAAU,UAAU,IAAI,UAA6B,CAAC,GAAG;GAC3E,MAAM,UAAU,MAAM,OAAO;GAC7B,MAAM,UAAU,MAAM,QAAQ,OAAO,aAAa,cAAc,QAAQ,GAAG,OAAO,GAAG;IACnF,SAAS,QAAQ;IACjB,UAAU,QAAQ,YAAY;IAC9B,OAAO,cAAc,SAAS,SAAS,OAAO;GAChD,CAAC;GACD,MAAM,SAAS,gBAAgB,QAAQ;GACvC,KAAK,MAAM,CAAC,SAAS,SAAS,aAAa,QAAQ,OAAO,GAAG;IAK3D,QAAQ,gBAAgB,eAAe;KACrC,GAAG,QAAQ;KACX,GAAG,KAAK;KACR,GAAG,KAAK;IACV,CAAC;IACD,IAAI,QAAQ,QAAQ,QAAQ,SAAS,SAAS,IAAI;GACpD;GACA,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/load.ts","../../src/runtime.ts"],"sourcesContent":["import { DEADLINE_MS } from '@open-pencil/std/timing'\n\nimport { HTMLEngine } from './engine'\n\n/**\n * Where the engine's module (`html-engine.wasm`) loads from. By default it is read beside this\n * package, as Node and Bun resolve it; a host that serves it elsewhere, such as a bundled app,\n * points here instead.\n */\nexport type HTMLEngineLocator = () => string\n\nlet locator: HTMLEngineLocator = () =>\n import.meta.resolve('@open-pencil/html-engine/wasm/html-engine.wasm')\n\nlet loading: Promise<HTMLEngine> | null = null\n\n/**\n * How long a remote module may take to arrive, so a request that never settles cannot hold every\n * later load waiting on it; a failed load is retried by the next caller.\n */\nconst MODULE_LOAD_TIMEOUT_MS = DEADLINE_MS.transfer\n\n/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */\nexport function setHTMLEngineLocator(locate: HTMLEngineLocator): void {\n locator = locate\n loading = null\n}\n\nasync function readModule(url: string): Promise<ArrayBuffer> {\n if (!url.startsWith('file:')) {\n const response = await fetch(url, { signal: AbortSignal.timeout(MODULE_LOAD_TIMEOUT_MS) })\n if (!response.ok)\n throw new Error(`html-engine.wasm failed to load from ${url}: ${response.status}`)\n return response.arrayBuffer()\n }\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n const file = await readFile(new URL(url)).catch((error: unknown) => {\n throw new Error(\n `html-engine.wasm is missing at ${url}; build it with bun run build in packages/html-engine`,\n { cause: error }\n )\n })\n return file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength)\n}\n\n/** The engine, loaded once; a failed load is retried by the next caller. */\nexport function loadHTMLEngine(): Promise<HTMLEngine> {\n if (loading) return loading\n const load = readModule(locator()).then((bytes) => HTMLEngine.instantiate(bytes))\n loading = load\n load.catch(() => {\n if (loading === load) loading = null\n })\n return load\n}\n","import {\n parseFontFaceRules,\n parseHTMLDocument,\n parseStylesheetImports,\n type CSSFontFaceRule,\n type CSSComputeOptions,\n type CSSRuntime,\n type DesignDocument,\n type DesignElement,\n type DesignLayout,\n type DesignResource,\n type DesignResourceFetch,\n type DesignStyleDeclaration,\n type DesignViewport\n} from '@open-pencil/dom-css'\nimport { serializeHTML } from '@open-pencil/dom-css/export'\nimport { parseCSSColor } from '@open-pencil/scene-graph/css'\nimport { computeBounds } from '@open-pencil/scene-graph/geometry'\nimport type { Rect } from '@open-pencil/scene-graph/primitives'\nimport { insertAll, maxOf, minOf } from '@open-pencil/std/arrays'\n\nimport type { HTMLEngine } from './engine'\nimport { loadHTMLEngine } from './load'\nimport type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'\n\n/** The viewport a document is laid out in when the caller names none, as HTML import uses. */\nconst DEFAULT_VIEWPORT: DesignViewport = { width: 1440, height: 900 }\n\n/** A font a page's `@font-face` rule loads: the face the rule declares, and the file as TrueType or OpenType. */\nexport interface HTMLEngineFontFace {\n family: string\n weight: number\n italic: boolean\n url: string\n bytes: Uint8Array\n}\n\nexport interface HTMLEngineRuntimeOptions {\n /** The engine to lay documents out with, with the fonts they may use registered. */\n engine?: () => Promise<HTMLEngine>\n /** The document's URL, which its relative URLs resolve against. */\n baseURL?: string\n /**\n * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for\n * its `@font-face` rules when it comes with a CSS content type.\n */\n fetch?: DesignResourceFetch\n /**\n * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so\n * a host can draw that text in the same font. The layout waits for it.\n */\n onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>\n}\n\nfunction isStylesheet(resource: DesignResource): boolean {\n return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'\n}\n\n/**\n * A fetch that also reads the page's `@font-face` rules, from its own CSS and every stylesheet it\n * fetches, and passes each font they load to `onFontFace` as the engine receives it.\n */\nfunction fontFaceFetch(\n engine: HTMLEngine,\n cssText: string,\n options: HTMLEngineRuntimeOptions\n): DesignResourceFetch | undefined {\n const { fetch, onFontFace } = options\n if (!fetch || !onFontFace) return fetch\n const rules = new Map<string, CSSFontFaceRule[]>()\n // What CSS imports is a stylesheet whatever its name or the type it is served as.\n const stylesheets = new Set<string>()\n // The engine fetches a file once per rule that names it; each face is passed on once.\n const delivered = new Set<string>()\n const learn = (css: string, base: string | undefined) => {\n for (const rule of parseFontFaceRules(css, base)) {\n for (const source of rule.sources) rules.set(source, [...(rules.get(source) ?? []), rule])\n }\n for (const url of parseStylesheetImports(css, base)) stylesheets.add(url)\n }\n learn(cssText, options.baseURL)\n return async (url, signal) => {\n const resource = await fetch(url, signal)\n if (!resource) return null\n if (isStylesheet(resource) || stylesheets.has(url) || stylesheets.has(resource.url)) {\n learn(new TextDecoder().decode(resource.bytes), resource.url)\n }\n // One file can serve several rules, such as a family and an alias of it.\n const served = rules.get(url) ?? rules.get(resource.url) ?? []\n const bytes = served.length > 0 ? engine.decodeFont(resource.bytes) : null\n for (const rule of served) {\n const face = `${url}|${rule.family}|${rule.weight}|${rule.italic}`\n if (!bytes || delivered.has(face)) continue\n delivered.add(face)\n await onFontFace({\n family: rule.family,\n weight: rule.weight,\n italic: rule.italic,\n url,\n bytes\n })\n }\n return resource\n }\n}\n\ntype Box = HTMLEngineCapture['nodes'][number]['box']\n\nfunction rect(box: NonNullable<Box>): Rect {\n const [x, y, width, height] = box\n return { x, y, width, height }\n}\n\nfunction hasArea(box: NonNullable<Box>): boolean {\n return box[2] > 0 && box[3] > 0\n}\n\n/** Children of each captured node that are elements, by the node's index; generated content left out. */\nfunction elementChildren(capture: HTMLEngineCapture): Map<number, number[]> {\n const children = new Map<number, number[]>()\n for (const [index, node] of capture.nodes.entries()) {\n if (node.parent === undefined || node.tag === undefined || node.tag.startsWith('::')) continue\n const siblings = children.get(node.parent) ?? []\n siblings.push(index)\n children.set(node.parent, siblings)\n }\n return children\n}\n\n/**\n * Elements the HTML parser inserts around others where the markup leaves them out, such as the\n * `tbody` around a table's rows; a serialized document need not hold them.\n */\nconst IMPLIED_WRAPPERS = new Set(['tbody'])\n\n/**\n * Each element of the document with the captured element it was laid out as: matched in order\n * and by tag, looking through wrappers the parser inserted. A mismatch ends the matching among\n * those siblings, so it never pairs an element with another's box.\n */\nfunction pairElements(\n document: DesignDocument,\n capture: HTMLEngineCapture\n): [DesignElement, HTMLEngineNode][] {\n const children = elementChildren(capture)\n const body = capture.nodes.findIndex((node) => node.tag === 'body')\n const pairs: [DesignElement, HTMLEngineNode][] = []\n const pair = (elements: readonly DesignElement[], parent: number, shaderFrame = false) => {\n const queue = [...(children.get(parent) ?? [])]\n // The serializer writes a shader's still frame as an image ahead of its layer's children.\n const first = queue.at(0)\n if (shaderFrame && first !== undefined && capture.nodes[first].tag === 'img') queue.shift()\n for (const element of elements) {\n let node = queue.shift()\n // The HTML parser keeps SVG's mixed-case names, such as `linearGradient`; the document may not.\n while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {\n const tag = capture.nodes[node].tag\n if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return\n insertAll(queue, 0, children.get(node) ?? [])\n node = queue.shift()\n }\n if (node === undefined) return\n pairs.push([element, capture.nodes[node]])\n pair(designElements(element.children), node, element.shader?.frame !== undefined)\n }\n }\n if (body !== -1) pair(designElements(document.children), body)\n return pairs\n}\n\nfunction sameTag(captured: string | undefined, tagName: string): boolean {\n return captured?.toLowerCase() === tagName.toLowerCase()\n}\n\nfunction designElements(nodes: DesignDocument['children']): DesignElement[] {\n return nodes.filter((node): node is DesignElement => node.type === 'element')\n}\n\n/** Shorthands a browser runtime reports, `overflow` and `gap`, built from their captured longhands. */\nfunction withShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n // Captures leave initial values out.\n const value = (property: string, initial: string) =>\n Object.hasOwn(style, property) ? style[property] : initial\n const pair = (first: string, second: string) => (first === second ? first : `${first} ${second}`)\n const shorthands: DesignStyleDeclaration = {}\n if (Object.hasOwn(style, 'overflow-x') || Object.hasOwn(style, 'overflow-y')) {\n shorthands.overflow = pair(value('overflow-x', 'visible'), value('overflow-y', 'visible'))\n }\n if (Object.hasOwn(style, 'row-gap') || Object.hasOwn(style, 'column-gap')) {\n shorthands.gap = pair(value('row-gap', 'normal'), value('column-gap', 'normal'))\n }\n return { ...style, ...shorthands }\n}\n\n/** White space values that keep spaces, so a line of them takes room as a line of words does. */\nconst PRESERVED_WHITE_SPACE = new Set(['pre', 'pre-wrap', 'break-spaces'])\n\n/**\n * A line as a browser's text rects make it: across its words, leaving out inline boxes, and\n * nothing for a line without text. Where white space is kept, a line of spaces counts too.\n */\nfunction textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {\n const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)\n const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')\n if (words.length === 0) return null\n const left = minOf(words.map((run) => run.x))\n const right = maxOf(words.map((run) => run.x + run.width))\n return { x: left, y: line.y, width: right - left, height: line.height }\n}\n\nfunction layoutOf(node: HTMLEngineNode): DesignLayout | undefined {\n if (!node.box) return undefined\n const layout: DesignLayout = { box: rect(node.box) }\n const fragments = node.fragments?.filter(hasArea)\n if (fragments && fragments.length > 0) {\n layout.fragments = fragments.map(rect)\n // An inline element's box is the one around its fragments, as getBoundingClientRect gives.\n layout.box = computeBounds(layout.fragments)\n return layout\n }\n const whiteSpace = node.style?.['white-space']\n const keepsSpaces = whiteSpace !== undefined && PRESERVED_WHITE_SPACE.has(whiteSpace)\n const lines = (node.lines ?? [])\n .map((line) => textLine(line, keepsSpaces))\n .filter((line) => line !== null)\n if (lines.length > 0) layout.lines = lines\n return layout\n}\n\nfunction documentHTML(body: string, cssText: string): string {\n // `</style` would end the stylesheet early.\n const css = cssText.replaceAll(/<\\/style/gi, '<\\\\/style')\n return `<!doctype html><html><head><style>${css}</style></head><body>${body}</body></html>`\n}\n\n/**\n * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,\n * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a\n * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.\n */\n/** The `::before` and `::after` nodes of each captured element, by the element's index. */\nfunction generatedChildren(capture: HTMLEngineCapture): Map<number, number[]> {\n const generated = new Map<number, number[]>()\n for (const [index, node] of capture.nodes.entries()) {\n if (node.parent === undefined || !node.tag?.startsWith('::')) continue\n generated.set(node.parent, [...(generated.get(node.parent) ?? []), index])\n }\n return generated\n}\n\n/** The text a captured node holds directly, as a pseudo-element's generated content. */\n/** Each captured node's own text, its text children's joined in order, by the node's index. */\nfunction ownTexts(capture: HTMLEngineCapture): Map<number, string> {\n const texts = new Map<number, string>()\n for (const node of capture.nodes) {\n if (node.text === undefined || node.parent === undefined) continue\n texts.set(node.parent, (texts.get(node.parent) ?? '') + node.text)\n }\n return texts\n}\n\n/**\n * Shows each element's `::before` and `::after` as elements of their own, first and last among its\n * children, with the style, box, and text the engine generated for them, so they are imported as\n * any element is.\n */\nfunction showGeneratedContent(\n capture: HTMLEngineCapture,\n pairs: readonly [DesignElement, HTMLEngineNode][],\n layout: boolean\n): void {\n const indexes = new Map(capture.nodes.map((node, index) => [node, index]))\n const generated = generatedChildren(capture)\n const texts = ownTexts(capture)\n for (const [element, node] of pairs) {\n const index = indexes.get(node)\n for (const pseudo of (index === undefined ? undefined : generated.get(index)) ?? []) {\n const captured = capture.nodes[pseudo]\n const text = texts.get(pseudo) ?? ''\n const child: DesignElement = {\n type: 'element',\n tagName: captured.tag ?? '::before',\n attrs: {},\n children: text ? [{ type: 'text', text }] : [],\n computedStyle: withShorthands({\n ...capture.initial,\n ...captured.style,\n ...captured.computed\n })\n }\n if (layout) child.layout = layoutOf(captured)\n if (captured.tag === '::after') element.children.push(child)\n else element.children.unshift(child)\n }\n }\n}\n\n/**\n * The color the page's canvas is painted, as CSS takes it: the root element's background, or the\n * body's when the root has none.\n */\nfunction canvasBackground(capture: HTMLEngineCapture): string | undefined {\n const background = (tag: string) => {\n const node = capture.nodes.find((candidate) => candidate.tag === tag)\n const color = node?.style?.['background-color']\n return color && parseCSSColor(color) ? color : undefined\n }\n return background('html') ?? background('body')\n}\n\n/** A fetch that also keeps what it answered, by the URL asked for and the one it came from. */\nfunction keepingFetch(\n fetch: DesignResourceFetch | undefined,\n answered: Map<string, DesignResource>\n): DesignResourceFetch | undefined {\n if (!fetch) return undefined\n return async (url, signal) => {\n const resource = await fetch(url, signal)\n if (resource) answered.set(url, resource).set(resource.url, resource)\n return resource\n }\n}\n\n/** What an `<img>` loaded, by its `src` resolved against the page's address. */\nfunction imageOf(\n element: DesignElement,\n answered: ReadonlyMap<string, DesignResource>,\n baseURL: string | undefined\n): DesignResource | undefined {\n const { src } = element.attrs\n if (element.tagName.toLowerCase() !== 'img' || !src || !URL.canParse(src, baseURL)) {\n return undefined\n }\n return answered.get(new URL(src, baseURL).href)\n}\n\nexport function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {\n const engine = options.engine ?? loadHTMLEngine\n return {\n kind: 'headless',\n parseHTML: parseHTMLDocument,\n serializeHTML,\n async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {\n const laidOut = await engine()\n // The pictures the engine loads to lay images out go with their elements, so the layers\n // they become show them without fetching them again.\n const answered = new Map<string, DesignResource>()\n const fetch = keepingFetch(options.fetch, answered)\n const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {\n baseURL: options.baseURL,\n viewport: compute.viewport ?? DEFAULT_VIEWPORT,\n fetch: fontFaceFetch(laidOut, cssText, { ...options, fetch })\n })\n const styled = structuredClone(document)\n const pairs = pairElements(styled, capture)\n for (const [element, node] of pairs) {\n // Every captured property's computed value, so none falls back to a stale inline one, with\n // sizes and line heights as the page set them rather than as layout resolved them, so the\n // importer tells a size the page fixed from one that fills or hugs and keeps a line height\n // that scales with the font; the boxes layout gave stay in `layout`.\n element.computedStyle = withShorthands({\n ...capture.initial,\n ...node.style,\n ...node.computed\n })\n if (compute.layout) element.layout = layoutOf(node)\n const image = imageOf(element, answered, options.baseURL)\n if (image) element.image = image\n }\n showGeneratedContent(capture, pairs, compute.layout === true)\n styled.background = canvasBackground(capture)\n return styled\n }\n }\n}\n"],"mappings":";;;;;;;;AAWA,IAAI,gBACF,YAAY,QAAQ,gDAAgD;AAEtE,IAAI,UAAsC;;;;;AAM1C,MAAM,yBAAyB,YAAY;;AA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O;IACxD,IAAI,OAAO,QAAQ,QAAQ;GAC7B;GACA,qBAAqB,SAAS,OAAO,QAAQ,WAAW,IAAI;GAC5D,OAAO,aAAa,iBAAiB,OAAO;GAC5C,OAAO;EACT;CACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as v from "valibot";
2
- import { CSSRuntime } from "@open-pencil/dom-css";
2
+ import { CSSRuntime, DesignResourceFetch } from "@open-pencil/dom-css";
3
3
  //#region src/schema.d.ts
4
4
  declare const lineSchema: v.ObjectSchema<{
5
5
  readonly x: v.NumberSchema<undefined>;
@@ -133,17 +133,6 @@ type HTMLEngineLine = v.InferOutput<typeof lineSchema>;
133
133
  //#endregion
134
134
  //#region src/engine.d.ts
135
135
  /** A resource the document asked for, as the host fetched it: its final URL and its bytes. */
136
- interface HTMLEngineResource {
137
- url: string;
138
- bytes: Uint8Array;
139
- /** The resource's media type, such as `text/css`, when the host knows it. */
140
- contentType?: string;
141
- }
142
- /**
143
- * Fetches a stylesheet, font, or image the document refers to; null when it cannot. `signal`
144
- * aborts when the request runs out of time, and the layout goes on without it.
145
- */
146
- type HTMLEngineFetch = (url: string, signal: AbortSignal) => Promise<HTMLEngineResource | null>;
147
136
  interface HTMLEngineLayoutOptions {
148
137
  /** The document's URL, which relative URLs in it resolve against. */
149
138
  baseURL?: string;
@@ -153,7 +142,7 @@ interface HTMLEngineLayoutOptions {
153
142
  height: number;
154
143
  };
155
144
  /** Answers the document's requests; without one, every request fails. */
156
- fetch?: HTMLEngineFetch;
145
+ fetch?: DesignResourceFetch;
157
146
  /** How long one request may take before the layout goes on without it. */
158
147
  requestTimeoutMs?: number;
159
148
  }
@@ -226,19 +215,14 @@ interface HTMLEngineRuntimeOptions {
226
215
  * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for
227
216
  * its `@font-face` rules when it comes with a CSS content type.
228
217
  */
229
- fetch?: HTMLEngineFetch;
218
+ fetch?: DesignResourceFetch;
230
219
  /**
231
220
  * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so
232
221
  * a host can draw that text in the same font. The layout waits for it.
233
222
  */
234
223
  onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>;
235
224
  }
236
- /**
237
- * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
238
- * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
239
- * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
240
- */
241
225
  declare function createHTMLEngineRuntime(options?: HTMLEngineRuntimeOptions): CSSRuntime;
242
226
  //#endregion
243
- export { HTMLEngine, type HTMLEngineCapture, type HTMLEngineFetch, type HTMLEngineFontFace, type HTMLEngineLayoutOptions, type HTMLEngineLine, type HTMLEngineLocator, type HTMLEngineNode, type HTMLEngineResource, type HTMLEngineRuntimeOptions, createHTMLEngineRuntime, loadHTMLEngine, rasterImageSize, setHTMLEngineLocator };
227
+ export { HTMLEngine, type HTMLEngineCapture, type HTMLEngineFontFace, type HTMLEngineLayoutOptions, type HTMLEngineLine, type HTMLEngineLocator, type HTMLEngineNode, type HTMLEngineRuntimeOptions, createHTMLEngineRuntime, loadHTMLEngine, rasterImageSize, setHTMLEngineLocator };
244
228
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/engine.ts","../src/images.ts","../src/load.ts","../src/runtime.ts"],"mappings":";;;cAmBM,YAAU,EAAA;;;;;;;;;;;;;;;;;;;cASV,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCX,eAAa,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAWd,oBAAoB,EAAE,mBAAmB;KACzC,iBAAiB,EAAE,mBAAmB;KACtC,iBAAiB,EAAE,mBAAmB;;;;UC9CjC;EACf;EACA,OAAO;;EAEP;;;;;;KAOU,mBACV,aACA,QAAQ,gB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AQ;;;;;;;;;KC/P7D,QAAQ,eAAe;;iBAoGZ,gBAAgB,OAAO,aAAa;;;;;;;;KCjGxC;;iBAcI,qBAAqB,QAAQ;;iBAuB7B,kBAAkB,QAAQ;;;;UCjBzB;EACf;EACA;EACA;EACA;EACA,OAAO;;UAGQ;;EAEf,eAAe,QAAQ;;EAEvB;;;;;EAKA,QAAQ;;;;;EAKR,cAAc,MAAM,8BAA8B;;iBA6RpC,wBAAwB,UAAS,2BAAgC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-pencil/html-engine",
3
- "version": "0.17.0-beta.5",
3
+ "version": "0.17.0-beta.7",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -11,11 +11,12 @@
11
11
  "main": "./dist/index.js",
12
12
  "types": "./dist/index.d.ts",
13
13
  "dependencies": {
14
- "@open-pencil/dom-css": "^0.17.0-beta.5",
14
+ "@open-pencil/dom-css": "^0.17.0-beta.7",
15
+ "@open-pencil/std": "^0.17.0-beta.7",
15
16
  "valibot": "^1.5.0"
16
17
  },
17
18
  "peerDependencies": {
18
- "@open-pencil/scene-graph": "^0.17.0-beta.5"
19
+ "@open-pencil/scene-graph": "^0.17.0-beta.7"
19
20
  },
20
21
  "exports": {
21
22
  ".": {
package/src/engine.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import * as v from 'valibot'
2
2
 
3
+ import type { DesignResourceFetch } from '@open-pencil/dom-css'
4
+ import { createMutex } from '@open-pencil/std/async'
5
+ import { DEADLINE_MS, untilAborted } from '@open-pencil/std/timing'
6
+
3
7
  import { imageStandIn, rasterImageSize } from './images'
4
8
  import { captureSchema, requestsSchema, type HTMLEngineCapture } from './schema'
5
9
 
@@ -27,29 +31,13 @@ type EngineExports = Record<(typeof EXPORTS)[number], (...args: number[]) => num
27
31
  }
28
32
 
29
33
  /** A resource the document asked for, as the host fetched it: its final URL and its bytes. */
30
- export interface HTMLEngineResource {
31
- url: string
32
- bytes: Uint8Array
33
- /** The resource's media type, such as `text/css`, when the host knows it. */
34
- contentType?: string
35
- }
36
-
37
- /**
38
- * Fetches a stylesheet, font, or image the document refers to; null when it cannot. `signal`
39
- * aborts when the request runs out of time, and the layout goes on without it.
40
- */
41
- export type HTMLEngineFetch = (
42
- url: string,
43
- signal: AbortSignal
44
- ) => Promise<HTMLEngineResource | null>
45
-
46
34
  export interface HTMLEngineLayoutOptions {
47
35
  /** The document's URL, which relative URLs in it resolve against. */
48
36
  baseURL?: string
49
37
  /** In whole CSS pixels. */
50
38
  viewport: { width: number; height: number }
51
39
  /** Answers the document's requests; without one, every request fails. */
52
- fetch?: HTMLEngineFetch
40
+ fetch?: DesignResourceFetch
53
41
  /** How long one request may take before the layout goes on without it. */
54
42
  requestTimeoutMs?: number
55
43
  }
@@ -58,7 +46,7 @@ export interface HTMLEngineLayoutOptions {
58
46
  * How long a request may take by default: as long as the browser runtime waits for an image, so
59
47
  * one request that never ends cannot hold this layout, or the ones queued behind it, forever.
60
48
  */
61
- const REQUEST_TIMEOUT_MS = 10_000
49
+ const REQUEST_TIMEOUT_MS = DEADLINE_MS.request
62
50
 
63
51
  /** The largest viewport side the module takes, as a signed 32-bit length. */
64
52
  const MAX_VIEWPORT = 0x7fffffff
@@ -71,12 +59,9 @@ function checkViewport({ width, height }: HTMLEngineLayoutOptions['viewport']):
71
59
  }
72
60
  }
73
61
 
74
- /** A fetch that gives up, answering null, once `signal` aborts. */
62
+ /** A fetch that gives up, answering null, once it fails or `signal` aborts. */
75
63
  function withDeadline<T>(request: Promise<T>, signal: AbortSignal): Promise<T | null> {
76
- const expired = new Promise<null>((resolve) => {
77
- signal.addEventListener('abort', () => resolve(null), { once: true })
78
- })
79
- return Promise.race([request.catch(() => null), expired])
64
+ return untilAborted(request, signal).catch(() => null)
80
65
  }
81
66
 
82
67
  /** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */
@@ -142,7 +127,7 @@ export class HTMLEngine {
142
127
  readonly #exports: EngineExports
143
128
  readonly #encoder = new TextEncoder()
144
129
  readonly #decoder = new TextDecoder()
145
- #queue: Promise<unknown> = Promise.resolve()
130
+ #layouts = createMutex()
146
131
 
147
132
  private constructor(exports: EngineExports) {
148
133
  this.#exports = exports
@@ -275,8 +260,6 @@ export class HTMLEngine {
275
260
 
276
261
  /** Lays the document out once every resource it asks for is answered, and captures it. */
277
262
  layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {
278
- const run = this.#queue.then(() => this.#layout(html, options))
279
- this.#queue = run.catch(() => undefined)
280
- return run
263
+ return this.#layouts.run(() => this.#layout(html, options))
281
264
  }
282
265
  }
package/src/index.ts CHANGED
@@ -1,9 +1,4 @@
1
- export {
2
- HTMLEngine,
3
- type HTMLEngineFetch,
4
- type HTMLEngineLayoutOptions,
5
- type HTMLEngineResource
6
- } from './engine'
1
+ export { HTMLEngine, type HTMLEngineLayoutOptions } from './engine'
7
2
  export { rasterImageSize } from './images'
8
3
  export { loadHTMLEngine, setHTMLEngineLocator, type HTMLEngineLocator } from './load'
9
4
  export {
package/src/load.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { DEADLINE_MS } from '@open-pencil/std/timing'
2
+
1
3
  import { HTMLEngine } from './engine'
2
4
 
3
5
  /**
@@ -16,7 +18,7 @@ let loading: Promise<HTMLEngine> | null = null
16
18
  * How long a remote module may take to arrive, so a request that never settles cannot hold every
17
19
  * later load waiting on it; a failed load is retried by the next caller.
18
20
  */
19
- const MODULE_LOAD_TIMEOUT_MS = 60_000
21
+ const MODULE_LOAD_TIMEOUT_MS = DEADLINE_MS.transfer
20
22
 
21
23
  /** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */
22
24
  export function setHTMLEngineLocator(locate: HTMLEngineLocator): void {
package/src/runtime.ts CHANGED
@@ -8,15 +8,18 @@ import {
8
8
  type DesignDocument,
9
9
  type DesignElement,
10
10
  type DesignLayout,
11
+ type DesignResource,
12
+ type DesignResourceFetch,
11
13
  type DesignStyleDeclaration,
12
14
  type DesignViewport
13
15
  } from '@open-pencil/dom-css'
14
16
  import { serializeHTML } from '@open-pencil/dom-css/export'
15
- import { insertAll, maxOf, minOf } from '@open-pencil/scene-graph/arrays'
17
+ import { parseCSSColor } from '@open-pencil/scene-graph/css'
16
18
  import { computeBounds } from '@open-pencil/scene-graph/geometry'
17
19
  import type { Rect } from '@open-pencil/scene-graph/primitives'
20
+ import { insertAll, maxOf, minOf } from '@open-pencil/std/arrays'
18
21
 
19
- import type { HTMLEngine, HTMLEngineFetch, HTMLEngineResource } from './engine'
22
+ import type { HTMLEngine } from './engine'
20
23
  import { loadHTMLEngine } from './load'
21
24
  import type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'
22
25
 
@@ -41,7 +44,7 @@ export interface HTMLEngineRuntimeOptions {
41
44
  * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for
42
45
  * its `@font-face` rules when it comes with a CSS content type.
43
46
  */
44
- fetch?: HTMLEngineFetch
47
+ fetch?: DesignResourceFetch
45
48
  /**
46
49
  * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so
47
50
  * a host can draw that text in the same font. The layout waits for it.
@@ -49,7 +52,7 @@ export interface HTMLEngineRuntimeOptions {
49
52
  onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>
50
53
  }
51
54
 
52
- function isStylesheet(resource: HTMLEngineResource): boolean {
55
+ function isStylesheet(resource: DesignResource): boolean {
53
56
  return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'
54
57
  }
55
58
 
@@ -61,7 +64,7 @@ function fontFaceFetch(
61
64
  engine: HTMLEngine,
62
65
  cssText: string,
63
66
  options: HTMLEngineRuntimeOptions
64
- ): HTMLEngineFetch | undefined {
67
+ ): DesignResourceFetch | undefined {
65
68
  const { fetch, onFontFace } = options
66
69
  if (!fetch || !onFontFace) return fetch
67
70
  const rules = new Map<string, CSSFontFaceRule[]>()
@@ -235,6 +238,102 @@ function documentHTML(body: string, cssText: string): string {
235
238
  * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
236
239
  * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
237
240
  */
241
+ /** The `::before` and `::after` nodes of each captured element, by the element's index. */
242
+ function generatedChildren(capture: HTMLEngineCapture): Map<number, number[]> {
243
+ const generated = new Map<number, number[]>()
244
+ for (const [index, node] of capture.nodes.entries()) {
245
+ if (node.parent === undefined || !node.tag?.startsWith('::')) continue
246
+ generated.set(node.parent, [...(generated.get(node.parent) ?? []), index])
247
+ }
248
+ return generated
249
+ }
250
+
251
+ /** The text a captured node holds directly, as a pseudo-element's generated content. */
252
+ /** Each captured node's own text, its text children's joined in order, by the node's index. */
253
+ function ownTexts(capture: HTMLEngineCapture): Map<number, string> {
254
+ const texts = new Map<number, string>()
255
+ for (const node of capture.nodes) {
256
+ if (node.text === undefined || node.parent === undefined) continue
257
+ texts.set(node.parent, (texts.get(node.parent) ?? '') + node.text)
258
+ }
259
+ return texts
260
+ }
261
+
262
+ /**
263
+ * Shows each element's `::before` and `::after` as elements of their own, first and last among its
264
+ * children, with the style, box, and text the engine generated for them, so they are imported as
265
+ * any element is.
266
+ */
267
+ function showGeneratedContent(
268
+ capture: HTMLEngineCapture,
269
+ pairs: readonly [DesignElement, HTMLEngineNode][],
270
+ layout: boolean
271
+ ): void {
272
+ const indexes = new Map(capture.nodes.map((node, index) => [node, index]))
273
+ const generated = generatedChildren(capture)
274
+ const texts = ownTexts(capture)
275
+ for (const [element, node] of pairs) {
276
+ const index = indexes.get(node)
277
+ for (const pseudo of (index === undefined ? undefined : generated.get(index)) ?? []) {
278
+ const captured = capture.nodes[pseudo]
279
+ const text = texts.get(pseudo) ?? ''
280
+ const child: DesignElement = {
281
+ type: 'element',
282
+ tagName: captured.tag ?? '::before',
283
+ attrs: {},
284
+ children: text ? [{ type: 'text', text }] : [],
285
+ computedStyle: withShorthands({
286
+ ...capture.initial,
287
+ ...captured.style,
288
+ ...captured.computed
289
+ })
290
+ }
291
+ if (layout) child.layout = layoutOf(captured)
292
+ if (captured.tag === '::after') element.children.push(child)
293
+ else element.children.unshift(child)
294
+ }
295
+ }
296
+ }
297
+
298
+ /**
299
+ * The color the page's canvas is painted, as CSS takes it: the root element's background, or the
300
+ * body's when the root has none.
301
+ */
302
+ function canvasBackground(capture: HTMLEngineCapture): string | undefined {
303
+ const background = (tag: string) => {
304
+ const node = capture.nodes.find((candidate) => candidate.tag === tag)
305
+ const color = node?.style?.['background-color']
306
+ return color && parseCSSColor(color) ? color : undefined
307
+ }
308
+ return background('html') ?? background('body')
309
+ }
310
+
311
+ /** A fetch that also keeps what it answered, by the URL asked for and the one it came from. */
312
+ function keepingFetch(
313
+ fetch: DesignResourceFetch | undefined,
314
+ answered: Map<string, DesignResource>
315
+ ): DesignResourceFetch | undefined {
316
+ if (!fetch) return undefined
317
+ return async (url, signal) => {
318
+ const resource = await fetch(url, signal)
319
+ if (resource) answered.set(url, resource).set(resource.url, resource)
320
+ return resource
321
+ }
322
+ }
323
+
324
+ /** What an `<img>` loaded, by its `src` resolved against the page's address. */
325
+ function imageOf(
326
+ element: DesignElement,
327
+ answered: ReadonlyMap<string, DesignResource>,
328
+ baseURL: string | undefined
329
+ ): DesignResource | undefined {
330
+ const { src } = element.attrs
331
+ if (element.tagName.toLowerCase() !== 'img' || !src || !URL.canParse(src, baseURL)) {
332
+ return undefined
333
+ }
334
+ return answered.get(new URL(src, baseURL).href)
335
+ }
336
+
238
337
  export function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {
239
338
  const engine = options.engine ?? loadHTMLEngine
240
339
  return {
@@ -243,13 +342,18 @@ export function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}):
243
342
  serializeHTML,
244
343
  async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {
245
344
  const laidOut = await engine()
345
+ // The pictures the engine loads to lay images out go with their elements, so the layers
346
+ // they become show them without fetching them again.
347
+ const answered = new Map<string, DesignResource>()
348
+ const fetch = keepingFetch(options.fetch, answered)
246
349
  const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {
247
350
  baseURL: options.baseURL,
248
351
  viewport: compute.viewport ?? DEFAULT_VIEWPORT,
249
- fetch: fontFaceFetch(laidOut, cssText, options)
352
+ fetch: fontFaceFetch(laidOut, cssText, { ...options, fetch })
250
353
  })
251
354
  const styled = structuredClone(document)
252
- for (const [element, node] of pairElements(styled, capture)) {
355
+ const pairs = pairElements(styled, capture)
356
+ for (const [element, node] of pairs) {
253
357
  // Every captured property's computed value, so none falls back to a stale inline one, with
254
358
  // sizes and line heights as the page set them rather than as layout resolved them, so the
255
359
  // importer tells a size the page fixed from one that fills or hugs and keeps a line height
@@ -260,7 +364,11 @@ export function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}):
260
364
  ...node.computed
261
365
  })
262
366
  if (compute.layout) element.layout = layoutOf(node)
367
+ const image = imageOf(element, answered, options.baseURL)
368
+ if (image) element.image = image
263
369
  }
370
+ showGeneratedContent(capture, pairs, compute.layout === true)
371
+ styled.background = canvasBackground(capture)
264
372
  return styled
265
373
  }
266
374
  }
@@ -3142,11 +3142,11 @@ limitations under the License.
3142
3142
 
3143
3143
  ## Apache License 2.0
3144
3144
 
3145
- - blitz-dom 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3146
- - blitz-html 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3147
- - blitz-traits 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3148
- - debug_timer 0.1.3, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3149
- - stylo_taffy 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3145
+ - blitz-dom 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
3146
+ - blitz-html 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
3147
+ - blitz-traits 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
3148
+ - debug_timer 0.1.3, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
3149
+ - stylo_taffy 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
3150
3150
  - [allocator-api2 0.2.21](https://crates.io/crates/allocator-api2/0.2.21)
3151
3151
  - [color 0.3.3](https://crates.io/crates/color/0.3.3)
3152
3152
  - [dtoa 1.0.11](https://crates.io/crates/dtoa/1.0.11)
Binary file
@@ -1 +1 @@
1
- 1afba8ec3f58a672766715c148916f03be542e3b1eb98be2e984d471c06d1dfe
1
+ 7537116e0011d6279bc75feb7d8e6dc37c71271915058fced780f014a53b78c1