@imggion/html2realpdf 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,8 +6,8 @@
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">
9
+ <a href="https://github.com/imggion/html2realpdf/releases/tag/v0.3.1">
10
+ <img src="https://img.shields.io/badge/release-0.3.1-2ea44f?style=flat-square" alt="Latest release: 0.3.1">
11
11
  </a>
12
12
  <a href="#compliance">
13
13
  <img src="https://img.shields.io/badge/PDF%2FA--3u-d32f2f?style=flat-square&amp;logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTE0IDJINXYyMGgxNFY3ek0xNCAydjVoNSIvPjx0ZXh0IHg9IjEyIiB5PSIxNyIgZmlsbD0id2hpdGUiIGZvbnQtZmFtaWx5PSJBcmlhbCxzYW5zLXNlcmlmIiBmb250LXNpemU9IjciIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QREY8L3RleHQ%2BPC9zdmc%2B" alt="PDF/A-3u">
@@ -248,6 +248,33 @@ See [PDF/A implementation and validation](https://github.com/imggion/html2realpd
248
248
  for limits and the pinned veraPDF gate. Existing calls without these options
249
249
  keep their ordinary PDF output.
250
250
 
251
+ ## Resource limits and untrusted input
252
+
253
+ The native renderer rejects documents deeper than 64 nested elements
254
+ (`DocumentTooDeep`). CSS `var()` substitution is limited to 64 KiB per value,
255
+ 8 MiB of cumulative expansion including intermediate values, and 65,536
256
+ substitutions per cascade (`CssExpansionLimitExceeded`). PNGs are limited to
257
+ 16,777,216 pixels (`ImageTooLarge`); alpha PNG decompression must fit the exact
258
+ scanline size declared by the image (`InvalidPng` otherwise). These limits
259
+ also apply to trusted documents and cannot be raised through render options.
260
+
261
+ These errors leave the renderer usable. An unexpected WASM trap instead
262
+ discards its instance: recreate an explicit `createRenderer()` instance, or
263
+ call `renderPdf()` again to create a fresh default Worker. Failed documents
264
+ are never retried automatically.
265
+
266
+ Returning `null` from `resourceResolver` denies an image, background image, or
267
+ stylesheet without fetching the original URL. `resourcePolicy: "error"`
268
+ rejects the render; `"omit"` skips the resource and returns a diagnostic.
269
+ Without a resolver, image URLs can be fetched normally. Already embedded
270
+ image data URLs bypass the resolver, and live DOM resources may already have
271
+ been loaded by the host page.
272
+
273
+ These are targeted safeguards, not a general CPU or memory quota. Keep Worker
274
+ execution for untrusted documents and apply application-level input-size and
275
+ resource allowlists; native service integrations also need process isolation
276
+ and external time/memory limits.
277
+
251
278
  ## Compliance
252
279
 
253
280
  <p align="center">
Binary file
@@ -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
- const error = new WasmRenderError(event.message || "PDF Worker failed", -22);
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 new Error("Renderer has been disposed");
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(new Error("Renderer was disposed"));
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
- const 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);
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
- return (await defaultRenderer).render(source, options);
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)
@@ -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,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,WAA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AAQ,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,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AAC;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
@@ -2727,6 +2727,8 @@ async function materializeImages(root, options, diagnostics, alreadyMaterialized
2727
2727
  try {
2728
2728
  const url = new URL(source, options.baseUrl ?? image.ownerDocument.baseURI);
2729
2729
  const resolved = await options.resourceResolver?.({ kind: "image", url });
2730
+ if (resolved === null)
2731
+ throw new Error("Image resource was declined by resourceResolver");
2730
2732
  if (typeof resolved === "string" && /^data:image\/(?:jpeg|jpg|png);/i.test(resolved)) {
2731
2733
  image.src = resolved;
2732
2734
  continue;
@@ -2800,7 +2802,12 @@ async function materializeBackgroundImages(root, options, diagnostics) {
2800
2802
  continue;
2801
2803
  try {
2802
2804
  const url = new URL(source, options.baseUrl ?? element.ownerDocument.baseURI);
2803
- const resolved = await options.resourceResolver?.({ kind: "image", url });
2805
+ // Embedded SVG follows the image path: bypass resolution, retain validation below.
2806
+ const resolved = /^data:image\/svg\+xml;/i.test(source)
2807
+ ? source
2808
+ : await options.resourceResolver?.({ kind: "image", url });
2809
+ if (resolved === null)
2810
+ throw new Error("Image resource was declined by resourceResolver");
2804
2811
  let dataUrl;
2805
2812
  if (typeof resolved === "string" && /^data:image\/(?:jpeg|jpg|png);/i.test(resolved)) {
2806
2813
  dataUrl = resolved;