@imggion/html2realpdf 0.3.0 → 0.3.2
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 +27 -3
- package/dist/libhtml2realpdf.wasm +0 -0
- package/dist/renderer.d.ts +6 -2
- package/dist/renderer.js +43 -13
- package/dist/renderer.js.map +1 -1
- package/dist/snapshot.js +134 -6
- package/dist/snapshot.js.map +1 -1
- package/dist/types.d.ts +14 -4
- package/dist/types.js.map +1 -1
- package/dist/wasm.d.ts +5 -1
- package/dist/wasm.js +50 -9
- package/dist/wasm.js.map +1 -1
- package/dist/worker.js +5 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/skills/html2realpdf/SKILL.md +6 -2
package/README.md
CHANGED
|
@@ -6,9 +6,6 @@
|
|
|
6
6
|
<a href="https://www.npmjs.com/package/@imggion/html2realpdf">
|
|
7
7
|
<img src="https://img.shields.io/npm/v/@imggion/html2realpdf.svg?style=flat-square" alt="npm version">
|
|
8
8
|
</a>
|
|
9
|
-
<a href="https://github.com/imggion/html2realpdf/releases/tag/v0.3.0">
|
|
10
|
-
<img src="https://img.shields.io/badge/release-0.3.0-2ea44f?style=flat-square" alt="Latest release: 0.3.0">
|
|
11
|
-
</a>
|
|
12
9
|
<a href="#compliance">
|
|
13
10
|
<img src="https://img.shields.io/badge/PDF%2FA--3u-d32f2f?style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTE0IDJINXYyMGgxNFY3ek0xNCAydjVoNSIvPjx0ZXh0IHg9IjEyIiB5PSIxNyIgZmlsbD0id2hpdGUiIGZvbnQtZmFtaWx5PSJBcmlhbCxzYW5zLXNlcmlmIiBmb250LXNpemU9IjciIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QREY8L3RleHQ%2BPC9zdmc%2B" alt="PDF/A-3u">
|
|
14
11
|
</a>
|
|
@@ -248,6 +245,33 @@ See [PDF/A implementation and validation](https://github.com/imggion/html2realpd
|
|
|
248
245
|
for limits and the pinned veraPDF gate. Existing calls without these options
|
|
249
246
|
keep their ordinary PDF output.
|
|
250
247
|
|
|
248
|
+
## Resource limits and untrusted input
|
|
249
|
+
|
|
250
|
+
The native renderer rejects documents deeper than 64 nested elements
|
|
251
|
+
(`DocumentTooDeep`). CSS `var()` substitution is limited to 64 KiB per value,
|
|
252
|
+
8 MiB of cumulative expansion including intermediate values, and 65,536
|
|
253
|
+
substitutions per cascade (`CssExpansionLimitExceeded`). PNGs are limited to
|
|
254
|
+
16,777,216 pixels (`ImageTooLarge`); alpha PNG decompression must fit the exact
|
|
255
|
+
scanline size declared by the image (`InvalidPng` otherwise). These limits
|
|
256
|
+
also apply to trusted documents and cannot be raised through render options.
|
|
257
|
+
|
|
258
|
+
These errors leave the renderer usable. An unexpected WASM trap instead
|
|
259
|
+
discards its instance: recreate an explicit `createRenderer()` instance, or
|
|
260
|
+
call `renderPdf()` again to create a fresh default Worker. Failed documents
|
|
261
|
+
are never retried automatically.
|
|
262
|
+
|
|
263
|
+
Returning `null` from `resourceResolver` denies an image, background image, or
|
|
264
|
+
stylesheet without fetching the original URL. `resourcePolicy: "error"`
|
|
265
|
+
rejects the render; `"omit"` skips the resource and returns a diagnostic.
|
|
266
|
+
Without a resolver, image URLs can be fetched normally. Already embedded
|
|
267
|
+
image data URLs bypass the resolver, and live DOM resources may already have
|
|
268
|
+
been loaded by the host page.
|
|
269
|
+
|
|
270
|
+
These are targeted safeguards, not a general CPU or memory quota. Keep Worker
|
|
271
|
+
execution for untrusted documents and apply application-level input-size and
|
|
272
|
+
resource allowlists; native service integrations also need process isolation
|
|
273
|
+
and external time/memory limits.
|
|
274
|
+
|
|
251
275
|
## Compliance
|
|
252
276
|
|
|
253
277
|
<p align="center">
|
|
Binary file
|
package/dist/renderer.d.ts
CHANGED
|
@@ -11,7 +11,8 @@ import type { HtmlSource, RendererInit, RenderOptions } from "./types.js";
|
|
|
11
11
|
* @remarks
|
|
12
12
|
* Create instances with `createRenderer`. Fonts and execution mode belong to
|
|
13
13
|
* the renderer lifetime; each returned `PdfDocument` has its own shorter
|
|
14
|
-
* lifetime. Call `dispose` when the renderer is no longer needed.
|
|
14
|
+
* lifetime. Call `dispose` when the renderer is no longer needed. Input-limit
|
|
15
|
+
* errors leave it reusable; an unexpected WASM trap disposes it permanently.
|
|
15
16
|
*/
|
|
16
17
|
export declare class Html2RealPdf {
|
|
17
18
|
private readonly backend;
|
|
@@ -23,6 +24,7 @@ export declare class Html2RealPdf {
|
|
|
23
24
|
* @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.
|
|
24
25
|
* @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.
|
|
25
26
|
* @throws {@link ResourceLoadError} when required resources cannot be materialized.
|
|
27
|
+
* @throws {@link WasmRenderError} when native limits reject input or WASM fails.
|
|
26
28
|
*/
|
|
27
29
|
render(source: HtmlSource, options?: RenderOptions): Promise<PdfDocument>;
|
|
28
30
|
/** Terminates the owned backend and rejects future renders. */
|
|
@@ -53,7 +55,9 @@ export declare function createRenderer(init?: RendererInit): Promise<Html2RealPd
|
|
|
53
55
|
* The default renderer is cached for the application lifetime and cannot be
|
|
54
56
|
* configured with custom fonts. Use `createRenderer` when deterministic
|
|
55
57
|
* backend disposal or renderer-level configuration is required. The returned
|
|
56
|
-
* document must still be disposed by the caller.
|
|
58
|
+
* document must still be disposed by the caller. After an unexpected WASM trap,
|
|
59
|
+
* the failed render is rejected and the next call creates a fresh renderer;
|
|
60
|
+
* the failed document is never retried automatically.
|
|
57
61
|
*
|
|
58
62
|
* @example
|
|
59
63
|
* ```ts
|
package/dist/renderer.js
CHANGED
|
@@ -8,7 +8,7 @@ import { normalizePage } from "./page.js";
|
|
|
8
8
|
import { PdfDocument } from "./pdf-document.js";
|
|
9
9
|
import { snapshotSource } from "./snapshot.js";
|
|
10
10
|
import { preparePdfExtras } from "./attachments.js";
|
|
11
|
-
import { WasmBridge } from "./wasm.js";
|
|
11
|
+
import { WASM_TRAP_STATUS, WasmBridge } from "./wasm.js";
|
|
12
12
|
/** Executes the synchronous bridge on the caller's browser thread. */
|
|
13
13
|
class MainThreadBackend {
|
|
14
14
|
bridge;
|
|
@@ -31,6 +31,7 @@ class WorkerBackend {
|
|
|
31
31
|
ready;
|
|
32
32
|
nextId = 1;
|
|
33
33
|
disposed = false;
|
|
34
|
+
failure;
|
|
34
35
|
constructor(wasmUrl, fonts) {
|
|
35
36
|
this.worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module", name: "html2realpdf" });
|
|
36
37
|
this.ready = new Promise((resolve, reject) => {
|
|
@@ -55,21 +56,20 @@ class WorkerBackend {
|
|
|
55
56
|
});
|
|
56
57
|
this.worker.addEventListener("message", (event) => this.handleMessage(event));
|
|
57
58
|
this.worker.addEventListener("error", (event) => {
|
|
58
|
-
|
|
59
|
-
for (const pending of this.pending.values()) {
|
|
60
|
-
pending.removeAbort?.();
|
|
61
|
-
pending.reject(error);
|
|
62
|
-
}
|
|
63
|
-
this.pending.clear();
|
|
59
|
+
this.stop(new WasmRenderError(event.message || "PDF Worker failed", WASM_TRAP_STATUS));
|
|
64
60
|
});
|
|
65
61
|
this.worker.postMessage({ type: "init", wasmUrl, fonts });
|
|
66
62
|
}
|
|
67
63
|
async render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal, extras) {
|
|
68
64
|
if (this.disposed)
|
|
69
|
-
throw
|
|
65
|
+
throw this.failure;
|
|
70
66
|
if (signal?.aborted)
|
|
71
67
|
throw abortReason(signal);
|
|
72
68
|
await this.ready;
|
|
69
|
+
if (this.disposed)
|
|
70
|
+
throw this.failure;
|
|
71
|
+
if (signal?.aborted)
|
|
72
|
+
throw abortReason(signal);
|
|
73
73
|
const id = this.nextId++;
|
|
74
74
|
return new Promise((resolve, reject) => {
|
|
75
75
|
const pending = { resolve, reject };
|
|
@@ -93,13 +93,17 @@ class WorkerBackend {
|
|
|
93
93
|
});
|
|
94
94
|
}
|
|
95
95
|
dispose() {
|
|
96
|
+
this.stop(new Error("Renderer was disposed"));
|
|
97
|
+
}
|
|
98
|
+
stop(error) {
|
|
96
99
|
if (this.disposed)
|
|
97
100
|
return;
|
|
98
101
|
this.disposed = true;
|
|
102
|
+
this.failure = error;
|
|
99
103
|
this.worker.terminate();
|
|
100
104
|
for (const pending of this.pending.values()) {
|
|
101
105
|
pending.removeAbort?.();
|
|
102
|
-
pending.reject(
|
|
106
|
+
pending.reject(error);
|
|
103
107
|
}
|
|
104
108
|
this.pending.clear();
|
|
105
109
|
}
|
|
@@ -107,6 +111,11 @@ class WorkerBackend {
|
|
|
107
111
|
const message = event.data;
|
|
108
112
|
if (message?.type !== "render-result" && message?.type !== "render-error")
|
|
109
113
|
return;
|
|
114
|
+
// Even an aborted request can report a trap that invalidates other work.
|
|
115
|
+
if (message.type === "render-error" && message.status === WASM_TRAP_STATUS) {
|
|
116
|
+
this.stop(new WasmRenderError(message.error, WASM_TRAP_STATUS));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
110
119
|
const pending = this.pending.get(message.id);
|
|
111
120
|
if (!pending)
|
|
112
121
|
return;
|
|
@@ -130,7 +139,8 @@ class WorkerBackend {
|
|
|
130
139
|
* @remarks
|
|
131
140
|
* Create instances with `createRenderer`. Fonts and execution mode belong to
|
|
132
141
|
* the renderer lifetime; each returned `PdfDocument` has its own shorter
|
|
133
|
-
* lifetime. Call `dispose` when the renderer is no longer needed.
|
|
142
|
+
* lifetime. Call `dispose` when the renderer is no longer needed. Input-limit
|
|
143
|
+
* errors leave it reusable; an unexpected WASM trap disposes it permanently.
|
|
134
144
|
*/
|
|
135
145
|
export class Html2RealPdf {
|
|
136
146
|
backend;
|
|
@@ -148,6 +158,7 @@ export class Html2RealPdf {
|
|
|
148
158
|
* @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.
|
|
149
159
|
* @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.
|
|
150
160
|
* @throws {@link ResourceLoadError} when required resources cannot be materialized.
|
|
161
|
+
* @throws {@link WasmRenderError} when native limits reject input or WASM fails.
|
|
151
162
|
*/
|
|
152
163
|
async render(source, options = {}) {
|
|
153
164
|
if (this.disposed)
|
|
@@ -192,7 +203,15 @@ export class Html2RealPdf {
|
|
|
192
203
|
options.onProgress?.({ phase: "snapshot", completed: 1, total: 1 });
|
|
193
204
|
options.onProgress?.({ phase: "wasm", completed: 0, total: 1 });
|
|
194
205
|
const page = options.page !== undefined ? normalizePage(options.page) : snapshot.page ?? normalizePage();
|
|
195
|
-
|
|
206
|
+
let rendered;
|
|
207
|
+
try {
|
|
208
|
+
rendered = await this.backend.render(applyPageBreakRules(snapshot.html, options.pageBreak), page, options.metadata, options.cssProfile ?? "document", snapshot.pageMarginBoxes, options.page === undefined ? snapshot.pageRules : undefined, options.signal, extras);
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS)
|
|
212
|
+
this.dispose();
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
196
215
|
options.onProgress?.({ phase: "wasm", completed: 1, total: 1 });
|
|
197
216
|
options.onProgress?.({ phase: "complete", completed: 1, total: 1 });
|
|
198
217
|
return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);
|
|
@@ -242,7 +261,9 @@ let defaultRenderer;
|
|
|
242
261
|
* The default renderer is cached for the application lifetime and cannot be
|
|
243
262
|
* configured with custom fonts. Use `createRenderer` when deterministic
|
|
244
263
|
* backend disposal or renderer-level configuration is required. The returned
|
|
245
|
-
* document must still be disposed by the caller.
|
|
264
|
+
* document must still be disposed by the caller. After an unexpected WASM trap,
|
|
265
|
+
* the failed render is rejected and the next call creates a fresh renderer;
|
|
266
|
+
* the failed document is never retried automatically.
|
|
246
267
|
*
|
|
247
268
|
* @example
|
|
248
269
|
* ```ts
|
|
@@ -255,7 +276,16 @@ export async function renderPdf(source, options = {}) {
|
|
|
255
276
|
defaultRenderer = undefined;
|
|
256
277
|
throw error;
|
|
257
278
|
});
|
|
258
|
-
|
|
279
|
+
const current = defaultRenderer;
|
|
280
|
+
try {
|
|
281
|
+
return await (await current).render(source, options);
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS && defaultRenderer === current) {
|
|
285
|
+
defaultRenderer = undefined;
|
|
286
|
+
}
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
259
289
|
}
|
|
260
290
|
function applyPageBreakRules(html, rules) {
|
|
261
291
|
if (!rules)
|
package/dist/renderer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,2BAA2B,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAuB,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAA2E,MAAM,eAAe,CAAC;AAExH,OAAO,EAAE,gBAAgB,EAAkB,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,UAAU,EAAyB,MAAM,WAAW,CAAC;AAQ9D,sEAAsE;AACtE,MAAM,iBAAiB;IACQ,MAAM;IAAnC,YAA6B,MAAkB;sBAAlB,MAAM;IAAe,CAAC;IAEnD,MAAM,CAAC,IAAY,EAAE,IAAoB,EAAE,QAAsB,EAAE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AAE,CAAC,WAAW,IAAI,EAAE,CAAC;AACzH,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAgB,EAAE,KAA6C,EAAE,WAAmB;IAC9G,MAAM,SAAS,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;IACpE,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACpH,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,WAAW,CAAC,MAAmB;IACtC,OAAO,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,2BAA2B,EAAE,YAAY,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/**\n * Renderer factories, execution backends, and per-render pipeline ownership.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedEnvironmentError, WasmRenderError } from \"./errors.js\";\nimport { normalizePage, type NormalizedPage } from \"./page.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { snapshotSource, type SnapshotOptions, type SnapshotPageMarginBox, type SnapshotPageRule } from \"./snapshot.js\";\nimport type { CssProfile, FontRegistration, HtmlSource, PageBreakRules, PdfMetadata, RendererInit, RenderOptions } from \"./types.js\";\nimport { preparePdfExtras, type PdfExtras } from \"./attachments.js\";\nimport { WasmBridge, type WasmRenderResult } from \"./wasm.js\";\n\n/** Common ownership boundary for main-thread and Worker WASM contexts. */\ninterface Backend {\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult>;\n dispose(): void;\n}\n\n/** Executes the synchronous bridge on the caller's browser thread. */\nclass MainThreadBackend implements Backend {\n constructor(private readonly bridge: WasmBridge) {}\n\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult> {\n if (signal?.aborted) return Promise.reject(abortReason(signal));\n return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules, extras));\n }\n\n dispose(): void {\n this.bridge.dispose();\n }\n}\n\n/** Caller state retained while a Worker render is in flight. */\ninterface PendingRender {\n resolve: (result: WasmRenderResult) => void;\n reject: (error: unknown) => void;\n removeAbort?: () => void;\n}\n\n/** Owns a module Worker and routes concurrent results by request identifier. */\nclass WorkerBackend implements Backend {\n private readonly worker: Worker;\n private readonly pending = new Map<number, PendingRender>();\n private readonly ready: Promise<void>;\n private nextId = 1;\n private disposed = false;\n\n constructor(wasmUrl: string, fonts: readonly FontRegistration[]) {\n this.worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\", name: \"html2realpdf\" });\n this.ready = new Promise<void>((resolve, reject) => {\n const onError = (event: ErrorEvent) => {\n this.worker.removeEventListener(\"message\", onMessage);\n reject(new WasmRenderError(event.message || \"PDF Worker initialization failed\", -20));\n };\n const onMessage = (event: MessageEvent) => {\n if (event.data?.type === \"ready\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n resolve();\n } else if (event.data?.type === \"init-error\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n reject(new WasmRenderError(event.data.error, -20));\n }\n };\n this.worker.addEventListener(\"message\", onMessage);\n this.worker.addEventListener(\"error\", onError, { once: true });\n });\n this.worker.addEventListener(\"message\", (event) => this.handleMessage(event));\n this.worker.addEventListener(\"error\", (event) => {\n const error = new WasmRenderError(event.message || \"PDF Worker failed\", -22);\n for (const pending of this.pending.values()) {\n pending.removeAbort?.();\n pending.reject(error);\n }\n this.pending.clear();\n });\n this.worker.postMessage({ type: \"init\", wasmUrl, fonts });\n }\n\n async render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult> {\n if (this.disposed) throw new Error(\"Renderer has been disposed\");\n if (signal?.aborted) throw abortReason(signal);\n await this.ready;\n\n const id = this.nextId++;\n return new Promise<WasmRenderResult>((resolve, reject) => {\n const pending: PendingRender = { resolve, reject };\n if (signal) {\n const onAbort = () => {\n this.pending.delete(id);\n reject(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.removeAbort = () => signal.removeEventListener(\"abort\", onAbort);\n }\n this.pending.set(id, pending);\n try {\n this.worker.postMessage({ type: \"render\", id, html, page, metadata, cssProfile, marginBoxes, pageRules, extras },\n extras?.attachments?.map((attachment) => attachment.data.buffer) ?? []);\n } catch (error) {\n this.pending.delete(id);\n pending.removeAbort?.();\n reject(error);\n }\n });\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.worker.terminate();\n for (const pending of this.pending.values()) {\n pending.removeAbort?.();\n pending.reject(new Error(\"Renderer was disposed\"));\n }\n this.pending.clear();\n }\n\n private handleMessage(event: MessageEvent): void {\n const message = event.data;\n if (message?.type !== \"render-result\" && message?.type !== \"render-error\") return;\n const pending = this.pending.get(message.id);\n if (!pending) return;\n this.pending.delete(message.id);\n pending.removeAbort?.();\n\n if (message.type === \"render-error\") {\n pending.reject(new WasmRenderError(message.error, -21));\n } else {\n pending.resolve({\n bytes: new Uint8Array(message.bytes),\n pageCount: message.pageCount,\n diagnostics: Array.isArray(message.diagnostics) ? message.diagnostics : [],\n });\n }\n }\n}\n\n/**\n * Reusable renderer backed by one Worker or main-thread WASM context.\n *\n * @remarks\n * Create instances with `createRenderer`. Fonts and execution mode belong to\n * the renderer lifetime; each returned `PdfDocument` has its own shorter\n * lifetime. Call `dispose` when the renderer is no longer needed.\n */\nexport class Html2RealPdf {\n private disposed = false;\n\n private constructor(private readonly backend: Backend) {}\n\n /** @internal */\n static create(backend: Backend): Html2RealPdf {\n return new Html2RealPdf(backend);\n }\n\n /**\n * Snapshots browser state and renders one PDF.\n *\n * @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.\n * @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.\n * @throws {@link ResourceLoadError} when required resources cannot be materialized.\n */\n async render(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n if (this.disposed) throw new Error(\"Renderer has been disposed\");\n if (options.signal?.aborted) throw abortReason(options.signal);\n const extras = preparePdfExtras(options);\n options.onProgress?.({ phase: \"snapshot\", completed: 0, total: 1 });\n const snapshotOptions: SnapshotOptions = {\n resourcePolicy: options.resourcePolicy ?? \"error\",\n cssProfile: options.cssProfile ?? \"document\",\n // Preserve the historical browser snapshot behavior unless callers\n // explicitly request print media. The web-profile example in the public\n // API opts into print rather than silently changing existing documents.\n mediaType: options.mediaType ?? \"screen\",\n unsupportedCss: options.unsupportedCss ?? (options.cssProfile === \"strict\" || options.strict ? \"error\" : \"warn\"),\n // Raster fallback is deliberately opt-in. A caller must acknowledge the\n // loss of native PDF primitives for the affected subtree explicitly.\n fallback: options.fallback ?? \"error\",\n };\n if (options.baseUrl !== undefined) snapshotOptions.baseUrl = options.baseUrl;\n if (options.resourceResolver !== undefined) snapshotOptions.resourceResolver = options.resourceResolver;\n if (options.strict !== undefined) snapshotOptions.strict = options.strict;\n if (options.enableLinks !== undefined) snapshotOptions.enableLinks = options.enableLinks;\n if (options.layoutContext !== undefined) snapshotOptions.layoutContext = options.layoutContext;\n if (options.viewport !== undefined) snapshotOptions.viewport = options.viewport;\n if (options.includeShadowDom !== undefined) snapshotOptions.includeShadowDom = options.includeShadowDom;\n if (options.canvasToSvg !== undefined) snapshotOptions.canvasToSvg = options.canvasToSvg;\n if (options.canvasFallback !== undefined) snapshotOptions.canvasFallback = options.canvasFallback;\n const snapshot = await snapshotSource(source, snapshotOptions);\n if (options.signal?.aborted) throw abortReason(options.signal);\n options.onProgress?.({ phase: \"snapshot\", completed: 1, total: 1 });\n\n options.onProgress?.({ phase: \"wasm\", completed: 0, total: 1 });\n const page = options.page !== undefined ? normalizePage(options.page) : snapshot.page ?? normalizePage();\n const rendered = await this.backend.render(\n applyPageBreakRules(snapshot.html, options.pageBreak),\n page,\n options.metadata,\n options.cssProfile ?? \"document\",\n snapshot.pageMarginBoxes,\n options.page === undefined ? snapshot.pageRules : undefined,\n options.signal,\n extras,\n );\n options.onProgress?.({ phase: \"wasm\", completed: 1, total: 1 });\n options.onProgress?.({ phase: \"complete\", completed: 1, total: 1 });\n return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);\n }\n\n /** Terminates the owned backend and rejects future renders. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.backend.dispose();\n }\n}\n\n/**\n * Creates a reusable renderer with explicit backend and font ownership.\n *\n * @example\n * ```ts\n * const renderer = await createRenderer({ fonts });\n * try {\n * const pdf = await renderer.render(element);\n * try { pdf.download(\"report.pdf\"); } finally { pdf.dispose(); }\n * } finally {\n * renderer.dispose();\n * }\n * ```\n *\n * @throws {@link UnsupportedEnvironmentError} outside a browser or when the\n * requested execution backend is unavailable.\n */\nexport async function createRenderer(init: RendererInit = {}): Promise<Html2RealPdf> {\n if (typeof window === \"undefined\") throw new UnsupportedEnvironmentError();\n if (init.execution !== \"main\" && typeof Worker === \"undefined\") {\n throw new UnsupportedEnvironmentError(\"html2realpdf Worker execution is unavailable; use execution: 'main' as a fallback\");\n }\n const wasmUrl = new URL(init.wasmUrl ?? new URL(\"./libhtml2realpdf.wasm\", import.meta.url), window.location.href).href;\n const backend: Backend = init.execution === \"main\"\n ? new MainThreadBackend(await WasmBridge.create(wasmUrl, init.fonts ?? []))\n : new WorkerBackend(wasmUrl, init.fonts ?? []);\n return Html2RealPdf.create(backend);\n}\n\nlet defaultRenderer: Promise<Html2RealPdf> | undefined;\n\n/**\n * Renders with a lazily created package-default Worker renderer.\n *\n * @remarks\n * The default renderer is cached for the application lifetime and cannot be\n * configured with custom fonts. Use `createRenderer` when deterministic\n * backend disposal or renderer-level configuration is required. The returned\n * document must still be disposed by the caller.\n *\n * @example\n * ```ts\n * const pdf = await renderPdf(document.querySelector(\"#invoice\")!);\n * try { pdf.download(\"invoice.pdf\"); } finally { pdf.dispose(); }\n * ```\n */\nexport async function renderPdf(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n defaultRenderer ??= createRenderer().catch((error: unknown) => {\n defaultRenderer = undefined;\n throw error;\n });\n return (await defaultRenderer).render(source, options);\n}\n\nfunction applyPageBreakRules(html: string, rules?: PageBreakRules): string {\n if (!rules) return html;\n const declarations: string[] = [];\n // DOM snapshots carry computed break properties as inline declarations.\n // Option-driven rules therefore need author importance to override the\n // snapshot's inline `auto` value while still yielding to inline !important.\n appendSelectorRule(declarations, rules.before, \"break-before:page!important\");\n appendSelectorRule(declarations, rules.after, \"break-after:page!important\");\n appendSelectorRule(declarations, rules.avoid, \"break-inside:avoid!important\");\n if (rules.legacy) declarations.push(\".html2pdf__page-break{break-before:page!important}\");\n if (rules.avoidAll) declarations.push(\"body *{break-inside:avoid!important}\");\n return declarations.length === 0 ? html : `<style data-html2realpdf-pagebreak>${declarations.join(\"\")}</style>${html}`;\n}\n\nfunction appendSelectorRule(output: string[], input: string | readonly string[] | undefined, declaration: string): void {\n const selectors = typeof input === \"string\" ? [input] : input ?? [];\n const safe = selectors.map((selector) => selector.trim()).filter((selector) => selector && !/[{};]/.test(selector));\n if (safe.length > 0) output.push(`${safe.join(\",\")}{${declaration}}`);\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,2BAA2B,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAuB,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAA2E,MAAM,eAAe,CAAC;AAExH,OAAO,EAAE,gBAAgB,EAAkB,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAyB,MAAM,WAAW,CAAC;AAQhF,sEAAsE;AACtE,MAAM,iBAAiB;IACQ,MAAM;IAAnC,YAA6B,MAAkB;sBAAlB,MAAM;IAAe,CAAC;IAEnD,MAAM,CAAC,IAAY,EAAE,IAAoB,EAAE,QAAsB,EAAE,UAAuB,EAAE,WAA8C,EAAE,SAAuC,EAAE,MAAoB,EAAE,MAAkB;QAC3N,IAAI,MAAM,EAAE,OAAO;YAAE,OAAO,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;QAChE,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IAC/G,CAAC;IAED,OAAO;QACL,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACF;AASD,gFAAgF;AAChF,MAAM,aAAa;IACA,MAAM,CAAS;IACf,OAAO,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC3C,KAAK,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M;QAAE,YAAY,CAAC,IAAI,CAAC,oDAAoD,CAAC,CAAC;IAC1F,IAAI,KAAK,CAAC,QAAQ;QAAE,YAAY,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;IAC9E,OAAO,YAAY,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,sCAAsC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC;AACzH,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAgB,EAAE,KAA6C,EAAE,WAAmB;IAC9G,MAAM,SAAS,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;IACpE,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACpH,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,WAAW,CAAC,MAAmB;IACtC,OAAO,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,2BAA2B,EAAE,YAAY,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/**\n * Renderer factories, execution backends, and per-render pipeline ownership.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedEnvironmentError, WasmRenderError } from \"./errors.js\";\nimport { normalizePage, type NormalizedPage } from \"./page.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { snapshotSource, type SnapshotOptions, type SnapshotPageMarginBox, type SnapshotPageRule } from \"./snapshot.js\";\nimport type { CssProfile, FontRegistration, HtmlSource, PageBreakRules, PdfMetadata, RendererInit, RenderOptions } from \"./types.js\";\nimport { preparePdfExtras, type PdfExtras } from \"./attachments.js\";\nimport { WASM_TRAP_STATUS, WasmBridge, type WasmRenderResult } from \"./wasm.js\";\n\n/** Common ownership boundary for main-thread and Worker WASM contexts. */\ninterface Backend {\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult>;\n dispose(): void;\n}\n\n/** Executes the synchronous bridge on the caller's browser thread. */\nclass MainThreadBackend implements Backend {\n constructor(private readonly bridge: WasmBridge) {}\n\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult> {\n if (signal?.aborted) return Promise.reject(abortReason(signal));\n return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules, extras));\n }\n\n dispose(): void {\n this.bridge.dispose();\n }\n}\n\n/** Caller state retained while a Worker render is in flight. */\ninterface PendingRender {\n resolve: (result: WasmRenderResult) => void;\n reject: (error: unknown) => void;\n removeAbort?: () => void;\n}\n\n/** Owns a module Worker and routes concurrent results by request identifier. */\nclass WorkerBackend implements Backend {\n private readonly worker: Worker;\n private readonly pending = new Map<number, PendingRender>();\n private readonly ready: Promise<void>;\n private nextId = 1;\n private disposed = false;\n private failure: unknown;\n\n constructor(wasmUrl: string, fonts: readonly FontRegistration[]) {\n this.worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\", name: \"html2realpdf\" });\n this.ready = new Promise<void>((resolve, reject) => {\n const onError = (event: ErrorEvent) => {\n this.worker.removeEventListener(\"message\", onMessage);\n reject(new WasmRenderError(event.message || \"PDF Worker initialization failed\", -20));\n };\n const onMessage = (event: MessageEvent) => {\n if (event.data?.type === \"ready\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n resolve();\n } else if (event.data?.type === \"init-error\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n reject(new WasmRenderError(event.data.error, -20));\n }\n };\n this.worker.addEventListener(\"message\", onMessage);\n this.worker.addEventListener(\"error\", onError, { once: true });\n });\n this.worker.addEventListener(\"message\", (event) => this.handleMessage(event));\n this.worker.addEventListener(\"error\", (event) => {\n this.stop(new WasmRenderError(event.message || \"PDF Worker failed\", WASM_TRAP_STATUS));\n });\n this.worker.postMessage({ type: \"init\", wasmUrl, fonts });\n }\n\n async render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult> {\n if (this.disposed) throw this.failure;\n if (signal?.aborted) throw abortReason(signal);\n await this.ready;\n if (this.disposed) throw this.failure;\n if (signal?.aborted) throw abortReason(signal);\n\n const id = this.nextId++;\n return new Promise<WasmRenderResult>((resolve, reject) => {\n const pending: PendingRender = { resolve, reject };\n if (signal) {\n const onAbort = () => {\n this.pending.delete(id);\n reject(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.removeAbort = () => signal.removeEventListener(\"abort\", onAbort);\n }\n this.pending.set(id, pending);\n try {\n this.worker.postMessage({ type: \"render\", id, html, page, metadata, cssProfile, marginBoxes, pageRules, extras },\n extras?.attachments?.map((attachment) => attachment.data.buffer) ?? []);\n } catch (error) {\n this.pending.delete(id);\n pending.removeAbort?.();\n reject(error);\n }\n });\n }\n\n dispose(): void {\n this.stop(new Error(\"Renderer was disposed\"));\n }\n\n private stop(error: unknown): void {\n if (this.disposed) return;\n this.disposed = true;\n this.failure = error;\n this.worker.terminate();\n for (const pending of this.pending.values()) {\n pending.removeAbort?.();\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n private handleMessage(event: MessageEvent): void {\n const message = event.data;\n if (message?.type !== \"render-result\" && message?.type !== \"render-error\") return;\n // Even an aborted request can report a trap that invalidates other work.\n if (message.type === \"render-error\" && message.status === WASM_TRAP_STATUS) {\n this.stop(new WasmRenderError(message.error, WASM_TRAP_STATUS));\n return;\n }\n const pending = this.pending.get(message.id);\n if (!pending) return;\n this.pending.delete(message.id);\n pending.removeAbort?.();\n\n if (message.type === \"render-error\") {\n pending.reject(new WasmRenderError(message.error, -21));\n } else {\n pending.resolve({\n bytes: new Uint8Array(message.bytes),\n pageCount: message.pageCount,\n diagnostics: Array.isArray(message.diagnostics) ? message.diagnostics : [],\n });\n }\n }\n}\n\n/**\n * Reusable renderer backed by one Worker or main-thread WASM context.\n *\n * @remarks\n * Create instances with `createRenderer`. Fonts and execution mode belong to\n * the renderer lifetime; each returned `PdfDocument` has its own shorter\n * lifetime. Call `dispose` when the renderer is no longer needed. Input-limit\n * errors leave it reusable; an unexpected WASM trap disposes it permanently.\n */\nexport class Html2RealPdf {\n private disposed = false;\n\n private constructor(private readonly backend: Backend) {}\n\n /** @internal */\n static create(backend: Backend): Html2RealPdf {\n return new Html2RealPdf(backend);\n }\n\n /**\n * Snapshots browser state and renders one PDF.\n *\n * @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.\n * @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.\n * @throws {@link ResourceLoadError} when required resources cannot be materialized.\n * @throws {@link WasmRenderError} when native limits reject input or WASM fails.\n */\n async render(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n if (this.disposed) throw new Error(\"Renderer has been disposed\");\n if (options.signal?.aborted) throw abortReason(options.signal);\n const extras = preparePdfExtras(options);\n options.onProgress?.({ phase: \"snapshot\", completed: 0, total: 1 });\n const snapshotOptions: SnapshotOptions = {\n resourcePolicy: options.resourcePolicy ?? \"error\",\n cssProfile: options.cssProfile ?? \"document\",\n // Preserve the historical browser snapshot behavior unless callers\n // explicitly request print media. The web-profile example in the public\n // API opts into print rather than silently changing existing documents.\n mediaType: options.mediaType ?? \"screen\",\n unsupportedCss: options.unsupportedCss ?? (options.cssProfile === \"strict\" || options.strict ? \"error\" : \"warn\"),\n // Raster fallback is deliberately opt-in. A caller must acknowledge the\n // loss of native PDF primitives for the affected subtree explicitly.\n fallback: options.fallback ?? \"error\",\n };\n if (options.baseUrl !== undefined) snapshotOptions.baseUrl = options.baseUrl;\n if (options.resourceResolver !== undefined) snapshotOptions.resourceResolver = options.resourceResolver;\n if (options.strict !== undefined) snapshotOptions.strict = options.strict;\n if (options.enableLinks !== undefined) snapshotOptions.enableLinks = options.enableLinks;\n if (options.layoutContext !== undefined) snapshotOptions.layoutContext = options.layoutContext;\n if (options.viewport !== undefined) snapshotOptions.viewport = options.viewport;\n if (options.includeShadowDom !== undefined) snapshotOptions.includeShadowDom = options.includeShadowDom;\n if (options.canvasToSvg !== undefined) snapshotOptions.canvasToSvg = options.canvasToSvg;\n if (options.canvasFallback !== undefined) snapshotOptions.canvasFallback = options.canvasFallback;\n const snapshot = await snapshotSource(source, snapshotOptions);\n if (options.signal?.aborted) throw abortReason(options.signal);\n options.onProgress?.({ phase: \"snapshot\", completed: 1, total: 1 });\n\n options.onProgress?.({ phase: \"wasm\", completed: 0, total: 1 });\n const page = options.page !== undefined ? normalizePage(options.page) : snapshot.page ?? normalizePage();\n let rendered: WasmRenderResult;\n try {\n rendered = await this.backend.render(\n applyPageBreakRules(snapshot.html, options.pageBreak),\n page,\n options.metadata,\n options.cssProfile ?? \"document\",\n snapshot.pageMarginBoxes,\n options.page === undefined ? snapshot.pageRules : undefined,\n options.signal,\n extras,\n );\n } catch (error) {\n if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS) this.dispose();\n throw error;\n }\n options.onProgress?.({ phase: \"wasm\", completed: 1, total: 1 });\n options.onProgress?.({ phase: \"complete\", completed: 1, total: 1 });\n return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);\n }\n\n /** Terminates the owned backend and rejects future renders. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.backend.dispose();\n }\n}\n\n/**\n * Creates a reusable renderer with explicit backend and font ownership.\n *\n * @example\n * ```ts\n * const renderer = await createRenderer({ fonts });\n * try {\n * const pdf = await renderer.render(element);\n * try { pdf.download(\"report.pdf\"); } finally { pdf.dispose(); }\n * } finally {\n * renderer.dispose();\n * }\n * ```\n *\n * @throws {@link UnsupportedEnvironmentError} outside a browser or when the\n * requested execution backend is unavailable.\n */\nexport async function createRenderer(init: RendererInit = {}): Promise<Html2RealPdf> {\n if (typeof window === \"undefined\") throw new UnsupportedEnvironmentError();\n if (init.execution !== \"main\" && typeof Worker === \"undefined\") {\n throw new UnsupportedEnvironmentError(\"html2realpdf Worker execution is unavailable; use execution: 'main' as a fallback\");\n }\n const wasmUrl = new URL(init.wasmUrl ?? new URL(\"./libhtml2realpdf.wasm\", import.meta.url), window.location.href).href;\n const backend: Backend = init.execution === \"main\"\n ? new MainThreadBackend(await WasmBridge.create(wasmUrl, init.fonts ?? []))\n : new WorkerBackend(wasmUrl, init.fonts ?? []);\n return Html2RealPdf.create(backend);\n}\n\nlet defaultRenderer: Promise<Html2RealPdf> | undefined;\n\n/**\n * Renders with a lazily created package-default Worker renderer.\n *\n * @remarks\n * The default renderer is cached for the application lifetime and cannot be\n * configured with custom fonts. Use `createRenderer` when deterministic\n * backend disposal or renderer-level configuration is required. The returned\n * document must still be disposed by the caller. After an unexpected WASM trap,\n * the failed render is rejected and the next call creates a fresh renderer;\n * the failed document is never retried automatically.\n *\n * @example\n * ```ts\n * const pdf = await renderPdf(document.querySelector(\"#invoice\")!);\n * try { pdf.download(\"invoice.pdf\"); } finally { pdf.dispose(); }\n * ```\n */\nexport async function renderPdf(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n defaultRenderer ??= createRenderer().catch((error: unknown) => {\n defaultRenderer = undefined;\n throw error;\n });\n const current = defaultRenderer;\n try {\n return await (await current).render(source, options);\n } catch (error) {\n if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS && defaultRenderer === current) {\n defaultRenderer = undefined;\n }\n throw error;\n }\n}\n\nfunction applyPageBreakRules(html: string, rules?: PageBreakRules): string {\n if (!rules) return html;\n const declarations: string[] = [];\n // DOM snapshots carry computed break properties as inline declarations.\n // Option-driven rules therefore need author importance to override the\n // snapshot's inline `auto` value while still yielding to inline !important.\n appendSelectorRule(declarations, rules.before, \"break-before:page!important\");\n appendSelectorRule(declarations, rules.after, \"break-after:page!important\");\n appendSelectorRule(declarations, rules.avoid, \"break-inside:avoid!important\");\n if (rules.legacy) declarations.push(\".html2pdf__page-break{break-before:page!important}\");\n if (rules.avoidAll) declarations.push(\"body *{break-inside:avoid!important}\");\n return declarations.length === 0 ? html : `<style data-html2realpdf-pagebreak>${declarations.join(\"\")}</style>${html}`;\n}\n\nfunction appendSelectorRule(output: string[], input: string | readonly string[] | undefined, declaration: string): void {\n const selectors = typeof input === \"string\" ? [input] : input ?? [];\n const safe = selectors.map((selector) => selector.trim()).filter((selector) => selector && !/[{};]/.test(selector));\n if (safe.length > 0) output.push(`${safe.join(\",\")}{${declaration}}`);\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n"]}
|
package/dist/snapshot.js
CHANGED
|
@@ -1794,6 +1794,9 @@ function materializeComputedStyle(original, target, options, diagnostics, isSnap
|
|
|
1794
1794
|
if (!isSvgElement(original)) {
|
|
1795
1795
|
const unsupportedComputed = [
|
|
1796
1796
|
["filter", computed.getPropertyValue("filter"), "none", false],
|
|
1797
|
+
// PDF output paints source-over; a dropped blend mode must be reported
|
|
1798
|
+
// rather than silently painting a multiply/overlay layer opaquely.
|
|
1799
|
+
["mix-blend-mode", computed.getPropertyValue("mix-blend-mode"), "normal", false],
|
|
1797
1800
|
["background-image", computed.getPropertyValue("background-image"), "none", true],
|
|
1798
1801
|
["box-shadow", computed.getPropertyValue("box-shadow"), "none", true],
|
|
1799
1802
|
["text-shadow", computed.getPropertyValue("text-shadow"), "none", true],
|
|
@@ -1813,9 +1816,17 @@ function materializeComputedStyle(original, target, options, diagnostics, isSnap
|
|
|
1813
1816
|
if (isSvgElement(original)) {
|
|
1814
1817
|
properties = [...SUPPORTED_COMPUTED_PROPERTIES, ...SVG_COMPUTED_PROPERTIES];
|
|
1815
1818
|
}
|
|
1819
|
+
// Pseudo-elements share their host's geometry, so only real elements can
|
|
1820
|
+
// freeze the parent tracks a subgrid spans.
|
|
1821
|
+
const isPseudo = target.hasAttribute("data-html2realpdf-pseudo");
|
|
1822
|
+
const subgridOverrides = isPseudo ? new Map() : resolveSubgridOverrides(original, computed, view, options, diagnostics);
|
|
1816
1823
|
for (const property of properties) {
|
|
1817
1824
|
let value = computed.getPropertyValue(property);
|
|
1818
1825
|
let authoredFlowDimension = "";
|
|
1826
|
+
if (subgridOverrides.has(property)) {
|
|
1827
|
+
declarations.push(`${property}:${subgridOverrides.get(property)}`);
|
|
1828
|
+
continue;
|
|
1829
|
+
}
|
|
1819
1830
|
if (property === "display") {
|
|
1820
1831
|
value = display;
|
|
1821
1832
|
}
|
|
@@ -1866,6 +1877,92 @@ function materializeComputedStyle(original, target, options, diagnostics, isSnap
|
|
|
1866
1877
|
}
|
|
1867
1878
|
target.setAttribute("style", declarations.join(";"));
|
|
1868
1879
|
}
|
|
1880
|
+
/**
|
|
1881
|
+
* The native Grid formatter has no subgrid. A subgrid uses its parent's
|
|
1882
|
+
* tracks, so the snapshot freezes the parent tracks it spans as explicit
|
|
1883
|
+
* lengths. Columns keep the browser's used sizes; rows keep them as minimums
|
|
1884
|
+
* so native text that measures slightly taller can still grow. A subgrid
|
|
1885
|
+
* whose tracks cannot be identified is reported and falls back to `none`.
|
|
1886
|
+
*/
|
|
1887
|
+
function resolveSubgridOverrides(original, computed, view, options, diagnostics) {
|
|
1888
|
+
const overrides = new Map();
|
|
1889
|
+
for (const axis of ["columns", "rows"]) {
|
|
1890
|
+
const property = axis === "columns" ? "grid-template-columns" : "grid-template-rows";
|
|
1891
|
+
if (!/^subgrid\b/i.test(computed.getPropertyValue(property).trim()))
|
|
1892
|
+
continue;
|
|
1893
|
+
const resolved = subgridTracks(original, computed, view, axis);
|
|
1894
|
+
if (!resolved) {
|
|
1895
|
+
reportUnsupportedCss(`${property}:subgrid`, options, diagnostics);
|
|
1896
|
+
overrides.set(property, "none");
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
overrides.set(property, resolved.tracks);
|
|
1900
|
+
if (resolved.gap !== null)
|
|
1901
|
+
overrides.set(axis === "columns" ? "column-gap" : "row-gap", resolved.gap);
|
|
1902
|
+
}
|
|
1903
|
+
return overrides;
|
|
1904
|
+
}
|
|
1905
|
+
function subgridTracks(original, computed, view, axis) {
|
|
1906
|
+
const parent = original.parentElement;
|
|
1907
|
+
if (!parent)
|
|
1908
|
+
return null;
|
|
1909
|
+
const parentStyle = view.getComputedStyle(parent);
|
|
1910
|
+
if (!/grid$/.test(parentStyle.getPropertyValue("display")))
|
|
1911
|
+
return null;
|
|
1912
|
+
if (axis === "columns" && parentStyle.getPropertyValue("direction") === "rtl")
|
|
1913
|
+
return null;
|
|
1914
|
+
// Grid containers report their used track sizes; line names are skipped.
|
|
1915
|
+
const rawTracks = parentStyle.getPropertyValue(axis === "columns" ? "grid-template-columns" : "grid-template-rows");
|
|
1916
|
+
const sizes = [];
|
|
1917
|
+
for (const token of rawTracks.replace(/\[[^\]]*\]/g, " ").trim().split(/\s+/).filter(Boolean)) {
|
|
1918
|
+
const match = token.match(/^(\d+(?:\.\d+)?(?:e[+-]?\d+)?)px$/i);
|
|
1919
|
+
if (!match)
|
|
1920
|
+
return null;
|
|
1921
|
+
sizes.push(Number.parseFloat(match[1]));
|
|
1922
|
+
}
|
|
1923
|
+
if (sizes.length === 0)
|
|
1924
|
+
return null;
|
|
1925
|
+
const gapProperty = axis === "columns" ? "column-gap" : "row-gap";
|
|
1926
|
+
const parentGap = Number.parseFloat(parentStyle.getPropertyValue(gapProperty)) || 0;
|
|
1927
|
+
const start = axis === "columns" ? "left" : "top";
|
|
1928
|
+
const end = axis === "columns" ? "right" : "bottom";
|
|
1929
|
+
const parentRect = parent.getBoundingClientRect();
|
|
1930
|
+
const rect = original.getBoundingClientRect();
|
|
1931
|
+
const pixels = (style, property) => Number.parseFloat(style.getPropertyValue(property)) || 0;
|
|
1932
|
+
const contentStart = parentRect[start] + pixels(parentStyle, `border-${start}-width`) + pixels(parentStyle, `padding-${start}`);
|
|
1933
|
+
const startEdges = pixels(computed, `margin-${start}`) + pixels(computed, `border-${start}-width`) + pixels(computed, `padding-${start}`);
|
|
1934
|
+
const endEdges = pixels(computed, `margin-${end}`) + pixels(computed, `border-${end}-width`) + pixels(computed, `padding-${end}`);
|
|
1935
|
+
const areaStart = rect[start] - pixels(computed, `margin-${start}`);
|
|
1936
|
+
const areaEnd = rect[end] + pixels(computed, `margin-${end}`);
|
|
1937
|
+
// Track lines from the parent's content edge; content-distribution offsets
|
|
1938
|
+
// other than `normal`/`start` make the match fail and fall back.
|
|
1939
|
+
const trackStarts = [];
|
|
1940
|
+
let cursor = contentStart;
|
|
1941
|
+
for (const size of sizes) {
|
|
1942
|
+
trackStarts.push(cursor);
|
|
1943
|
+
cursor += size + parentGap;
|
|
1944
|
+
}
|
|
1945
|
+
const tolerance = 1;
|
|
1946
|
+
const first = trackStarts.findIndex((line) => Math.abs(line - areaStart) <= tolerance);
|
|
1947
|
+
if (first < 0)
|
|
1948
|
+
return null;
|
|
1949
|
+
let last = -1;
|
|
1950
|
+
for (let index = first; index < sizes.length; index += 1) {
|
|
1951
|
+
if (Math.abs(trackStarts[index] + sizes[index] - areaEnd) <= tolerance)
|
|
1952
|
+
last = index;
|
|
1953
|
+
}
|
|
1954
|
+
if (last < 0)
|
|
1955
|
+
return null;
|
|
1956
|
+
// The subgrid's own margin, border, and padding shrink its edge tracks.
|
|
1957
|
+
const spanned = sizes.slice(first, last + 1);
|
|
1958
|
+
spanned[0] = Math.max(spanned[0] - startEdges, 0);
|
|
1959
|
+
spanned[spanned.length - 1] = Math.max(spanned[spanned.length - 1] - endEdges, 0);
|
|
1960
|
+
const tracks = spanned
|
|
1961
|
+
.map((size) => (axis === "columns" ? `${size}px` : `minmax(${size}px, auto)`))
|
|
1962
|
+
.join(" ");
|
|
1963
|
+
const ownGap = computed.getPropertyValue(gapProperty).trim();
|
|
1964
|
+
return { tracks, gap: ownGap === "normal" ? `${parentGap}px` : null };
|
|
1965
|
+
}
|
|
1869
1966
|
function authoredInsetOverrides(element, computed, view) {
|
|
1870
1967
|
const authored = new Set();
|
|
1871
1968
|
if ("style" in element)
|
|
@@ -2294,6 +2391,8 @@ async function materializeInlineSvgs(root, options, diagnostics) {
|
|
|
2294
2391
|
try {
|
|
2295
2392
|
if (!svg.hasAttribute("xmlns"))
|
|
2296
2393
|
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
|
2394
|
+
if (options.fallback !== "rasterize-subtree")
|
|
2395
|
+
omitOuterSvgBoxEffects(svg, options, diagnostics);
|
|
2297
2396
|
const unsupportedReason = vectorSvgUnsupportedReason(svg);
|
|
2298
2397
|
const source = serializeVectorSvg(svg);
|
|
2299
2398
|
const replacement = svg.ownerDocument.createElement("img");
|
|
@@ -2313,7 +2412,7 @@ async function materializeInlineSvgs(root, options, diagnostics) {
|
|
|
2313
2412
|
if (options.fallback === "error") {
|
|
2314
2413
|
throw new UnsupportedCssError(`Inline SVG requires subtree rasterization: ${unsupportedReason}`);
|
|
2315
2414
|
}
|
|
2316
|
-
replacement.src = await rasterizeBlobToPng(new Blob([source], { type: "image/svg+xml" }));
|
|
2415
|
+
replacement.src = await rasterizeBlobToPng(new Blob([source], { type: "image/svg+xml" }), SVG_RASTER_SCALE);
|
|
2317
2416
|
diagnostics.push({
|
|
2318
2417
|
code: "CSS_SUBTREE_RASTERIZED",
|
|
2319
2418
|
severity: "warning",
|
|
@@ -2342,6 +2441,23 @@ async function materializeInlineSvgs(root, options, diagnostics) {
|
|
|
2342
2441
|
}
|
|
2343
2442
|
return replacements;
|
|
2344
2443
|
}
|
|
2444
|
+
/**
|
|
2445
|
+
* CSS `filter` and `mix-blend-mode` on the outer `<svg>` box are box effects,
|
|
2446
|
+
* like on any HTML element. Without an explicit rasterization opt-in they are
|
|
2447
|
+
* reported through the unsupported-CSS policy and omitted, so a decorative
|
|
2448
|
+
* drop-shadow keeps the SVG vector instead of failing the whole document.
|
|
2449
|
+
*/
|
|
2450
|
+
function omitOuterSvgBoxEffects(svg, options, diagnostics) {
|
|
2451
|
+
for (const property of ["filter", "mix-blend-mode"]) {
|
|
2452
|
+
const value = svg.style.getPropertyValue(property);
|
|
2453
|
+
if (!value || !svgUnsupportedPropertyIsActive(property, value))
|
|
2454
|
+
continue;
|
|
2455
|
+
reportUnsupportedCss(property, options, diagnostics);
|
|
2456
|
+
// Edit the attribute text: CSSOM removal re-serializes the declaration
|
|
2457
|
+
// block and folds `marker-*` longhands into an unsupported `marker`.
|
|
2458
|
+
svg.setAttribute("style", stripStyleProperties(svg.getAttribute("style") ?? "", [property]));
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2345
2461
|
function serializeVectorSvg(source) {
|
|
2346
2462
|
const svg = source.cloneNode(true);
|
|
2347
2463
|
for (const element of [svg, ...svg.querySelectorAll("*")]) {
|
|
@@ -2727,6 +2843,8 @@ async function materializeImages(root, options, diagnostics, alreadyMaterialized
|
|
|
2727
2843
|
try {
|
|
2728
2844
|
const url = new URL(source, options.baseUrl ?? image.ownerDocument.baseURI);
|
|
2729
2845
|
const resolved = await options.resourceResolver?.({ kind: "image", url });
|
|
2846
|
+
if (resolved === null)
|
|
2847
|
+
throw new Error("Image resource was declined by resourceResolver");
|
|
2730
2848
|
if (typeof resolved === "string" && /^data:image\/(?:jpeg|jpg|png);/i.test(resolved)) {
|
|
2731
2849
|
image.src = resolved;
|
|
2732
2850
|
continue;
|
|
@@ -2800,7 +2918,12 @@ async function materializeBackgroundImages(root, options, diagnostics) {
|
|
|
2800
2918
|
continue;
|
|
2801
2919
|
try {
|
|
2802
2920
|
const url = new URL(source, options.baseUrl ?? element.ownerDocument.baseURI);
|
|
2803
|
-
|
|
2921
|
+
// Embedded SVG follows the image path: bypass resolution, retain validation below.
|
|
2922
|
+
const resolved = /^data:image\/svg\+xml;/i.test(source)
|
|
2923
|
+
? source
|
|
2924
|
+
: await options.resourceResolver?.({ kind: "image", url });
|
|
2925
|
+
if (resolved === null)
|
|
2926
|
+
throw new Error("Image resource was declined by resourceResolver");
|
|
2804
2927
|
let dataUrl;
|
|
2805
2928
|
if (typeof resolved === "string" && /^data:image\/(?:jpeg|jpg|png);/i.test(resolved)) {
|
|
2806
2929
|
dataUrl = resolved;
|
|
@@ -2950,19 +3073,24 @@ function canvasToPng(source) {
|
|
|
2950
3073
|
context.drawImage(source, 0, 0);
|
|
2951
3074
|
return canvas.toDataURL("image/png");
|
|
2952
3075
|
}
|
|
2953
|
-
|
|
3076
|
+
/**
|
|
3077
|
+
* Device pixels per CSS pixel for rasterized SVG fallbacks. Layout keeps the
|
|
3078
|
+
* SVG's CSS size, so the extra pixels only sharpen the printed image.
|
|
3079
|
+
*/
|
|
3080
|
+
const SVG_RASTER_SCALE = 2;
|
|
3081
|
+
async function rasterizeBlobToPng(blob, scale = 1) {
|
|
2954
3082
|
const objectUrl = URL.createObjectURL(blob);
|
|
2955
3083
|
try {
|
|
2956
3084
|
const image = new Image();
|
|
2957
3085
|
image.src = objectUrl;
|
|
2958
3086
|
await image.decode();
|
|
2959
3087
|
const canvas = document.createElement("canvas");
|
|
2960
|
-
canvas.width = Math.max(image.naturalWidth, 1);
|
|
2961
|
-
canvas.height = Math.max(image.naturalHeight, 1);
|
|
3088
|
+
canvas.width = Math.max(Math.round(image.naturalWidth * scale), 1);
|
|
3089
|
+
canvas.height = Math.max(Math.round(image.naturalHeight * scale), 1);
|
|
2962
3090
|
const context = canvas.getContext("2d");
|
|
2963
3091
|
if (!context)
|
|
2964
3092
|
throw new Error("Canvas 2D context is unavailable");
|
|
2965
|
-
context.drawImage(image, 0, 0);
|
|
3093
|
+
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
2966
3094
|
return canvas.toDataURL("image/png");
|
|
2967
3095
|
}
|
|
2968
3096
|
finally {
|