@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/README.md +99 -1
- package/dist/image.d.ts +83 -0
- package/dist/image.js +169 -0
- package/dist/image.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/libhtml2realpdf.wasm +0 -0
- package/dist/node-source.d.ts +16 -0
- package/dist/node-source.js +155 -0
- package/dist/node-source.js.map +1 -0
- package/dist/node.d.ts +78 -0
- package/dist/node.js +105 -0
- package/dist/node.js.map +1 -0
- package/dist/renderer.d.ts +64 -1
- package/dist/renderer.js +164 -41
- package/dist/renderer.js.map +1 -1
- package/dist/snapshot.d.ts +6 -0
- package/dist/snapshot.js +51 -0
- package/dist/snapshot.js.map +1 -1
- package/dist/types.d.ts +42 -1
- package/dist/types.js.map +1 -1
- package/dist/wasm.d.ts +39 -9
- package/dist/wasm.js +77 -28
- package/dist/wasm.js.map +1 -1
- package/dist/worker.js +9 -0
- package/dist/worker.js.map +1 -1
- package/package.json +11 -2
- package/skills/html2realpdf/SKILL.md +74 -3
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
<img src="https://img.shields.io/badge/-TypeScript-3178c6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript">
|
|
18
18
|
</p>
|
|
19
19
|
<p>
|
|
20
|
-
Generate selectable, searchable, vector-based PDFs from HTML in the browser.<br>
|
|
20
|
+
Generate selectable, searchable, vector-based PDFs and JPEG images from HTML, in the browser or in Node.<br>
|
|
21
21
|
Written in Zig, compiled to WebAssembly, and packaged with a typed TypeScript API.
|
|
22
22
|
</p>
|
|
23
23
|
</div>
|
|
@@ -31,6 +31,8 @@
|
|
|
31
31
|
- [Vue](#vue)
|
|
32
32
|
- [Preview](#preview)
|
|
33
33
|
- [Page layouts](#page-layouts)
|
|
34
|
+
- [Images](#images)
|
|
35
|
+
- [Node and servers](#node-and-servers)
|
|
34
36
|
- [PDF/A and attachments](#pdfa-and-attachments)
|
|
35
37
|
- [Compliance](#compliance)
|
|
36
38
|
- [Benchmark](#benchmark)
|
|
@@ -211,6 +213,102 @@ const pdf = await renderPdf(postcard, {
|
|
|
211
213
|
});
|
|
212
214
|
```
|
|
213
215
|
|
|
216
|
+
## Images
|
|
217
|
+
|
|
218
|
+
`renderImage()` takes the same sources and snapshot options as `renderPdf()`
|
|
219
|
+
(elements, refs, HTML strings, `resourceResolver`, `resourcePolicy`,
|
|
220
|
+
`mediaType`, `viewport`, `canvasToSvg`, ...) and returns a JPEG. The same
|
|
221
|
+
layout and display list feed a rasterizer and JPEG encoder written in Zig,
|
|
222
|
+
so text, borders, gradients, shadows, PNG images, canvases, and inline SVG
|
|
223
|
+
charts all become pixels without a browser screenshot API.
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
import { renderImage } from "@imggion/html2realpdf";
|
|
227
|
+
|
|
228
|
+
const image = await renderImage(chartRef, {
|
|
229
|
+
width: 800, // CSS width; defaults to the element's rendered width
|
|
230
|
+
scale: 2, // device pixels per CSS pixel (0.5–4), default 1
|
|
231
|
+
quality: 0.8, // 0–1, default 0.8 = 80%, like canvas.toBlob
|
|
232
|
+
chromaSubsampling: "4:4:4", // default "4:2:0", or "4:4:4" when quality >= 0.9
|
|
233
|
+
background: "#ffffff",
|
|
234
|
+
});
|
|
235
|
+
image.width; image.height; // device pixels
|
|
236
|
+
image.download("chart.jpg");
|
|
237
|
+
image.dispose();
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
The image height follows the content, so a whole report becomes one tall
|
|
241
|
+
image and page breaks are ignored. `quality` uses the libjpeg scale shared by
|
|
242
|
+
Photoshop, Lightroom, and `canvas.toBlob`. Values outside 0–1 (for example
|
|
243
|
+
`quality: 80`) throw a `RangeError` instead of being clamped; `0` encodes at
|
|
244
|
+
the minimum quality (1%) and adds an `IMAGE_QUALITY_ADJUSTED` diagnostic.
|
|
245
|
+
Output is limited to 16,777,216 pixels and a 4096 CSS pixel width. The
|
|
246
|
+
default `cssProfile` for images is `web`.
|
|
247
|
+
|
|
248
|
+
JPEG resources inside the page are converted to PNG during the browser
|
|
249
|
+
snapshot. Link annotations have no pixel representation and are omitted.
|
|
250
|
+
`createRenderer()` instances expose the same method as `renderer.renderImage()`.
|
|
251
|
+
|
|
252
|
+
## Node and servers
|
|
253
|
+
|
|
254
|
+
In Node the same import renders HTML strings without a browser, for example
|
|
255
|
+
markup from React's `renderToStaticMarkup`:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
259
|
+
import { renderToStaticMarkup } from "react-dom/server";
|
|
260
|
+
import { createRenderer } from "@imggion/html2realpdf"; // or "@imggion/html2realpdf/node"
|
|
261
|
+
|
|
262
|
+
const renderer = await createRenderer({
|
|
263
|
+
fonts: [{ family: "Inter", data: await readFile("fonts/Inter-Regular.ttf") }],
|
|
264
|
+
});
|
|
265
|
+
try {
|
|
266
|
+
const html = renderToStaticMarkup(<ReportDocument data={data} />);
|
|
267
|
+
const image = await renderer.renderImage(html, { width: 1200, scale: 2, quality: 0.8 });
|
|
268
|
+
await writeFile("report.jpg", image.bytes);
|
|
269
|
+
|
|
270
|
+
const pdf = await renderer.render(html, { cssProfile: "web" });
|
|
271
|
+
await writeFile("report.pdf", pdf.toUint8Array());
|
|
272
|
+
} finally {
|
|
273
|
+
renderer.dispose();
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
The package `exports` select this build under the `node` condition, so
|
|
278
|
+
browser bundles never include it. Differences from the browser:
|
|
279
|
+
|
|
280
|
+
- Sources must be HTML strings; Elements and refs throw
|
|
281
|
+
`UnsupportedEnvironmentError` because they need a DOM.
|
|
282
|
+
- The WASM module is read from the packaged file (override with `wasmPath`
|
|
283
|
+
or `wasmBytes`) and renders run on the calling thread.
|
|
284
|
+
- Nothing is fetched. `<img src>`, `<link rel="stylesheet">`, and CSS
|
|
285
|
+
`url(...)` references go through `resourceResolver`, which must return CSS
|
|
286
|
+
text for stylesheets and a PNG, JPEG, or SVG data URL or `Blob` for images.
|
|
287
|
+
Relative URLs need `baseUrl`. Without a resolver, or when it returns
|
|
288
|
+
`null`, `resourcePolicy` decides: `"error"` (default) throws
|
|
289
|
+
`ResourceLoadError`, `"omit"` removes the resource with a `RESOURCE_OMITTED`
|
|
290
|
+
diagnostic.
|
|
291
|
+
- Fonts other than the built-in Noto families must be registered with
|
|
292
|
+
`createRenderer({ fonts })`.
|
|
293
|
+
- Inline `<svg>` is drawn natively at its CSS or `width`/`height`/`viewBox`
|
|
294
|
+
size, with `currentColor`, presentation attributes, inline styles, and
|
|
295
|
+
stylesheet rules (classes, `var()`) applied to its elements. SVG outside the
|
|
296
|
+
native subset (`<foreignObject>`, filters, `<use>`, ...) cannot be
|
|
297
|
+
rasterized without a browser: it throws `UnsupportedCssError` with the
|
|
298
|
+
default `fallback: "error"`, and is left blank with an
|
|
299
|
+
`INLINE_SVG_UNSUPPORTED` diagnostic otherwise. Malformed SVG follows
|
|
300
|
+
`resourcePolicy` (`INLINE_SVG_INVALID`). SVG text never becomes page text.
|
|
301
|
+
- JPEG `<img>` sources are embedded in PDFs but not decoded by the image
|
|
302
|
+
rasterizer (`IMAGE_FORMAT_NOT_RASTERIZED`); use PNG for `renderImage`.
|
|
303
|
+
- Browser-only options (`viewport`, `mediaType`, `includeShadowDom`,
|
|
304
|
+
`canvasToSvg`, `enableLinks: false`) have no effect. `toBlob()` works,
|
|
305
|
+
`download()` and `preview()` need a browser.
|
|
306
|
+
- HTML strings are styled by the core cascade. It matches type, class, id,
|
|
307
|
+
universal, descendant, and child selectors; rules using pseudo-classes or
|
|
308
|
+
attribute selectors are skipped, and pseudo-element selectors are dropped
|
|
309
|
+
from their selector list. `line-height` does not inherit yet and `normal`
|
|
310
|
+
is 1.2em, so set it on the elements where it matters.
|
|
311
|
+
|
|
214
312
|
## PDF/A and attachments
|
|
215
313
|
|
|
216
314
|
Opt into PDF/A-3u independently of the CSS profile:
|
package/dist/image.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Raster image option normalization and the owned `RenderedImage` result.
|
|
3
|
+
*
|
|
4
|
+
* @packageDocumentation
|
|
5
|
+
*/
|
|
6
|
+
import type { ChromaSubsampling, Diagnostic, ImageFormat, ImageRenderOptions } from "./types.js";
|
|
7
|
+
/** Default `quality`, matching the common `canvas.toBlob(cb, "image/jpeg", 0.8)` choice. */
|
|
8
|
+
export declare const DEFAULT_IMAGE_QUALITY = 0.8;
|
|
9
|
+
/** Default canvas width in CSS pixels for HTML strings without a viewport. */
|
|
10
|
+
export declare const DEFAULT_IMAGE_WIDTH = 800;
|
|
11
|
+
/** Image options in the units of the WASM JSON contract. */
|
|
12
|
+
export interface NormalizedImageOptions {
|
|
13
|
+
format: ImageFormat;
|
|
14
|
+
widthCss: number;
|
|
15
|
+
scale: number;
|
|
16
|
+
/** Integer encoder quality from 1 to 100. */
|
|
17
|
+
quality: number;
|
|
18
|
+
chromaSubsampling: ChromaSubsampling;
|
|
19
|
+
background: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Validates public image options and converts `quality` from 0...1 to the
|
|
23
|
+
* encoder's 1...100 integer.
|
|
24
|
+
*
|
|
25
|
+
* @remarks
|
|
26
|
+
* Out-of-range values throw instead of clamping, so `quality: 80` written as a
|
|
27
|
+
* percentage fails loudly rather than encoding at maximum quality. Only `0`
|
|
28
|
+
* and tiny positive values are raised to the minimum valid JPEG quality, and
|
|
29
|
+
* that adjustment is reported as a diagnostic.
|
|
30
|
+
*
|
|
31
|
+
* @throws {RangeError} for invalid format, quality, scale, width, or subsampling.
|
|
32
|
+
*/
|
|
33
|
+
export declare function normalizeImageOptions(options: ImageRenderOptions, defaultWidth: number): {
|
|
34
|
+
options: NormalizedImageOptions;
|
|
35
|
+
diagnostics: Diagnostic[];
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Encoded image returned by `renderImage`.
|
|
39
|
+
*
|
|
40
|
+
* @remarks
|
|
41
|
+
* Byte exports are defensive copies. `dispose` revokes object URLs created
|
|
42
|
+
* through this instance and invalidates later exports. Instances are
|
|
43
|
+
* renderer-owned results and cannot be constructed directly.
|
|
44
|
+
*/
|
|
45
|
+
export declare class RenderedImage {
|
|
46
|
+
private readonly data;
|
|
47
|
+
/** Width in device pixels (CSS width multiplied by `scale`). */
|
|
48
|
+
readonly width: number;
|
|
49
|
+
/** Height in device pixels, derived from the laid-out content. */
|
|
50
|
+
readonly height: number;
|
|
51
|
+
/** Diagnostics retained from option normalization, snapshotting, and native rendering. */
|
|
52
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
53
|
+
/** Encoded format. */
|
|
54
|
+
readonly format: ImageFormat;
|
|
55
|
+
/** MIME type of `bytes`. */
|
|
56
|
+
readonly mimeType = "image/jpeg";
|
|
57
|
+
private readonly objectUrls;
|
|
58
|
+
private disposed;
|
|
59
|
+
private constructor();
|
|
60
|
+
/** A defensive copy of the encoded bytes. */
|
|
61
|
+
get bytes(): Uint8Array;
|
|
62
|
+
/** Returns a defensive copy of the encoded bytes. */
|
|
63
|
+
toUint8Array(): Uint8Array;
|
|
64
|
+
/** Returns a standalone copy suitable for storage or transfer APIs. */
|
|
65
|
+
toArrayBuffer(): ArrayBuffer;
|
|
66
|
+
/** Returns a new Blob typed with `mimeType`. */
|
|
67
|
+
toBlob(): Blob;
|
|
68
|
+
/** Returns a `data:` URL, convenient for small images and `<img src>`. */
|
|
69
|
+
toDataURL(): string;
|
|
70
|
+
/**
|
|
71
|
+
* Creates an object URL tracked by this image.
|
|
72
|
+
*
|
|
73
|
+
* @remarks Revoke long-lived URLs explicitly or let `dispose` revoke them.
|
|
74
|
+
*/
|
|
75
|
+
createObjectURL(): string;
|
|
76
|
+
/** Revokes an object URL previously created by this image. */
|
|
77
|
+
revokeObjectURL(url: string): void;
|
|
78
|
+
/** Starts a browser download and revokes its temporary object URL. */
|
|
79
|
+
download(filename?: string): void;
|
|
80
|
+
/** Revokes object URLs and invalidates byte exports. */
|
|
81
|
+
dispose(): void;
|
|
82
|
+
private assertActive;
|
|
83
|
+
}
|
package/dist/image.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Raster image option normalization and the owned `RenderedImage` result.
|
|
3
|
+
*
|
|
4
|
+
* @packageDocumentation
|
|
5
|
+
*/
|
|
6
|
+
/** Default `quality`, matching the common `canvas.toBlob(cb, "image/jpeg", 0.8)` choice. */
|
|
7
|
+
export const DEFAULT_IMAGE_QUALITY = 0.8;
|
|
8
|
+
/** Default canvas width in CSS pixels for HTML strings without a viewport. */
|
|
9
|
+
export const DEFAULT_IMAGE_WIDTH = 800;
|
|
10
|
+
const MIN_SCALE = 0.5;
|
|
11
|
+
const MAX_SCALE = 4;
|
|
12
|
+
const MAX_WIDTH = 4096;
|
|
13
|
+
/**
|
|
14
|
+
* Validates public image options and converts `quality` from 0...1 to the
|
|
15
|
+
* encoder's 1...100 integer.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* Out-of-range values throw instead of clamping, so `quality: 80` written as a
|
|
19
|
+
* percentage fails loudly rather than encoding at maximum quality. Only `0`
|
|
20
|
+
* and tiny positive values are raised to the minimum valid JPEG quality, and
|
|
21
|
+
* that adjustment is reported as a diagnostic.
|
|
22
|
+
*
|
|
23
|
+
* @throws {RangeError} for invalid format, quality, scale, width, or subsampling.
|
|
24
|
+
*/
|
|
25
|
+
export function normalizeImageOptions(options, defaultWidth) {
|
|
26
|
+
const diagnostics = [];
|
|
27
|
+
const format = options.format ?? "jpeg";
|
|
28
|
+
if (format !== "jpeg")
|
|
29
|
+
throw new RangeError(`Unsupported image format ${JSON.stringify(format)}; only "jpeg" is available`);
|
|
30
|
+
const rawQuality = options.quality ?? DEFAULT_IMAGE_QUALITY;
|
|
31
|
+
if (typeof rawQuality !== "number" || Number.isNaN(rawQuality) || rawQuality < 0 || rawQuality > 1) {
|
|
32
|
+
throw new RangeError(`Image quality must be a number from 0 to 1 (0.8 means 80%); received ${String(rawQuality)}`);
|
|
33
|
+
}
|
|
34
|
+
const percent = Math.round(rawQuality * 100);
|
|
35
|
+
const quality = Math.min(Math.max(percent, 1), 100);
|
|
36
|
+
if (quality !== percent) {
|
|
37
|
+
diagnostics.push({
|
|
38
|
+
code: "IMAGE_QUALITY_ADJUSTED",
|
|
39
|
+
severity: "warning",
|
|
40
|
+
message: `JPEG quality ${rawQuality} is below the minimum encoder quality; encoded at 0.01 (1%)`,
|
|
41
|
+
phase: "raster",
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const scale = options.scale ?? 1;
|
|
45
|
+
if (typeof scale !== "number" || !Number.isFinite(scale) || scale < MIN_SCALE || scale > MAX_SCALE) {
|
|
46
|
+
throw new RangeError(`Image scale must be between ${MIN_SCALE} and ${MAX_SCALE}; received ${String(scale)}`);
|
|
47
|
+
}
|
|
48
|
+
const widthCss = options.width ?? defaultWidth;
|
|
49
|
+
if (typeof widthCss !== "number" || !Number.isFinite(widthCss) || widthCss < 1 || widthCss > MAX_WIDTH) {
|
|
50
|
+
throw new RangeError(`Image width must be between 1 and ${MAX_WIDTH} CSS pixels; received ${String(widthCss)}`);
|
|
51
|
+
}
|
|
52
|
+
const chromaSubsampling = options.chromaSubsampling ?? (quality >= 90 ? "4:4:4" : "4:2:0");
|
|
53
|
+
if (chromaSubsampling !== "4:2:0" && chromaSubsampling !== "4:4:4") {
|
|
54
|
+
throw new RangeError(`chromaSubsampling must be "4:2:0" or "4:4:4"; received ${String(chromaSubsampling)}`);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
options: {
|
|
58
|
+
format,
|
|
59
|
+
widthCss,
|
|
60
|
+
scale,
|
|
61
|
+
quality,
|
|
62
|
+
chromaSubsampling,
|
|
63
|
+
background: options.background ?? "#ffffff",
|
|
64
|
+
},
|
|
65
|
+
diagnostics,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Encoded image returned by `renderImage`.
|
|
70
|
+
*
|
|
71
|
+
* @remarks
|
|
72
|
+
* Byte exports are defensive copies. `dispose` revokes object URLs created
|
|
73
|
+
* through this instance and invalidates later exports. Instances are
|
|
74
|
+
* renderer-owned results and cannot be constructed directly.
|
|
75
|
+
*/
|
|
76
|
+
export class RenderedImage {
|
|
77
|
+
data;
|
|
78
|
+
width;
|
|
79
|
+
height;
|
|
80
|
+
/** Diagnostics retained from option normalization, snapshotting, and native rendering. */
|
|
81
|
+
diagnostics;
|
|
82
|
+
/** Encoded format. */
|
|
83
|
+
format = "jpeg";
|
|
84
|
+
/** MIME type of `bytes`. */
|
|
85
|
+
mimeType = "image/jpeg";
|
|
86
|
+
objectUrls = new Set();
|
|
87
|
+
disposed = false;
|
|
88
|
+
constructor(data,
|
|
89
|
+
/** Width in device pixels (CSS width multiplied by `scale`). */
|
|
90
|
+
width,
|
|
91
|
+
/** Height in device pixels, derived from the laid-out content. */
|
|
92
|
+
height, diagnostics) {
|
|
93
|
+
this.data = data;
|
|
94
|
+
this.width = width;
|
|
95
|
+
this.height = height;
|
|
96
|
+
this.diagnostics = Object.freeze([...diagnostics]);
|
|
97
|
+
}
|
|
98
|
+
/** @internal */
|
|
99
|
+
static create(data, width, height, diagnostics = []) {
|
|
100
|
+
return new RenderedImage(data, width, height, diagnostics);
|
|
101
|
+
}
|
|
102
|
+
/** A defensive copy of the encoded bytes. */
|
|
103
|
+
get bytes() {
|
|
104
|
+
return this.toUint8Array();
|
|
105
|
+
}
|
|
106
|
+
/** Returns a defensive copy of the encoded bytes. */
|
|
107
|
+
toUint8Array() {
|
|
108
|
+
this.assertActive();
|
|
109
|
+
return this.data.slice();
|
|
110
|
+
}
|
|
111
|
+
/** Returns a standalone copy suitable for storage or transfer APIs. */
|
|
112
|
+
toArrayBuffer() {
|
|
113
|
+
return this.toUint8Array().buffer;
|
|
114
|
+
}
|
|
115
|
+
/** Returns a new Blob typed with `mimeType`. */
|
|
116
|
+
toBlob() {
|
|
117
|
+
return new Blob([this.toArrayBuffer()], { type: this.mimeType });
|
|
118
|
+
}
|
|
119
|
+
/** Returns a `data:` URL, convenient for small images and `<img src>`. */
|
|
120
|
+
toDataURL() {
|
|
121
|
+
const bytes = this.toUint8Array();
|
|
122
|
+
let binary = "";
|
|
123
|
+
for (let offset = 0; offset < bytes.length; offset += 16_384) {
|
|
124
|
+
binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 16_384, bytes.length)));
|
|
125
|
+
}
|
|
126
|
+
return `data:${this.mimeType};base64,${btoa(binary)}`;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Creates an object URL tracked by this image.
|
|
130
|
+
*
|
|
131
|
+
* @remarks Revoke long-lived URLs explicitly or let `dispose` revoke them.
|
|
132
|
+
*/
|
|
133
|
+
createObjectURL() {
|
|
134
|
+
const url = URL.createObjectURL(this.toBlob());
|
|
135
|
+
this.objectUrls.add(url);
|
|
136
|
+
return url;
|
|
137
|
+
}
|
|
138
|
+
/** Revokes an object URL previously created by this image. */
|
|
139
|
+
revokeObjectURL(url) {
|
|
140
|
+
if (!this.objectUrls.delete(url))
|
|
141
|
+
return;
|
|
142
|
+
URL.revokeObjectURL(url);
|
|
143
|
+
}
|
|
144
|
+
/** Starts a browser download and revokes its temporary object URL. */
|
|
145
|
+
download(filename = "image.jpg") {
|
|
146
|
+
const url = this.createObjectURL();
|
|
147
|
+
const anchor = document.createElement("a");
|
|
148
|
+
anchor.href = url;
|
|
149
|
+
anchor.download = filename;
|
|
150
|
+
document.body.append(anchor);
|
|
151
|
+
anchor.click();
|
|
152
|
+
anchor.remove();
|
|
153
|
+
queueMicrotask(() => this.revokeObjectURL(url));
|
|
154
|
+
}
|
|
155
|
+
/** Revokes object URLs and invalidates byte exports. */
|
|
156
|
+
dispose() {
|
|
157
|
+
if (this.disposed)
|
|
158
|
+
return;
|
|
159
|
+
for (const url of this.objectUrls)
|
|
160
|
+
URL.revokeObjectURL(url);
|
|
161
|
+
this.objectUrls.clear();
|
|
162
|
+
this.disposed = true;
|
|
163
|
+
}
|
|
164
|
+
assertActive() {
|
|
165
|
+
if (this.disposed)
|
|
166
|
+
throw new Error("RenderedImage has been disposed");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
//# sourceMappingURL=image.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image.js","sourceRoot":"","sources":["../src/image.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,4FAA4F;AAC5F,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AACzC,8EAA8E;AAC9E,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,SAAS,GAAG,IAAI,CAAC;AAavB;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,qBAAqB,CACnC,OAA2B,EAC3B,YAAoB;IAEpB,MAAM,WAAW,GAAiB,EAAE,CAAC;IACrC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC;IACxC,IAAI,MAAM,KAAK,MAAM;QAAE,MAAM,IAAI,UAAU,CAAC,4BAA4B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,4BAA4B,CAAC,CAAC;IAE5H,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,IAAI,qBAAqB,CAAC;IAC5D,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;QACnG,MAAM,IAAI,UAAU,CAAC,wEAAwE,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;IACrH,CAAC;IACD,MAAM,OAAO,GAAG,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MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QAC3C,MAAM,CAAC,IAAI,GAAG,GAAG,CAAC;QAClB,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC3B,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC7B,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,cAAc,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;IAClD,CAAC;IAED,wDAAwD;IACxD,OAAO;QACL,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO;QAC1B,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU;YAAE,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;QAC5D,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvB,CAAC;IAEO,YAAY;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACxE,CAAC;CACF","sourcesContent":["/**\n * Raster image option normalization and the owned `RenderedImage` result.\n *\n * @packageDocumentation\n */\n\nimport type { ChromaSubsampling, Diagnostic, ImageFormat, ImageRenderOptions } from \"./types.js\";\n\n/** Default `quality`, matching the common `canvas.toBlob(cb, \"image/jpeg\", 0.8)` choice. */\nexport const DEFAULT_IMAGE_QUALITY = 0.8;\n/** Default canvas width in CSS pixels for HTML strings without a viewport. */\nexport const DEFAULT_IMAGE_WIDTH = 800;\nconst MIN_SCALE = 0.5;\nconst MAX_SCALE = 4;\nconst MAX_WIDTH = 4096;\n\n/** Image options in the units of the WASM JSON contract. */\nexport interface NormalizedImageOptions {\n format: ImageFormat;\n widthCss: number;\n scale: number;\n /** Integer encoder quality from 1 to 100. */\n quality: number;\n chromaSubsampling: ChromaSubsampling;\n background: string;\n}\n\n/**\n * Validates public image options and converts `quality` from 0...1 to the\n * encoder's 1...100 integer.\n *\n * @remarks\n * Out-of-range values throw instead of clamping, so `quality: 80` written as a\n * percentage fails loudly rather than encoding at maximum quality. Only `0`\n * and tiny positive values are raised to the minimum valid JPEG quality, and\n * that adjustment is reported as a diagnostic.\n *\n * @throws {RangeError} for invalid format, quality, scale, width, or subsampling.\n */\nexport function normalizeImageOptions(\n options: ImageRenderOptions,\n defaultWidth: number,\n): { options: NormalizedImageOptions; diagnostics: Diagnostic[] } {\n const diagnostics: Diagnostic[] = [];\n const format = options.format ?? \"jpeg\";\n if (format !== \"jpeg\") throw new RangeError(`Unsupported image format ${JSON.stringify(format)}; only \"jpeg\" is available`);\n\n const rawQuality = options.quality ?? DEFAULT_IMAGE_QUALITY;\n if (typeof rawQuality !== \"number\" || Number.isNaN(rawQuality) || rawQuality < 0 || rawQuality > 1) {\n throw new RangeError(`Image quality must be a number from 0 to 1 (0.8 means 80%); received ${String(rawQuality)}`);\n }\n const percent = Math.round(rawQuality * 100);\n const quality = Math.min(Math.max(percent, 1), 100);\n if (quality !== percent) {\n diagnostics.push({\n code: \"IMAGE_QUALITY_ADJUSTED\",\n severity: \"warning\",\n message: `JPEG quality ${rawQuality} is below the minimum encoder quality; encoded at 0.01 (1%)`,\n phase: \"raster\",\n });\n }\n\n const scale = options.scale ?? 1;\n if (typeof scale !== \"number\" || !Number.isFinite(scale) || scale < MIN_SCALE || scale > MAX_SCALE) {\n throw new RangeError(`Image scale must be between ${MIN_SCALE} and ${MAX_SCALE}; received ${String(scale)}`);\n }\n\n const widthCss = options.width ?? defaultWidth;\n if (typeof widthCss !== \"number\" || !Number.isFinite(widthCss) || widthCss < 1 || widthCss > MAX_WIDTH) {\n throw new RangeError(`Image width must be between 1 and ${MAX_WIDTH} CSS pixels; received ${String(widthCss)}`);\n }\n\n const chromaSubsampling = options.chromaSubsampling ?? (quality >= 90 ? \"4:4:4\" : \"4:2:0\");\n if (chromaSubsampling !== \"4:2:0\" && chromaSubsampling !== \"4:4:4\") {\n throw new RangeError(`chromaSubsampling must be \"4:2:0\" or \"4:4:4\"; received ${String(chromaSubsampling)}`);\n }\n\n return {\n options: {\n format,\n widthCss,\n scale,\n quality,\n chromaSubsampling,\n background: options.background ?? \"#ffffff\",\n },\n diagnostics,\n };\n}\n\n/**\n * Encoded image returned by `renderImage`.\n *\n * @remarks\n * Byte exports are defensive copies. `dispose` revokes object URLs created\n * through this instance and invalidates later exports. Instances are\n * renderer-owned results and cannot be constructed directly.\n */\nexport class RenderedImage {\n /** Diagnostics retained from option normalization, snapshotting, and native rendering. */\n readonly diagnostics: readonly Diagnostic[];\n /** Encoded format. */\n readonly format: ImageFormat = \"jpeg\";\n /** MIME type of `bytes`. */\n readonly mimeType = \"image/jpeg\";\n private readonly objectUrls = new Set<string>();\n private disposed = false;\n\n private constructor(\n private readonly data: Uint8Array,\n /** Width in device pixels (CSS width multiplied by `scale`). */\n readonly width: number,\n /** Height in device pixels, derived from the laid-out content. */\n readonly height: number,\n diagnostics: readonly Diagnostic[],\n ) {\n this.diagnostics = Object.freeze([...diagnostics]);\n }\n\n /** @internal */\n static create(data: Uint8Array, width: number, height: number, diagnostics: readonly Diagnostic[] = []): RenderedImage {\n return new RenderedImage(data, width, height, diagnostics);\n }\n\n /** A defensive copy of the encoded bytes. */\n get bytes(): Uint8Array {\n return this.toUint8Array();\n }\n\n /** Returns a defensive copy of the encoded bytes. */\n toUint8Array(): Uint8Array {\n this.assertActive();\n return this.data.slice();\n }\n\n /** Returns a standalone copy suitable for storage or transfer APIs. */\n toArrayBuffer(): ArrayBuffer {\n return this.toUint8Array().buffer as ArrayBuffer;\n }\n\n /** Returns a new Blob typed with `mimeType`. */\n toBlob(): Blob {\n return new Blob([this.toArrayBuffer()], { type: this.mimeType });\n }\n\n /** Returns a `data:` URL, convenient for small images and `<img src>`. */\n toDataURL(): string {\n const bytes = this.toUint8Array();\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 16_384) {\n binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 16_384, bytes.length)));\n }\n return `data:${this.mimeType};base64,${btoa(binary)}`;\n }\n\n /**\n * Creates an object URL tracked by this image.\n *\n * @remarks Revoke long-lived URLs explicitly or let `dispose` revoke them.\n */\n createObjectURL(): string {\n const url = URL.createObjectURL(this.toBlob());\n this.objectUrls.add(url);\n return url;\n }\n\n /** Revokes an object URL previously created by this image. */\n revokeObjectURL(url: string): void {\n if (!this.objectUrls.delete(url)) return;\n URL.revokeObjectURL(url);\n }\n\n /** Starts a browser download and revokes its temporary object URL. */\n download(filename = \"image.jpg\"): void {\n const url = this.createObjectURL();\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = filename;\n document.body.append(anchor);\n anchor.click();\n anchor.remove();\n queueMicrotask(() => this.revokeObjectURL(url));\n }\n\n /** Revokes object URLs and invalidates byte exports. */\n dispose(): void {\n if (this.disposed) return;\n for (const url of this.objectUrls) URL.revokeObjectURL(url);\n this.objectUrls.clear();\n this.disposed = true;\n }\n\n private assertActive(): void {\n if (this.disposed) throw new Error(\"RenderedImage has been disposed\");\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Browser-first HTML-to-PDF rendering with selectable text,
|
|
3
|
-
* typed configuration, and an html2pdf.js compatibility layer.
|
|
2
|
+
* Browser-first HTML-to-PDF and HTML-to-image rendering with selectable text,
|
|
3
|
+
* native vectors, typed configuration, and an html2pdf.js compatibility layer.
|
|
4
4
|
*
|
|
5
5
|
* @packageDocumentation
|
|
6
6
|
*/
|
|
@@ -10,5 +10,6 @@ export { CompatWorker } from "./compat.js";
|
|
|
10
10
|
export * from "./errors.js";
|
|
11
11
|
export { PdfDocument } from "./pdf-document.js";
|
|
12
12
|
export { PdfPreview, type PdfPreviewOptions, type PdfPreviewTheme } from "./preview.js";
|
|
13
|
-
export {
|
|
13
|
+
export { RenderedImage } from "./image.js";
|
|
14
|
+
export { createRenderer, Html2RealPdf, renderImage, renderPdf } from "./renderer.js";
|
|
14
15
|
export type * from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Browser-first HTML-to-PDF rendering with selectable text,
|
|
3
|
-
* typed configuration, and an html2pdf.js compatibility layer.
|
|
2
|
+
* Browser-first HTML-to-PDF and HTML-to-image rendering with selectable text,
|
|
3
|
+
* native vectors, typed configuration, and an html2pdf.js compatibility layer.
|
|
4
4
|
*
|
|
5
5
|
* @packageDocumentation
|
|
6
6
|
*/
|
|
@@ -10,5 +10,6 @@ export { CompatWorker } from "./compat.js";
|
|
|
10
10
|
export * from "./errors.js";
|
|
11
11
|
export { PdfDocument } from "./pdf-document.js";
|
|
12
12
|
export { PdfPreview } from "./preview.js";
|
|
13
|
-
export {
|
|
13
|
+
export { RenderedImage } from "./image.js";
|
|
14
|
+
export { createRenderer, Html2RealPdf, renderImage, renderPdf } from "./renderer.js";
|
|
14
15
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,QAAQ,MAAM,aAAa,CAAC;AAEnC,eAAe,QAAQ,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAgD,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC","sourcesContent":["/**\n * Browser-first HTML-to-PDF rendering with selectable text
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,QAAQ,MAAM,aAAa,CAAC;AAEnC,eAAe,QAAQ,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAgD,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC","sourcesContent":["/**\n * Browser-first HTML-to-PDF and HTML-to-image rendering with selectable text,\n * native vectors, typed configuration, and an html2pdf.js compatibility layer.\n *\n * @packageDocumentation\n */\nimport html2pdf from \"./compat.js\";\n\nexport default html2pdf;\nexport { CompatWorker } from \"./compat.js\";\nexport * from \"./errors.js\";\nexport { PdfDocument } from \"./pdf-document.js\";\nexport { PdfPreview, type PdfPreviewOptions, type PdfPreviewTheme } from \"./preview.js\";\nexport { RenderedImage } from \"./image.js\";\nexport { createRenderer, Html2RealPdf, renderImage, renderPdf } from \"./renderer.js\";\nexport type * from \"./types.js\";\n"]}
|
|
Binary file
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML-string preparation for hosts without a DOM (Node).
|
|
3
|
+
*
|
|
4
|
+
* The browser snapshot embeds every resource and replaces inline SVG before
|
|
5
|
+
* the core runs. Without a DOM the core does the structural work itself
|
|
6
|
+
* (inline `<svg>` becomes a replaced element natively); this module only
|
|
7
|
+
* routes external resources through `resourceResolver`, using byte ranges the
|
|
8
|
+
* core tokenizer reports, and maps core diagnostics onto the caller's
|
|
9
|
+
* policies after the render. Nothing is ever fetched implicitly.
|
|
10
|
+
*
|
|
11
|
+
* @packageDocumentation
|
|
12
|
+
*/
|
|
13
|
+
import type { SourcePreparation } from "./renderer.js";
|
|
14
|
+
import type { WasmBridge } from "./wasm.js";
|
|
15
|
+
/** Source preparation for one Node renderer and its WASM bridge. */
|
|
16
|
+
export declare function nodeSourcePreparation(bridge: WasmBridge): SourcePreparation;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML-string preparation for hosts without a DOM (Node).
|
|
3
|
+
*
|
|
4
|
+
* The browser snapshot embeds every resource and replaces inline SVG before
|
|
5
|
+
* the core runs. Without a DOM the core does the structural work itself
|
|
6
|
+
* (inline `<svg>` becomes a replaced element natively); this module only
|
|
7
|
+
* routes external resources through `resourceResolver`, using byte ranges the
|
|
8
|
+
* core tokenizer reports, and maps core diagnostics onto the caller's
|
|
9
|
+
* policies after the render. Nothing is ever fetched implicitly.
|
|
10
|
+
*
|
|
11
|
+
* @packageDocumentation
|
|
12
|
+
*/
|
|
13
|
+
import { ResourceLoadError, UnsupportedCssError, UnsupportedEnvironmentError } from "./errors.js";
|
|
14
|
+
const EMBEDDED_IMAGE = /^data:image\/(?:png|jpeg|jpg|svg\+xml);base64,/i;
|
|
15
|
+
const SVG_DATA_URL = /^data:image\/svg\+xml(?:;charset=[^;,]+)?,/i;
|
|
16
|
+
const EMBEDDABLE_BLOB_TYPES = new Set(["image/png", "image/jpeg", "image/svg+xml"]);
|
|
17
|
+
/** Source preparation for one Node renderer and its WASM bridge. */
|
|
18
|
+
export function nodeSourcePreparation(bridge) {
|
|
19
|
+
return {
|
|
20
|
+
prepare: (source, options) => prepareHtmlString(bridge, source, options),
|
|
21
|
+
check: enforceNodePolicies,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
async function prepareHtmlString(bridge, source, options) {
|
|
25
|
+
if (typeof source !== "string") {
|
|
26
|
+
throw new UnsupportedEnvironmentError("Element and ref sources need a browser DOM; pass an HTML string when rendering in Node");
|
|
27
|
+
}
|
|
28
|
+
const diagnostics = [];
|
|
29
|
+
const references = bridge.resourceReferences(source);
|
|
30
|
+
if (references.length === 0)
|
|
31
|
+
return { html: source, diagnostics };
|
|
32
|
+
const edits = [];
|
|
33
|
+
for (const reference of references) {
|
|
34
|
+
let replacement;
|
|
35
|
+
try {
|
|
36
|
+
replacement = await resolveReference(reference, options);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (options.resourcePolicy === "error")
|
|
40
|
+
throw new ResourceLoadError(reference.url, { cause: error });
|
|
41
|
+
// Backgrounds stay in place: the core omits non-embedded URLs and
|
|
42
|
+
// reports them itself. Elements are removed like the browser snapshot.
|
|
43
|
+
if (reference.kind === "background" || reference.tagStart === undefined || reference.tagEnd === undefined)
|
|
44
|
+
continue;
|
|
45
|
+
addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: "" });
|
|
46
|
+
diagnostics.push({
|
|
47
|
+
code: "RESOURCE_OMITTED",
|
|
48
|
+
severity: "warning",
|
|
49
|
+
message: `${reference.kind === "stylesheet" ? "Stylesheet" : "Image"} resource was omitted: ${reference.url}`,
|
|
50
|
+
phase: "snapshot",
|
|
51
|
+
});
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (reference.kind === "stylesheet" && reference.tagStart !== undefined && reference.tagEnd !== undefined) {
|
|
55
|
+
addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: replacement });
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
addEdit(edits, { start: reference.start, end: reference.end, text: replacement });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { html: applyEdits(source, edits), diagnostics };
|
|
62
|
+
}
|
|
63
|
+
/** Returns the embedded replacement text, or throws when the resource is unavailable. */
|
|
64
|
+
async function resolveReference(reference, options) {
|
|
65
|
+
let url;
|
|
66
|
+
try {
|
|
67
|
+
url = options.baseUrl === undefined ? new URL(reference.url) : new URL(reference.url, options.baseUrl);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
throw new Error(`Relative resource URL "${reference.url}" needs baseUrl outside the browser`, { cause: error });
|
|
71
|
+
}
|
|
72
|
+
const resolver = options.resourceResolver;
|
|
73
|
+
if (!resolver)
|
|
74
|
+
throw new Error("Resources are never fetched outside the browser; provide resourceResolver");
|
|
75
|
+
const kind = reference.kind === "stylesheet" ? "stylesheet" : "image";
|
|
76
|
+
const resolved = await resolver({ kind, url });
|
|
77
|
+
if (resolved === null || resolved === undefined)
|
|
78
|
+
throw new Error(`The ${kind} resource was declined by resourceResolver`);
|
|
79
|
+
if (kind === "stylesheet") {
|
|
80
|
+
const css = typeof resolved === "string" ? resolved : await resolved.text();
|
|
81
|
+
// Raw-text content cannot contain its own end tag.
|
|
82
|
+
return `<style data-html2realpdf-resolved-from="${escapeAttribute(url.href)}">${css.replace(/<\/style/gi, "<\\/style")}</style>`;
|
|
83
|
+
}
|
|
84
|
+
if (typeof resolved === "string") {
|
|
85
|
+
if (EMBEDDED_IMAGE.test(resolved))
|
|
86
|
+
return resolved;
|
|
87
|
+
if (SVG_DATA_URL.test(resolved)) {
|
|
88
|
+
const payload = decodeURIComponent(resolved.slice(resolved.indexOf(",") + 1));
|
|
89
|
+
return `data:image/svg+xml;base64,${base64(new TextEncoder().encode(payload))}`;
|
|
90
|
+
}
|
|
91
|
+
throw new Error("Outside the browser an image resolver must return a PNG, JPEG, or SVG data URL or Blob; replacement URLs are not fetched");
|
|
92
|
+
}
|
|
93
|
+
const type = resolved.type.toLowerCase();
|
|
94
|
+
if (!EMBEDDABLE_BLOB_TYPES.has(type)) {
|
|
95
|
+
throw new Error(`Image type "${resolved.type || "unknown"}" cannot be embedded outside the browser; use PNG, JPEG, or SVG`);
|
|
96
|
+
}
|
|
97
|
+
return `data:${type};base64,${base64(new Uint8Array(await resolved.arrayBuffer()))}`;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Maps core diagnostics onto the browser-equivalent policies. The browser
|
|
101
|
+
* rasterizes unsupported SVG only after `fallback: "rasterize-subtree"`;
|
|
102
|
+
* Node cannot rasterize, so it keeps the omission and its diagnostic.
|
|
103
|
+
*/
|
|
104
|
+
function enforceNodePolicies(diagnostics, options) {
|
|
105
|
+
const has = (code) => diagnostics.some((diagnostic) => diagnostic.code === code);
|
|
106
|
+
if (options.fallback === "error" && has("INLINE_SVG_UNSUPPORTED")) {
|
|
107
|
+
throw new UnsupportedCssError("Inline SVG uses features outside the native vector subset and cannot be rasterized outside the browser");
|
|
108
|
+
}
|
|
109
|
+
if (options.unsupportedCss === "error" && has("UNSUPPORTED_CSS_PROPERTY")) {
|
|
110
|
+
const property = diagnostics.find((diagnostic) => diagnostic.code === "UNSUPPORTED_CSS_PROPERTY")?.property ?? "unknown";
|
|
111
|
+
throw new UnsupportedCssError(`Unsupported CSS property: ${property}`);
|
|
112
|
+
}
|
|
113
|
+
if (options.resourcePolicy === "error") {
|
|
114
|
+
const failed = diagnostics.find((diagnostic) => diagnostic.code === "INLINE_SVG_INVALID" || diagnostic.code === "RESOURCE_OMITTED");
|
|
115
|
+
if (failed)
|
|
116
|
+
throw new ResourceLoadError(failed.code === "INLINE_SVG_INVALID" ? "inline SVG" : failed.message);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** Keeps edits disjoint: an element removal supersedes edits inside it. */
|
|
120
|
+
function addEdit(edits, edit) {
|
|
121
|
+
if (edits.some((existing) => edit.start >= existing.start && edit.end <= existing.end && existing.end - existing.start > edit.end - edit.start))
|
|
122
|
+
return;
|
|
123
|
+
for (let index = edits.length - 1; index >= 0; index -= 1) {
|
|
124
|
+
const existing = edits[index];
|
|
125
|
+
if (existing.start >= edit.start && existing.end <= edit.end)
|
|
126
|
+
edits.splice(index, 1);
|
|
127
|
+
}
|
|
128
|
+
edits.push(edit);
|
|
129
|
+
}
|
|
130
|
+
/** Applies byte-range edits to the UTF-8 encoding of `source`. */
|
|
131
|
+
function applyEdits(source, edits) {
|
|
132
|
+
if (edits.length === 0)
|
|
133
|
+
return source;
|
|
134
|
+
const encoder = new TextEncoder();
|
|
135
|
+
const bytes = encoder.encode(source);
|
|
136
|
+
const decoder = new TextDecoder();
|
|
137
|
+
let output = "";
|
|
138
|
+
let cursor = 0;
|
|
139
|
+
for (const edit of [...edits].sort((left, right) => left.start - right.start)) {
|
|
140
|
+
output += decoder.decode(bytes.subarray(cursor, edit.start)) + edit.text;
|
|
141
|
+
cursor = edit.end;
|
|
142
|
+
}
|
|
143
|
+
return output + decoder.decode(bytes.subarray(cursor));
|
|
144
|
+
}
|
|
145
|
+
function escapeAttribute(value) {
|
|
146
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
147
|
+
}
|
|
148
|
+
function base64(bytes) {
|
|
149
|
+
let binary = "";
|
|
150
|
+
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
|
|
151
|
+
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
|
|
152
|
+
}
|
|
153
|
+
return btoa(binary);
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=node-source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-source.js","sourceRoot":"","sources":["../src/node-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAMlG,MAAM,cAAc,GAAG,iDAAiD,CAAC;AACzE,MAAM,YAAY,GAAG,6CAA6C,CAAC;AACnE,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC,CAAC;AAQpF,oEAAoE;AACpE,MAAM,UAAU,qBAAqB,CAAC,MAAkB;IACtD,OAAO;QACL,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC;QACxE,KAAK,EAAE,mBAAmB;KAC3B,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,iBAAiB,CAAC,MAAkB,EAAE,MA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MAAM,IAAI,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9E,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC;QACzE,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC;IACpB,CAAC;IACD,OAAO,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AACzD,CAAC;AAED,SAAS,eAAe,CAAC,KAAa;IACpC,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AACpF,CAAC;AAED,SAAS,MAAM,CAAC,KAAiB;IAC/B,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,EAAE,MAAM,IAAI,MAAM,EAAE,CAAC;QAC7D,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["/**\n * HTML-string preparation for hosts without a DOM (Node).\n *\n * The browser snapshot embeds every resource and replaces inline SVG before\n * the core runs. Without a DOM the core does the structural work itself\n * (inline `<svg>` becomes a replaced element natively); this module only\n * routes external resources through `resourceResolver`, using byte ranges the\n * core tokenizer reports, and maps core diagnostics onto the caller's\n * policies after the render. Nothing is ever fetched implicitly.\n *\n * @packageDocumentation\n */\n\nimport { ResourceLoadError, UnsupportedCssError, UnsupportedEnvironmentError } from \"./errors.js\";\nimport type { SourcePreparation } from \"./renderer.js\";\nimport type { SnapshotOptions, SnapshotResult } from \"./snapshot.js\";\nimport type { Diagnostic, HtmlSource } from \"./types.js\";\nimport type { ResourceReference, WasmBridge } from \"./wasm.js\";\n\nconst EMBEDDED_IMAGE = /^data:image\\/(?:png|jpeg|jpg|svg\\+xml);base64,/i;\nconst SVG_DATA_URL = /^data:image\\/svg\\+xml(?:;charset=[^;,]+)?,/i;\nconst EMBEDDABLE_BLOB_TYPES = new Set([\"image/png\", \"image/jpeg\", \"image/svg+xml\"]);\n\ninterface Edit {\n start: number;\n end: number;\n text: string;\n}\n\n/** Source preparation for one Node renderer and its WASM bridge. */\nexport function nodeSourcePreparation(bridge: WasmBridge): SourcePreparation {\n return {\n prepare: (source, options) => prepareHtmlString(bridge, source, options),\n check: enforceNodePolicies,\n };\n}\n\nasync function prepareHtmlString(bridge: WasmBridge, source: HtmlSource, options: SnapshotOptions): Promise<SnapshotResult> {\n if (typeof source !== \"string\") {\n throw new UnsupportedEnvironmentError(\"Element and ref sources need a browser DOM; pass an HTML string when rendering in Node\");\n }\n const diagnostics: Diagnostic[] = [];\n const references = bridge.resourceReferences(source);\n if (references.length === 0) return { html: source, diagnostics };\n\n const edits: Edit[] = [];\n for (const reference of references) {\n let replacement: string;\n try {\n replacement = await resolveReference(reference, options);\n } catch (error) {\n if (options.resourcePolicy === \"error\") throw new ResourceLoadError(reference.url, { cause: error });\n // Backgrounds stay in place: the core omits non-embedded URLs and\n // reports them itself. Elements are removed like the browser snapshot.\n if (reference.kind === \"background\" || reference.tagStart === undefined || reference.tagEnd === undefined) continue;\n addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: \"\" });\n diagnostics.push({\n code: \"RESOURCE_OMITTED\",\n severity: \"warning\",\n message: `${reference.kind === \"stylesheet\" ? \"Stylesheet\" : \"Image\"} resource was omitted: ${reference.url}`,\n phase: \"snapshot\",\n });\n continue;\n }\n if (reference.kind === \"stylesheet\" && reference.tagStart !== undefined && reference.tagEnd !== undefined) {\n addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: replacement });\n } else {\n addEdit(edits, { start: reference.start, end: reference.end, text: replacement });\n }\n }\n return { html: applyEdits(source, edits), diagnostics };\n}\n\n/** Returns the embedded replacement text, or throws when the resource is unavailable. */\nasync function resolveReference(reference: ResourceReference, options: SnapshotOptions): Promise<string> {\n let url: URL;\n try {\n url = options.baseUrl === undefined ? new URL(reference.url) : new URL(reference.url, options.baseUrl);\n } catch (error) {\n throw new Error(`Relative resource URL \"${reference.url}\" needs baseUrl outside the browser`, { cause: error });\n }\n const resolver = options.resourceResolver;\n if (!resolver) throw new Error(\"Resources are never fetched outside the browser; provide resourceResolver\");\n const kind = reference.kind === \"stylesheet\" ? \"stylesheet\" : \"image\";\n const resolved = await resolver({ kind, url });\n if (resolved === null || resolved === undefined) throw new Error(`The ${kind} resource was declined by resourceResolver`);\n\n if (kind === \"stylesheet\") {\n const css = typeof resolved === \"string\" ? resolved : await resolved.text();\n // Raw-text content cannot contain its own end tag.\n return `<style data-html2realpdf-resolved-from=\"${escapeAttribute(url.href)}\">${css.replace(/<\\/style/gi, \"<\\\\/style\")}</style>`;\n }\n if (typeof resolved === \"string\") {\n if (EMBEDDED_IMAGE.test(resolved)) return resolved;\n if (SVG_DATA_URL.test(resolved)) {\n const payload = decodeURIComponent(resolved.slice(resolved.indexOf(\",\") + 1));\n return `data:image/svg+xml;base64,${base64(new TextEncoder().encode(payload))}`;\n }\n throw new Error(\"Outside the browser an image resolver must return a PNG, JPEG, or SVG data URL or Blob; replacement URLs are not fetched\");\n }\n const type = resolved.type.toLowerCase();\n if (!EMBEDDABLE_BLOB_TYPES.has(type)) {\n throw new Error(`Image type \"${resolved.type || \"unknown\"}\" cannot be embedded outside the browser; use PNG, JPEG, or SVG`);\n }\n return `data:${type};base64,${base64(new Uint8Array(await resolved.arrayBuffer()))}`;\n}\n\n/**\n * Maps core diagnostics onto the browser-equivalent policies. The browser\n * rasterizes unsupported SVG only after `fallback: \"rasterize-subtree\"`;\n * Node cannot rasterize, so it keeps the omission and its diagnostic.\n */\nfunction enforceNodePolicies(diagnostics: readonly Diagnostic[], options: SnapshotOptions): void {\n const has = (code: string) => diagnostics.some((diagnostic) => diagnostic.code === code);\n if (options.fallback === \"error\" && has(\"INLINE_SVG_UNSUPPORTED\")) {\n throw new UnsupportedCssError(\"Inline SVG uses features outside the native vector subset and cannot be rasterized outside the browser\");\n }\n if (options.unsupportedCss === \"error\" && has(\"UNSUPPORTED_CSS_PROPERTY\")) {\n const property = diagnostics.find((diagnostic) => diagnostic.code === \"UNSUPPORTED_CSS_PROPERTY\")?.property ?? \"unknown\";\n throw new UnsupportedCssError(`Unsupported CSS property: ${property}`);\n }\n if (options.resourcePolicy === \"error\") {\n const failed = diagnostics.find((diagnostic) => diagnostic.code === \"INLINE_SVG_INVALID\" || diagnostic.code === \"RESOURCE_OMITTED\");\n if (failed) throw new ResourceLoadError(failed.code === \"INLINE_SVG_INVALID\" ? \"inline SVG\" : failed.message);\n }\n}\n\n/** Keeps edits disjoint: an element removal supersedes edits inside it. */\nfunction addEdit(edits: Edit[], edit: Edit): void {\n if (edits.some((existing) => edit.start >= existing.start && edit.end <= existing.end && existing.end - existing.start > edit.end - edit.start)) return;\n for (let index = edits.length - 1; index >= 0; index -= 1) {\n const existing = edits[index]!;\n if (existing.start >= edit.start && existing.end <= edit.end) edits.splice(index, 1);\n }\n edits.push(edit);\n}\n\n/** Applies byte-range edits to the UTF-8 encoding of `source`. */\nfunction applyEdits(source: string, edits: readonly Edit[]): string {\n if (edits.length === 0) return source;\n const encoder = new TextEncoder();\n const bytes = encoder.encode(source);\n const decoder = new TextDecoder();\n let output = \"\";\n let cursor = 0;\n for (const edit of [...edits].sort((left, right) => left.start - right.start)) {\n output += decoder.decode(bytes.subarray(cursor, edit.start)) + edit.text;\n cursor = edit.end;\n }\n return output + decoder.decode(bytes.subarray(cursor));\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, \"&\").replace(/\"/g, \""\").replace(/</g, \"<\");\n}\n\nfunction base64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n }\n return btoa(binary);\n}\n"]}
|