@formepdf/core 0.9.2 → 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 +11 -25
- package/dist/browser.js +30 -175
- package/dist/index.js +13 -32
- package/dist/shared/browserHelpers.d.ts +19 -0
- package/dist/shared/browserHelpers.js +128 -0
- package/dist/worker.d.ts +68 -0
- package/dist/worker.js +158 -0
- package/package.json +27 -12
- package/pkg/forme.d.ts +0 -46
- package/pkg/forme.js +7 -477
- package/pkg/forme_bg.js +379 -0
- package/pkg/forme_bg.wasm +0 -0
- package/pkg/package.json +3 -1
- package/pkg-node/LICENSE +21 -0
- package/pkg-node/README.md +84 -0
- package/pkg-node/forme.d.ts +39 -0
- package/pkg-node/forme.js +394 -0
- package/pkg-node/forme_bg.wasm +0 -0
- package/pkg-node/forme_bg.wasm.d.ts +21 -0
- package/pkg-node/package.json +25 -0
- package/pkg-web/LICENSE +21 -0
- package/pkg-web/README.md +84 -0
- package/pkg-web/forme.d.ts +85 -0
- package/pkg-web/forme.js +479 -0
- package/pkg-web/forme_bg.wasm +0 -0
- package/pkg-web/forme_bg.wasm.d.ts +21 -0
- package/pkg-web/package.json +29 -0
- package/scripts/assert-tarball.sh +62 -0
package/dist/browser.d.ts
CHANGED
|
@@ -1,31 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Browser entry point for @formepdf/core.
|
|
2
|
+
* Browser / edge entry point for @formepdf/core.
|
|
3
3
|
*
|
|
4
4
|
* Import as `@formepdf/core/browser` — no Node APIs, works in any
|
|
5
|
-
* modern browser with WebAssembly support.
|
|
5
|
+
* modern browser, edge runtime, or worker with WebAssembly support.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
* module
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* Backed by the wasm-pack `--target bundler` build of pkg/, so the
|
|
8
|
+
* WASM module is wired up implicitly by the consuming bundler at
|
|
9
|
+
* module-load time (via `import * as wasm from './forme_bg.wasm'`
|
|
10
|
+
* inside pkg/forme.js). Vite, esbuild, Webpack, Turbopack, and
|
|
11
|
+
* Wrangler all handle this — there is no explicit init step.
|
|
11
12
|
*/
|
|
12
|
-
import type { InitInput } from '../pkg/forme.js';
|
|
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
|
-
/**
|
|
16
|
-
*
|
|
17
|
-
|
|
18
|
-
* WASM URL/bytes.
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* // Auto-resolve (works with bundlers)
|
|
22
|
-
* await initWasm();
|
|
23
|
-
*
|
|
24
|
-
* // Explicit URL (CDN, custom path, etc.)
|
|
25
|
-
* await initWasm('/wasm/forme_bg.wasm');
|
|
26
|
-
* await initWasm(new URL('./forme_bg.wasm', import.meta.url));
|
|
27
|
-
*/
|
|
28
|
-
export declare function init(module?: InitInput | Promise<InitInput>): Promise<void>;
|
|
15
|
+
/** @deprecated No-op under the bundler-target build. For explicit
|
|
16
|
+
* instantiation in Workers/edge, import from `@formepdf/core/worker`. */
|
|
17
|
+
export declare function init(_module?: unknown): Promise<void>;
|
|
29
18
|
export declare function renderPdf(json: string): Promise<Uint8Array>;
|
|
30
19
|
export declare function renderPdfWithLayout(json: string): Promise<RenderWithLayoutResult>;
|
|
31
20
|
export declare function renderDocument(element: import('react').ReactElement, options?: RenderDocumentOptions): Promise<Uint8Array>;
|
|
@@ -82,8 +71,5 @@ export declare function redactText(pdfBytes: Uint8Array, patterns: RedactionPatt
|
|
|
82
71
|
* @returns The merged PDF as a Uint8Array.
|
|
83
72
|
*/
|
|
84
73
|
export declare function mergePdfs(pdfs: Uint8Array[]): Promise<Uint8Array>;
|
|
85
|
-
/**
|
|
86
|
-
* Extract embedded JSON data from a Forme-generated PDF.
|
|
87
|
-
* Uses the browser-native DecompressionStream API (no node:zlib).
|
|
88
|
-
*/
|
|
74
|
+
/** Extract embedded JSON data from a Forme-generated PDF. */
|
|
89
75
|
export declare function extractData(pdfBytes: Uint8Array): Promise<unknown | null>;
|
package/dist/browser.js
CHANGED
|
@@ -1,108 +1,37 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Browser entry point for @formepdf/core.
|
|
2
|
+
* Browser / edge entry point for @formepdf/core.
|
|
3
3
|
*
|
|
4
4
|
* Import as `@formepdf/core/browser` — no Node APIs, works in any
|
|
5
|
-
* modern browser with WebAssembly support.
|
|
5
|
+
* modern browser, edge runtime, or worker with WebAssembly support.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
* module
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* Backed by the wasm-pack `--target bundler` build of pkg/, so the
|
|
8
|
+
* WASM module is wired up implicitly by the consuming bundler at
|
|
9
|
+
* module-load time (via `import * as wasm from './forme_bg.wasm'`
|
|
10
|
+
* inside pkg/forme.js). Vite, esbuild, Webpack, Turbopack, and
|
|
11
|
+
* Wrangler all handle this — there is no explicit init step.
|
|
11
12
|
*/
|
|
12
|
-
import
|
|
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';
|
|
13
15
|
// ── WASM initialization ────────────────────────────────────────────
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
*
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
*/
|
|
28
|
-
export async function init(module) {
|
|
29
|
-
if (initialized)
|
|
30
|
-
return;
|
|
31
|
-
if (module !== undefined) {
|
|
32
|
-
await initWasm({ module_or_path: module });
|
|
33
|
-
}
|
|
34
|
-
else {
|
|
35
|
-
await initWasm();
|
|
36
|
-
}
|
|
37
|
-
initialized = true;
|
|
38
|
-
}
|
|
39
|
-
// ── Helpers ────────────────────────────────────────────────────────
|
|
40
|
-
function uint8ArrayToBase64(bytes) {
|
|
41
|
-
// Browser-native: binary string → btoa
|
|
42
|
-
let binary = '';
|
|
43
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
44
|
-
binary += String.fromCharCode(bytes[i]);
|
|
45
|
-
}
|
|
46
|
-
return btoa(binary);
|
|
47
|
-
}
|
|
48
|
-
async function resolveFonts(doc) {
|
|
49
|
-
const fonts = doc.fonts;
|
|
50
|
-
if (!fonts?.length)
|
|
51
|
-
return;
|
|
52
|
-
for (const font of fonts) {
|
|
53
|
-
if (font.src instanceof Uint8Array) {
|
|
54
|
-
font.src = uint8ArrayToBase64(font.src);
|
|
55
|
-
}
|
|
56
|
-
else if (typeof font.src === 'string' && !font.src.startsWith('data:')) {
|
|
57
|
-
// In the browser, non-data-URI strings are treated as URLs
|
|
58
|
-
const res = await fetch(font.src);
|
|
59
|
-
if (!res.ok)
|
|
60
|
-
throw new Error(`Failed to fetch font: ${font.src} (${res.status})`);
|
|
61
|
-
const buf = new Uint8Array(await res.arrayBuffer());
|
|
62
|
-
font.src = uint8ArrayToBase64(buf);
|
|
63
|
-
}
|
|
64
|
-
// data URIs pass through as-is (engine extracts base64 portion)
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
async function resolveImages(doc) {
|
|
68
|
-
const children = doc.children;
|
|
69
|
-
if (!children?.length)
|
|
70
|
-
return;
|
|
71
|
-
for (const child of children) {
|
|
72
|
-
await resolveImagesInNode(child);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
async function resolveImagesInNode(node) {
|
|
76
|
-
const kind = node.kind;
|
|
77
|
-
if (kind?.type === 'Image' && typeof kind.src === 'string') {
|
|
78
|
-
const src = kind.src;
|
|
79
|
-
if (src.startsWith('http://') || src.startsWith('https://')) {
|
|
80
|
-
const res = await fetch(src);
|
|
81
|
-
if (!res.ok)
|
|
82
|
-
throw new Error(`Failed to fetch image: ${src} (${res.status})`);
|
|
83
|
-
const contentType = res.headers.get('content-type') || 'image/png';
|
|
84
|
-
const buf = new Uint8Array(await res.arrayBuffer());
|
|
85
|
-
kind.src = `data:${contentType};base64,${uint8ArrayToBase64(buf)}`;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
const children = node.children;
|
|
89
|
-
if (children?.length) {
|
|
90
|
-
for (const child of children) {
|
|
91
|
-
await resolveImagesInNode(child);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
16
|
+
//
|
|
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.
|
|
20
|
+
//
|
|
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`. */
|
|
27
|
+
export async function init(_module) {
|
|
28
|
+
return;
|
|
94
29
|
}
|
|
95
30
|
// ── Render functions ───────────────────────────────────────────────
|
|
96
|
-
async function ensureInit() {
|
|
97
|
-
if (!initialized)
|
|
98
|
-
await init();
|
|
99
|
-
}
|
|
100
31
|
export async function renderPdf(json) {
|
|
101
|
-
await ensureInit();
|
|
102
32
|
return wasmRenderPdf(json);
|
|
103
33
|
}
|
|
104
34
|
export async function renderPdfWithLayout(json) {
|
|
105
|
-
await ensureInit();
|
|
106
35
|
const result = wasmRenderPdfWithLayout(json);
|
|
107
36
|
return result;
|
|
108
37
|
}
|
|
@@ -164,27 +93,21 @@ export async function renderSerializedDocWithLayout(doc, options) {
|
|
|
164
93
|
}
|
|
165
94
|
// ── Template rendering ──────────────────────────────────────────────
|
|
166
95
|
export async function renderTemplate(templateJson, dataJson) {
|
|
167
|
-
await ensureInit();
|
|
168
96
|
return wasmRenderTemplatePdf(templateJson, dataJson);
|
|
169
97
|
}
|
|
170
98
|
export async function renderTemplateWithLayout(templateJson, dataJson) {
|
|
171
|
-
await ensureInit();
|
|
172
99
|
const result = wasmRenderTemplatePdfWithLayout(templateJson, dataJson);
|
|
173
100
|
return result;
|
|
174
101
|
}
|
|
175
102
|
// ── PDF certification ────────────────────────────────────────────────
|
|
176
103
|
export async function certifyPdf(pdfBytes, config) {
|
|
177
|
-
|
|
178
|
-
const { certify_pdf } = await import('../pkg/forme.js');
|
|
179
|
-
return certify_pdf(pdfBytes, JSON.stringify(config));
|
|
104
|
+
return wasmCertifyPdf(pdfBytes, JSON.stringify(config));
|
|
180
105
|
}
|
|
181
106
|
/** @deprecated Use certifyPdf */
|
|
182
107
|
export const signPdf = certifyPdf;
|
|
183
108
|
// ── PDF redaction ────────────────────────────────────────────────────
|
|
184
109
|
export async function redactPdf(pdfBytes, regions) {
|
|
185
|
-
|
|
186
|
-
const { redact_pdf } = await import('../pkg/forme.js');
|
|
187
|
-
return redact_pdf(pdfBytes, JSON.stringify(regions));
|
|
110
|
+
return wasmRedactPdf(pdfBytes, JSON.stringify(regions));
|
|
188
111
|
}
|
|
189
112
|
// ── Text-search redaction ─────────────────────────────────────────────
|
|
190
113
|
/**
|
|
@@ -194,9 +117,7 @@ export async function redactPdf(pdfBytes, regions) {
|
|
|
194
117
|
* redaction regions (in web top-origin coordinates) for each match.
|
|
195
118
|
*/
|
|
196
119
|
export async function findTextRegions(pdfBytes, patterns) {
|
|
197
|
-
|
|
198
|
-
const { find_text_regions } = await import('../pkg/forme.js');
|
|
199
|
-
const json = find_text_regions(pdfBytes, JSON.stringify(patterns));
|
|
120
|
+
const json = wasmFindTextRegions(pdfBytes, JSON.stringify(patterns));
|
|
200
121
|
return JSON.parse(json);
|
|
201
122
|
}
|
|
202
123
|
/**
|
|
@@ -206,9 +127,7 @@ export async function findTextRegions(pdfBytes, patterns) {
|
|
|
206
127
|
* applies coordinate-based redaction to each match.
|
|
207
128
|
*/
|
|
208
129
|
export async function redactText(pdfBytes, patterns) {
|
|
209
|
-
|
|
210
|
-
const { redact_text } = await import('../pkg/forme.js');
|
|
211
|
-
return redact_text(pdfBytes, JSON.stringify(patterns));
|
|
130
|
+
return wasmRedactText(pdfBytes, JSON.stringify(patterns));
|
|
212
131
|
}
|
|
213
132
|
// ── PDF merging ──────────────────────────────────────────────────────
|
|
214
133
|
/**
|
|
@@ -218,75 +137,11 @@ export async function redactText(pdfBytes, patterns) {
|
|
|
218
137
|
* @returns The merged PDF as a Uint8Array.
|
|
219
138
|
*/
|
|
220
139
|
export async function mergePdfs(pdfs) {
|
|
221
|
-
await ensureInit();
|
|
222
|
-
const { merge_pdfs } = await import('../pkg/forme.js');
|
|
223
140
|
const base64Pdfs = pdfs.map((pdf) => btoa(Array.from(pdf, (b) => String.fromCharCode(b)).join('')));
|
|
224
|
-
return
|
|
141
|
+
return wasmMergePdfs(JSON.stringify(base64Pdfs));
|
|
225
142
|
}
|
|
226
|
-
// ── Data extraction
|
|
227
|
-
/**
|
|
228
|
-
* Extract embedded JSON data from a Forme-generated PDF.
|
|
229
|
-
* Uses the browser-native DecompressionStream API (no node:zlib).
|
|
230
|
-
*/
|
|
143
|
+
// ── Data extraction ─────────────────────────────────────────────────
|
|
144
|
+
/** Extract embedded JSON data from a Forme-generated PDF. */
|
|
231
145
|
export async function extractData(pdfBytes) {
|
|
232
|
-
|
|
233
|
-
// Find the FileSpec referencing forme-data.json
|
|
234
|
-
const fsMatch = text.match(/\/F\s*\(forme-data\.json\)/);
|
|
235
|
-
if (!fsMatch)
|
|
236
|
-
return null;
|
|
237
|
-
// Extract the EmbeddedFile stream object number from /EF << /F N 0 R >>
|
|
238
|
-
const fsStart = fsMatch.index;
|
|
239
|
-
const fsRegion = text.slice(Math.max(0, fsStart - 200), fsStart + 200);
|
|
240
|
-
const efMatch = fsRegion.match(/\/EF\s*<<\s*\/F\s+(\d+)\s+0\s+R\s*>>/);
|
|
241
|
-
if (!efMatch)
|
|
242
|
-
return null;
|
|
243
|
-
const streamObjId = efMatch[1];
|
|
244
|
-
// Find the stream object
|
|
245
|
-
const objPattern = new RegExp(streamObjId + '\\s+0\\s+obj\\b');
|
|
246
|
-
const objMatch = text.match(objPattern);
|
|
247
|
-
if (!objMatch)
|
|
248
|
-
return null;
|
|
249
|
-
const objStart = objMatch.index;
|
|
250
|
-
// Find stream start
|
|
251
|
-
const streamKeyword = text.indexOf('stream', objStart);
|
|
252
|
-
if (streamKeyword === -1)
|
|
253
|
-
return null;
|
|
254
|
-
let streamDataStart = streamKeyword + 6;
|
|
255
|
-
if (pdfBytes[streamDataStart] === 0x0d)
|
|
256
|
-
streamDataStart++;
|
|
257
|
-
if (pdfBytes[streamDataStart] === 0x0a)
|
|
258
|
-
streamDataStart++;
|
|
259
|
-
const endstreamPos = text.indexOf('\nendstream', streamDataStart);
|
|
260
|
-
if (endstreamPos === -1)
|
|
261
|
-
return null;
|
|
262
|
-
const compressedBytes = pdfBytes.slice(streamDataStart, endstreamPos);
|
|
263
|
-
const objRegion = text.slice(objStart, streamKeyword);
|
|
264
|
-
const isCompressed = objRegion.includes('/FlateDecode');
|
|
265
|
-
let jsonBytes;
|
|
266
|
-
if (isCompressed) {
|
|
267
|
-
const ds = new DecompressionStream('deflate');
|
|
268
|
-
const writer = ds.writable.getWriter();
|
|
269
|
-
writer.write(compressedBytes);
|
|
270
|
-
writer.close();
|
|
271
|
-
const reader = ds.readable.getReader();
|
|
272
|
-
const chunks = [];
|
|
273
|
-
while (true) {
|
|
274
|
-
const { done, value } = await reader.read();
|
|
275
|
-
if (done)
|
|
276
|
-
break;
|
|
277
|
-
chunks.push(value);
|
|
278
|
-
}
|
|
279
|
-
const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
|
|
280
|
-
jsonBytes = new Uint8Array(totalLength);
|
|
281
|
-
let offset = 0;
|
|
282
|
-
for (const chunk of chunks) {
|
|
283
|
-
jsonBytes.set(chunk, offset);
|
|
284
|
-
offset += chunk.length;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
else {
|
|
288
|
-
jsonBytes = compressedBytes;
|
|
289
|
-
}
|
|
290
|
-
const jsonString = new TextDecoder('utf-8').decode(jsonBytes);
|
|
291
|
-
return JSON.parse(jsonString);
|
|
146
|
+
return extractDataFromPdf(pdfBytes);
|
|
292
147
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
// Node entry uses the wasm-pack `--target nodejs` build, which is a
|
|
2
|
+
// self-initializing CJS module: it `require('fs').readFileSync`s its
|
|
3
|
+
// own .wasm at import time, so callers don't need to await any init.
|
|
4
|
+
import { render_pdf as wasmRenderPdf } from '../pkg-node/forme.js';
|
|
2
5
|
import { readFile } from 'node:fs/promises';
|
|
3
|
-
import {
|
|
4
|
-
import { dirname, join, resolve } from 'node:path';
|
|
5
|
-
// ── WASM initialization ────────────────────────────────────────────
|
|
6
|
-
let initialized = false;
|
|
7
|
-
async function ensureInit() {
|
|
8
|
-
if (initialized)
|
|
9
|
-
return;
|
|
10
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
11
|
-
const wasmPath = join(__dirname, '..', 'pkg', 'forme_bg.wasm');
|
|
12
|
-
const wasmBytes = await readFile(wasmPath);
|
|
13
|
-
await initWasm({ module_or_path: wasmBytes });
|
|
14
|
-
initialized = true;
|
|
15
|
-
}
|
|
6
|
+
import { resolve } from 'node:path';
|
|
16
7
|
// ── Font resolution ──────────────────────────────────────────────
|
|
17
8
|
function uint8ArrayToBase64(bytes) {
|
|
18
9
|
return Buffer.from(bytes).toString('base64');
|
|
@@ -63,13 +54,10 @@ async function resolveImagesInNode(node) {
|
|
|
63
54
|
}
|
|
64
55
|
// ── Render functions ───────────────────────────────────────────────
|
|
65
56
|
export async function renderPdf(json) {
|
|
66
|
-
await ensureInit();
|
|
67
57
|
return wasmRenderPdf(json);
|
|
68
58
|
}
|
|
69
59
|
export async function renderPdfWithLayout(json) {
|
|
70
|
-
await
|
|
71
|
-
// Dynamic import to access the WASM binding that returns { pdf, layout }
|
|
72
|
-
const { render_pdf_with_layout } = await import('../pkg/forme.js');
|
|
60
|
+
const { render_pdf_with_layout } = await import('../pkg-node/forme.js');
|
|
73
61
|
const result = render_pdf_with_layout(json);
|
|
74
62
|
return result;
|
|
75
63
|
}
|
|
@@ -99,27 +87,23 @@ export async function renderDocumentWithLayout(element, options) {
|
|
|
99
87
|
}
|
|
100
88
|
// ── Template rendering ──────────────────────────────────────────────
|
|
101
89
|
export async function renderTemplate(templateJson, dataJson) {
|
|
102
|
-
await
|
|
103
|
-
const { render_template_pdf } = await import('../pkg/forme.js');
|
|
90
|
+
const { render_template_pdf } = await import('../pkg-node/forme.js');
|
|
104
91
|
return render_template_pdf(templateJson, dataJson);
|
|
105
92
|
}
|
|
106
93
|
export async function renderTemplateWithLayout(templateJson, dataJson) {
|
|
107
|
-
await
|
|
108
|
-
const { render_template_pdf_with_layout } = await import('../pkg/forme.js');
|
|
94
|
+
const { render_template_pdf_with_layout } = await import('../pkg-node/forme.js');
|
|
109
95
|
const result = render_template_pdf_with_layout(templateJson, dataJson);
|
|
110
96
|
return result;
|
|
111
97
|
}
|
|
112
98
|
// ── PDF certification ────────────────────────────────────────────────
|
|
113
99
|
export async function certifyPdf(pdfBytes, config) {
|
|
114
|
-
await
|
|
115
|
-
const { certify_pdf } = await import('../pkg/forme.js');
|
|
100
|
+
const { certify_pdf } = await import('../pkg-node/forme.js');
|
|
116
101
|
return certify_pdf(pdfBytes, JSON.stringify(config));
|
|
117
102
|
}
|
|
118
103
|
/** @deprecated Use certifyPdf */
|
|
119
104
|
export const signPdf = certifyPdf;
|
|
120
105
|
export async function redactPdf(pdfBytes, regions) {
|
|
121
|
-
await
|
|
122
|
-
const { redact_pdf } = await import('../pkg/forme.js');
|
|
106
|
+
const { redact_pdf } = await import('../pkg-node/forme.js');
|
|
123
107
|
return redact_pdf(pdfBytes, JSON.stringify(regions));
|
|
124
108
|
}
|
|
125
109
|
/**
|
|
@@ -129,8 +113,7 @@ export async function redactPdf(pdfBytes, regions) {
|
|
|
129
113
|
* redaction regions (in web top-origin coordinates) for each match.
|
|
130
114
|
*/
|
|
131
115
|
export async function findTextRegions(pdfBytes, patterns) {
|
|
132
|
-
await
|
|
133
|
-
const { find_text_regions } = await import('../pkg/forme.js');
|
|
116
|
+
const { find_text_regions } = await import('../pkg-node/forme.js');
|
|
134
117
|
const json = find_text_regions(pdfBytes, JSON.stringify(patterns));
|
|
135
118
|
return JSON.parse(json);
|
|
136
119
|
}
|
|
@@ -141,8 +124,7 @@ export async function findTextRegions(pdfBytes, patterns) {
|
|
|
141
124
|
* applies coordinate-based redaction to each match.
|
|
142
125
|
*/
|
|
143
126
|
export async function redactText(pdfBytes, patterns) {
|
|
144
|
-
await
|
|
145
|
-
const { redact_text } = await import('../pkg/forme.js');
|
|
127
|
+
const { redact_text } = await import('../pkg-node/forme.js');
|
|
146
128
|
return redact_text(pdfBytes, JSON.stringify(patterns));
|
|
147
129
|
}
|
|
148
130
|
// ── PDF merging ──────────────────────────────────────────────────────
|
|
@@ -153,8 +135,7 @@ export async function redactText(pdfBytes, patterns) {
|
|
|
153
135
|
* @returns The merged PDF as a Uint8Array.
|
|
154
136
|
*/
|
|
155
137
|
export async function mergePdfs(pdfs) {
|
|
156
|
-
await
|
|
157
|
-
const { merge_pdfs } = await import('../pkg/forme.js');
|
|
138
|
+
const { merge_pdfs } = await import('../pkg-node/forme.js');
|
|
158
139
|
const base64Pdfs = pdfs.map((pdf) => Buffer.from(pdf).toString('base64'));
|
|
159
140
|
return merge_pdfs(JSON.stringify(base64Pdfs));
|
|
160
141
|
}
|
|
@@ -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
|
+
}
|
package/dist/worker.d.ts
ADDED
|
@@ -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>;
|