@imggion/html2realpdf 0.3.1 → 0.4.0
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/README.md +99 -4
- package/dist/image.d.ts +83 -0
- package/dist/image.js +169 -0
- package/dist/image.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/libhtml2realpdf.wasm +0 -0
- package/dist/node-source.d.ts +16 -0
- package/dist/node-source.js +155 -0
- package/dist/node-source.js.map +1 -0
- package/dist/node.d.ts +78 -0
- package/dist/node.js +105 -0
- package/dist/node.js.map +1 -0
- package/dist/renderer.d.ts +64 -1
- package/dist/renderer.js +164 -41
- package/dist/renderer.js.map +1 -1
- package/dist/snapshot.d.ts +6 -0
- package/dist/snapshot.js +177 -5
- package/dist/snapshot.js.map +1 -1
- package/dist/types.d.ts +52 -3
- package/dist/types.js.map +1 -1
- package/dist/wasm.d.ts +39 -9
- package/dist/wasm.js +83 -28
- package/dist/wasm.js.map +1 -1
- package/dist/worker.js +9 -0
- package/dist/worker.js.map +1 -1
- package/package.json +11 -2
- package/skills/html2realpdf/SKILL.md +80 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-source.js","sourceRoot":"","sources":["../src/node-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAMlG,MAAM,cAAc,GAAG,iDAAiD,CAAC;AACzE,MAAM,YAAY,GAAG,6CAA6C,CAAC;AACnE,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC,CAAC;AAQpF,oEAAoE;AACpE,MAAM,UAAU,qBAAqB,CAAC,MAAkB;IACtD,OAAO;QACL,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,EA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ser snapshot embeds every resource and replaces inline SVG before\n * the core runs. Without a DOM the core does the structural work itself\n * (inline `<svg>` becomes a replaced element natively); this module only\n * routes external resources through `resourceResolver`, using byte ranges the\n * core tokenizer reports, and maps core diagnostics onto the caller's\n * policies after the render. Nothing is ever fetched implicitly.\n *\n * @packageDocumentation\n */\n\nimport { ResourceLoadError, UnsupportedCssError, UnsupportedEnvironmentError } from \"./errors.js\";\nimport type { SourcePreparation } from \"./renderer.js\";\nimport type { SnapshotOptions, SnapshotResult } from \"./snapshot.js\";\nimport type { Diagnostic, HtmlSource } from \"./types.js\";\nimport type { ResourceReference, WasmBridge } from \"./wasm.js\";\n\nconst EMBEDDED_IMAGE = /^data:image\\/(?:png|jpeg|jpg|svg\\+xml);base64,/i;\nconst SVG_DATA_URL = /^data:image\\/svg\\+xml(?:;charset=[^;,]+)?,/i;\nconst EMBEDDABLE_BLOB_TYPES = new Set([\"image/png\", \"image/jpeg\", \"image/svg+xml\"]);\n\ninterface Edit {\n start: number;\n end: number;\n text: string;\n}\n\n/** Source preparation for one Node renderer and its WASM bridge. */\nexport function nodeSourcePreparation(bridge: WasmBridge): SourcePreparation {\n return {\n prepare: (source, options) => prepareHtmlString(bridge, source, options),\n check: enforceNodePolicies,\n };\n}\n\nasync function prepareHtmlString(bridge: WasmBridge, source: HtmlSource, options: SnapshotOptions): Promise<SnapshotResult> {\n if (typeof source !== \"string\") {\n throw new UnsupportedEnvironmentError(\"Element and ref sources need a browser DOM; pass an HTML string when rendering in Node\");\n }\n const diagnostics: Diagnostic[] = [];\n const references = bridge.resourceReferences(source);\n if (references.length === 0) return { html: source, diagnostics };\n\n const edits: Edit[] = [];\n for (const reference of references) {\n let replacement: string;\n try {\n replacement = await resolveReference(reference, options);\n } catch (error) {\n if (options.resourcePolicy === \"error\") throw new ResourceLoadError(reference.url, { cause: error });\n // Backgrounds stay in place: the core omits non-embedded URLs and\n // reports them itself. Elements are removed like the browser snapshot.\n if (reference.kind === \"background\" || reference.tagStart === undefined || reference.tagEnd === undefined) continue;\n addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: \"\" });\n diagnostics.push({\n code: \"RESOURCE_OMITTED\",\n severity: \"warning\",\n message: `${reference.kind === \"stylesheet\" ? \"Stylesheet\" : \"Image\"} resource was omitted: ${reference.url}`,\n phase: \"snapshot\",\n });\n continue;\n }\n if (reference.kind === \"stylesheet\" && reference.tagStart !== undefined && reference.tagEnd !== undefined) {\n addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: replacement });\n } else {\n addEdit(edits, { start: reference.start, end: reference.end, text: replacement });\n }\n }\n return { html: applyEdits(source, edits), diagnostics };\n}\n\n/** Returns the embedded replacement text, or throws when the resource is unavailable. */\nasync function resolveReference(reference: ResourceReference, options: SnapshotOptions): Promise<string> {\n let url: URL;\n try {\n url = options.baseUrl === undefined ? new URL(reference.url) : new URL(reference.url, options.baseUrl);\n } catch (error) {\n throw new Error(`Relative resource URL \"${reference.url}\" needs baseUrl outside the browser`, { cause: error });\n }\n const resolver = options.resourceResolver;\n if (!resolver) throw new Error(\"Resources are never fetched outside the browser; provide resourceResolver\");\n const kind = reference.kind === \"stylesheet\" ? \"stylesheet\" : \"image\";\n const resolved = await resolver({ kind, url });\n if (resolved === null || resolved === undefined) throw new Error(`The ${kind} resource was declined by resourceResolver`);\n\n if (kind === \"stylesheet\") {\n const css = typeof resolved === \"string\" ? resolved : await resolved.text();\n // Raw-text content cannot contain its own end tag.\n return `<style data-html2realpdf-resolved-from=\"${escapeAttribute(url.href)}\">${css.replace(/<\\/style/gi, \"<\\\\/style\")}</style>`;\n }\n if (typeof resolved === \"string\") {\n if (EMBEDDED_IMAGE.test(resolved)) return resolved;\n if (SVG_DATA_URL.test(resolved)) {\n const payload = decodeURIComponent(resolved.slice(resolved.indexOf(\",\") + 1));\n return `data:image/svg+xml;base64,${base64(new TextEncoder().encode(payload))}`;\n }\n throw new Error(\"Outside the browser an image resolver must return a PNG, JPEG, or SVG data URL or Blob; replacement URLs are not fetched\");\n }\n const type = resolved.type.toLowerCase();\n if (!EMBEDDABLE_BLOB_TYPES.has(type)) {\n throw new Error(`Image type \"${resolved.type || \"unknown\"}\" cannot be embedded outside the browser; use PNG, JPEG, or SVG`);\n }\n return `data:${type};base64,${base64(new Uint8Array(await resolved.arrayBuffer()))}`;\n}\n\n/**\n * Maps core diagnostics onto the browser-equivalent policies. The browser\n * rasterizes unsupported SVG only after `fallback: \"rasterize-subtree\"`;\n * Node cannot rasterize, so it keeps the omission and its diagnostic.\n */\nfunction enforceNodePolicies(diagnostics: readonly Diagnostic[], options: SnapshotOptions): void {\n const has = (code: string) => diagnostics.some((diagnostic) => diagnostic.code === code);\n if (options.fallback === \"error\" && has(\"INLINE_SVG_UNSUPPORTED\")) {\n throw new UnsupportedCssError(\"Inline SVG uses features outside the native vector subset and cannot be rasterized outside the browser\");\n }\n if (options.unsupportedCss === \"error\" && has(\"UNSUPPORTED_CSS_PROPERTY\")) {\n const property = diagnostics.find((diagnostic) => diagnostic.code === \"UNSUPPORTED_CSS_PROPERTY\")?.property ?? \"unknown\";\n throw new UnsupportedCssError(`Unsupported CSS property: ${property}`);\n }\n if (options.resourcePolicy === \"error\") {\n const failed = diagnostics.find((diagnostic) => diagnostic.code === \"INLINE_SVG_INVALID\" || diagnostic.code === \"RESOURCE_OMITTED\");\n if (failed) throw new ResourceLoadError(failed.code === \"INLINE_SVG_INVALID\" ? \"inline SVG\" : failed.message);\n }\n}\n\n/** Keeps edits disjoint: an element removal supersedes edits inside it. */\nfunction addEdit(edits: Edit[], edit: Edit): void {\n if (edits.some((existing) => edit.start >= existing.start && edit.end <= existing.end && existing.end - existing.start > edit.end - edit.start)) return;\n for (let index = edits.length - 1; index >= 0; index -= 1) {\n const existing = edits[index]!;\n if (existing.start >= edit.start && existing.end <= edit.end) edits.splice(index, 1);\n }\n edits.push(edit);\n}\n\n/** Applies byte-range edits to the UTF-8 encoding of `source`. */\nfunction applyEdits(source: string, edits: readonly Edit[]): string {\n if (edits.length === 0) return source;\n const encoder = new TextEncoder();\n const bytes = encoder.encode(source);\n const decoder = new TextDecoder();\n let output = \"\";\n let cursor = 0;\n for (const edit of [...edits].sort((left, right) => left.start - right.start)) {\n output += decoder.decode(bytes.subarray(cursor, edit.start)) + edit.text;\n cursor = edit.end;\n }\n return output + decoder.decode(bytes.subarray(cursor));\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, \"&\").replace(/\"/g, \""\").replace(/</g, \"<\");\n}\n\nfunction base64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n }\n return btoa(binary);\n}\n"]}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node entry: renders HTML strings to PDF and JPEG without a browser.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Resolved for `import "@imggion/html2realpdf"` under the `node` export
|
|
6
|
+
* condition and always available as `@imggion/html2realpdf/node`. It exports
|
|
7
|
+
* the same names as the browser entry, so server-side rendering code can
|
|
8
|
+
* import shared modules; only `createRenderer`, `renderPdf`, and
|
|
9
|
+
* `renderImage` differ:
|
|
10
|
+
*
|
|
11
|
+
* - the WASM module is read from the packaged file instead of fetched;
|
|
12
|
+
* - renders run on the calling thread;
|
|
13
|
+
* - sources must be HTML strings, because Elements and refs need a DOM;
|
|
14
|
+
* - inline `<svg>` is handled by the core, and external images and
|
|
15
|
+
* stylesheets reach the render only through `resourceResolver` (nothing is
|
|
16
|
+
* fetched implicitly).
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { renderImage } from "@imggion/html2realpdf";
|
|
21
|
+
* const image = await renderImage(renderToStaticMarkup(<Report />), { width: 1200, scale: 2 });
|
|
22
|
+
* await writeFile("report.jpg", image.bytes);
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @packageDocumentation
|
|
26
|
+
*/
|
|
27
|
+
import type { RenderedImage } from "./image.js";
|
|
28
|
+
import type { PdfDocument } from "./pdf-document.js";
|
|
29
|
+
import { Html2RealPdf } from "./renderer.js";
|
|
30
|
+
import type { FontRegistration, HtmlSource, ImageRenderOptions, RendererInit, RenderOptions } from "./types.js";
|
|
31
|
+
export * from "./index.js";
|
|
32
|
+
export { default } from "./index.js";
|
|
33
|
+
/** Renderer configuration outside the browser. */
|
|
34
|
+
export interface NodeRendererInit extends RendererInit {
|
|
35
|
+
/**
|
|
36
|
+
* Path or `file:` URL of `libhtml2realpdf.wasm`. Defaults to the file
|
|
37
|
+
* shipped next to this module. `wasmUrl` is accepted as an alias.
|
|
38
|
+
*/
|
|
39
|
+
wasmPath?: string | URL;
|
|
40
|
+
/** Module bytes already in memory. Takes precedence over `wasmPath`. */
|
|
41
|
+
wasmBytes?: BufferSource;
|
|
42
|
+
/** Embeddable TrueType fonts registered once for every render. */
|
|
43
|
+
fonts?: readonly FontRegistration[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Creates a reusable renderer that loads the packaged WASM from disk.
|
|
47
|
+
*
|
|
48
|
+
* @remarks
|
|
49
|
+
* `execution` is ignored: renders run on the calling thread. Dispose the
|
|
50
|
+
* renderer to free its native context and fonts.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* const renderer = await createRenderer({ fonts: [{ family: "Inter", data: await readFile("Inter.ttf") }] });
|
|
55
|
+
* try {
|
|
56
|
+
* const pdf = await renderer.render(html, { cssProfile: "web" });
|
|
57
|
+
* await writeFile("report.pdf", pdf.bytes);
|
|
58
|
+
* } finally {
|
|
59
|
+
* renderer.dispose();
|
|
60
|
+
* }
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export declare function createRenderer(init?: NodeRendererInit): Promise<Html2RealPdf>;
|
|
64
|
+
/**
|
|
65
|
+
* Renders an HTML string to PDF with a lazily created default renderer.
|
|
66
|
+
*
|
|
67
|
+
* @throws {@link UnsupportedEnvironmentError} for Element or ref sources.
|
|
68
|
+
*/
|
|
69
|
+
export declare function renderPdf(source: HtmlSource, options?: RenderOptions): Promise<PdfDocument>;
|
|
70
|
+
/**
|
|
71
|
+
* Renders an HTML string to an auto-height JPEG with the default renderer.
|
|
72
|
+
*
|
|
73
|
+
* @remarks
|
|
74
|
+
* Without `width`, the image is `viewport.width` or 800 CSS pixels wide.
|
|
75
|
+
*
|
|
76
|
+
* @throws {@link UnsupportedEnvironmentError} for Element or ref sources.
|
|
77
|
+
*/
|
|
78
|
+
export declare function renderImage(source: HtmlSource, options?: ImageRenderOptions): Promise<RenderedImage>;
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node entry: renders HTML strings to PDF and JPEG without a browser.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Resolved for `import "@imggion/html2realpdf"` under the `node` export
|
|
6
|
+
* condition and always available as `@imggion/html2realpdf/node`. It exports
|
|
7
|
+
* the same names as the browser entry, so server-side rendering code can
|
|
8
|
+
* import shared modules; only `createRenderer`, `renderPdf`, and
|
|
9
|
+
* `renderImage` differ:
|
|
10
|
+
*
|
|
11
|
+
* - the WASM module is read from the packaged file instead of fetched;
|
|
12
|
+
* - renders run on the calling thread;
|
|
13
|
+
* - sources must be HTML strings, because Elements and refs need a DOM;
|
|
14
|
+
* - inline `<svg>` is handled by the core, and external images and
|
|
15
|
+
* stylesheets reach the render only through `resourceResolver` (nothing is
|
|
16
|
+
* fetched implicitly).
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { renderImage } from "@imggion/html2realpdf";
|
|
21
|
+
* const image = await renderImage(renderToStaticMarkup(<Report />), { width: 1200, scale: 2 });
|
|
22
|
+
* await writeFile("report.jpg", image.bytes);
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @packageDocumentation
|
|
26
|
+
*/
|
|
27
|
+
import { WasmRenderError } from "./errors.js";
|
|
28
|
+
import { nodeSourcePreparation } from "./node-source.js";
|
|
29
|
+
import { Html2RealPdf, MainThreadBackend } from "./renderer.js";
|
|
30
|
+
import { WASM_TRAP_STATUS, WasmBridge } from "./wasm.js";
|
|
31
|
+
export * from "./index.js";
|
|
32
|
+
export { default } from "./index.js";
|
|
33
|
+
/**
|
|
34
|
+
* Creates a reusable renderer that loads the packaged WASM from disk.
|
|
35
|
+
*
|
|
36
|
+
* @remarks
|
|
37
|
+
* `execution` is ignored: renders run on the calling thread. Dispose the
|
|
38
|
+
* renderer to free its native context and fonts.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* const renderer = await createRenderer({ fonts: [{ family: "Inter", data: await readFile("Inter.ttf") }] });
|
|
43
|
+
* try {
|
|
44
|
+
* const pdf = await renderer.render(html, { cssProfile: "web" });
|
|
45
|
+
* await writeFile("report.pdf", pdf.bytes);
|
|
46
|
+
* } finally {
|
|
47
|
+
* renderer.dispose();
|
|
48
|
+
* }
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export async function createRenderer(init = {}) {
|
|
52
|
+
const bytes = init.wasmBytes ?? await readWasm(init.wasmPath ?? init.wasmUrl ?? new URL("./libhtml2realpdf.wasm", import.meta.url));
|
|
53
|
+
const bridge = await WasmBridge.fromBytes(bytes, init.fonts ?? []);
|
|
54
|
+
return Html2RealPdf.create(new MainThreadBackend(bridge), nodeSourcePreparation(bridge));
|
|
55
|
+
}
|
|
56
|
+
let defaultRenderer;
|
|
57
|
+
/**
|
|
58
|
+
* Renders an HTML string to PDF with a lazily created default renderer.
|
|
59
|
+
*
|
|
60
|
+
* @throws {@link UnsupportedEnvironmentError} for Element or ref sources.
|
|
61
|
+
*/
|
|
62
|
+
export async function renderPdf(source, options = {}) {
|
|
63
|
+
return withDefaultRenderer((renderer) => renderer.render(source, options));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Renders an HTML string to an auto-height JPEG with the default renderer.
|
|
67
|
+
*
|
|
68
|
+
* @remarks
|
|
69
|
+
* Without `width`, the image is `viewport.width` or 800 CSS pixels wide.
|
|
70
|
+
*
|
|
71
|
+
* @throws {@link UnsupportedEnvironmentError} for Element or ref sources.
|
|
72
|
+
*/
|
|
73
|
+
export async function renderImage(source, options = {}) {
|
|
74
|
+
return withDefaultRenderer((renderer) => renderer.renderImage(source, options));
|
|
75
|
+
}
|
|
76
|
+
async function withDefaultRenderer(render) {
|
|
77
|
+
defaultRenderer ??= createRenderer().catch((error) => {
|
|
78
|
+
defaultRenderer = undefined;
|
|
79
|
+
throw error;
|
|
80
|
+
});
|
|
81
|
+
const current = defaultRenderer;
|
|
82
|
+
try {
|
|
83
|
+
return await render(await current);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// A trap discards the instance; the next call creates a fresh one.
|
|
87
|
+
if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS && defaultRenderer === current) {
|
|
88
|
+
defaultRenderer = undefined;
|
|
89
|
+
}
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function readWasm(location) {
|
|
94
|
+
// A computed specifier keeps browser bundlers from resolving a Node builtin;
|
|
95
|
+
// this module is only selected under the `node` condition.
|
|
96
|
+
const specifier = "node:fs/promises";
|
|
97
|
+
const fs = await import(specifier);
|
|
98
|
+
try {
|
|
99
|
+
return await fs.readFile(location);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
throw new WasmRenderError(`Could not read WASM module: ${String(location)}`, -10, { cause: error });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAA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AAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAClF,CAAC;AAED,KAAK,UAAU,mBAAmB,CAAI,MAA8C;IAClF,eAAe,KAAK,cAAc,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC5D,eAAe,GAAG,SAAS,CAAC;QAC5B,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,eAAe,CAAC;IAChC,IAAI,CAAC;QACH,OAAO,MAAM,MAAM,CAAC,MAAM,OAAO,CAAC,CAAC;IACrC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mEAAmE;QACnE,IAAI,KAAK,YAAY,eAAe,IAAI,KAAK,CAAC,MAAM,KAAK,gBAAgB,IAAI,eAAe,KAAK,OAAO,EAAE,CAAC;YACzG,eAAe,GAAG,SAAS,CAAC;QAC9B,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,QAAsB;IAC5C,6EAA6E;IAC7E,2DAA2D;IAC3D,MAAM,SAAS,GAAG,kBAAkB,CAAC;IACrC,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,SAAS,CAAmB,CAAC;IACrD,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACrC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,eAAe,CAAC,+BAA+B,MAAM,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACtG,CAAC;AACH,CAAC","sourcesContent":["/**\n * Node entry: renders HTML strings to PDF and JPEG without a browser.\n *\n * @remarks\n * Resolved for `import \"@imggion/html2realpdf\"` under the `node` export\n * condition and always available as `@imggion/html2realpdf/node`. It exports\n * the same names as the browser entry, so server-side rendering code can\n * import shared modules; only `createRenderer`, `renderPdf`, and\n * `renderImage` differ:\n *\n * - the WASM module is read from the packaged file instead of fetched;\n * - renders run on the calling thread;\n * - sources must be HTML strings, because Elements and refs need a DOM;\n * - inline `<svg>` is handled by the core, and external images and\n * stylesheets reach the render only through `resourceResolver` (nothing is\n * fetched implicitly).\n *\n * @example\n * ```ts\n * import { renderImage } from \"@imggion/html2realpdf\";\n * const image = await renderImage(renderToStaticMarkup(<Report />), { width: 1200, scale: 2 });\n * await writeFile(\"report.jpg\", image.bytes);\n * ```\n *\n * @packageDocumentation\n */\n\nimport { WasmRenderError } from \"./errors.js\";\nimport type { RenderedImage } from \"./image.js\";\nimport { nodeSourcePreparation } from \"./node-source.js\";\nimport type { PdfDocument } from \"./pdf-document.js\";\nimport { Html2RealPdf, MainThreadBackend } from \"./renderer.js\";\nimport type { FontRegistration, HtmlSource, ImageRenderOptions, RendererInit, RenderOptions } from \"./types.js\";\nimport { WASM_TRAP_STATUS, WasmBridge } from \"./wasm.js\";\n\nexport * from \"./index.js\";\nexport { default } from \"./index.js\";\n\n/** Renderer configuration outside the browser. */\nexport interface NodeRendererInit extends RendererInit {\n /**\n * Path or `file:` URL of `libhtml2realpdf.wasm`. Defaults to the file\n * shipped next to this module. `wasmUrl` is accepted as an alias.\n */\n wasmPath?: string | URL;\n /** Module bytes already in memory. Takes precedence over `wasmPath`. */\n wasmBytes?: BufferSource;\n /** Embeddable TrueType fonts registered once for every render. */\n fonts?: readonly FontRegistration[];\n}\n\ninterface NodeFileSystem {\n readFile(path: string | URL): Promise<Uint8Array<ArrayBuffer>>;\n}\n\n/**\n * Creates a reusable renderer that loads the packaged WASM from disk.\n *\n * @remarks\n * `execution` is ignored: renders run on the calling thread. Dispose the\n * renderer to free its native context and fonts.\n *\n * @example\n * ```ts\n * const renderer = await createRenderer({ fonts: [{ family: \"Inter\", data: await readFile(\"Inter.ttf\") }] });\n * try {\n * const pdf = await renderer.render(html, { cssProfile: \"web\" });\n * await writeFile(\"report.pdf\", pdf.bytes);\n * } finally {\n * renderer.dispose();\n * }\n * ```\n */\nexport async function createRenderer(init: NodeRendererInit = {}): Promise<Html2RealPdf> {\n const bytes = init.wasmBytes ?? await readWasm(init.wasmPath ?? init.wasmUrl ?? new URL(\"./libhtml2realpdf.wasm\", import.meta.url));\n const bridge = await WasmBridge.fromBytes(bytes, init.fonts ?? []);\n return Html2RealPdf.create(new MainThreadBackend(bridge), nodeSourcePreparation(bridge));\n}\n\nlet defaultRenderer: Promise<Html2RealPdf> | undefined;\n\n/**\n * Renders an HTML string to PDF with a lazily created default renderer.\n *\n * @throws {@link UnsupportedEnvironmentError} for Element or ref sources.\n */\nexport async function renderPdf(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n return withDefaultRenderer((renderer) => renderer.render(source, options));\n}\n\n/**\n * Renders an HTML string to an auto-height JPEG with the default renderer.\n *\n * @remarks\n * Without `width`, the image is `viewport.width` or 800 CSS pixels wide.\n *\n * @throws {@link UnsupportedEnvironmentError} for Element or ref sources.\n */\nexport async function renderImage(source: HtmlSource, options: ImageRenderOptions = {}): Promise<RenderedImage> {\n return withDefaultRenderer((renderer) => renderer.renderImage(source, options));\n}\n\nasync function withDefaultRenderer<T>(render: (renderer: Html2RealPdf) => Promise<T>): Promise<T> {\n defaultRenderer ??= createRenderer().catch((error: unknown) => {\n defaultRenderer = undefined;\n throw error;\n });\n const current = defaultRenderer;\n try {\n return await render(await current);\n } catch (error) {\n // A trap discards the instance; the next call creates a fresh one.\n if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS && defaultRenderer === current) {\n defaultRenderer = undefined;\n }\n throw error;\n }\n}\n\nasync function readWasm(location: string | URL): Promise<Uint8Array<ArrayBuffer>> {\n // A computed specifier keeps browser bundlers from resolving a Node builtin;\n // this module is only selected under the `node` condition.\n const specifier = \"node:fs/promises\";\n const fs = await import(specifier) as NodeFileSystem;\n try {\n return await fs.readFile(location);\n } catch (error) {\n throw new WasmRenderError(`Could not read WASM module: ${String(location)}`, -10, { cause: error });\n }\n}\n"]}
|
package/dist/renderer.d.ts
CHANGED
|
@@ -3,8 +3,37 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
|
+
import { RenderedImage, type NormalizedImageOptions } from "./image.js";
|
|
7
|
+
import { type NormalizedPage } from "./page.js";
|
|
6
8
|
import { PdfDocument } from "./pdf-document.js";
|
|
7
|
-
import type
|
|
9
|
+
import { type SnapshotOptions, type SnapshotPageMarginBox, type SnapshotPageRule, type SnapshotResult } from "./snapshot.js";
|
|
10
|
+
import type { CssProfile, Diagnostic, HtmlSource, ImageRenderOptions, PdfMetadata, RendererInit, RenderOptions } from "./types.js";
|
|
11
|
+
import { type PdfExtras } from "./attachments.js";
|
|
12
|
+
import { WasmBridge, type WasmImageResult, type WasmRenderResult } from "./wasm.js";
|
|
13
|
+
/**
|
|
14
|
+
* Turns a public source into the HTML the core renders. Not part of the
|
|
15
|
+
* public API: the browser snapshots live DOM state; Node prepares strings
|
|
16
|
+
* (see `node-source.ts`) and checks core diagnostics against the caller's
|
|
17
|
+
* policies after the render.
|
|
18
|
+
*/
|
|
19
|
+
export interface SourcePreparation {
|
|
20
|
+
prepare(source: HtmlSource, options: SnapshotOptions): Promise<SnapshotResult>;
|
|
21
|
+
check?(diagnostics: readonly Diagnostic[], options: SnapshotOptions): void;
|
|
22
|
+
}
|
|
23
|
+
/** Common ownership boundary for main-thread and Worker WASM contexts. */
|
|
24
|
+
export interface Backend {
|
|
25
|
+
render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult>;
|
|
26
|
+
renderImage(html: string, image: NormalizedImageOptions, cssProfile: CssProfile, signal?: AbortSignal): Promise<WasmImageResult>;
|
|
27
|
+
dispose(): void;
|
|
28
|
+
}
|
|
29
|
+
/** Executes the synchronous bridge on the caller's thread. */
|
|
30
|
+
export declare class MainThreadBackend implements Backend {
|
|
31
|
+
private readonly bridge;
|
|
32
|
+
constructor(bridge: WasmBridge);
|
|
33
|
+
render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult>;
|
|
34
|
+
renderImage(html: string, image: NormalizedImageOptions, cssProfile: CssProfile, signal?: AbortSignal): Promise<WasmImageResult>;
|
|
35
|
+
dispose(): void;
|
|
36
|
+
}
|
|
8
37
|
/**
|
|
9
38
|
* Reusable renderer backed by one Worker or main-thread WASM context.
|
|
10
39
|
*
|
|
@@ -16,6 +45,7 @@ import type { HtmlSource, RendererInit, RenderOptions } from "./types.js";
|
|
|
16
45
|
*/
|
|
17
46
|
export declare class Html2RealPdf {
|
|
18
47
|
private readonly backend;
|
|
48
|
+
private readonly preparation;
|
|
19
49
|
private disposed;
|
|
20
50
|
private constructor();
|
|
21
51
|
/**
|
|
@@ -27,6 +57,22 @@ export declare class Html2RealPdf {
|
|
|
27
57
|
* @throws {@link WasmRenderError} when native limits reject input or WASM fails.
|
|
28
58
|
*/
|
|
29
59
|
render(source: HtmlSource, options?: RenderOptions): Promise<PdfDocument>;
|
|
60
|
+
/**
|
|
61
|
+
* Snapshots browser state and renders one auto-height image.
|
|
62
|
+
*
|
|
63
|
+
* @remarks
|
|
64
|
+
* Accepts the same sources and snapshot/resource options as `render`. The
|
|
65
|
+
* image is `width` CSS pixels wide (multiplied by `scale`) and exactly as
|
|
66
|
+
* tall as the laid-out content. Option errors are thrown before any
|
|
67
|
+
* snapshot work begins.
|
|
68
|
+
*
|
|
69
|
+
* @throws {RangeError} when `quality`, `scale`, `width`, `format`, or `chromaSubsampling` is invalid.
|
|
70
|
+
* @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.
|
|
71
|
+
* @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.
|
|
72
|
+
* @throws {@link ResourceLoadError} when required resources cannot be materialized.
|
|
73
|
+
* @throws {@link WasmRenderError} when native limits reject input or WASM fails.
|
|
74
|
+
*/
|
|
75
|
+
renderImage(source: HtmlSource, options?: ImageRenderOptions): Promise<RenderedImage>;
|
|
30
76
|
/** Terminates the owned backend and rejects future renders. */
|
|
31
77
|
dispose(): void;
|
|
32
78
|
}
|
|
@@ -66,3 +112,20 @@ export declare function createRenderer(init?: RendererInit): Promise<Html2RealPd
|
|
|
66
112
|
* ```
|
|
67
113
|
*/
|
|
68
114
|
export declare function renderPdf(source: HtmlSource, options?: RenderOptions): Promise<PdfDocument>;
|
|
115
|
+
/**
|
|
116
|
+
* Renders one image with the lazily created package-default Worker renderer.
|
|
117
|
+
*
|
|
118
|
+
* @remarks
|
|
119
|
+
* Shares the default renderer, its caching, and its trap recovery with
|
|
120
|
+
* `renderPdf`. Dispose the returned image when its object URLs are no
|
|
121
|
+
* longer needed.
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* const image = await renderImage(chartRef, { width: 800, scale: 2, quality: 0.8 });
|
|
126
|
+
* try { image.download("chart.jpg"); } finally { image.dispose(); }
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
export declare function renderImage(source: HtmlSource, options?: ImageRenderOptions): Promise<RenderedImage>;
|
|
130
|
+
/** Builds snapshot policy shared by PDF and image renders. */
|
|
131
|
+
export declare function snapshotOptionsFor(options: RenderOptions | ImageRenderOptions, cssProfile: CssProfile): SnapshotOptions;
|
package/dist/renderer.js
CHANGED
|
@@ -4,13 +4,15 @@
|
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
6
|
import { UnsupportedEnvironmentError, WasmRenderError } from "./errors.js";
|
|
7
|
+
import { DEFAULT_IMAGE_WIDTH, normalizeImageOptions, RenderedImage } from "./image.js";
|
|
7
8
|
import { normalizePage } from "./page.js";
|
|
8
9
|
import { PdfDocument } from "./pdf-document.js";
|
|
9
10
|
import { snapshotSource } from "./snapshot.js";
|
|
10
11
|
import { preparePdfExtras } from "./attachments.js";
|
|
11
12
|
import { WASM_TRAP_STATUS, WasmBridge } from "./wasm.js";
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
const browserPreparation = { prepare: snapshotSource };
|
|
14
|
+
/** Executes the synchronous bridge on the caller's thread. */
|
|
15
|
+
export class MainThreadBackend {
|
|
14
16
|
bridge;
|
|
15
17
|
constructor(bridge) {
|
|
16
18
|
this.bridge = bridge;
|
|
@@ -20,6 +22,11 @@ class MainThreadBackend {
|
|
|
20
22
|
return Promise.reject(abortReason(signal));
|
|
21
23
|
return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules, extras));
|
|
22
24
|
}
|
|
25
|
+
renderImage(html, image, cssProfile, signal) {
|
|
26
|
+
if (signal?.aborted)
|
|
27
|
+
return Promise.reject(abortReason(signal));
|
|
28
|
+
return Promise.resolve(this.bridge.renderImage(html, image, cssProfile));
|
|
29
|
+
}
|
|
23
30
|
dispose() {
|
|
24
31
|
this.bridge.dispose();
|
|
25
32
|
}
|
|
@@ -61,6 +68,24 @@ class WorkerBackend {
|
|
|
61
68
|
this.worker.postMessage({ type: "init", wasmUrl, fonts });
|
|
62
69
|
}
|
|
63
70
|
async render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal, extras) {
|
|
71
|
+
const result = await this.request({ type: "render", html, page, metadata, cssProfile, marginBoxes, pageRules, extras }, extras?.attachments?.map((attachment) => attachment.data.buffer) ?? [], signal);
|
|
72
|
+
return {
|
|
73
|
+
bytes: new Uint8Array(result.bytes),
|
|
74
|
+
pageCount: result.pageCount ?? 0,
|
|
75
|
+
diagnostics: Array.isArray(result.diagnostics) ? result.diagnostics : [],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
async renderImage(html, image, cssProfile, signal) {
|
|
79
|
+
const result = await this.request({ type: "render-image", html, image, cssProfile }, [], signal);
|
|
80
|
+
return {
|
|
81
|
+
bytes: new Uint8Array(result.bytes),
|
|
82
|
+
width: result.width ?? 0,
|
|
83
|
+
height: result.height ?? 0,
|
|
84
|
+
diagnostics: Array.isArray(result.diagnostics) ? result.diagnostics : [],
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Posts one request after initialization and resolves its raw result. */
|
|
88
|
+
async request(message, transfer, signal) {
|
|
64
89
|
if (this.disposed)
|
|
65
90
|
throw this.failure;
|
|
66
91
|
if (signal?.aborted)
|
|
@@ -83,7 +108,7 @@ class WorkerBackend {
|
|
|
83
108
|
}
|
|
84
109
|
this.pending.set(id, pending);
|
|
85
110
|
try {
|
|
86
|
-
this.worker.postMessage({
|
|
111
|
+
this.worker.postMessage({ ...message, id }, transfer);
|
|
87
112
|
}
|
|
88
113
|
catch (error) {
|
|
89
114
|
this.pending.delete(id);
|
|
@@ -122,14 +147,11 @@ class WorkerBackend {
|
|
|
122
147
|
this.pending.delete(message.id);
|
|
123
148
|
pending.removeAbort?.();
|
|
124
149
|
if (message.type === "render-error") {
|
|
125
|
-
|
|
150
|
+
// Input-limit and option statuses stay distinguishable from Worker failures.
|
|
151
|
+
pending.reject(new WasmRenderError(message.error, typeof message.status === "number" && message.status < 0 ? message.status : -21));
|
|
126
152
|
}
|
|
127
153
|
else {
|
|
128
|
-
pending.resolve(
|
|
129
|
-
bytes: new Uint8Array(message.bytes),
|
|
130
|
-
pageCount: message.pageCount,
|
|
131
|
-
diagnostics: Array.isArray(message.diagnostics) ? message.diagnostics : [],
|
|
132
|
-
});
|
|
154
|
+
pending.resolve(message);
|
|
133
155
|
}
|
|
134
156
|
}
|
|
135
157
|
}
|
|
@@ -144,13 +166,15 @@ class WorkerBackend {
|
|
|
144
166
|
*/
|
|
145
167
|
export class Html2RealPdf {
|
|
146
168
|
backend;
|
|
169
|
+
preparation;
|
|
147
170
|
disposed = false;
|
|
148
|
-
constructor(backend) {
|
|
171
|
+
constructor(backend, preparation) {
|
|
149
172
|
this.backend = backend;
|
|
173
|
+
this.preparation = preparation;
|
|
150
174
|
}
|
|
151
175
|
/** @internal */
|
|
152
|
-
static create(backend) {
|
|
153
|
-
return new Html2RealPdf(backend);
|
|
176
|
+
static create(backend, preparation = browserPreparation) {
|
|
177
|
+
return new Html2RealPdf(backend, preparation);
|
|
154
178
|
}
|
|
155
179
|
/**
|
|
156
180
|
* Snapshots browser state and renders one PDF.
|
|
@@ -167,37 +191,10 @@ export class Html2RealPdf {
|
|
|
167
191
|
throw abortReason(options.signal);
|
|
168
192
|
const extras = preparePdfExtras(options);
|
|
169
193
|
options.onProgress?.({ phase: "snapshot", completed: 0, total: 1 });
|
|
170
|
-
const snapshotOptions =
|
|
171
|
-
resourcePolicy: options.resourcePolicy ?? "error",
|
|
172
|
-
cssProfile: options.cssProfile ?? "document",
|
|
173
|
-
// Preserve the historical browser snapshot behavior unless callers
|
|
174
|
-
// explicitly request print media. The web-profile example in the public
|
|
175
|
-
// API opts into print rather than silently changing existing documents.
|
|
176
|
-
mediaType: options.mediaType ?? "screen",
|
|
177
|
-
unsupportedCss: options.unsupportedCss ?? (options.cssProfile === "strict" || options.strict ? "error" : "warn"),
|
|
178
|
-
// Raster fallback is deliberately opt-in. A caller must acknowledge the
|
|
179
|
-
// loss of native PDF primitives for the affected subtree explicitly.
|
|
180
|
-
fallback: options.fallback ?? "error",
|
|
181
|
-
};
|
|
182
|
-
if (options.baseUrl !== undefined)
|
|
183
|
-
snapshotOptions.baseUrl = options.baseUrl;
|
|
184
|
-
if (options.resourceResolver !== undefined)
|
|
185
|
-
snapshotOptions.resourceResolver = options.resourceResolver;
|
|
186
|
-
if (options.strict !== undefined)
|
|
187
|
-
snapshotOptions.strict = options.strict;
|
|
194
|
+
const snapshotOptions = snapshotOptionsFor(options, options.cssProfile ?? "document");
|
|
188
195
|
if (options.enableLinks !== undefined)
|
|
189
196
|
snapshotOptions.enableLinks = options.enableLinks;
|
|
190
|
-
|
|
191
|
-
snapshotOptions.layoutContext = options.layoutContext;
|
|
192
|
-
if (options.viewport !== undefined)
|
|
193
|
-
snapshotOptions.viewport = options.viewport;
|
|
194
|
-
if (options.includeShadowDom !== undefined)
|
|
195
|
-
snapshotOptions.includeShadowDom = options.includeShadowDom;
|
|
196
|
-
if (options.canvasToSvg !== undefined)
|
|
197
|
-
snapshotOptions.canvasToSvg = options.canvasToSvg;
|
|
198
|
-
if (options.canvasFallback !== undefined)
|
|
199
|
-
snapshotOptions.canvasFallback = options.canvasFallback;
|
|
200
|
-
const snapshot = await snapshotSource(source, snapshotOptions);
|
|
197
|
+
const snapshot = await this.preparation.prepare(source, snapshotOptions);
|
|
201
198
|
if (options.signal?.aborted)
|
|
202
199
|
throw abortReason(options.signal);
|
|
203
200
|
options.onProgress?.({ phase: "snapshot", completed: 1, total: 1 });
|
|
@@ -212,10 +209,61 @@ export class Html2RealPdf {
|
|
|
212
209
|
this.dispose();
|
|
213
210
|
throw error;
|
|
214
211
|
}
|
|
212
|
+
this.preparation.check?.(rendered.diagnostics, snapshotOptions);
|
|
215
213
|
options.onProgress?.({ phase: "wasm", completed: 1, total: 1 });
|
|
216
214
|
options.onProgress?.({ phase: "complete", completed: 1, total: 1 });
|
|
217
215
|
return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);
|
|
218
216
|
}
|
|
217
|
+
/**
|
|
218
|
+
* Snapshots browser state and renders one auto-height image.
|
|
219
|
+
*
|
|
220
|
+
* @remarks
|
|
221
|
+
* Accepts the same sources and snapshot/resource options as `render`. The
|
|
222
|
+
* image is `width` CSS pixels wide (multiplied by `scale`) and exactly as
|
|
223
|
+
* tall as the laid-out content. Option errors are thrown before any
|
|
224
|
+
* snapshot work begins.
|
|
225
|
+
*
|
|
226
|
+
* @throws {RangeError} when `quality`, `scale`, `width`, `format`, or `chromaSubsampling` is invalid.
|
|
227
|
+
* @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.
|
|
228
|
+
* @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.
|
|
229
|
+
* @throws {@link ResourceLoadError} when required resources cannot be materialized.
|
|
230
|
+
* @throws {@link WasmRenderError} when native limits reject input or WASM fails.
|
|
231
|
+
*/
|
|
232
|
+
async renderImage(source, options = {}) {
|
|
233
|
+
if (this.disposed)
|
|
234
|
+
throw new Error("Renderer has been disposed");
|
|
235
|
+
if (options.signal?.aborted)
|
|
236
|
+
throw abortReason(options.signal);
|
|
237
|
+
const normalized = normalizeImageOptions(options, defaultImageWidth(source, options));
|
|
238
|
+
const cssProfile = options.cssProfile ?? "web";
|
|
239
|
+
options.onProgress?.({ phase: "snapshot", completed: 0, total: 1 });
|
|
240
|
+
const snapshotOptions = snapshotOptionsFor(options, cssProfile);
|
|
241
|
+
// Images have no annotations, and the raster backend reads PNG pixels.
|
|
242
|
+
snapshotOptions.enableLinks = false;
|
|
243
|
+
snapshotOptions.imageTarget = true;
|
|
244
|
+
const snapshot = await this.preparation.prepare(source, snapshotOptions);
|
|
245
|
+
if (options.signal?.aborted)
|
|
246
|
+
throw abortReason(options.signal);
|
|
247
|
+
options.onProgress?.({ phase: "snapshot", completed: 1, total: 1 });
|
|
248
|
+
options.onProgress?.({ phase: "wasm", completed: 0, total: 1 });
|
|
249
|
+
let rendered;
|
|
250
|
+
try {
|
|
251
|
+
rendered = await this.backend.renderImage(snapshot.html, normalized.options, cssProfile, options.signal);
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS)
|
|
255
|
+
this.dispose();
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
this.preparation.check?.(rendered.diagnostics, snapshotOptions);
|
|
259
|
+
options.onProgress?.({ phase: "wasm", completed: 1, total: 1 });
|
|
260
|
+
options.onProgress?.({ phase: "complete", completed: 1, total: 1 });
|
|
261
|
+
return RenderedImage.create(rendered.bytes, rendered.width, rendered.height, [
|
|
262
|
+
...normalized.diagnostics,
|
|
263
|
+
...snapshot.diagnostics,
|
|
264
|
+
...rendered.diagnostics,
|
|
265
|
+
]);
|
|
266
|
+
}
|
|
219
267
|
/** Terminates the owned backend and rejects future renders. */
|
|
220
268
|
dispose() {
|
|
221
269
|
if (this.disposed)
|
|
@@ -287,6 +335,81 @@ export async function renderPdf(source, options = {}) {
|
|
|
287
335
|
throw error;
|
|
288
336
|
}
|
|
289
337
|
}
|
|
338
|
+
/**
|
|
339
|
+
* Renders one image with the lazily created package-default Worker renderer.
|
|
340
|
+
*
|
|
341
|
+
* @remarks
|
|
342
|
+
* Shares the default renderer, its caching, and its trap recovery with
|
|
343
|
+
* `renderPdf`. Dispose the returned image when its object URLs are no
|
|
344
|
+
* longer needed.
|
|
345
|
+
*
|
|
346
|
+
* @example
|
|
347
|
+
* ```ts
|
|
348
|
+
* const image = await renderImage(chartRef, { width: 800, scale: 2, quality: 0.8 });
|
|
349
|
+
* try { image.download("chart.jpg"); } finally { image.dispose(); }
|
|
350
|
+
* ```
|
|
351
|
+
*/
|
|
352
|
+
export async function renderImage(source, options = {}) {
|
|
353
|
+
defaultRenderer ??= createRenderer().catch((error) => {
|
|
354
|
+
defaultRenderer = undefined;
|
|
355
|
+
throw error;
|
|
356
|
+
});
|
|
357
|
+
const current = defaultRenderer;
|
|
358
|
+
try {
|
|
359
|
+
return await (await current).renderImage(source, options);
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS && defaultRenderer === current) {
|
|
363
|
+
defaultRenderer = undefined;
|
|
364
|
+
}
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/** Builds snapshot policy shared by PDF and image renders. */
|
|
369
|
+
export function snapshotOptionsFor(options, cssProfile) {
|
|
370
|
+
const snapshotOptions = {
|
|
371
|
+
resourcePolicy: options.resourcePolicy ?? "error",
|
|
372
|
+
cssProfile,
|
|
373
|
+
// Preserve the historical browser snapshot behavior unless callers
|
|
374
|
+
// explicitly request print media. The web-profile example in the public
|
|
375
|
+
// API opts into print rather than silently changing existing documents.
|
|
376
|
+
mediaType: options.mediaType ?? "screen",
|
|
377
|
+
unsupportedCss: options.unsupportedCss ?? (cssProfile === "strict" || options.strict ? "error" : "warn"),
|
|
378
|
+
// Raster fallback is deliberately opt-in. A caller must acknowledge the
|
|
379
|
+
// loss of native PDF primitives for the affected subtree explicitly.
|
|
380
|
+
fallback: options.fallback ?? "error",
|
|
381
|
+
};
|
|
382
|
+
if (options.baseUrl !== undefined)
|
|
383
|
+
snapshotOptions.baseUrl = options.baseUrl;
|
|
384
|
+
if (options.resourceResolver !== undefined)
|
|
385
|
+
snapshotOptions.resourceResolver = options.resourceResolver;
|
|
386
|
+
if (options.strict !== undefined)
|
|
387
|
+
snapshotOptions.strict = options.strict;
|
|
388
|
+
if (options.layoutContext !== undefined)
|
|
389
|
+
snapshotOptions.layoutContext = options.layoutContext;
|
|
390
|
+
if (options.viewport !== undefined)
|
|
391
|
+
snapshotOptions.viewport = options.viewport;
|
|
392
|
+
if (options.includeShadowDom !== undefined)
|
|
393
|
+
snapshotOptions.includeShadowDom = options.includeShadowDom;
|
|
394
|
+
if (options.canvasToSvg !== undefined)
|
|
395
|
+
snapshotOptions.canvasToSvg = options.canvasToSvg;
|
|
396
|
+
if (options.canvasFallback !== undefined)
|
|
397
|
+
snapshotOptions.canvasFallback = options.canvasFallback;
|
|
398
|
+
return snapshotOptions;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Element and ref sources default to their rendered width so the image
|
|
402
|
+
* matches what is on screen; strings use the viewport or 800 CSS pixels.
|
|
403
|
+
*/
|
|
404
|
+
function defaultImageWidth(source, options) {
|
|
405
|
+
if (typeof source === "string")
|
|
406
|
+
return Math.min(options.viewport?.width ?? DEFAULT_IMAGE_WIDTH, 4096);
|
|
407
|
+
const element = "current" in source ? source.current : source;
|
|
408
|
+
if (!element || typeof element.getBoundingClientRect !== "function")
|
|
409
|
+
return DEFAULT_IMAGE_WIDTH;
|
|
410
|
+
const width = Math.ceil(element.getBoundingClientRect().width);
|
|
411
|
+
return width >= 1 ? Math.min(width, 4096) : DEFAULT_IMAGE_WIDTH;
|
|
412
|
+
}
|
|
290
413
|
function applyPageBreakRules(html, rules) {
|
|
291
414
|
if (!rules)
|
|
292
415
|
return html;
|