@formepdf/core 0.10.0 → 0.10.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/dist/browser.d.ts CHANGED
@@ -12,8 +12,8 @@
12
12
  */
13
13
  export type { Color, EdgeValues, CornerValues, ElementStyleInfo, ElementInfo, PageInfo, LayoutInfo, RenderWithLayoutResult, RenderDocumentOptions, RedactionRegion, RedactionPattern, } from './index.js';
14
14
  import type { RenderWithLayoutResult, RenderDocumentOptions, RedactionRegion, RedactionPattern } from './index.js';
15
- /** @deprecated The bundler now wires up WASM automatically; calling
16
- * this is a no-op. Safe to delete from your code. */
15
+ /** @deprecated No-op under the bundler-target build. For explicit
16
+ * instantiation in Workers/edge, import from `@formepdf/core/worker`. */
17
17
  export declare function init(_module?: unknown): Promise<void>;
18
18
  export declare function renderPdf(json: string): Promise<Uint8Array>;
19
19
  export declare function renderPdfWithLayout(json: string): Promise<RenderWithLayoutResult>;
@@ -71,8 +71,5 @@ export declare function redactText(pdfBytes: Uint8Array, patterns: RedactionPatt
71
71
  * @returns The merged PDF as a Uint8Array.
72
72
  */
73
73
  export declare function mergePdfs(pdfs: Uint8Array[]): Promise<Uint8Array>;
74
- /**
75
- * Extract embedded JSON data from a Forme-generated PDF.
76
- * Uses the browser-native DecompressionStream API (no node:zlib).
77
- */
74
+ /** Extract embedded JSON data from a Forme-generated PDF. */
78
75
  export declare function extractData(pdfBytes: Uint8Array): Promise<unknown | null>;
package/dist/browser.js CHANGED
@@ -11,75 +11,22 @@
11
11
  * Wrangler all handle this — there is no explicit init step.
12
12
  */
13
13
  import { certify_pdf as wasmCertifyPdf, find_text_regions as wasmFindTextRegions, merge_pdfs as wasmMergePdfs, redact_pdf as wasmRedactPdf, redact_text as wasmRedactText, render_pdf as wasmRenderPdf, render_pdf_with_layout as wasmRenderPdfWithLayout, render_template_pdf as wasmRenderTemplatePdf, render_template_pdf_with_layout as wasmRenderTemplatePdfWithLayout, } from '../pkg/forme.js';
14
+ import { resolveFonts, resolveImages, extractDataFromPdf, } from './shared/browserHelpers.js';
14
15
  // ── WASM initialization ────────────────────────────────────────────
15
16
  //
16
- // Kept as a no-op for backward compatibility with callers that did
17
- // `await init()` against the old --target web build. The bundler-
18
- // target build instantiates the WASM at module-load time, so by the
19
- // time anyone could invoke any of the exports below, the engine is
20
- // already live.
17
+ // Kept as a no-op for backward compatibility. The bundler-target build
18
+ // instantiates the WASM at module-load time, so by the time anyone can
19
+ // invoke any of the exports below, the engine is already live.
21
20
  //
22
- /** @deprecated The bundler now wires up WASM automatically; calling
23
- * this is a no-op. Safe to delete from your code. */
21
+ // If you need an explicit `init(module)` driven by a `WebAssembly.Module`
22
+ // you imported yourself (e.g. Cloudflare Workers), import from
23
+ // `@formepdf/core/worker` instead — that entry is backed by the web
24
+ // target which supports manual instantiation.
25
+ /** @deprecated No-op under the bundler-target build. For explicit
26
+ * instantiation in Workers/edge, import from `@formepdf/core/worker`. */
24
27
  export async function init(_module) {
25
28
  return;
26
29
  }
27
- // ── Helpers ────────────────────────────────────────────────────────
28
- function uint8ArrayToBase64(bytes) {
29
- // Browser-native: binary string → btoa
30
- let binary = '';
31
- for (let i = 0; i < bytes.length; i++) {
32
- binary += String.fromCharCode(bytes[i]);
33
- }
34
- return btoa(binary);
35
- }
36
- async function resolveFonts(doc) {
37
- const fonts = doc.fonts;
38
- if (!fonts?.length)
39
- return;
40
- for (const font of fonts) {
41
- if (font.src instanceof Uint8Array) {
42
- font.src = uint8ArrayToBase64(font.src);
43
- }
44
- else if (typeof font.src === 'string' && !font.src.startsWith('data:')) {
45
- // In the browser, non-data-URI strings are treated as URLs
46
- const res = await fetch(font.src);
47
- if (!res.ok)
48
- throw new Error(`Failed to fetch font: ${font.src} (${res.status})`);
49
- const buf = new Uint8Array(await res.arrayBuffer());
50
- font.src = uint8ArrayToBase64(buf);
51
- }
52
- // data URIs pass through as-is (engine extracts base64 portion)
53
- }
54
- }
55
- async function resolveImages(doc) {
56
- const children = doc.children;
57
- if (!children?.length)
58
- return;
59
- for (const child of children) {
60
- await resolveImagesInNode(child);
61
- }
62
- }
63
- async function resolveImagesInNode(node) {
64
- const kind = node.kind;
65
- if (kind?.type === 'Image' && typeof kind.src === 'string') {
66
- const src = kind.src;
67
- if (src.startsWith('http://') || src.startsWith('https://')) {
68
- const res = await fetch(src);
69
- if (!res.ok)
70
- throw new Error(`Failed to fetch image: ${src} (${res.status})`);
71
- const contentType = res.headers.get('content-type') || 'image/png';
72
- const buf = new Uint8Array(await res.arrayBuffer());
73
- kind.src = `data:${contentType};base64,${uint8ArrayToBase64(buf)}`;
74
- }
75
- }
76
- const children = node.children;
77
- if (children?.length) {
78
- for (const child of children) {
79
- await resolveImagesInNode(child);
80
- }
81
- }
82
- }
83
30
  // ── Render functions ───────────────────────────────────────────────
84
31
  export async function renderPdf(json) {
85
32
  return wasmRenderPdf(json);
@@ -193,70 +140,8 @@ export async function mergePdfs(pdfs) {
193
140
  const base64Pdfs = pdfs.map((pdf) => btoa(Array.from(pdf, (b) => String.fromCharCode(b)).join('')));
194
141
  return wasmMergePdfs(JSON.stringify(base64Pdfs));
195
142
  }
196
- // ── Data extraction (browser-native decompression) ──────────────────
197
- /**
198
- * Extract embedded JSON data from a Forme-generated PDF.
199
- * Uses the browser-native DecompressionStream API (no node:zlib).
200
- */
143
+ // ── Data extraction ─────────────────────────────────────────────────
144
+ /** Extract embedded JSON data from a Forme-generated PDF. */
201
145
  export async function extractData(pdfBytes) {
202
- const text = new TextDecoder('latin1').decode(pdfBytes);
203
- // Find the FileSpec referencing forme-data.json
204
- const fsMatch = text.match(/\/F\s*\(forme-data\.json\)/);
205
- if (!fsMatch)
206
- return null;
207
- // Extract the EmbeddedFile stream object number from /EF << /F N 0 R >>
208
- const fsStart = fsMatch.index;
209
- const fsRegion = text.slice(Math.max(0, fsStart - 200), fsStart + 200);
210
- const efMatch = fsRegion.match(/\/EF\s*<<\s*\/F\s+(\d+)\s+0\s+R\s*>>/);
211
- if (!efMatch)
212
- return null;
213
- const streamObjId = efMatch[1];
214
- // Find the stream object
215
- const objPattern = new RegExp(streamObjId + '\\s+0\\s+obj\\b');
216
- const objMatch = text.match(objPattern);
217
- if (!objMatch)
218
- return null;
219
- const objStart = objMatch.index;
220
- // Find stream start
221
- const streamKeyword = text.indexOf('stream', objStart);
222
- if (streamKeyword === -1)
223
- return null;
224
- let streamDataStart = streamKeyword + 6;
225
- if (pdfBytes[streamDataStart] === 0x0d)
226
- streamDataStart++;
227
- if (pdfBytes[streamDataStart] === 0x0a)
228
- streamDataStart++;
229
- const endstreamPos = text.indexOf('\nendstream', streamDataStart);
230
- if (endstreamPos === -1)
231
- return null;
232
- const compressedBytes = pdfBytes.slice(streamDataStart, endstreamPos);
233
- const objRegion = text.slice(objStart, streamKeyword);
234
- const isCompressed = objRegion.includes('/FlateDecode');
235
- let jsonBytes;
236
- if (isCompressed) {
237
- const ds = new DecompressionStream('deflate');
238
- const writer = ds.writable.getWriter();
239
- writer.write(compressedBytes);
240
- writer.close();
241
- const reader = ds.readable.getReader();
242
- const chunks = [];
243
- while (true) {
244
- const { done, value } = await reader.read();
245
- if (done)
246
- break;
247
- chunks.push(value);
248
- }
249
- const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
250
- jsonBytes = new Uint8Array(totalLength);
251
- let offset = 0;
252
- for (const chunk of chunks) {
253
- jsonBytes.set(chunk, offset);
254
- offset += chunk.length;
255
- }
256
- }
257
- else {
258
- jsonBytes = compressedBytes;
259
- }
260
- const jsonString = new TextDecoder('utf-8').decode(jsonBytes);
261
- return JSON.parse(jsonString);
146
+ return extractDataFromPdf(pdfBytes);
262
147
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Helpers shared between the browser entry (`src/browser.ts`, backed by
3
+ * the wasm-pack `--target bundler` build) and the worker entry
4
+ * (`src/worker.ts`, backed by `--target web`). The two entries differ
5
+ * only in how the WASM module gets instantiated; everything from
6
+ * font/image URL resolution through embedded-JSON extraction is the
7
+ * same and lives here.
8
+ *
9
+ * Strictly browser/edge primitives: `fetch`, `btoa`, `TextDecoder`,
10
+ * `DecompressionStream`. No Node-only APIs.
11
+ */
12
+ export declare function uint8ArrayToBase64(bytes: Uint8Array): string;
13
+ export declare function resolveFonts(doc: Record<string, unknown>): Promise<void>;
14
+ export declare function resolveImages(doc: Record<string, unknown>): Promise<void>;
15
+ /**
16
+ * Extract embedded JSON data from a Forme-generated PDF using browser-
17
+ * native DecompressionStream (no node:zlib needed).
18
+ */
19
+ export declare function extractDataFromPdf(pdfBytes: Uint8Array): Promise<unknown | null>;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Helpers shared between the browser entry (`src/browser.ts`, backed by
3
+ * the wasm-pack `--target bundler` build) and the worker entry
4
+ * (`src/worker.ts`, backed by `--target web`). The two entries differ
5
+ * only in how the WASM module gets instantiated; everything from
6
+ * font/image URL resolution through embedded-JSON extraction is the
7
+ * same and lives here.
8
+ *
9
+ * Strictly browser/edge primitives: `fetch`, `btoa`, `TextDecoder`,
10
+ * `DecompressionStream`. No Node-only APIs.
11
+ */
12
+ export function uint8ArrayToBase64(bytes) {
13
+ // Browser-native: binary string → btoa
14
+ let binary = '';
15
+ for (let i = 0; i < bytes.length; i++) {
16
+ binary += String.fromCharCode(bytes[i]);
17
+ }
18
+ return btoa(binary);
19
+ }
20
+ export async function resolveFonts(doc) {
21
+ const fonts = doc.fonts;
22
+ if (!fonts?.length)
23
+ return;
24
+ for (const font of fonts) {
25
+ if (font.src instanceof Uint8Array) {
26
+ font.src = uint8ArrayToBase64(font.src);
27
+ }
28
+ else if (typeof font.src === 'string' && !font.src.startsWith('data:')) {
29
+ // In the browser, non-data-URI strings are treated as URLs
30
+ const res = await fetch(font.src);
31
+ if (!res.ok)
32
+ throw new Error(`Failed to fetch font: ${font.src} (${res.status})`);
33
+ const buf = new Uint8Array(await res.arrayBuffer());
34
+ font.src = uint8ArrayToBase64(buf);
35
+ }
36
+ // data URIs pass through as-is (engine extracts base64 portion)
37
+ }
38
+ }
39
+ export async function resolveImages(doc) {
40
+ const children = doc.children;
41
+ if (!children?.length)
42
+ return;
43
+ for (const child of children) {
44
+ await resolveImagesInNode(child);
45
+ }
46
+ }
47
+ async function resolveImagesInNode(node) {
48
+ const kind = node.kind;
49
+ if (kind?.type === 'Image' && typeof kind.src === 'string') {
50
+ const src = kind.src;
51
+ if (src.startsWith('http://') || src.startsWith('https://')) {
52
+ const res = await fetch(src);
53
+ if (!res.ok)
54
+ throw new Error(`Failed to fetch image: ${src} (${res.status})`);
55
+ const contentType = res.headers.get('content-type') || 'image/png';
56
+ const buf = new Uint8Array(await res.arrayBuffer());
57
+ kind.src = `data:${contentType};base64,${uint8ArrayToBase64(buf)}`;
58
+ }
59
+ }
60
+ const children = node.children;
61
+ if (children?.length) {
62
+ for (const child of children) {
63
+ await resolveImagesInNode(child);
64
+ }
65
+ }
66
+ }
67
+ /**
68
+ * Extract embedded JSON data from a Forme-generated PDF using browser-
69
+ * native DecompressionStream (no node:zlib needed).
70
+ */
71
+ export async function extractDataFromPdf(pdfBytes) {
72
+ const text = new TextDecoder('latin1').decode(pdfBytes);
73
+ const fsMatch = text.match(/\/F\s*\(forme-data\.json\)/);
74
+ if (!fsMatch)
75
+ return null;
76
+ const fsStart = fsMatch.index;
77
+ const fsRegion = text.slice(Math.max(0, fsStart - 200), fsStart + 200);
78
+ const efMatch = fsRegion.match(/\/EF\s*<<\s*\/F\s+(\d+)\s+0\s+R\s*>>/);
79
+ if (!efMatch)
80
+ return null;
81
+ const streamObjId = efMatch[1];
82
+ const objPattern = new RegExp(streamObjId + '\\s+0\\s+obj\\b');
83
+ const objMatch = text.match(objPattern);
84
+ if (!objMatch)
85
+ return null;
86
+ const objStart = objMatch.index;
87
+ const streamKeyword = text.indexOf('stream', objStart);
88
+ if (streamKeyword === -1)
89
+ return null;
90
+ let streamDataStart = streamKeyword + 6;
91
+ if (pdfBytes[streamDataStart] === 0x0d)
92
+ streamDataStart++;
93
+ if (pdfBytes[streamDataStart] === 0x0a)
94
+ streamDataStart++;
95
+ const endstreamPos = text.indexOf('\nendstream', streamDataStart);
96
+ if (endstreamPos === -1)
97
+ return null;
98
+ const compressedBytes = pdfBytes.slice(streamDataStart, endstreamPos);
99
+ const objRegion = text.slice(objStart, streamKeyword);
100
+ const isCompressed = objRegion.includes('/FlateDecode');
101
+ let jsonBytes;
102
+ if (isCompressed) {
103
+ const ds = new DecompressionStream('deflate');
104
+ const writer = ds.writable.getWriter();
105
+ writer.write(compressedBytes);
106
+ writer.close();
107
+ const reader = ds.readable.getReader();
108
+ const chunks = [];
109
+ while (true) {
110
+ const { done, value } = await reader.read();
111
+ if (done)
112
+ break;
113
+ chunks.push(value);
114
+ }
115
+ const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
116
+ jsonBytes = new Uint8Array(totalLength);
117
+ let offset = 0;
118
+ for (const chunk of chunks) {
119
+ jsonBytes.set(chunk, offset);
120
+ offset += chunk.length;
121
+ }
122
+ }
123
+ else {
124
+ jsonBytes = compressedBytes;
125
+ }
126
+ const jsonString = new TextDecoder('utf-8').decode(jsonBytes);
127
+ return JSON.parse(jsonString);
128
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Cloudflare Workers / edge entry point for @formepdf/core.
3
+ *
4
+ * Backed by the wasm-pack `--target web` build of `pkg-web/`. Unlike
5
+ * the bundler-target browser entry, this one does **not** auto-init
6
+ * the WASM at module load — that's incompatible with Wrangler's
7
+ * WASM-as-ESM contract (Wrangler returns `{ default: WebAssembly.Module }`
8
+ * rather than an instantiated namespace, so the bundler glue's
9
+ * top-level `wasm.__wbindgen_start()` would throw).
10
+ *
11
+ * Instead, callers pass the `WebAssembly.Module` they imported
12
+ * themselves into `init(module)` once at request time:
13
+ *
14
+ * import { init, renderDocument } from '@formepdf/core' // resolves here under the 'worker' condition
15
+ * import wasm from '@formepdf/core/pkg-web/forme_bg.wasm' // recommended
16
+ * // or:
17
+ * import wasm from '@formepdf/core/pkg/forme_bg.wasm' // legacy, also works
18
+ *
19
+ * export default {
20
+ * async fetch() {
21
+ * await init(wasm);
22
+ * const pdf = await renderDocument(<Doc />);
23
+ * return new Response(pdf, { headers: { 'content-type': 'application/pdf' } });
24
+ * },
25
+ * };
26
+ */
27
+ export type { Color, EdgeValues, CornerValues, ElementStyleInfo, ElementInfo, PageInfo, LayoutInfo, RenderWithLayoutResult, RenderDocumentOptions, RedactionRegion, RedactionPattern, } from './index.js';
28
+ import type { RenderWithLayoutResult, RenderDocumentOptions, RedactionRegion, RedactionPattern } from './index.js';
29
+ /**
30
+ * Initialize the WASM engine. Pass a `WebAssembly.Module` (the default
31
+ * shape Wrangler/esbuild give you when you `import wasm from '…/forme_bg.wasm'`)
32
+ * or any other value `__wbg_init` accepts: a `URL`, a `Response`, a
33
+ * `Promise<Response>`, raw bytes (`BufferSource`), or `undefined` to
34
+ * fall back to fetching `forme_bg.wasm` next to `pkg-web/forme.js`.
35
+ *
36
+ * Idempotent: subsequent calls reuse the first invocation's promise.
37
+ * Must complete before any render/redact/merge call.
38
+ */
39
+ export declare function init(module?: unknown): Promise<void>;
40
+ export declare function renderPdf(json: string): Promise<Uint8Array>;
41
+ export declare function renderPdfWithLayout(json: string): Promise<RenderWithLayoutResult>;
42
+ export declare function renderDocument(element: import('react').ReactElement, options?: RenderDocumentOptions): Promise<Uint8Array>;
43
+ export declare function renderDocumentWithLayout(element: import('react').ReactElement, options?: RenderDocumentOptions): Promise<RenderWithLayoutResult>;
44
+ export declare function renderSerializedDoc(doc: Record<string, unknown>, options?: RenderDocumentOptions): Promise<Uint8Array>;
45
+ export declare function renderSerializedDocWithLayout(doc: Record<string, unknown>, options?: RenderDocumentOptions): Promise<RenderWithLayoutResult>;
46
+ export declare function renderTemplate(templateJson: string, dataJson: string): Promise<Uint8Array>;
47
+ export declare function renderTemplateWithLayout(templateJson: string, dataJson: string): Promise<RenderWithLayoutResult>;
48
+ export declare function certifyPdf(pdfBytes: Uint8Array, config: {
49
+ certificatePem: string;
50
+ privateKeyPem: string;
51
+ reason?: string;
52
+ location?: string;
53
+ contact?: string;
54
+ visible?: boolean;
55
+ page?: number;
56
+ x?: number;
57
+ y?: number;
58
+ width?: number;
59
+ height?: number;
60
+ }): Promise<Uint8Array>;
61
+ /** @deprecated Use certifyPdf */
62
+ export declare const signPdf: typeof certifyPdf;
63
+ export declare function redactPdf(pdfBytes: Uint8Array, regions: RedactionRegion[]): Promise<Uint8Array>;
64
+ export declare function findTextRegions(pdfBytes: Uint8Array, patterns: RedactionPattern[]): Promise<RedactionRegion[]>;
65
+ export declare function redactText(pdfBytes: Uint8Array, patterns: RedactionPattern[]): Promise<Uint8Array>;
66
+ export declare function mergePdfs(pdfs: Uint8Array[]): Promise<Uint8Array>;
67
+ /** Extract embedded JSON data from a Forme-generated PDF. */
68
+ export declare function extractData(pdfBytes: Uint8Array): Promise<unknown | null>;
package/dist/worker.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Cloudflare Workers / edge entry point for @formepdf/core.
3
+ *
4
+ * Backed by the wasm-pack `--target web` build of `pkg-web/`. Unlike
5
+ * the bundler-target browser entry, this one does **not** auto-init
6
+ * the WASM at module load — that's incompatible with Wrangler's
7
+ * WASM-as-ESM contract (Wrangler returns `{ default: WebAssembly.Module }`
8
+ * rather than an instantiated namespace, so the bundler glue's
9
+ * top-level `wasm.__wbindgen_start()` would throw).
10
+ *
11
+ * Instead, callers pass the `WebAssembly.Module` they imported
12
+ * themselves into `init(module)` once at request time:
13
+ *
14
+ * import { init, renderDocument } from '@formepdf/core' // resolves here under the 'worker' condition
15
+ * import wasm from '@formepdf/core/pkg-web/forme_bg.wasm' // recommended
16
+ * // or:
17
+ * import wasm from '@formepdf/core/pkg/forme_bg.wasm' // legacy, also works
18
+ *
19
+ * export default {
20
+ * async fetch() {
21
+ * await init(wasm);
22
+ * const pdf = await renderDocument(<Doc />);
23
+ * return new Response(pdf, { headers: { 'content-type': 'application/pdf' } });
24
+ * },
25
+ * };
26
+ */
27
+ import __wbg_init, { certify_pdf as wasmCertifyPdf, find_text_regions as wasmFindTextRegions, merge_pdfs as wasmMergePdfs, redact_pdf as wasmRedactPdf, redact_text as wasmRedactText, render_pdf as wasmRenderPdf, render_pdf_with_layout as wasmRenderPdfWithLayout, render_template_pdf as wasmRenderTemplatePdf, render_template_pdf_with_layout as wasmRenderTemplatePdfWithLayout, } from '../pkg-web/forme.js';
28
+ import { resolveFonts, resolveImages, extractDataFromPdf, } from './shared/browserHelpers.js';
29
+ // ── WASM initialization ────────────────────────────────────────────
30
+ let initPromise = null;
31
+ /**
32
+ * Initialize the WASM engine. Pass a `WebAssembly.Module` (the default
33
+ * shape Wrangler/esbuild give you when you `import wasm from '…/forme_bg.wasm'`)
34
+ * or any other value `__wbg_init` accepts: a `URL`, a `Response`, a
35
+ * `Promise<Response>`, raw bytes (`BufferSource`), or `undefined` to
36
+ * fall back to fetching `forme_bg.wasm` next to `pkg-web/forme.js`.
37
+ *
38
+ * Idempotent: subsequent calls reuse the first invocation's promise.
39
+ * Must complete before any render/redact/merge call.
40
+ */
41
+ export async function init(module) {
42
+ if (!initPromise) {
43
+ initPromise = __wbg_init(module === undefined ? undefined : { module_or_path: module });
44
+ }
45
+ await initPromise;
46
+ }
47
+ function ensureInit() {
48
+ if (!initPromise) {
49
+ throw new Error('[@formepdf/core/worker] WASM not initialized. Call `await init(wasmModule)` ' +
50
+ 'with the `WebAssembly.Module` imported from `@formepdf/core/pkg-web/forme_bg.wasm` ' +
51
+ 'before invoking any render/redact/merge function.');
52
+ }
53
+ }
54
+ // ── Render functions ───────────────────────────────────────────────
55
+ export async function renderPdf(json) {
56
+ ensureInit();
57
+ await initPromise;
58
+ return wasmRenderPdf(json);
59
+ }
60
+ export async function renderPdfWithLayout(json) {
61
+ ensureInit();
62
+ await initPromise;
63
+ return wasmRenderPdfWithLayout(json);
64
+ }
65
+ export async function renderDocument(element, options) {
66
+ const { serialize } = await import('@formepdf/react');
67
+ const doc = serialize(element);
68
+ if (options?.embedData !== undefined) {
69
+ doc.embeddedData = JSON.stringify(options.embedData);
70
+ }
71
+ if (options?.flattenForms) {
72
+ doc.flattenForms = true;
73
+ }
74
+ await Promise.all([resolveFonts(doc), resolveImages(doc)]);
75
+ return renderPdf(JSON.stringify(doc));
76
+ }
77
+ export async function renderDocumentWithLayout(element, options) {
78
+ const { serialize } = await import('@formepdf/react');
79
+ const doc = serialize(element);
80
+ if (options?.embedData !== undefined) {
81
+ doc.embeddedData = JSON.stringify(options.embedData);
82
+ }
83
+ if (options?.flattenForms) {
84
+ doc.flattenForms = true;
85
+ }
86
+ await Promise.all([resolveFonts(doc), resolveImages(doc)]);
87
+ return renderPdfWithLayout(JSON.stringify(doc));
88
+ }
89
+ // ── Serialized document rendering ────────────────────────────────────
90
+ export async function renderSerializedDoc(doc, options) {
91
+ if (options?.embedData !== undefined) {
92
+ doc.embeddedData = JSON.stringify(options.embedData);
93
+ }
94
+ if (options?.flattenForms) {
95
+ doc.flattenForms = true;
96
+ }
97
+ await Promise.all([resolveFonts(doc), resolveImages(doc)]);
98
+ return renderPdf(JSON.stringify(doc));
99
+ }
100
+ export async function renderSerializedDocWithLayout(doc, options) {
101
+ if (options?.embedData !== undefined) {
102
+ doc.embeddedData = JSON.stringify(options.embedData);
103
+ }
104
+ if (options?.flattenForms) {
105
+ doc.flattenForms = true;
106
+ }
107
+ await Promise.all([resolveFonts(doc), resolveImages(doc)]);
108
+ return renderPdfWithLayout(JSON.stringify(doc));
109
+ }
110
+ // ── Template rendering ──────────────────────────────────────────────
111
+ export async function renderTemplate(templateJson, dataJson) {
112
+ ensureInit();
113
+ await initPromise;
114
+ return wasmRenderTemplatePdf(templateJson, dataJson);
115
+ }
116
+ export async function renderTemplateWithLayout(templateJson, dataJson) {
117
+ ensureInit();
118
+ await initPromise;
119
+ return wasmRenderTemplatePdfWithLayout(templateJson, dataJson);
120
+ }
121
+ // ── PDF certification ────────────────────────────────────────────────
122
+ export async function certifyPdf(pdfBytes, config) {
123
+ ensureInit();
124
+ await initPromise;
125
+ return wasmCertifyPdf(pdfBytes, JSON.stringify(config));
126
+ }
127
+ /** @deprecated Use certifyPdf */
128
+ export const signPdf = certifyPdf;
129
+ // ── PDF redaction ────────────────────────────────────────────────────
130
+ export async function redactPdf(pdfBytes, regions) {
131
+ ensureInit();
132
+ await initPromise;
133
+ return wasmRedactPdf(pdfBytes, JSON.stringify(regions));
134
+ }
135
+ // ── Text-search redaction ─────────────────────────────────────────────
136
+ export async function findTextRegions(pdfBytes, patterns) {
137
+ ensureInit();
138
+ await initPromise;
139
+ const json = wasmFindTextRegions(pdfBytes, JSON.stringify(patterns));
140
+ return JSON.parse(json);
141
+ }
142
+ export async function redactText(pdfBytes, patterns) {
143
+ ensureInit();
144
+ await initPromise;
145
+ return wasmRedactText(pdfBytes, JSON.stringify(patterns));
146
+ }
147
+ // ── PDF merging ──────────────────────────────────────────────────────
148
+ export async function mergePdfs(pdfs) {
149
+ ensureInit();
150
+ await initPromise;
151
+ const base64Pdfs = pdfs.map((pdf) => btoa(Array.from(pdf, (b) => String.fromCharCode(b)).join('')));
152
+ return wasmMergePdfs(JSON.stringify(base64Pdfs));
153
+ }
154
+ // ── Data extraction ─────────────────────────────────────────────────
155
+ /** Extract embedded JSON data from a Forme-generated PDF. */
156
+ export async function extractData(pdfBytes) {
157
+ return extractDataFromPdf(pdfBytes);
158
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formepdf/core",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "description": "WASM-powered PDF rendering engine for Forme",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -8,16 +8,16 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "worker": {
11
- "types": "./dist/browser.d.ts",
12
- "import": "./dist/browser.js"
11
+ "types": "./dist/worker.d.ts",
12
+ "import": "./dist/worker.js"
13
13
  },
14
14
  "edge-light": {
15
- "types": "./dist/browser.d.ts",
16
- "import": "./dist/browser.js"
15
+ "types": "./dist/worker.d.ts",
16
+ "import": "./dist/worker.js"
17
17
  },
18
18
  "deno": {
19
- "types": "./dist/browser.d.ts",
20
- "import": "./dist/browser.js"
19
+ "types": "./dist/worker.d.ts",
20
+ "import": "./dist/worker.js"
21
21
  },
22
22
  "react-native": {
23
23
  "types": "./dist/browser.d.ts",
@@ -35,25 +35,37 @@
35
35
  "types": "./dist/browser.d.ts",
36
36
  "import": "./dist/browser.js"
37
37
  },
38
+ "./worker": {
39
+ "types": "./dist/worker.d.ts",
40
+ "import": "./dist/worker.js"
41
+ },
38
42
  "./pkg/forme.js": {
39
43
  "types": "./pkg/forme.d.ts",
40
44
  "import": "./pkg/forme.js"
41
45
  },
42
- "./pkg/forme_bg.wasm": "./pkg/forme_bg.wasm"
46
+ "./pkg/forme_bg.wasm": "./pkg/forme_bg.wasm",
47
+ "./pkg-web/forme.js": {
48
+ "types": "./pkg-web/forme.d.ts",
49
+ "import": "./pkg-web/forme.js"
50
+ },
51
+ "./pkg-web/forme_bg.wasm": "./pkg-web/forme_bg.wasm"
43
52
  },
44
53
  "scripts": {
45
- "build:wasm": "./build.sh && rm -f pkg/.gitignore",
54
+ "build:wasm": "./build.sh && rm -f pkg/.gitignore pkg-web/.gitignore pkg-node/.gitignore",
46
55
  "build:ts": "tsc",
47
56
  "build": "npm run build:wasm && npm run build:ts",
48
- "test": "vitest run"
57
+ "test": "vitest run",
58
+ "test:workers": "vitest run --config vitest.config.workers.ts",
59
+ "prepublishOnly": "npm run build && ./scripts/assert-tarball.sh"
49
60
  },
50
61
  "dependencies": {
51
- "@formepdf/react": "0.10.0"
62
+ "@formepdf/react": "0.10.1"
52
63
  },
53
64
  "peerDependencies": {
54
65
  "react": "^18 || ^19"
55
66
  },
56
67
  "devDependencies": {
68
+ "@cloudflare/vitest-pool-workers": "^0.12.21",
57
69
  "@types/node": "^22.0.0",
58
70
  "@types/react": "^19.0.0",
59
71
  "react": "^19.0.0",
@@ -63,7 +75,9 @@
63
75
  "files": [
64
76
  "dist/",
65
77
  "pkg/",
66
- "pkg-node/"
78
+ "pkg-web/",
79
+ "pkg-node/",
80
+ "scripts/"
67
81
  ],
68
82
  "license": "MIT",
69
83
  "repository": {
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel Molitor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.