bm-render 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +38 -0
- package/README.md +51 -3
- package/README.vi.md +51 -0
- package/THIRD-PARTY-NOTICES.md +1228 -0
- package/js/addons.d.mts +13 -0
- package/js/addons.mjs +74 -0
- package/js/bm_render.core.wasm +0 -0
- package/js/bm_render.pdf.wasm +0 -0
- package/js/bm_render.standard.wasm +0 -0
- package/js/bm_render.wasm +0 -0
- package/js/bm_woff.wasm +0 -0
- package/js/build-manifest.json +46 -0
- package/js/core.d.mts +16 -0
- package/js/core.mjs +20 -0
- package/js/engine.mjs +797 -0
- package/js/full.d.mts +16 -0
- package/js/full.mjs +20 -0
- package/js/index.d.mts +381 -0
- package/js/index.mjs +64 -0
- package/js/native.d.mts +4 -0
- package/js/native.mjs +250 -0
- package/js/node-core.mjs +9 -0
- package/js/node-full.mjs +9 -0
- package/js/node-native.mjs +15 -0
- package/js/node-pdf.mjs +34 -0
- package/js/node-standard.mjs +9 -0
- package/js/node.mjs +63 -0
- package/js/pdf-api.mjs +232 -0
- package/js/pdf-resources.mjs +152 -0
- package/js/pdf-types.d.mts +211 -0
- package/js/pdf.d.mts +85 -0
- package/js/pdf.mjs +26 -0
- package/js/standard.d.mts +16 -0
- package/js/standard.mjs +20 -0
- package/js/wasm-file.mjs +93 -0
- package/js/wasm.d.mts +9 -0
- package/package.json +252 -4
package/js/engine.mjs
ADDED
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
// bm-render internal: the JS binding around one engine backend (a bm_render.wasm instance, or the native
|
|
2
|
+
// Node-API addon: see "backend" in createBinding and docs/NATIVE.md).
|
|
3
|
+
/** True for a WebAssembly.Module from any realm (Next.js Edge, vm contexts, iframes), where `instanceof` fails. */
|
|
4
|
+
const isWasmModule = (x) => Object.prototype.toString.call(x) === "[object WebAssembly.Module]";
|
|
5
|
+
//
|
|
6
|
+
// `createBinding(defaultWasm?)` returns `{ init, initSync, Renderer, features, ... }` bound to its own
|
|
7
|
+
// module instance. Every public entry creates exactly one binding when it is first evaluated:
|
|
8
|
+
// js/index.mjs (bm-render, explicit init) js/node.mjs (bm-render on Node: index.mjs + auto-init)
|
|
9
|
+
// js/core.mjs / standard.mjs / full.mjs js/node-core.mjs / node-standard.mjs / node-full.mjs
|
|
10
|
+
// (bm-render/<profile>, init() finds the wasm) (bm-render/<profile> on Node: same binding + auto-init)
|
|
11
|
+
// so one process can load several profiles side by side; within one binding the first successful
|
|
12
|
+
// init wins (later calls return the same instance). This file is not part of the public API.
|
|
13
|
+
|
|
14
|
+
/** Optional features in `bm_features()` bit order (src/config.zig `feature_bits`). */
|
|
15
|
+
const FEATURE_NAMES = ["css", "tw", "html", "svg", "woff", "variableFonts", "cff", "effects", "modernColor", "tables",
|
|
16
|
+
"floats", "webpGifDecode", "textWrapBalance", "colorFonts", "complexText", "animation", "extraCodecs", "renderSvg", "pdf"];
|
|
17
|
+
const FEATURE_LABELS = { css: "stylesheet (`css` option)", html: "HTML input", woff: "WOFF/WOFF2 font", renderSvg: "renderSvg", pdf: "renderPdf",
|
|
18
|
+
animation: "animation", extraCodecs: "ICO output" };
|
|
19
|
+
|
|
20
|
+
const enc = new TextEncoder();
|
|
21
|
+
const dec = new TextDecoder();
|
|
22
|
+
const DISPOSE = typeof Symbol.dispose === "symbol" ? Symbol.dispose : Symbol.for("nodejs.dispose");
|
|
23
|
+
|
|
24
|
+
/** sfnt converter installed by js/addons.mjs (`loadWoff`) for builds without WOFF support (shared by every binding). */
|
|
25
|
+
let woffDecoder = null;
|
|
26
|
+
/** WOFF decoder of the native addon when it is loaded (js/native.mjs): `loadWoff()` is then a no-op. */
|
|
27
|
+
let builtInWoff = null;
|
|
28
|
+
|
|
29
|
+
/** @internal used by js/addons.mjs */
|
|
30
|
+
export function setWoffDecoder(fn) {
|
|
31
|
+
woffDecoder = fn;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @internal used by js/native.mjs (sets) and js/addons.mjs (reads): the process-wide built-in WOFF decoder, or null */
|
|
35
|
+
export function builtInWoffDecoder(fn) {
|
|
36
|
+
if (fn !== undefined) {
|
|
37
|
+
builtInWoff = fn;
|
|
38
|
+
woffDecoder = fn;
|
|
39
|
+
}
|
|
40
|
+
return builtInWoff;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isWoff(b) {
|
|
44
|
+
return b.length >= 4 && b[0] === 0x77 && b[1] === 0x4f && b[2] === 0x46 && (b[3] === 0x46 || b[3] === 0x32); // wOFF / wOF2
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function toBytes(data) {
|
|
48
|
+
if (data instanceof Uint8Array) return data;
|
|
49
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
50
|
+
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
51
|
+
throw new TypeError("expected Uint8Array or ArrayBuffer");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isBinary(v) {
|
|
55
|
+
return v instanceof Uint8Array || v instanceof ArrayBuffer || ArrayBuffer.isView(v);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function normalizeUnicodeRange(value) {
|
|
59
|
+
if (value == null) return null;
|
|
60
|
+
const input = Array.isArray(value) ? value : typeof value === "string" ? value.split(",").map((part) => {
|
|
61
|
+
const m = /^\s*U\+([0-9a-f?]{1,6})(?:-([0-9a-f]{1,6}))?\s*$/i.exec(part);
|
|
62
|
+
if (!m) throw new TypeError(`bm-render: invalid unicodeRange: ${part}`);
|
|
63
|
+
return [parseInt(m[1].replaceAll("?", "0"), 16), parseInt(m[2] ?? m[1].replaceAll("?", "f"), 16)];
|
|
64
|
+
}) : null;
|
|
65
|
+
if (!input) throw new TypeError("bm-render: unicodeRange must be ranges or a CSS unicode-range string");
|
|
66
|
+
return input.map((range) => {
|
|
67
|
+
if (!Array.isArray(range) || range.length !== 2 || !Number.isInteger(range[0]) || !Number.isInteger(range[1]) ||
|
|
68
|
+
range[0] < 0 || range[1] > 0x10ffff || range[0] > range[1]) throw new TypeError("bm-render: invalid unicodeRange bounds");
|
|
69
|
+
return [range[0], range[1]];
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function unsupported(what) {
|
|
74
|
+
return new Error(`bm-render: ${what} is not supported in bm-render`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const PREPARED = Symbol.for("bm-render.prepared");
|
|
78
|
+
|
|
79
|
+
/** Handle returned by `prepare` / `prepareAnimation` (opaque, like takumi's `Prepared`). */
|
|
80
|
+
export class Prepared {
|
|
81
|
+
constructor(kind, source, options) {
|
|
82
|
+
this[PREPARED] = { kind, source, options };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function unwrap(source, options, kind) {
|
|
87
|
+
const p = source && source[PREPARED];
|
|
88
|
+
if (!p) return [source, options];
|
|
89
|
+
if (p.kind !== kind) throw new TypeError(`bm-render: this prepared handle is for ${p.kind === "anim" ? "renderAnimation" : "render"}`);
|
|
90
|
+
return [p.source, { ...p.options, ...options }];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function throwIfAborted(signal) {
|
|
94
|
+
if (signal && signal.aborted) throw signal.reason ?? new Error("bm-render: aborted");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function imageList(images) {
|
|
98
|
+
return Array.isArray(images) ? images : images && images.sources ? images.sources : [];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Resolves lazy `images[].data()` entries (async paths only). */
|
|
102
|
+
async function resolveImages(images) {
|
|
103
|
+
const list = imageList(images);
|
|
104
|
+
if (!list.some((i) => typeof i.data === "function" || (i.data && typeof i.data.then === "function"))) return images;
|
|
105
|
+
return Promise.all(list.map(async (i) => ({ ...i, data: await (typeof i.data === "function" ? i.data() : i.data) })));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Reads a `file:` URL without a static `node:fs` import (keeps browser bundlers happy). */
|
|
109
|
+
export async function readFileUrl(url) {
|
|
110
|
+
const name = "node:fs/promises";
|
|
111
|
+
const fs = await import(/* @vite-ignore */ /* webpackIgnore: true */ name);
|
|
112
|
+
return new Uint8Array(await fs.readFile(url));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const MIME = { png: "image/png", jpeg: "image/jpeg", jpg: "image/jpeg", webp: "image/webp", ico: "image/x-icon" };
|
|
116
|
+
|
|
117
|
+
function dataUrl(format, bytes) {
|
|
118
|
+
let bin = "";
|
|
119
|
+
for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
|
|
120
|
+
return `data:${MIME[format || "png"]};base64,${btoa(bin)}`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function mimeCheck(options) {
|
|
124
|
+
if (!MIME[options.format || "png"]) throw new Error("bm-render: renderAsDataUrl needs an encoded format");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const NEEDS_INPUT = "bm-render: init() needs the wasm binary: bytes, a URL / Request / Response, or a WebAssembly.Module " +
|
|
128
|
+
"(e.g. `import wasm from \"bm-render/full.wasm\"` on Cloudflare Workers). The profile entries bm-render/core, " +
|
|
129
|
+
"bm-render/standard and bm-render/full locate their wasm file themselves.";
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* @param {(() => URL) | undefined} defaultWasm where `init()` without an argument loads the wasm from
|
|
133
|
+
* (called lazily, so a runtime without a usable `import.meta.url` only fails when it is actually needed)
|
|
134
|
+
* @param {object} [external] a ready backend to use instead of a wasm instance (js/native.mjs passes the
|
|
135
|
+
* native addon's); see the backend interface below. init() / initSync() are then no-ops.
|
|
136
|
+
*/
|
|
137
|
+
export function createBinding(defaultWasm, external) {
|
|
138
|
+
/** @type {WebAssembly.Exports & Record<string, any>} */
|
|
139
|
+
let wasm = null;
|
|
140
|
+
/** in-flight `init()` (concurrent callers share it) */
|
|
141
|
+
let pending = null;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Optional features of the loaded wasm binary (all false before init). Binaries older than the
|
|
145
|
+
* `bm_features` export report every feature as available.
|
|
146
|
+
* @type {Record<string, boolean>}
|
|
147
|
+
*/
|
|
148
|
+
const features = Object.fromEntries(FEATURE_NAMES.map((n) => [n, false]));
|
|
149
|
+
|
|
150
|
+
function setFeatures(m = typeof wasm.bm_features === "function" ? wasm.bm_features() >>> 0 : 0xffffffff) {
|
|
151
|
+
FEATURE_NAMES.forEach((n, i) => { features[n] = ((m >>> i) & 1) === 1; });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const FULL_ONLY = new Set(["renderSvg", "animation", "extraCodecs", "colorFonts", "complexText"]);
|
|
155
|
+
function requireFeature(name) {
|
|
156
|
+
if (!features[name]) {
|
|
157
|
+
if (name === "pdf") throw new Error("bm-render: renderPdf is not supported by this build (use the pdf build: import from \"bm-render/pdf\")");
|
|
158
|
+
throw new Error(`bm-render: this build has no ${FEATURE_LABELS[name] || name} support (use the ${FULL_ONLY.has(name) ? "full" : "standard / full"} build${name === "woff" ? ", or load the WOFF add-on: import { loadWoff } from \"bm-render/woff\"; await loadWoff()" : ""})`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function u8() {
|
|
163
|
+
return new Uint8Array(wasm.memory.buffer);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Copies bytes into wasm memory; returns [ptr, len]. Caller frees unless ownership is transferred. */
|
|
167
|
+
function copyIn(bytes) {
|
|
168
|
+
const len = bytes.length;
|
|
169
|
+
const ptr = wasm.bm_alloc(len || 1);
|
|
170
|
+
if (!ptr) throw new Error("bm-render: out of memory");
|
|
171
|
+
u8().set(bytes, ptr);
|
|
172
|
+
return [ptr, len];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function copyInString(str) {
|
|
176
|
+
// Worst case 3 bytes per UTF-16 unit; encodeInto avoids an intermediate buffer.
|
|
177
|
+
const cap = str.length * 3 || 1;
|
|
178
|
+
const ptr = wasm.bm_alloc(cap);
|
|
179
|
+
if (!ptr) throw new Error("bm-render: out of memory");
|
|
180
|
+
const { written } = enc.encodeInto(str, u8().subarray(ptr, ptr + cap));
|
|
181
|
+
return [ptr, written, cap];
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function lastError() {
|
|
185
|
+
const ptr = wasm.bm_last_error_ptr();
|
|
186
|
+
const len = wasm.bm_last_error_len();
|
|
187
|
+
return dec.decode(u8().subarray(ptr, ptr + len));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function check(status) {
|
|
191
|
+
if (status !== 0) throw new Error("bm-render: " + (lastError() || "error " + status));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function adopt(instance) {
|
|
195
|
+
if (!wasm) {
|
|
196
|
+
wasm = instance.exports;
|
|
197
|
+
setFeatures();
|
|
198
|
+
}
|
|
199
|
+
return wasm;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ---- backend -----------------------------------------------------------------------------------------
|
|
203
|
+
// Everything below this block talks to the engine only through `backend`:
|
|
204
|
+
//
|
|
205
|
+
// name "wasm" | "native"
|
|
206
|
+
// ready() false until the engine can be used (wasm: before init)
|
|
207
|
+
// has(op) whether the build provides the operation
|
|
208
|
+
// create() -> handle a renderer (truthy); destroy(handle)
|
|
209
|
+
// run(handle, op, arg0, arg1, input, options, attachments, text) -> Uint8Array | string
|
|
210
|
+
// One engine operation. `op`: "render" | "measure" | "svg" | "pdf" | "pdfMeasure" (arg0 = source kind:
|
|
211
|
+
// 0 JSON tree, 1 HTML; input = the source text, options = options JSON), "animation" (input = options JSON),
|
|
212
|
+
// "registerFont" (arg0 = weight, arg1 = italic -1 | 0 | 1 as u32, input = family name, attachments =
|
|
213
|
+
// the font file), "unregisterFont" (input = family; result [0 | 1]), "clearFonts".
|
|
214
|
+
// `attachments`: null or a flat array of [key, bytes, flags, width, height] groups; for the source
|
|
215
|
+
// ops they are the call's image sources (flags bit 0 = raw RGBA width x height, bit 1 = premultiplied).
|
|
216
|
+
// Returns a fresh Uint8Array, or with `text` the result decoded as UTF-8. Throws Error("bm-render: ...").
|
|
217
|
+
// runAsync?(same) -> Promise optional: the same off the calling thread, inputs snapshotted at the call
|
|
218
|
+
// (native). Without it the async API runs `run`.
|
|
219
|
+
// memoryBytes() bytes the engine currently holds
|
|
220
|
+
//
|
|
221
|
+
// A new output kind (e.g. PDF) = one more `op` here (the wasm export to call) + its entry in
|
|
222
|
+
// src/native/ops.zig + the public method below. See docs/NATIVE.md.
|
|
223
|
+
|
|
224
|
+
/** The result of the last call on `h`: a copy of the bytes, or the decoded text. */
|
|
225
|
+
function take(h, text, release) {
|
|
226
|
+
const ptr = wasm.bm_result_ptr(h);
|
|
227
|
+
const len = wasm.bm_result_len(h);
|
|
228
|
+
const out = text ? dec.decode(u8().subarray(ptr, ptr + len)) : u8().slice(ptr, ptr + len);
|
|
229
|
+
if (release) wasm.bm_release_result(h);
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Replaces the renderer's image sources with `atts` (copied into wasm memory). */
|
|
234
|
+
function putImages(h, atts) {
|
|
235
|
+
wasm.bm_clear_images(h);
|
|
236
|
+
for (let i = 0; atts && i < atts.length; i += 5) {
|
|
237
|
+
const [sptr, slen, scap] = copyInString(atts[i]);
|
|
238
|
+
const [dptr, dlen] = copyIn(atts[i + 1]);
|
|
239
|
+
const status = atts[i + 2] & 1
|
|
240
|
+
? wasm.bm_put_rgba(h, sptr, slen, dptr, dlen, atts[i + 3], atts[i + 4], atts[i + 2] & 2 ? 1 : 0)
|
|
241
|
+
: wasm.bm_put_image(h, sptr, slen, dptr, dlen);
|
|
242
|
+
wasm.bm_free(sptr, scap);
|
|
243
|
+
wasm.bm_free(dptr, dlen || 1);
|
|
244
|
+
check(status);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Source ops: the export taking (handle, kind, source, options); [1] = pre-`*_src` export (JSON only). */
|
|
249
|
+
const SOURCE_OPS = { render: ["bm_render_src", "bm_render"], measure: ["bm_measure_src", "bm_measure"], svg: ["bm_render_svg"],
|
|
250
|
+
pdf: ["bm_render_pdf"], pdfMeasure: ["bm_measure_pdf"], pdfNeeds: ["bm_needs_pdf"] };
|
|
251
|
+
|
|
252
|
+
const backend = external || {
|
|
253
|
+
name: "wasm",
|
|
254
|
+
ready: () => wasm !== null,
|
|
255
|
+
has: (op) => (op === "animation" ? !!wasm.bm_render_animation : true),
|
|
256
|
+
create: () => wasm.bm_renderer_new(),
|
|
257
|
+
destroy: (h) => wasm.bm_renderer_free(h),
|
|
258
|
+
memoryBytes: () => wasm.memory.buffer.byteLength,
|
|
259
|
+
run(h, op, arg0, arg1, input, options, atts, text) {
|
|
260
|
+
if (SOURCE_OPS[op]) {
|
|
261
|
+
putImages(h, atts);
|
|
262
|
+
const [jptr, jlen, jcap] = copyInString(input);
|
|
263
|
+
const [optr, olen, ocap] = copyInString(options);
|
|
264
|
+
const [name, legacy] = SOURCE_OPS[op];
|
|
265
|
+
// (older binaries without the *_src exports accept JSON only)
|
|
266
|
+
const status = wasm[name] ? wasm[name](h, arg0, jptr, jlen, optr, olen)
|
|
267
|
+
: arg0 === 0 && legacy ? wasm[legacy](h, jptr, jlen, optr, olen)
|
|
268
|
+
: -1;
|
|
269
|
+
wasm.bm_free(jptr, jcap);
|
|
270
|
+
wasm.bm_free(optr, ocap);
|
|
271
|
+
if (status === -1) throw new Error("bm-render: this wasm build does not accept HTML sources");
|
|
272
|
+
check(status);
|
|
273
|
+
return take(h, text, true);
|
|
274
|
+
}
|
|
275
|
+
if (op === "animation") {
|
|
276
|
+
putImages(h, atts);
|
|
277
|
+
const [ptr, len, cap] = copyInString(input);
|
|
278
|
+
const status = wasm.bm_render_animation(h, ptr, len);
|
|
279
|
+
wasm.bm_free(ptr, cap);
|
|
280
|
+
check(status);
|
|
281
|
+
return take(h, text, true);
|
|
282
|
+
}
|
|
283
|
+
if (op === "registerFont") {
|
|
284
|
+
const [ptr, len] = copyIn(atts[1]);
|
|
285
|
+
const [nptr, nlen, ncap] = copyInString(input);
|
|
286
|
+
const [optr, olen, ocap] = copyInString(options || "");
|
|
287
|
+
// Ownership of the font bytes moves to the renderer (zero-copy parsing inside wasm).
|
|
288
|
+
const status = wasm.bm_register_font_options
|
|
289
|
+
? wasm.bm_register_font_options(h, ptr, len, nptr, nlen, arg0, arg1, optr, olen)
|
|
290
|
+
: wasm.bm_register_font(h, ptr, len, nptr, nlen, arg0, arg1);
|
|
291
|
+
wasm.bm_free(nptr, ncap);
|
|
292
|
+
wasm.bm_free(optr, ocap);
|
|
293
|
+
check(status);
|
|
294
|
+
return take(h, text, false);
|
|
295
|
+
}
|
|
296
|
+
if (op === "unregisterFont") {
|
|
297
|
+
const [nptr, nlen, ncap] = copyInString(input);
|
|
298
|
+
const r = wasm.bm_unregister_font(h, nptr, nlen);
|
|
299
|
+
wasm.bm_free(nptr, ncap);
|
|
300
|
+
return Uint8Array.of(r !== 0 ? 1 : 0);
|
|
301
|
+
}
|
|
302
|
+
if (op === "clearFonts") {
|
|
303
|
+
wasm.bm_clear_fonts(h);
|
|
304
|
+
return new Uint8Array(0);
|
|
305
|
+
}
|
|
306
|
+
throw unsupported(op);
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
if (external) setFeatures(external.featureBits());
|
|
310
|
+
|
|
311
|
+
/** Synchronously instantiate from bytes or a compiled WebAssembly.Module (or `{ module }`). */
|
|
312
|
+
function initSync(input) {
|
|
313
|
+
if (external) return external.exports;
|
|
314
|
+
if (wasm) return wasm;
|
|
315
|
+
if (input && typeof input === "object" && "module" in input && !isWasmModule(input)) input = input.module;
|
|
316
|
+
if (input == null) throw new Error(NEEDS_INPUT.replace("init()", "initSync()"));
|
|
317
|
+
const mod = isWasmModule(input) ? input : new WebAssembly.Module(input);
|
|
318
|
+
return adopt(new WebAssembly.Instance(mod, {}));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function load(input) {
|
|
322
|
+
input = await input;
|
|
323
|
+
if (input && typeof input === "object" && "module_or_path" in input) input = await input.module_or_path;
|
|
324
|
+
if (input == null) {
|
|
325
|
+
if (!defaultWasm) throw new Error(NEEDS_INPUT);
|
|
326
|
+
let url;
|
|
327
|
+
try {
|
|
328
|
+
url = defaultWasm();
|
|
329
|
+
} catch (e) {
|
|
330
|
+
throw new Error("bm-render: cannot locate the wasm file in this runtime (no usable import.meta.url); pass it to init() " +
|
|
331
|
+
"explicitly, e.g. `import wasm from \"bm-render/core.wasm\"; await init(wasm)` (" + (e && e.message) + ")");
|
|
332
|
+
}
|
|
333
|
+
input = url.protocol === "file:" ? await readFileUrl(url) : url;
|
|
334
|
+
}
|
|
335
|
+
if (typeof input === "string" || (typeof URL !== "undefined" && input instanceof URL) ||
|
|
336
|
+
(typeof Request !== "undefined" && input instanceof Request)) {
|
|
337
|
+
const res = await fetch(input);
|
|
338
|
+
if (!res.ok) throw new Error(`bm-render: failed to fetch the wasm (${res.status} ${res.statusText || ""}): ${res.url || input}`);
|
|
339
|
+
input = res;
|
|
340
|
+
}
|
|
341
|
+
if (typeof Response !== "undefined" && input instanceof Response) {
|
|
342
|
+
if (WebAssembly.instantiateStreaming && (input.headers.get("content-type") || "").startsWith("application/wasm")) {
|
|
343
|
+
const { instance } = await WebAssembly.instantiateStreaming(input, {});
|
|
344
|
+
return adopt(instance);
|
|
345
|
+
}
|
|
346
|
+
input = await input.arrayBuffer();
|
|
347
|
+
}
|
|
348
|
+
if (isWasmModule(input)) return adopt(await WebAssembly.instantiate(input, {}));
|
|
349
|
+
const { instance } = await WebAssembly.instantiate(input, {});
|
|
350
|
+
return adopt(instance);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Instantiate from a URL / Request / Response / Promise<Response> / bytes / WebAssembly.Module
|
|
355
|
+
* (or `{ module_or_path }`). Idempotent: once initialised, every call resolves to the same instance and
|
|
356
|
+
* ignores its argument; concurrent calls share one instantiation; a failed call can be retried.
|
|
357
|
+
*/
|
|
358
|
+
function init(input) {
|
|
359
|
+
if (external) return Promise.resolve(external.exports);
|
|
360
|
+
if (wasm) return Promise.resolve(wasm);
|
|
361
|
+
if (!pending) {
|
|
362
|
+
pending = load(input).finally(() => { pending = null; });
|
|
363
|
+
}
|
|
364
|
+
return pending;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
class Renderer {
|
|
368
|
+
#h = 0;
|
|
369
|
+
#resSeq = 0;
|
|
370
|
+
/** `fonts` entries of renders registered so far (takumi dedupes them across calls), by the loader's
|
|
371
|
+
* bytes / object and its name, weight and style; stale once a font is unregistered or cleared */
|
|
372
|
+
#fontsSeen = new WeakMap();
|
|
373
|
+
#fontsByUrl = new Map();
|
|
374
|
+
#fontsGen = 0;
|
|
375
|
+
/** attachments of the call being prepared: flat [key, bytes, flags, width, height] groups */
|
|
376
|
+
#atts = [];
|
|
377
|
+
|
|
378
|
+
constructor(options = {}) {
|
|
379
|
+
if (!backend.ready()) throw new Error("bm-render: call init()/initSync() before creating a Renderer");
|
|
380
|
+
this.#h = backend.create();
|
|
381
|
+
if (!this.#h) throw new Error("bm-render: out of memory");
|
|
382
|
+
void options;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
#handle() {
|
|
386
|
+
if (!this.#h) throw new Error("bm-render: renderer has been freed");
|
|
387
|
+
return this.#h;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Register a font: TTF/OTF/TTC (every face of a collection), variable fonts, and WOFF/WOFF2 when the
|
|
392
|
+
* build includes them. Accepts raw bytes or `{ name, data, weight, style }`. Returns takumi's
|
|
393
|
+
* `RegisteredFamily[]`: `[{ name, faces: [{ weight, style, width, index }], weight, style }]`.
|
|
394
|
+
* A URL string, or `data` given as a function / promise, makes it async (returns a Promise).
|
|
395
|
+
*/
|
|
396
|
+
registerFont(font) {
|
|
397
|
+
if (typeof font === "string" || (typeof URL !== "undefined" && font instanceof URL)) {
|
|
398
|
+
return fetch(font).then((res) => {
|
|
399
|
+
if (!res.ok) throw new Error(`bm-render: failed to fetch font ${font}: ${res.status}`);
|
|
400
|
+
return res.arrayBuffer();
|
|
401
|
+
}).then((buf) => this.registerFont(new Uint8Array(buf)));
|
|
402
|
+
}
|
|
403
|
+
if (font && typeof font.then === "function") return font.then((f) => this.registerFont(f));
|
|
404
|
+
const details = isBinary(font) ? { data: font } : font;
|
|
405
|
+
if (!details || details.data == null) throw new TypeError("bm-render: registerFont expects bytes or { data }");
|
|
406
|
+
if (typeof details.data === "function" || typeof details.data.then === "function") {
|
|
407
|
+
return Promise.resolve(typeof details.data === "function" ? details.data() : details.data)
|
|
408
|
+
.then((data) => this.registerFont({ ...details, data }));
|
|
409
|
+
}
|
|
410
|
+
const h = this.#handle();
|
|
411
|
+
let bytes = toBytes(details.data);
|
|
412
|
+
if (!features.woff && isWoff(bytes)) {
|
|
413
|
+
if (!woffDecoder) requireFeature("woff");
|
|
414
|
+
bytes = woffDecoder(bytes);
|
|
415
|
+
}
|
|
416
|
+
const italic = details.style == null ? -1 : /italic|oblique/.test(String(details.style)) ? 1 : 0;
|
|
417
|
+
const unicodeRange = normalizeUnicodeRange(details.unicodeRange);
|
|
418
|
+
const fontOptions = unicodeRange == null ? null : JSON.stringify({ unicodeRange });
|
|
419
|
+
return JSON.parse(backend.run(h, "registerFont", (details.weight | 0) >>> 0, italic >>> 0, details.name || "", fontOptions, ["", bytes, 0, 0, 0], true));
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** takumi-compatible alias. */
|
|
423
|
+
loadFont(font) {
|
|
424
|
+
return this.registerFont(font);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Removes every face of `family` (a name or `{ name }`). Returns true when something was removed. */
|
|
428
|
+
unregisterFont(family) {
|
|
429
|
+
this.#fontsGen++;
|
|
430
|
+
const name = family && typeof family === "object" ? family.name : family;
|
|
431
|
+
return backend.run(this.#handle(), "unregisterFont", 0, 0, String(name), null, null, false)[0] !== 0;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
clearFonts() {
|
|
435
|
+
this.#fontsGen++;
|
|
436
|
+
backend.run(this.#handle(), "clearFonts", 0, 0, null, null, null, false);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** Runs a prepared call (`#call` / `#animation`) on the calling thread; `text`: decode the result as UTF-8. */
|
|
440
|
+
#run(job, text = false) {
|
|
441
|
+
return backend.run(this.#handle(), job.op, job.kind, 0, job.text, job.opts, job.atts, text);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** Like #run for the async API: off the calling thread when the backend can (native), else the same call. */
|
|
445
|
+
#runAsync(job, text = false) {
|
|
446
|
+
return backend.runAsync ? backend.runAsync(this.#handle(), job.op, job.kind, job.rawBytes || 0, job.text, job.opts, job.atts, text) : this.#run(job, text);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Attaches encoded image bytes to the call being prepared, as the image source `src`. */
|
|
450
|
+
#putImage(src, data) {
|
|
451
|
+
this.#atts.push(String(src), toBytes(data), 0, 0, 0);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Attaches raw RGBA pixels to the call being prepared, as the image source `src`. */
|
|
455
|
+
#putRgba(src, img) {
|
|
456
|
+
this.#atts.push(String(src), toBytes(img.data), img.premultiplied ? 3 : 1, img.width >>> 0, img.height >>> 0);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** JSON.stringify where binary / RGBA image `src` values become attachments and are replaced by ids. */
|
|
460
|
+
#stringify(value) {
|
|
461
|
+
const self = this;
|
|
462
|
+
return JSON.stringify(value, function (key, v) {
|
|
463
|
+
// `this[key]` is the raw value: a Node Buffer reaches the replacer already converted by Buffer#toJSON.
|
|
464
|
+
if (key === "src" && this && this[key] && typeof this[key] === "object") v = this[key];
|
|
465
|
+
if (key === "src" && v && typeof v === "object") {
|
|
466
|
+
const id = "bm-res:" + self.#resSeq++;
|
|
467
|
+
if (isBinary(v)) self.#putImage(id, v);
|
|
468
|
+
else if (v.data && v.width) self.#putRgba(id, v);
|
|
469
|
+
else return v;
|
|
470
|
+
return id;
|
|
471
|
+
}
|
|
472
|
+
return v;
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Attaches the `images` option entries the source text references. */
|
|
477
|
+
#putImages(images, text, own) {
|
|
478
|
+
for (const img of imageList(images)) {
|
|
479
|
+
if (typeof img.data === "function") throw new TypeError("bm-render: lazy images[].data() needs the async API");
|
|
480
|
+
const needle = JSON.stringify(String(img.src)).slice(1, -1);
|
|
481
|
+
if (!own || text.includes(needle)) this.#putImage(img.src, img.data);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Serialises the source; binary image sources become attachments of the call and are replaced by ids.
|
|
487
|
+
* Returns [text, kind] with kind 0 = JSON node tree, 1 = HTML markup.
|
|
488
|
+
*/
|
|
489
|
+
#prepareSource(node, options, extra) {
|
|
490
|
+
this.#handle();
|
|
491
|
+
this.#atts = [];
|
|
492
|
+
let json;
|
|
493
|
+
let kind = 0;
|
|
494
|
+
let own = false; // true when we produced the JSON ourselves (so escaping is predictable)
|
|
495
|
+
// takumi semantics: every JS string is HTML; a JSON tree as text is passed as { json }.
|
|
496
|
+
if (typeof node === "string") { requireFeature("html"); json = node; kind = 1; }
|
|
497
|
+
else if (node && typeof node === "object" && typeof node.json === "string" && node.type === undefined) json = node.json;
|
|
498
|
+
else { own = true; json = this.#stringify(node); }
|
|
499
|
+
// `extra` (renderPdf): produces more text that may reference images (header / footer bands) and attaches
|
|
500
|
+
// its own blobs to the call (after the reset above).
|
|
501
|
+
const more = extra ? extra() : "";
|
|
502
|
+
// Only images the tree actually references are passed to the engine.
|
|
503
|
+
this.#putImages(options.images, more ? json + "\n" + more : json, own);
|
|
504
|
+
return [json, kind];
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Validates and serialises one render / svg / measure call; returns the job for #run / #runAsync. */
|
|
508
|
+
#call(which, node, options) {
|
|
509
|
+
[node, options] = unwrap(node, options, "render");
|
|
510
|
+
throwIfAborted(options.signal);
|
|
511
|
+
if ((options.css != null && options.css.length !== 0) || (options.stylesheets != null && options.stylesheets.length !== 0)) requireFeature("css");
|
|
512
|
+
if (options.format === "ico") requireFeature("extraCodecs");
|
|
513
|
+
if (which === "svg") requireFeature("renderSvg");
|
|
514
|
+
const [json, kind] = this.#prepareSource(node, options);
|
|
515
|
+
// `images` were attached above; `fonts`/`signal` are JS-side takumi options.
|
|
516
|
+
const { images: _i, fonts: _f, signal: _s, ...rest } = options;
|
|
517
|
+
// (native async: the byte size of a raw frame whose size is given, so its buffer can be made up front)
|
|
518
|
+
const { width: w, height: h } = rest;
|
|
519
|
+
const rawBytes = which === "render" && rest.format === "raw" && Number.isInteger(w) && Number.isInteger(h) && w > 0 && h > 0 && w * h <= 40e6 ? w * h * 4 : 0;
|
|
520
|
+
return { op: which, kind, text: json, opts: JSON.stringify(rest), atts: this.#atts, rawBytes };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** Async option extras (takumi `RenderExtras`): `fonts` loaders and lazy `images`. */
|
|
524
|
+
async #extras(options) {
|
|
525
|
+
let o = options;
|
|
526
|
+
if (o.fonts) {
|
|
527
|
+
const loaders = await o.fonts;
|
|
528
|
+
const names = [];
|
|
529
|
+
for (const f of loaders) {
|
|
530
|
+
const fams = await this.#registerOnce(f);
|
|
531
|
+
for (const fam of fams || []) if (!names.includes(fam.name)) names.push(fam.name);
|
|
532
|
+
}
|
|
533
|
+
const { fonts: _f, ...rest } = o;
|
|
534
|
+
o = o.fontFamilies || names.length === 0 ? rest : { ...rest, fontFamilies: names };
|
|
535
|
+
}
|
|
536
|
+
if (o.images) o = { ...o, images: await resolveImages(o.images) };
|
|
537
|
+
return o;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Registers one `fonts` entry of a render unless this renderer already holds it (a Promise when the entry is lazy). */
|
|
541
|
+
#registerOnce(f) {
|
|
542
|
+
let map = this.#fontsByUrl;
|
|
543
|
+
let obj = null;
|
|
544
|
+
let sub = "";
|
|
545
|
+
if (f !== null && typeof f === "object" && !(typeof URL !== "undefined" && f instanceof URL) && typeof f.then !== "function") {
|
|
546
|
+
obj = isBinary(f) || f.data == null || (typeof f.data !== "object" && typeof f.data !== "function") ? f : f.data;
|
|
547
|
+
if (obj !== f) sub = JSON.stringify([f.name ?? "", f.weight ?? null, f.style ?? null, f.key ?? null, f.unicodeRange ?? null]);
|
|
548
|
+
map = this.#fontsSeen.get(obj);
|
|
549
|
+
if (!map) this.#fontsSeen.set(obj, (map = new Map()));
|
|
550
|
+
} else if (typeof f === "string" || (typeof URL !== "undefined" && f instanceof URL)) sub = String(f);
|
|
551
|
+
else return this.registerFont(f);
|
|
552
|
+
const hit = map.get(sub);
|
|
553
|
+
if (hit && hit.gen === this.#fontsGen) return hit.fams;
|
|
554
|
+
const gen = this.#fontsGen;
|
|
555
|
+
const keep = (fams) => { map.set(sub, { gen, fams }); return fams; };
|
|
556
|
+
const r = this.registerFont(f);
|
|
557
|
+
return r && typeof r.then === "function" ? r.then(keep) : keep(r);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* #extras for the sync API: registers `fonts` given as bytes or `{ data: bytes }` (a URL, a promise
|
|
562
|
+
* or a lazy `data()` loader needs the async API and throws). Lazy images throw later, in #putImages.
|
|
563
|
+
*/
|
|
564
|
+
#extrasSync(options) {
|
|
565
|
+
if (!options.fonts) return options;
|
|
566
|
+
const loaders = options.fonts;
|
|
567
|
+
if (typeof loaders.then === "function" || !loaders[Symbol.iterator]) throw new TypeError("bm-render: a fonts promise needs the async API");
|
|
568
|
+
for (const f of loaders) {
|
|
569
|
+
const lazy = typeof f === "string" || (typeof URL !== "undefined" && f instanceof URL) || (f && typeof f.then === "function") ||
|
|
570
|
+
(f && !isBinary(f) && (typeof f.data === "function" || (f.data && typeof f.data.then === "function")));
|
|
571
|
+
if (lazy) throw new TypeError("bm-render: fonts[] entries given as a URL, a promise or a lazy data() loader need the async API");
|
|
572
|
+
}
|
|
573
|
+
const names = [];
|
|
574
|
+
for (const f of loaders) {
|
|
575
|
+
for (const fam of this.#registerOnce(f) || []) if (!names.includes(fam.name)) names.push(fam.name);
|
|
576
|
+
}
|
|
577
|
+
const { fonts: _f, ...rest } = options;
|
|
578
|
+
return options.fontFamilies || names.length === 0 ? rest : { ...rest, fontFamilies: names };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Render synchronously. Returns a fresh Uint8Array (PNG by default; `format: "raw"` = straight RGBA8).
|
|
583
|
+
*
|
|
584
|
+
* `source`: a takumi node object, `{ json: string }` (a node tree as JSON text), a STRING = HTML
|
|
585
|
+
* markup (`<style>` elements are honoured), or a handle from `prepare()`.
|
|
586
|
+
* `options` (takumi RenderOptions): `width`, `height`, `format` ("png"|"jpeg"|"webp"|"ico"|"raw"),
|
|
587
|
+
* `quality` (jpeg), `lossless` (ignored: webp is always lossless), `devicePixelRatio`, `images`
|
|
588
|
+
* ([{src, data}] or {sources}), `css` (stylesheet strings and/or takumi rule objects), `stylesheets`
|
|
589
|
+
* (deprecated), `keyframes` (deprecated keyframes map/list), `timeMs` (CSS animation timeline, default 0),
|
|
590
|
+
* `fontFamilies`, `lang`, `drawDebugBorder` / `dithering` (accepted, ignored).
|
|
591
|
+
*/
|
|
592
|
+
renderSync(node, options = {}) {
|
|
593
|
+
[node, options] = unwrap(node, options, "render");
|
|
594
|
+
return this.#run(this.#call("render", node, this.#extrasSync(options)));
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* takumi-compatible async signature. On the wasm backend rendering itself is synchronous; the native
|
|
599
|
+
* backend renders on a thread-pool thread (the inputs are snapshotted when the call is made).
|
|
600
|
+
*/
|
|
601
|
+
async render(node, options = {}) {
|
|
602
|
+
[node, options] = unwrap(node, options, "render");
|
|
603
|
+
return this.#runAsync(this.#call("render", node, await this.#extras(options)));
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
renderAsDataUrlSync(node, options = {}) {
|
|
607
|
+
[node, options] = unwrap(node, options, "render");
|
|
608
|
+
mimeCheck(options);
|
|
609
|
+
return dataUrl(options.format, this.renderSync(node, options));
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async renderAsDataUrl(node, options = {}) {
|
|
613
|
+
[node, options] = unwrap(node, options, "render");
|
|
614
|
+
options = await this.#extras(options);
|
|
615
|
+
mimeCheck(options);
|
|
616
|
+
return dataUrl(options.format, await this.#runAsync(this.#call("render", node, options)));
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* takumi `renderSvg`: the source as an SVG document string (vector boxes, gradients, borders,
|
|
621
|
+
* shadows as filters, images embedded as data URLs, text as glyph outlines). Needs a build with
|
|
622
|
+
* `render_svg` (the full profile); `format` / `quality` are ignored.
|
|
623
|
+
*/
|
|
624
|
+
renderSvgSync(node, options = {}) {
|
|
625
|
+
[node, options] = unwrap(node, options, "render");
|
|
626
|
+
return this.#run(this.#call("svg", node, this.#extrasSync(options)), true);
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async renderSvg(node, options = {}) {
|
|
630
|
+
[node, options] = unwrap(node, options, "render");
|
|
631
|
+
return this.#runAsync(this.#call("svg", node, await this.#extras(options)), true);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** renderPdf / measurePdf options as JSON text; attachment bytes and band images become attachments of the call. */
|
|
635
|
+
#pdfOptionsText(options) {
|
|
636
|
+
const { images: _i, fonts: _f, signal: _s, attachments, ...rest } = options;
|
|
637
|
+
const o = { ...rest };
|
|
638
|
+
if (attachments != null) {
|
|
639
|
+
if (!Array.isArray(attachments)) throw new TypeError("bm-render: attachments takes an array");
|
|
640
|
+
o.attachments = attachments.map((a) => {
|
|
641
|
+
if (a == null || typeof a !== "object") return a;
|
|
642
|
+
let { data, ...meta } = a;
|
|
643
|
+
// takumi-pdf (serde ByteBuf) also takes a plain array of byte values
|
|
644
|
+
if (Array.isArray(data) && data.every((v) => Number.isInteger(v) && v >= 0 && v <= 255)) data = Uint8Array.from(data);
|
|
645
|
+
if (isBinary(data)) {
|
|
646
|
+
const id = "bm-att:" + this.#resSeq++;
|
|
647
|
+
this.#putImage(id, data);
|
|
648
|
+
return { ...meta, dataRef: id };
|
|
649
|
+
}
|
|
650
|
+
return data === undefined ? meta : { ...meta, data };
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
return this.#stringify(o);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** Validates and serialises one renderPdf / measurePdf call; returns the job for #run / #runAsync. */
|
|
657
|
+
#callPdf(which, node, options) {
|
|
658
|
+
[node, options] = unwrap(node, options, "render");
|
|
659
|
+
throwIfAborted(options.signal);
|
|
660
|
+
requireFeature("pdf");
|
|
661
|
+
if ((options.css != null && options.css.length !== 0) || (options.stylesheets != null && options.stylesheets.length !== 0)) requireFeature("css");
|
|
662
|
+
let text;
|
|
663
|
+
const [json, kind] = this.#prepareSource(node, options, () => (text = this.#pdfOptionsText(options)));
|
|
664
|
+
return { op: which === "render" ? "pdf" : which === "needs" ? "pdfNeeds" : "pdfMeasure", kind, text: json, opts: text, atts: this.#atts };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* takumi-pdf `render`: the source as a PDF file. Needs a build with `pdf` (bm-render/pdf). Options: takumi-pdf's
|
|
669
|
+
* `PdfRenderOptions` (`viewport` | `size` / `landscape` / `margin` / `header` / `footer` / `pages` /
|
|
670
|
+
* `pageRanges`, `metadata`, `outline`, `pdfa`, `tagged`, `attachments`, `uncoveredText`, `backgroundColor`,
|
|
671
|
+
* `css`, `cssVariables`, `fontFamilies`, `lang`, `images`, `fonts`, `signal`); see js/pdf-types.d.mts.
|
|
672
|
+
*/
|
|
673
|
+
renderPdfSync(node, options = {}) {
|
|
674
|
+
[node, options] = unwrap(node, options, "render");
|
|
675
|
+
return this.#run(this.#callPdf("render", node, this.#extrasSync(options)));
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
async renderPdf(node, options = {}) {
|
|
679
|
+
[node, options] = unwrap(node, options, "render");
|
|
680
|
+
return this.#runAsync(this.#callPdf("render", node, await this.#extras(options)));
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/** takumi-pdf `measure`: `{ width, height }` in CSS px, laid out like a header / footer band (see pdf.d.mts). */
|
|
684
|
+
measurePdfSync(node, options = {}) {
|
|
685
|
+
[node, options] = unwrap(node, options, "render");
|
|
686
|
+
return JSON.parse(this.#run(this.#callPdf("measure", node, this.#extrasSync(options)), true));
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
async measurePdf(node, options = {}) {
|
|
690
|
+
[node, options] = unwrap(node, options, "render");
|
|
691
|
+
return JSON.parse(await this.#runAsync(this.#callPdf("measure", node, await this.#extras(options)), true));
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** Internal cascade-only resource discovery; no font loaders or image fetches run here. */
|
|
695
|
+
needsPdfSync(node, options = {}) {
|
|
696
|
+
return JSON.parse(this.#run(this.#callPdf("needs", node, options), true));
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** Lay out only. Returns `{ width, height, transform, children, runs }` like takumi's `measure`. */
|
|
700
|
+
measureSync(node, options = {}) {
|
|
701
|
+
[node, options] = unwrap(node, options, "render");
|
|
702
|
+
return JSON.parse(this.#run(this.#call("measure", node, this.#extrasSync(options)), true));
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
async measure(node, options = {}) {
|
|
706
|
+
[node, options] = unwrap(node, options, "render");
|
|
707
|
+
return JSON.parse(await this.#runAsync(this.#call("measure", node, await this.#extras(options)), true));
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* takumi `prepare`: resolves `fonts` / lazy `images` and returns a handle for `render`,
|
|
712
|
+
* `renderAsDataUrl` and `measure` (whose options are merged over the prepared ones). bm-render does
|
|
713
|
+
* not fetch remote resources here (no `needs` pass): pass image bytes via `images`.
|
|
714
|
+
*/
|
|
715
|
+
async prepare(source, options = {}) {
|
|
716
|
+
return new Prepared("render", source, await this.#extras(options));
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** takumi `prepareAnimation`: like `prepare`, for `renderAnimation`. */
|
|
720
|
+
async prepareAnimation(options = {}) {
|
|
721
|
+
const { scenes, ...rest } = options;
|
|
722
|
+
return new Prepared("anim", scenes, await this.#extras(rest));
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* takumi `renderAnimation`: `{ scenes: [{ node, durationMs }], width, height, fps, format?: "webp" |
|
|
727
|
+
* "apng" | "gif" (default webp, always lossless), css?, stylesheets?, keyframes?, images?,
|
|
728
|
+
* devicePixelRatio?, fontFamilies?, lang? }` -> encoded animation. Frame schedule as takumi-raster:
|
|
729
|
+
* ceil(total * fps / 1000) frames, frame i at floor(i * 1000 / fps) ms (time restarts per scene).
|
|
730
|
+
* Max fps: 50 for gif, 90 for webp / apng.
|
|
731
|
+
*/
|
|
732
|
+
renderAnimationSync(options) {
|
|
733
|
+
return this.#run(this.#animation(options && !options[PREPARED] ? this.#extrasSync(options) : options));
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Validates and serialises one renderAnimation call; returns the job for #run / #runAsync. */
|
|
737
|
+
#animation(options) {
|
|
738
|
+
let scenes = options.scenes;
|
|
739
|
+
if (options[PREPARED]) {
|
|
740
|
+
const p = options[PREPARED];
|
|
741
|
+
if (p.kind !== "anim") throw new TypeError("bm-render: this prepared handle is for render");
|
|
742
|
+
scenes = p.source;
|
|
743
|
+
options = { ...p.options };
|
|
744
|
+
}
|
|
745
|
+
throwIfAborted(options.signal);
|
|
746
|
+
if (!backend.has("animation")) throw unsupported("renderAnimation (this wasm build)");
|
|
747
|
+
requireFeature("animation");
|
|
748
|
+
this.#handle();
|
|
749
|
+
this.#atts = [];
|
|
750
|
+
const { images, fonts: _f, signal: _s, scenes: _sc, ...rest } = options;
|
|
751
|
+
const text = this.#stringify({ ...rest, scenes: scenes || [] });
|
|
752
|
+
this.#putImages(images, text, true);
|
|
753
|
+
return { op: "animation", kind: 0, text, opts: null, atts: this.#atts };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async renderAnimation(options, extra = {}) {
|
|
757
|
+
if (options && options[PREPARED]) {
|
|
758
|
+
throwIfAborted(extra.signal);
|
|
759
|
+
return this.#runAsync(this.#animation(options));
|
|
760
|
+
}
|
|
761
|
+
return this.#runAsync(this.#animation(await this.#extras(options)));
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Bytes the engine currently holds: the wasm linear memory size (shared by all renderers of this module
|
|
766
|
+
* instance), or on the native backend the bytes allocated by the addon in this process.
|
|
767
|
+
*/
|
|
768
|
+
memoryBytes() {
|
|
769
|
+
return backend.memoryBytes();
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
static memoryBytes() {
|
|
773
|
+
return backend.ready() ? backend.memoryBytes() : 0;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
free() {
|
|
777
|
+
if (this.#h) backend.destroy(this.#h);
|
|
778
|
+
this.#h = 0;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
[DISPOSE]() {
|
|
782
|
+
this.free();
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** takumi module function. bm-render's glyph-mask budget is fixed (8 MiB): accepted and ignored. */
|
|
787
|
+
function setGlyphCacheMaxBytes(bytes) {
|
|
788
|
+
void bytes;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** Where `init()` without an argument loads the wasm from (profile entries), else undefined. */
|
|
792
|
+
function wasmUrl() {
|
|
793
|
+
return defaultWasm ? defaultWasm() : undefined;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
return { init, initSync, Renderer, Prepared, features, setGlyphCacheMaxBytes, wasmUrl, backend: backend.name };
|
|
797
|
+
}
|