@imggion/html2realpdf 0.3.2 → 0.4.0

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