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