@arbidocs/react 0.4.55 → 0.4.56

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.
Files changed (49) hide show
  1. package/dist/PdfViewer-bQH9yxFg.d.cts +55 -0
  2. package/dist/PdfViewer-bQH9yxFg.d.ts +55 -0
  3. package/dist/annotations/freeze/index.cjs +748 -0
  4. package/dist/annotations/freeze/index.cjs.map +1 -0
  5. package/dist/annotations/freeze/index.d.cts +199 -0
  6. package/dist/annotations/freeze/index.d.ts +199 -0
  7. package/dist/annotations/freeze/index.js +738 -0
  8. package/dist/annotations/freeze/index.js.map +1 -0
  9. package/dist/annotations/index.cjs +1737 -0
  10. package/dist/annotations/index.cjs.map +1 -0
  11. package/dist/annotations/index.d.cts +291 -0
  12. package/dist/annotations/index.d.ts +291 -0
  13. package/dist/annotations/index.js +1671 -0
  14. package/dist/annotations/index.js.map +1 -0
  15. package/dist/artifacts/index.cjs +16 -16
  16. package/dist/artifacts/index.js +5 -5
  17. package/dist/chunk-BGDE4DP5.cjs +192 -0
  18. package/dist/chunk-BGDE4DP5.cjs.map +1 -0
  19. package/dist/{chunk-MS7VH2BY.js → chunk-CVN7MAGQ.js} +6 -146
  20. package/dist/chunk-CVN7MAGQ.js.map +1 -0
  21. package/dist/chunk-JWXIRUWN.js +183 -0
  22. package/dist/chunk-JWXIRUWN.js.map +1 -0
  23. package/dist/chunk-QS3Q5542.js +151 -0
  24. package/dist/chunk-QS3Q5542.js.map +1 -0
  25. package/dist/{chunk-RI3BZQWD.cjs → chunk-R6V6YHPD.cjs} +3 -3
  26. package/dist/{chunk-RI3BZQWD.cjs.map → chunk-R6V6YHPD.cjs.map} +1 -1
  27. package/dist/{chunk-LOESXNVT.cjs → chunk-X3F5ABY2.cjs} +5 -158
  28. package/dist/chunk-X3F5ABY2.cjs.map +1 -0
  29. package/dist/chunk-XDCRWZF2.cjs +185 -0
  30. package/dist/chunk-XDCRWZF2.cjs.map +1 -0
  31. package/dist/{chunk-GT6KN3DV.js → chunk-XKGTZ3H6.js} +3 -3
  32. package/dist/{chunk-GT6KN3DV.js.map → chunk-XKGTZ3H6.js.map} +1 -1
  33. package/dist/index.cjs +475 -474
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.js +11 -9
  36. package/dist/index.js.map +1 -1
  37. package/dist/model-DzQxhMMz.d.cts +102 -0
  38. package/dist/model-DzQxhMMz.d.ts +102 -0
  39. package/dist/ui/index.cjs +186 -185
  40. package/dist/ui/index.js +3 -2
  41. package/dist/viewers/index.cjs +61 -52
  42. package/dist/viewers/index.cjs.map +1 -1
  43. package/dist/viewers/index.d.cts +3 -43
  44. package/dist/viewers/index.d.ts +3 -43
  45. package/dist/viewers/index.js +61 -52
  46. package/dist/viewers/index.js.map +1 -1
  47. package/package.json +31 -9
  48. package/dist/chunk-LOESXNVT.cjs.map +0 -1
  49. package/dist/chunk-MS7VH2BY.js.map +0 -1
@@ -0,0 +1,748 @@
1
+ 'use strict';
2
+
3
+ var chunkBGDE4DP5_cjs = require('../../chunk-BGDE4DP5.cjs');
4
+ var pdfLib = require('pdf-lib');
5
+ var reactPdf = require('react-pdf');
6
+
7
+ // src/annotations/freeze/coords.ts
8
+ function normaliseRotation(angle) {
9
+ const a = (Math.round(angle / 90) * 90 % 360 + 360) % 360;
10
+ return a;
11
+ }
12
+ function displayedSize(g) {
13
+ return g.rotation === 90 || g.rotation === 270 ? { width: g.height, height: g.width } : { width: g.width, height: g.height };
14
+ }
15
+ function displayedToUser(g, dx, dy) {
16
+ switch (g.rotation) {
17
+ case 0:
18
+ return { x: g.x + dx, y: g.y + g.height - dy };
19
+ case 90:
20
+ return { x: g.x + dy, y: g.y + dx };
21
+ case 180:
22
+ return { x: g.x + g.width - dx, y: g.y + dy };
23
+ case 270:
24
+ return { x: g.x + g.width - dy, y: g.y + g.height - dx };
25
+ }
26
+ }
27
+ function normToUserRect(g, r) {
28
+ const size = displayedSize(g);
29
+ const a = displayedToUser(g, r.x * size.width, r.y * size.height);
30
+ const b = displayedToUser(g, (r.x + r.w) * size.width, (r.y + r.h) * size.height);
31
+ return {
32
+ x: Math.min(a.x, b.x),
33
+ y: Math.min(a.y, b.y),
34
+ width: Math.abs(b.x - a.x),
35
+ height: Math.abs(b.y - a.y)
36
+ };
37
+ }
38
+
39
+ // src/annotations/freeze/hash.ts
40
+ async function sha256Hex(bytes) {
41
+ const copy = new Uint8Array(bytes.byteLength);
42
+ copy.set(bytes);
43
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", copy.buffer);
44
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
45
+ }
46
+ function canonicalJson(value) {
47
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
48
+ if (value && typeof value === "object") {
49
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
50
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
51
+ }
52
+ return JSON.stringify(value);
53
+ }
54
+ function layerFingerprint(layer) {
55
+ return {
56
+ ...layer,
57
+ annotations: layer.annotations.map((a) => {
58
+ return a.kind === "redaction" ? { ...a, text: void 0 } : a;
59
+ })
60
+ };
61
+ }
62
+ var hashLayer = (layer) => sha256Hex(new TextEncoder().encode(canonicalJson(layerFingerprint(layer))));
63
+
64
+ // src/annotations/freeze/types.ts
65
+ var ENCRYPTED_MESSAGE = "This PDF is password-protected, so a copy cannot be frozen from it. Remove the protection first.";
66
+ var FreezeError = class extends Error {
67
+ code;
68
+ constructor(code, message) {
69
+ super(message);
70
+ this.name = "FreezeError";
71
+ this.code = code;
72
+ }
73
+ };
74
+
75
+ // src/annotations/freeze/vector.ts
76
+ var HIGHLIGHT_OPACITY = 0.7;
77
+ var MARKER_SIZE_PT = 12;
78
+ var MARKER_COLOR = "#ffd43b";
79
+ var MARKER_BORDER = "#7a5c00";
80
+ var CAP_HEIGHT = 0.72;
81
+ function hexToRgb(hex) {
82
+ const n = parseInt(hex.slice(1), 16);
83
+ return pdfLib.rgb((n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255);
84
+ }
85
+ function pageGeometry(page) {
86
+ const media = page.getMediaBox();
87
+ const crop = page.getCropBox();
88
+ const x1 = Math.max(media.x, crop.x);
89
+ const y1 = Math.max(media.y, crop.y);
90
+ const x2 = Math.min(media.x + media.width, crop.x + crop.width);
91
+ const y2 = Math.min(media.y + media.height, crop.y + crop.height);
92
+ const usable = x2 > x1 && y2 > y1;
93
+ return {
94
+ x: usable ? x1 : media.x,
95
+ y: usable ? y1 : media.y,
96
+ width: usable ? x2 - x1 : media.width,
97
+ height: usable ? y2 - y1 : media.height,
98
+ rotation: normaliseRotation(page.getRotation().angle)
99
+ };
100
+ }
101
+ function numberComments(marks) {
102
+ const comments = marks.filter((a) => a.kind === "comment").sort(
103
+ (a, b) => a.page - b.page || a.rect.y - b.rect.y || a.rect.x - b.rect.x || (a.id < b.id ? -1 : 1)
104
+ );
105
+ return new Map(comments.map((c, i) => [c.id, i + 1]));
106
+ }
107
+ var TextSanitiser = class {
108
+ supported;
109
+ replaced = /* @__PURE__ */ new Set();
110
+ constructor(font) {
111
+ this.supported = new Set(font.getCharacterSet());
112
+ }
113
+ clean(text) {
114
+ let out = "";
115
+ for (const ch of text) {
116
+ const cp = ch.codePointAt(0);
117
+ if (this.supported.has(cp)) out += ch;
118
+ else {
119
+ out += "?";
120
+ this.replaced.add(ch);
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ supports(text) {
126
+ for (const ch of text) if (!this.supported.has(ch.codePointAt(0))) return false;
127
+ return true;
128
+ }
129
+ };
130
+ async function createVectorContext(doc, marks, comments) {
131
+ const regular = await doc.embedFont(pdfLib.StandardFonts.Helvetica);
132
+ const bold = await doc.embedFont(pdfLib.StandardFonts.HelveticaBold);
133
+ return {
134
+ doc,
135
+ regular,
136
+ bold,
137
+ numbers: numberComments(marks),
138
+ comments,
139
+ sanitiser: new TextSanitiser(regular)
140
+ };
141
+ }
142
+ function drawHighlight(page, g, a) {
143
+ for (const r of a.rects) {
144
+ const u = normToUserRect(g, r);
145
+ page.drawRectangle({
146
+ x: u.x,
147
+ y: u.y,
148
+ width: u.width,
149
+ height: u.height,
150
+ color: hexToRgb(a.color),
151
+ opacity: HIGHLIGHT_OPACITY,
152
+ blendMode: pdfLib.BlendMode.Multiply
153
+ });
154
+ }
155
+ }
156
+ function drawBox(page, g, a) {
157
+ const u = normToUserRect(g, a.rect);
158
+ page.drawRectangle({
159
+ x: u.x,
160
+ y: u.y,
161
+ width: u.width,
162
+ height: u.height,
163
+ borderColor: hexToRgb(a.color),
164
+ borderWidth: a.strokeWidth,
165
+ borderOpacity: 1,
166
+ opacity: 0
167
+ });
168
+ }
169
+ function fitFontSize(font, text, widthPt, heightPt) {
170
+ const probe = font.widthOfTextAtSize(text || " ", 100);
171
+ const byWidth = probe > 0 ? widthPt * 0.9 * 100 / probe : heightPt;
172
+ return Math.max(1, Math.min(heightPt * 0.6, byWidth));
173
+ }
174
+ function drawCentredText(page, g, font, text, box, size, color) {
175
+ const textWidth = font.widthOfTextAtSize(text, size);
176
+ const dx = box.x + (box.w - textWidth) / 2;
177
+ const dy = box.y + box.h / 2 + size * CAP_HEIGHT / 2;
178
+ const origin = displayedToUser(g, dx, dy);
179
+ page.drawText(text, { x: origin.x, y: origin.y, size, font, color, rotate: pdfLib.degrees(g.rotation) });
180
+ }
181
+ function drawStamp(page, g, a, ctx) {
182
+ if (!ctx.sanitiser.supports(a.label)) {
183
+ throw new FreezeError(
184
+ "unsupported-text",
185
+ `Stamp "${a.label}" uses characters a vector stamp cannot draw; freeze as an image instead`
186
+ );
187
+ }
188
+ const u = normToUserRect(g, a.rect);
189
+ const color = hexToRgb(a.color);
190
+ page.drawRectangle({
191
+ x: u.x,
192
+ y: u.y,
193
+ width: u.width,
194
+ height: u.height,
195
+ borderColor: color,
196
+ borderWidth: 2,
197
+ opacity: 0,
198
+ borderOpacity: 1
199
+ });
200
+ const size = displayedSize(g);
201
+ const box = {
202
+ x: a.rect.x * size.width,
203
+ y: a.rect.y * size.height,
204
+ w: a.rect.w * size.width,
205
+ h: a.rect.h * size.height
206
+ };
207
+ const fontSize = fitFontSize(ctx.bold, a.label, box.w, box.h);
208
+ drawCentredText(page, g, ctx.bold, a.label, box, fontSize, color);
209
+ }
210
+ function drawCommentMarker(page, g, a, ctx) {
211
+ const n = ctx.numbers.get(a.id);
212
+ if (n === void 0) return;
213
+ const size = displayedSize(g);
214
+ const box = {
215
+ x: Math.min(a.rect.x * size.width, size.width - MARKER_SIZE_PT),
216
+ y: Math.min(a.rect.y * size.height, size.height - MARKER_SIZE_PT),
217
+ w: MARKER_SIZE_PT,
218
+ h: MARKER_SIZE_PT
219
+ };
220
+ const u = normToUserRect(g, {
221
+ x: box.x / size.width,
222
+ y: box.y / size.height,
223
+ w: box.w / size.width,
224
+ h: box.h / size.height
225
+ });
226
+ page.drawRectangle({
227
+ x: u.x,
228
+ y: u.y,
229
+ width: u.width,
230
+ height: u.height,
231
+ color: hexToRgb(MARKER_COLOR),
232
+ borderColor: hexToRgb(MARKER_BORDER),
233
+ borderWidth: 0.75
234
+ });
235
+ drawCentredText(page, g, ctx.bold, String(n), box, 7, hexToRgb(MARKER_BORDER));
236
+ }
237
+ function drawVectorMark(page, a, ctx) {
238
+ const g = pageGeometry(page);
239
+ switch (a.kind) {
240
+ case "highlight":
241
+ return drawHighlight(page, g, a);
242
+ case "box":
243
+ return drawBox(page, g, a);
244
+ case "stamp":
245
+ return drawStamp(page, g, a, ctx);
246
+ case "comment":
247
+ return ctx.comments === "omit" ? void 0 : drawCommentMarker(page, g, a, ctx);
248
+ case "redaction":
249
+ throw new Error("redactions are never drawn as vectors");
250
+ }
251
+ }
252
+ function wrap(font, text, size, maxWidth) {
253
+ const lines = [];
254
+ for (const paragraph of text.split(/\r?\n/)) {
255
+ let line = "";
256
+ for (const word of paragraph.split(/\s+/).filter(Boolean)) {
257
+ const candidate = line ? `${line} ${word}` : word;
258
+ if (font.widthOfTextAtSize(candidate, size) <= maxWidth || !line) line = candidate;
259
+ else {
260
+ lines.push(line);
261
+ line = word;
262
+ }
263
+ }
264
+ lines.push(line);
265
+ }
266
+ return lines;
267
+ }
268
+ function appendCommentAppendix(ctx, comments, pageSize) {
269
+ if (comments.length === 0) return;
270
+ const { doc, regular, bold, sanitiser } = ctx;
271
+ const margin = 54;
272
+ const lineHeight = 13;
273
+ const maxWidth = pageSize[0] - margin * 2;
274
+ let page = doc.addPage(pageSize);
275
+ let y = pageSize[1] - margin;
276
+ const ensure = (needed) => {
277
+ if (y - needed < margin) {
278
+ page = doc.addPage(pageSize);
279
+ y = pageSize[1] - margin;
280
+ }
281
+ };
282
+ const line = (text, font, size, indent = 0) => {
283
+ ensure(lineHeight);
284
+ page.drawText(sanitiser.clean(text), {
285
+ x: margin + indent,
286
+ y: y - size,
287
+ size,
288
+ font,
289
+ color: pdfLib.rgb(0.1, 0.1, 0.1)
290
+ });
291
+ y -= lineHeight;
292
+ };
293
+ line("Comments", bold, 14);
294
+ y -= 6;
295
+ const ordered = [...comments].sort(
296
+ (a, b) => (ctx.numbers.get(a.id) ?? 0) - (ctx.numbers.get(b.id) ?? 0)
297
+ );
298
+ for (const c of ordered) {
299
+ ensure(lineHeight * 3);
300
+ line(
301
+ `[${ctx.numbers.get(c.id)}] Page ${c.page} - ${c.author}${c.resolved ? " (resolved)" : ""}`,
302
+ bold,
303
+ 10
304
+ );
305
+ for (const l of wrap(regular, sanitiser.clean(c.body), 10, maxWidth - 12))
306
+ line(l, regular, 10, 12);
307
+ for (const r of c.replies) {
308
+ line(`${r.author}:`, bold, 9, 24);
309
+ for (const l of wrap(regular, sanitiser.clean(r.body), 9, maxWidth - 36))
310
+ line(l, regular, 9, 36);
311
+ }
312
+ y -= 8;
313
+ }
314
+ }
315
+
316
+ // src/annotations/freeze/raster.ts
317
+ var MAX_PAGE_PIXELS = 36e6;
318
+ var MARKER_FILL = "#ffd43b";
319
+ var MARKER_INK = "#7a5c00";
320
+ function browserCanvasFactory() {
321
+ return (width, height) => {
322
+ if (typeof OffscreenCanvas !== "undefined") {
323
+ const canvas2 = new OffscreenCanvas(width, height);
324
+ const ctx2 = canvas2.getContext("2d");
325
+ return {
326
+ canvas: canvas2,
327
+ ctx: ctx2,
328
+ async encode(format, quality) {
329
+ const blob = await canvas2.convertToBlob({ type: `image/${format}`, quality });
330
+ return new Uint8Array(await blob.arrayBuffer());
331
+ },
332
+ release() {
333
+ canvas2.width = 0;
334
+ canvas2.height = 0;
335
+ }
336
+ };
337
+ }
338
+ const canvas = document.createElement("canvas");
339
+ canvas.width = width;
340
+ canvas.height = height;
341
+ const ctx = canvas.getContext("2d");
342
+ return {
343
+ canvas,
344
+ ctx,
345
+ encode(format, quality) {
346
+ return new Promise((resolve, reject) => {
347
+ canvas.toBlob(
348
+ (blob) => {
349
+ if (!blob) return reject(new Error("canvas could not be encoded"));
350
+ void blob.arrayBuffer().then((buf) => resolve(new Uint8Array(buf)), reject);
351
+ },
352
+ `image/${format}`,
353
+ quality
354
+ );
355
+ });
356
+ },
357
+ release() {
358
+ canvas.width = 0;
359
+ canvas.height = 0;
360
+ }
361
+ };
362
+ };
363
+ }
364
+ async function createPdfJsRasterizer(pdfjs2, data, canvases, options = {}) {
365
+ const task = pdfjs2.getDocument({
366
+ data: data.slice(),
367
+ password: options.password,
368
+ ...options.documentOptions
369
+ });
370
+ let doc;
371
+ try {
372
+ doc = await task.promise;
373
+ } catch (error) {
374
+ await task.destroy().catch(() => {
375
+ });
376
+ if (error?.name === "PasswordException") {
377
+ throw new FreezeError("encrypted", ENCRYPTED_MESSAGE);
378
+ }
379
+ throw error;
380
+ }
381
+ return {
382
+ numPages: doc.numPages,
383
+ async renderPage(pageNumber, dpi) {
384
+ const page = await doc.getPage(pageNumber);
385
+ try {
386
+ const base = page.getViewport({ scale: 1 });
387
+ let scale = dpi / 72;
388
+ const pixels = base.width * scale * (base.height * scale);
389
+ if (pixels > MAX_PAGE_PIXELS) scale *= Math.sqrt(MAX_PAGE_PIXELS / pixels);
390
+ const viewport = page.getViewport({ scale });
391
+ const widthPx = Math.max(1, Math.ceil(viewport.width));
392
+ const heightPx = Math.max(1, Math.ceil(viewport.height));
393
+ const handle = canvases(widthPx, heightPx);
394
+ handle.ctx.fillStyle = "#ffffff";
395
+ handle.ctx.fillRect(0, 0, widthPx, heightPx);
396
+ await page.render({ canvasContext: handle.ctx, canvas: handle.canvas, viewport }).promise;
397
+ return {
398
+ widthPt: base.width,
399
+ heightPt: base.height,
400
+ widthPx,
401
+ heightPx,
402
+ dpi: scale * 72,
403
+ ctx: handle.ctx,
404
+ encode: handle.encode,
405
+ release: handle.release
406
+ };
407
+ } finally {
408
+ page.cleanup();
409
+ }
410
+ },
411
+ destroy: () => task.destroy()
412
+ };
413
+ }
414
+ function burnMarks(page, marks, options) {
415
+ const { ctx } = page;
416
+ const w = page.widthPx;
417
+ const h = page.heightPx;
418
+ const pxPerPt = page.widthPx / page.widthPt;
419
+ ctx.save();
420
+ for (const a of marks) {
421
+ if (a.kind === "highlight") {
422
+ ctx.globalCompositeOperation = "multiply";
423
+ ctx.globalAlpha = HIGHLIGHT_OPACITY;
424
+ ctx.fillStyle = a.color;
425
+ for (const r of a.rects) ctx.fillRect(r.x * w, r.y * h, r.w * w, r.h * h);
426
+ ctx.globalCompositeOperation = "source-over";
427
+ ctx.globalAlpha = 1;
428
+ }
429
+ }
430
+ for (const a of marks) {
431
+ if (a.kind === "box") {
432
+ ctx.strokeStyle = a.color;
433
+ ctx.lineWidth = a.strokeWidth * pxPerPt;
434
+ ctx.strokeRect(a.rect.x * w, a.rect.y * h, a.rect.w * w, a.rect.h * h);
435
+ } else if (a.kind === "stamp") {
436
+ drawStampOnCanvas(
437
+ ctx,
438
+ a.label,
439
+ a.color,
440
+ { x: a.rect.x * w, y: a.rect.y * h, w: a.rect.w * w, h: a.rect.h * h },
441
+ pxPerPt
442
+ );
443
+ } else if (a.kind === "comment" && options.comments !== "omit") {
444
+ drawMarkerOnCanvas(ctx, a, options.numbers.get(a.id), w, h, pxPerPt);
445
+ }
446
+ }
447
+ for (const a of marks) {
448
+ if (!chunkBGDE4DP5_cjs.isEffectiveRedaction(a)) continue;
449
+ const pad = options.paddingPt * pxPerPt;
450
+ a.rects.forEach((r, i) => {
451
+ const x0 = Math.max(0, Math.floor(r.x * w - pad));
452
+ const y0 = Math.max(0, Math.floor(r.y * h - pad));
453
+ const x1 = Math.min(w, Math.ceil((r.x + r.w) * w + pad));
454
+ const y1 = Math.min(h, Math.ceil((r.y + r.h) * h + pad));
455
+ ctx.fillStyle = "#000000";
456
+ ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
457
+ if (options.labels && i === 0 && a.reason)
458
+ drawLabel(ctx, a.reason, { x: x0, y: y0, w: x1 - x0, h: y1 - y0 });
459
+ });
460
+ }
461
+ ctx.restore();
462
+ }
463
+ function drawStampOnCanvas(ctx, label, color, box, pxPerPt) {
464
+ ctx.strokeStyle = color;
465
+ ctx.lineWidth = 2 * pxPerPt;
466
+ ctx.strokeRect(box.x, box.y, box.w, box.h);
467
+ ctx.fillStyle = color;
468
+ ctx.textAlign = "center";
469
+ ctx.textBaseline = "middle";
470
+ ctx.font = "bold 100px Helvetica, Arial, sans-serif";
471
+ const probe = ctx.measureText(label).width;
472
+ const size = Math.max(1, Math.min(box.h * 0.6, probe > 0 ? box.w * 0.9 * 100 / probe : box.h));
473
+ ctx.font = `bold ${size}px Helvetica, Arial, sans-serif`;
474
+ ctx.fillText(label, box.x + box.w / 2, box.y + box.h / 2);
475
+ }
476
+ function drawMarkerOnCanvas(ctx, a, n, w, h, pxPerPt) {
477
+ if (n === void 0) return;
478
+ const size = MARKER_SIZE_PT * pxPerPt;
479
+ const x = Math.min(a.rect.x * w, w - size);
480
+ const y = Math.min(a.rect.y * h, h - size);
481
+ ctx.fillStyle = MARKER_FILL;
482
+ ctx.fillRect(x, y, size, size);
483
+ ctx.strokeStyle = MARKER_INK;
484
+ ctx.lineWidth = 0.75 * pxPerPt;
485
+ ctx.strokeRect(x, y, size, size);
486
+ ctx.fillStyle = MARKER_INK;
487
+ ctx.textAlign = "center";
488
+ ctx.textBaseline = "middle";
489
+ ctx.font = `bold ${7 * pxPerPt}px Helvetica, Arial, sans-serif`;
490
+ ctx.fillText(String(n), x + size / 2, y + size / 2);
491
+ }
492
+ function drawLabel(ctx, text, box) {
493
+ const size = Math.min(box.h * 0.7, 14);
494
+ if (size < 6) return;
495
+ ctx.font = `${size}px Helvetica, Arial, sans-serif`;
496
+ const width = ctx.measureText(text).width;
497
+ if (width > box.w - 4) return;
498
+ ctx.fillStyle = "#ffffff";
499
+ ctx.textAlign = "center";
500
+ ctx.textBaseline = "middle";
501
+ ctx.fillText(text, box.x + box.w / 2, box.y + box.h / 2);
502
+ }
503
+
504
+ // src/annotations/freeze/freeze.ts
505
+ var DEFAULT_DPI = 200;
506
+ var DEFAULT_JPEG_QUALITY = 0.92;
507
+ var DEFAULT_REDACTION_PADDING_PT = 1.5;
508
+ var MIN_DPI = 72;
509
+ var MAX_DPI = 600;
510
+ var FALLBACK_PAGE = [595.28, 841.89];
511
+ var PROVENANCE_KEY = "ArbiProvenance";
512
+ var KINDS = ["highlight", "box", "comment", "stamp", "redaction"];
513
+ async function freezePdf(original, rawLayer, options) {
514
+ const layer = chunkBGDE4DP5_cjs.parseLayer(rawLayer);
515
+ const now = options.now ?? (/* @__PURE__ */ new Date()).toISOString();
516
+ const comments = options.comments ?? "omit";
517
+ const dpi = options.dpi ?? DEFAULT_DPI;
518
+ if (!(dpi >= MIN_DPI && dpi <= MAX_DPI)) {
519
+ throw new FreezeError("invalid-option", `dpi must be between ${MIN_DPI} and ${MAX_DPI}`);
520
+ }
521
+ const redactions = layer.annotations.filter(chunkBGDE4DP5_cjs.isEffectiveRedaction);
522
+ const pending = redactions.filter((r) => r.status === "pending");
523
+ if (pending.length > 0 && (options.pendingRedactions ?? "error") === "error") {
524
+ throw new FreezeError(
525
+ "pending-redactions",
526
+ `${pending.length} redaction mark(s) have not been approved or rejected`
527
+ );
528
+ }
529
+ const marks = layer.annotations.filter((a) => a.kind !== "redaction" || chunkBGDE4DP5_cjs.isEffectiveRedaction(a));
530
+ const modeApplied = redactions.length > 0 ? "image" : options.mode;
531
+ const [originalSha256, layerSha256] = await Promise.all([sha256Hex(original), hashLayer(layer)]);
532
+ const warnings = [];
533
+ if (redactions.length > 0 && comments !== "omit" && marks.some((a) => a.kind === "comment")) {
534
+ warnings.push(
535
+ "Comments are included in a document with redactions and may repeat redacted text"
536
+ );
537
+ }
538
+ let built;
539
+ if (modeApplied === "image") {
540
+ built = await freezeAsImage(marks, options, comments, dpi, now, warnings);
541
+ } else {
542
+ built = await freezeAsVector(original, marks, comments, now, warnings);
543
+ }
544
+ const provenance = {
545
+ schema: 1,
546
+ derivedFrom: layer.documentId,
547
+ originalSha256,
548
+ layerSha256,
549
+ modeRequested: options.mode,
550
+ modeApplied,
551
+ ...modeApplied !== options.mode ? { modeChangedBecause: "redactions-present" } : {},
552
+ frozenAt: now,
553
+ frozenBy: options.author,
554
+ pages: built.pages,
555
+ ...built.dpi === void 0 ? {} : { dpi: built.dpi },
556
+ counts: countKinds(marks),
557
+ redactions: summariseRedactions(redactions)
558
+ };
559
+ setProvenance(built.doc, provenance);
560
+ return { bytes: await built.doc.save(), provenance, warnings };
561
+ }
562
+ function countKinds(marks) {
563
+ const counts = Object.fromEntries(KINDS.map((k) => [k, 0]));
564
+ for (const a of marks) counts[a.kind]++;
565
+ return counts;
566
+ }
567
+ function summariseRedactions(redactions) {
568
+ const reasons = {};
569
+ const pages = /* @__PURE__ */ new Set();
570
+ for (const r of redactions) {
571
+ if (r.kind !== "redaction") continue;
572
+ pages.add(r.page);
573
+ reasons[r.reason] = (reasons[r.reason] ?? 0) + 1;
574
+ }
575
+ return { count: redactions.length, pages: [...pages].sort((a, b) => a - b), reasons };
576
+ }
577
+ function checkPages(marks, pages) {
578
+ for (const a of marks) {
579
+ if (a.page > pages) {
580
+ throw new FreezeError(
581
+ "page-out-of-range",
582
+ `mark ${a.id} is on page ${a.page}; the document has ${pages}`
583
+ );
584
+ }
585
+ }
586
+ }
587
+ function checkAborted(signal) {
588
+ if (signal?.aborted) throw new DOMException("Freeze aborted", "AbortError");
589
+ }
590
+ async function freezeAsVector(original, marks, comments, now, warnings) {
591
+ let doc;
592
+ try {
593
+ doc = await pdfLib.PDFDocument.load(original);
594
+ } catch (error) {
595
+ if (error instanceof pdfLib.EncryptedPDFError || /is encrypted/i.test(error?.message ?? "")) {
596
+ throw new FreezeError("encrypted", ENCRYPTED_MESSAGE);
597
+ }
598
+ throw new FreezeError("invalid-pdf", `The PDF could not be read: ${error.message}`);
599
+ }
600
+ const pages = doc.getPages();
601
+ checkPages(marks, pages.length);
602
+ const ctx = await createVectorContext(doc, marks, comments);
603
+ for (const a of marks) drawVectorMark(pages[a.page - 1], a, ctx);
604
+ if (comments === "appendix") {
605
+ const first = pages[0] ? displayedSize(pageGeometry(pages[0])) : void 0;
606
+ const size = first ? [first.width, first.height] : FALLBACK_PAGE;
607
+ appendCommentAppendix(
608
+ ctx,
609
+ marks.filter((a) => a.kind === "comment"),
610
+ size
611
+ );
612
+ }
613
+ reportReplaced(ctx.sanitiser, warnings);
614
+ doc.setProducer("ARBI");
615
+ doc.setModificationDate(new Date(now));
616
+ return { doc, pages: pages.length };
617
+ }
618
+ async function freezeAsImage(marks, options, comments, dpi, now, warnings) {
619
+ const rasterizer = options.rasterizer;
620
+ if (!rasterizer) {
621
+ throw new FreezeError("rasterizer-required", "Image freeze needs a page rasterizer");
622
+ }
623
+ try {
624
+ checkPages(marks, rasterizer.numPages);
625
+ const out = await pdfLib.PDFDocument.create();
626
+ out.setProducer("ARBI");
627
+ out.setCreator("ARBI");
628
+ out.setCreationDate(new Date(now));
629
+ out.setModificationDate(new Date(now));
630
+ const numbers = numberComments(marks);
631
+ const format = options.imageFormat ?? "jpeg";
632
+ const quality = options.jpegQuality ?? DEFAULT_JPEG_QUALITY;
633
+ const burn = {
634
+ paddingPt: options.redactionPaddingPt ?? DEFAULT_REDACTION_PADDING_PT,
635
+ labels: options.redactionLabels ?? true,
636
+ comments,
637
+ numbers
638
+ };
639
+ const ocrFont = options.ocr ? await out.embedFont(pdfLib.StandardFonts.Helvetica) : void 0;
640
+ const ocrSanitiser = ocrFont ? new TextSanitiser(ocrFont) : void 0;
641
+ let lowestDpi = dpi;
642
+ let firstSize;
643
+ for (let n = 1; n <= rasterizer.numPages; n++) {
644
+ checkAborted(options.signal);
645
+ const page = await rasterizer.renderPage(n, dpi);
646
+ try {
647
+ burnMarks(
648
+ page,
649
+ marks.filter((a) => a.page === n),
650
+ burn
651
+ );
652
+ const bytes = await page.encode(format, quality);
653
+ const image = format === "png" ? await out.embedPng(bytes) : await out.embedJpg(bytes);
654
+ const outPage = out.addPage([page.widthPt, page.heightPt]);
655
+ outPage.drawImage(image, { x: 0, y: 0, width: page.widthPt, height: page.heightPt });
656
+ lowestDpi = Math.min(lowestDpi, page.dpi);
657
+ firstSize ??= [page.widthPt, page.heightPt];
658
+ if (options.ocr && ocrFont && ocrSanitiser) {
659
+ const words = await options.ocr({
660
+ pageNumber: n,
661
+ bytes,
662
+ format,
663
+ widthPx: page.widthPx,
664
+ heightPx: page.heightPx
665
+ });
666
+ drawInvisibleText(outPage, words, page.widthPt, page.heightPt, ocrFont, ocrSanitiser);
667
+ }
668
+ } finally {
669
+ page.release();
670
+ }
671
+ options.onProgress?.(n, rasterizer.numPages);
672
+ }
673
+ if (comments === "appendix") {
674
+ const ctx = await createVectorContext(out, marks, comments);
675
+ appendCommentAppendix(
676
+ ctx,
677
+ marks.filter((a) => a.kind === "comment"),
678
+ firstSize ?? FALLBACK_PAGE
679
+ );
680
+ reportReplaced(ctx.sanitiser, warnings);
681
+ }
682
+ return { doc: out, pages: rasterizer.numPages, dpi: Math.round(lowestDpi) };
683
+ } finally {
684
+ await rasterizer.destroy();
685
+ }
686
+ }
687
+ function drawInvisibleText(page, words, widthPt, heightPt, font, sanitiser) {
688
+ for (const w of words) {
689
+ if (!w.text || !sanitiser.supports(w.text)) continue;
690
+ const size = Math.max(1, w.h * heightPt * 0.8);
691
+ page.drawText(w.text, {
692
+ x: w.x * widthPt,
693
+ y: heightPt - (w.y + w.h) * heightPt,
694
+ size,
695
+ font,
696
+ color: pdfLib.rgb(0, 0, 0),
697
+ opacity: 0
698
+ });
699
+ }
700
+ }
701
+ function reportReplaced(sanitiser, warnings) {
702
+ if (sanitiser.replaced.size > 0) {
703
+ warnings.push(
704
+ `${sanitiser.replaced.size} character(s) in comments cannot be drawn by the built-in font and were replaced with "?"`
705
+ );
706
+ }
707
+ }
708
+ function setProvenance(doc, provenance) {
709
+ const info = doc.context.lookup(doc.context.trailerInfo.Info);
710
+ if (!info || !("set" in info)) throw new Error("document has no info dictionary");
711
+ info.set(
712
+ pdfLib.PDFName.of(PROVENANCE_KEY),
713
+ pdfLib.PDFHexString.fromText(JSON.stringify(provenance))
714
+ );
715
+ }
716
+ async function readProvenance(bytes) {
717
+ const doc = await pdfLib.PDFDocument.load(bytes);
718
+ const info = doc.context.lookup(doc.context.trailerInfo.Info);
719
+ if (!info || !("get" in info)) return null;
720
+ const value = info.get(pdfLib.PDFName.of(PROVENANCE_KEY));
721
+ if (!(value instanceof pdfLib.PDFHexString)) return null;
722
+ return JSON.parse(value.decodeText());
723
+ }
724
+ async function freezePdfInBrowser(bytes, layer, { assets, password, ...options }) {
725
+ const needsRaster = options.mode === "image" || layer.annotations.some(chunkBGDE4DP5_cjs.isEffectiveRedaction);
726
+ const rasterizer = needsRaster ? await createPdfJsRasterizer(reactPdf.pdfjs, bytes, browserCanvasFactory(), {
727
+ password,
728
+ documentOptions: {
729
+ cMapUrl: assets?.cMapUrl ?? "/cmaps/",
730
+ cMapPacked: true,
731
+ standardFontDataUrl: assets?.standardFontDataUrl ?? "/standard_fonts/",
732
+ wasmUrl: assets?.wasmUrl ?? "/wasm/"
733
+ }
734
+ }) : void 0;
735
+ return freezePdf(bytes, layer, { ...options, rasterizer });
736
+ }
737
+
738
+ exports.DEFAULT_DPI = DEFAULT_DPI;
739
+ exports.FreezeError = FreezeError;
740
+ exports.MAX_PAGE_PIXELS = MAX_PAGE_PIXELS;
741
+ exports.browserCanvasFactory = browserCanvasFactory;
742
+ exports.burnMarks = burnMarks;
743
+ exports.createPdfJsRasterizer = createPdfJsRasterizer;
744
+ exports.freezePdf = freezePdf;
745
+ exports.freezePdfInBrowser = freezePdfInBrowser;
746
+ exports.readProvenance = readProvenance;
747
+ //# sourceMappingURL=index.cjs.map
748
+ //# sourceMappingURL=index.cjs.map