@arbidocs/react 0.4.68 → 0.4.70

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 (70) hide show
  1. package/README.md +8 -0
  2. package/dist/annotations/index.cjs +186 -2450
  3. package/dist/annotations/index.cjs.map +1 -1
  4. package/dist/annotations/index.d.cts +3 -33
  5. package/dist/annotations/index.d.ts +3 -33
  6. package/dist/annotations/index.js +4 -2411
  7. package/dist/annotations/index.js.map +1 -1
  8. package/dist/artifacts/index.cjs +88 -112
  9. package/dist/artifacts/index.cjs.map +1 -1
  10. package/dist/artifacts/index.js +12 -61
  11. package/dist/artifacts/index.js.map +1 -1
  12. package/dist/artifacts/redline-core.cjs +8 -7
  13. package/dist/artifacts/redline-core.js +2 -1
  14. package/dist/{chunk-PATLJSAO.cjs → chunk-3AADNIOK.cjs} +9 -52
  15. package/dist/chunk-3AADNIOK.cjs.map +1 -0
  16. package/dist/chunk-3QF5DNAP.js +2413 -0
  17. package/dist/chunk-3QF5DNAP.js.map +1 -0
  18. package/dist/chunk-5DCRIWCA.cjs +243 -0
  19. package/dist/chunk-5DCRIWCA.cjs.map +1 -0
  20. package/dist/{chunk-NA3FOYSF.cjs → chunk-5SZ2J2WT.cjs} +5 -177
  21. package/dist/chunk-5SZ2J2WT.cjs.map +1 -0
  22. package/dist/{chunk-43AKLNBC.js → chunk-74N436VK.js} +4 -40
  23. package/dist/chunk-74N436VK.js.map +1 -0
  24. package/dist/{chunk-Z3RRZ3KV.cjs → chunk-7CL7QHT6.cjs} +2 -240
  25. package/dist/chunk-7CL7QHT6.cjs.map +1 -0
  26. package/dist/{chunk-BWVIAATD.cjs → chunk-BTRIS3HY.cjs} +4 -4
  27. package/dist/{chunk-BWVIAATD.cjs.map → chunk-BTRIS3HY.cjs.map} +1 -1
  28. package/dist/chunk-G6FHNURH.js +234 -0
  29. package/dist/chunk-G6FHNURH.js.map +1 -0
  30. package/dist/chunk-HKUD2NZN.js +61 -0
  31. package/dist/chunk-HKUD2NZN.js.map +1 -0
  32. package/dist/chunk-QRCMKEE6.js +173 -0
  33. package/dist/chunk-QRCMKEE6.js.map +1 -0
  34. package/dist/{chunk-PFKLOVGQ.js → chunk-SYPUFZGA.js} +3 -233
  35. package/dist/chunk-SYPUFZGA.js.map +1 -0
  36. package/dist/chunk-T4IJHRRD.cjs +71 -0
  37. package/dist/chunk-T4IJHRRD.cjs.map +1 -0
  38. package/dist/chunk-ULU5LEWF.cjs +2460 -0
  39. package/dist/chunk-ULU5LEWF.cjs.map +1 -0
  40. package/dist/{chunk-TQ6FRVAH.js → chunk-V4CXOPLB.js} +3 -3
  41. package/dist/{chunk-TQ6FRVAH.js.map → chunk-V4CXOPLB.js.map} +1 -1
  42. package/dist/chunk-VOFNX4P6.cjs +50 -0
  43. package/dist/chunk-VOFNX4P6.cjs.map +1 -0
  44. package/dist/chunk-WUTL62MC.js +42 -0
  45. package/dist/chunk-WUTL62MC.js.map +1 -0
  46. package/dist/{chunk-JPGV7NMY.js → chunk-YXSXGTYQ.js} +4 -173
  47. package/dist/chunk-YXSXGTYQ.js.map +1 -0
  48. package/dist/chunk-Z3LLUO32.cjs +177 -0
  49. package/dist/chunk-Z3LLUO32.cjs.map +1 -0
  50. package/dist/document-tools/index.cjs +683 -0
  51. package/dist/document-tools/index.cjs.map +1 -0
  52. package/dist/document-tools/index.d.cts +392 -0
  53. package/dist/document-tools/index.d.ts +392 -0
  54. package/dist/document-tools/index.js +639 -0
  55. package/dist/document-tools/index.js.map +1 -0
  56. package/dist/index.cjs +320 -318
  57. package/dist/index.cjs.map +1 -1
  58. package/dist/index.js +9 -6
  59. package/dist/index.js.map +1 -1
  60. package/dist/store-CqkkD7Ho.d.cts +35 -0
  61. package/dist/store-D1nhbkgk.d.ts +35 -0
  62. package/dist/ui/index.cjs +138 -137
  63. package/dist/ui/index.js +3 -2
  64. package/package.json +11 -3
  65. package/dist/chunk-43AKLNBC.js.map +0 -1
  66. package/dist/chunk-JPGV7NMY.js.map +0 -1
  67. package/dist/chunk-NA3FOYSF.cjs.map +0 -1
  68. package/dist/chunk-PATLJSAO.cjs.map +0 -1
  69. package/dist/chunk-PFKLOVGQ.js.map +0 -1
  70. package/dist/chunk-Z3RRZ3KV.cjs.map +0 -1
@@ -0,0 +1,639 @@
1
+ import { parseVersionRef } from '../chunk-HKUD2NZN.js';
2
+ import '../chunk-G6FHNURH.js';
3
+ import '../chunk-WUTL62MC.js';
4
+ import { mergeLayers, AnnotationStoreOfflineError } from '../chunk-3QF5DNAP.js';
5
+ import { parseLayer, emptyLayer, LAYER_SCHEMA_VERSION } from '../chunk-COWZGCL5.js';
6
+ import '../chunk-QRCMKEE6.js';
7
+ import '../chunk-WS6DF5X4.js';
8
+ import '../chunk-47CCGUWR.js';
9
+ import '../chunk-SN5YV6FF.js';
10
+ import { createContext, useMemo, useContext, useState, useCallback, useEffect, useSyncExternalStore } from 'react';
11
+ import { jsx } from 'react/jsx-runtime';
12
+ import { onlineManager, useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
13
+ import { generateUserKeypairs, signMessage } from '@arbidocs/client';
14
+
15
+ function downloadBlob(blob, fileName) {
16
+ const url = URL.createObjectURL(blob);
17
+ const a = document.createElement("a");
18
+ a.href = url;
19
+ a.download = fileName;
20
+ document.body.appendChild(a);
21
+ a.click();
22
+ a.remove();
23
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
24
+ }
25
+ function clientUpload(client) {
26
+ return async ({ file, query }) => {
27
+ const formData = new FormData();
28
+ formData.append("files", file);
29
+ const { data, response } = await client.POST("/v1/document/upload", {
30
+ params: { query },
31
+ body: formData,
32
+ bodySerializer: (body) => body
33
+ });
34
+ if (!response.ok) throw new Error(`Upload failed with status ${response.status}`);
35
+ return data;
36
+ };
37
+ }
38
+ function defaultCertificateUrl(reference) {
39
+ const origin = typeof location === "undefined" ? "" : location.origin;
40
+ return `${origin}/verify/${encodeURIComponent(reference)}`;
41
+ }
42
+ var DocumentToolsContext = createContext(null);
43
+ function DocumentToolsProvider({ children, ...env }) {
44
+ const {
45
+ client,
46
+ deploymentDomain,
47
+ user,
48
+ notify,
49
+ openDocument,
50
+ onDocumentsChanged,
51
+ uploadDocument,
52
+ saveFile,
53
+ emailDocument,
54
+ certificateUrl
55
+ } = env;
56
+ const value = useMemo(
57
+ () => ({
58
+ client,
59
+ deploymentDomain,
60
+ user,
61
+ openDocument,
62
+ onDocumentsChanged,
63
+ emailDocument,
64
+ notify: notify ?? (() => {
65
+ }),
66
+ saveFile: saveFile ?? downloadBlob,
67
+ uploadDocument: uploadDocument ?? clientUpload(client),
68
+ certificateUrl: certificateUrl ?? defaultCertificateUrl
69
+ }),
70
+ [
71
+ client,
72
+ deploymentDomain,
73
+ user,
74
+ notify,
75
+ openDocument,
76
+ onDocumentsChanged,
77
+ uploadDocument,
78
+ saveFile,
79
+ emailDocument,
80
+ certificateUrl
81
+ ]
82
+ );
83
+ return /* @__PURE__ */ jsx(DocumentToolsContext.Provider, { value, children });
84
+ }
85
+ function useDocumentTools() {
86
+ const env = useContext(DocumentToolsContext);
87
+ if (!env) throw new Error("The document tools must be used within a <DocumentToolsProvider>");
88
+ return env;
89
+ }
90
+
91
+ // src/document-tools/markup-store.ts
92
+ var MAX_MERGE_ATTEMPTS = 5;
93
+ var KEEPALIVE_LIMIT = 6e4;
94
+ var MarkupStoreError = class extends Error {
95
+ constructor(message, status) {
96
+ super(message);
97
+ this.status = status;
98
+ this.name = "MarkupStoreError";
99
+ }
100
+ status;
101
+ };
102
+ var detailOf = (error, fallback) => {
103
+ const detail = error?.detail;
104
+ return typeof detail === "string" ? detail : fallback;
105
+ };
106
+ async function call(request) {
107
+ try {
108
+ return await request();
109
+ } catch (e) {
110
+ if (e instanceof TypeError || typeof navigator !== "undefined" && !navigator.onLine) {
111
+ throw new AnnotationStoreOfflineError();
112
+ }
113
+ throw e;
114
+ }
115
+ }
116
+ function createMarkupStore({ version, client, onSaved }) {
117
+ let revision = 0;
118
+ let count = 0;
119
+ let canEdit = false;
120
+ let base = null;
121
+ const seen = /* @__PURE__ */ new Set();
122
+ const remember = (layer) => {
123
+ for (const a of layer.annotations) seen.add(a.id);
124
+ };
125
+ const query = version ? { version } : {};
126
+ async function read(documentId, ifNoneMatch) {
127
+ const { data, error, response } = await call(
128
+ () => client.GET("/v1/document/{document_ext_id}/markup", {
129
+ params: { path: { document_ext_id: documentId }, query },
130
+ headers: ifNoneMatch === void 0 ? void 0 : { "If-None-Match": `"${ifNoneMatch}"` }
131
+ })
132
+ );
133
+ if (response.status === 304) return null;
134
+ if (error || !data) {
135
+ throw new MarkupStoreError(
136
+ detailOf(error, `The markup could not be loaded (${response.status})`),
137
+ response.status
138
+ );
139
+ }
140
+ const layer = parseLayer({
141
+ schema: LAYER_SCHEMA_VERSION,
142
+ documentId,
143
+ annotations: data.annotations ?? [],
144
+ updatedAt: data.updated_at ?? (/* @__PURE__ */ new Date()).toISOString()
145
+ });
146
+ return { revision: data.revision ?? 0, layer, canEdit: !!data.can_edit };
147
+ }
148
+ function adopt(server) {
149
+ revision = server.revision;
150
+ canEdit = server.canEdit;
151
+ base = server.layer;
152
+ count = server.layer.annotations.length;
153
+ remember(server.layer);
154
+ }
155
+ async function put(layer, from) {
156
+ return call(
157
+ () => client.PUT("/v1/document/{document_ext_id}/markup", {
158
+ params: { path: { document_ext_id: layer.documentId }, query },
159
+ headers: { "If-Match": `"${from}"` },
160
+ body: { annotations: layer.annotations, base_revision: from },
161
+ // A save started as the page closes must outlive it; browsers cap such bodies at 64 KB.
162
+ keepalive: JSON.stringify(layer.annotations).length < KEEPALIVE_LIMIT
163
+ })
164
+ );
165
+ }
166
+ return {
167
+ snapshot: () => ({ revision, count, canEdit }),
168
+ canEdit: () => canEdit,
169
+ async load(documentId) {
170
+ const server = await read(documentId);
171
+ if (!server) throw new MarkupStoreError("The markup could not be loaded");
172
+ adopt(server);
173
+ return server.layer;
174
+ },
175
+ async save(layer) {
176
+ remember(layer);
177
+ let mine = layer;
178
+ for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {
179
+ const { data, error, response } = await put(mine, revision);
180
+ if (response.ok && data) {
181
+ revision = data.revision;
182
+ count = data.count;
183
+ base = mine;
184
+ remember(mine);
185
+ onSaved?.({ revision, count, canEdit });
186
+ return mine;
187
+ }
188
+ if (response.status === 409) {
189
+ const latest = await read(layer.documentId);
190
+ if (!latest) throw new MarkupStoreError("The markup could not be re-read");
191
+ const deleted = new Set(
192
+ [...seen].filter((id) => !mine.annotations.some((a) => a.id === id))
193
+ );
194
+ const merged = mergeLayers({ base, mine, theirs: latest.layer, deleted });
195
+ revision = latest.revision;
196
+ canEdit = latest.canEdit;
197
+ base = latest.layer;
198
+ remember(latest.layer);
199
+ mine = merged;
200
+ continue;
201
+ }
202
+ if (response.status === 403) canEdit = false;
203
+ throw new MarkupStoreError(
204
+ detailOf(error, `The markup could not be saved (${response.status})`),
205
+ response.status
206
+ );
207
+ }
208
+ throw new MarkupStoreError("The markup keeps changing; it will be saved on the next edit");
209
+ },
210
+ async pull(documentId) {
211
+ const server = await read(documentId, revision);
212
+ if (!server || server.revision === revision) return null;
213
+ adopt(server);
214
+ return server.layer;
215
+ }
216
+ };
217
+ }
218
+
219
+ // src/document-tools/markup-transfer.ts
220
+ var LEGACY_LAYER_PREFIX = "arbi:annotations:";
221
+ function storage() {
222
+ try {
223
+ return typeof localStorage === "undefined" ? void 0 : localStorage;
224
+ } catch {
225
+ return void 0;
226
+ }
227
+ }
228
+ function readLegacyLayer(documentId) {
229
+ try {
230
+ const raw = storage()?.getItem(LEGACY_LAYER_PREFIX + documentId);
231
+ if (!raw) return null;
232
+ return parseLayer(JSON.parse(raw));
233
+ } catch {
234
+ return null;
235
+ }
236
+ }
237
+ function forgetLegacyLayer(documentId) {
238
+ try {
239
+ storage()?.removeItem(LEGACY_LAYER_PREFIX + documentId);
240
+ } catch {
241
+ }
242
+ }
243
+ function marksByVersion(layer, versions) {
244
+ const sorted = [...versions].sort((a, b) => a.n - b.n);
245
+ const out = /* @__PURE__ */ new Map();
246
+ for (const mark of layer.annotations) {
247
+ const at = Date.parse(mark.createdAt);
248
+ let target = sorted[0]?.n ?? 1;
249
+ for (const v of sorted) {
250
+ const created = v.created_at ? Date.parse(v.created_at) : Number.NaN;
251
+ if (!Number.isNaN(created) && !Number.isNaN(at) && created <= at) target = v.n;
252
+ }
253
+ out.set(target, [...out.get(target) ?? [], mark]);
254
+ }
255
+ return out;
256
+ }
257
+ async function addToMarkup(documentId, version, marks, client) {
258
+ const store = createMarkupStore({ version, client });
259
+ const current = await store.load(documentId);
260
+ const incoming = {
261
+ ...emptyLayer(documentId, (/* @__PURE__ */ new Date()).toISOString()),
262
+ annotations: marks
263
+ };
264
+ const merged = mergeLayers({ base: null, mine: current, theirs: incoming });
265
+ const added = merged.annotations.length - current.annotations.length;
266
+ if (added > 0) await store.save(parseLayer({ ...merged, schema: LAYER_SCHEMA_VERSION }));
267
+ return added;
268
+ }
269
+ async function migrateLegacyLayer(documentId, layer, versions, currentVersion, client) {
270
+ let added = 0;
271
+ for (const [n, marks] of marksByVersion(layer, versions.length ? versions : [{ n: 1 }])) {
272
+ added += await addToMarkup(documentId, n === currentVersion ? void 0 : n, marks, client);
273
+ }
274
+ forgetLegacyLayer(documentId);
275
+ return added;
276
+ }
277
+ async function openThreadsOf(documentId, version, client) {
278
+ const layer = await createMarkupStore({ version, client }).load(documentId);
279
+ return layer.annotations.filter((a) => a.kind === "comment" && !a.resolved);
280
+ }
281
+ async function copyOpenThreads(documentId, fromVersion, client) {
282
+ const threads = await openThreadsOf(documentId, fromVersion, client);
283
+ if (!threads.length) return 0;
284
+ return addToMarkup(documentId, void 0, threads, client);
285
+ }
286
+ function versionsWithMarkup(versions) {
287
+ return (versions ?? []).filter((v) => (v.markup_count ?? 0) > 0);
288
+ }
289
+
290
+ // src/document-tools/markup-download.ts
291
+ var SIGNED_LOCKED_REASON = "Signed documents can't be changed \u2014 download the signed file instead";
292
+ function isSignedVersion(doc, version) {
293
+ const n = version ?? doc.current_version ?? 1;
294
+ return (doc.versions ?? []).some((v) => v.n === n && v.reason === "signed");
295
+ }
296
+ var MarkupDownloadError = class extends Error {
297
+ constructor(message, status) {
298
+ super(message);
299
+ this.status = status;
300
+ this.name = "MarkupDownloadError";
301
+ }
302
+ status;
303
+ };
304
+ function currentHasMarkup(doc) {
305
+ const n = doc.current_version ?? 1;
306
+ return (doc.versions ?? []).some((v) => v.n === n && (v.markup_count ?? 0) > 0);
307
+ }
308
+ async function fetchMarkupPdf(client, documentId, version) {
309
+ const { data, response } = await client.GET("/v1/document/{document_ext_id}/markup/pdf", {
310
+ params: { path: { document_ext_id: documentId }, query: version ? { version } : {} },
311
+ parseAs: "blob"
312
+ });
313
+ if (!response.ok || !data) {
314
+ throw new MarkupDownloadError(
315
+ response.status === 404 ? "This document has no markup yet" : (
316
+ // The server refuses a signed version: its PDF takes no more changes.
317
+ response.status === 409 ? SIGNED_LOCKED_REASON : "The markup could not be downloaded"
318
+ ),
319
+ response.status
320
+ );
321
+ }
322
+ const disposition = response.headers.get("content-disposition") ?? "";
323
+ const utf8 = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1];
324
+ const plain = /filename="([^"]+)"/i.exec(disposition)?.[1];
325
+ const fileName = utf8 ? decodeURIComponent(utf8) : plain ?? "markup.pdf";
326
+ return { blob: data, fileName };
327
+ }
328
+ var SIGNED_UNCHANGED = "The signed PDF is unchanged: the comments are kept beside it as markup.";
329
+ function useDocumentMarkup(documentData, snapshotVersion, currentSigned = false) {
330
+ const { client, notify, saveFile, onDocumentsChanged } = useDocumentTools();
331
+ const documentId = documentData?.external_id;
332
+ const currentVersion = documentData?.current_version ?? 1;
333
+ const shownVersion = snapshotVersion ?? currentVersion;
334
+ const versions = useMemo(() => documentData?.versions ?? [], [documentData?.versions]);
335
+ const [localCounts, setLocalCounts] = useState({});
336
+ const countOf = useCallback(
337
+ (n) => localCounts[`${documentId}@${n}`] ?? versions.find((v) => v.n === n)?.markup_count ?? 0,
338
+ [localCounts, documentId, versions]
339
+ );
340
+ const hasMarkup = countOf(shownVersion) > 0;
341
+ const [showOriginal, setShowOriginal] = useState(false);
342
+ useEffect(() => setShowOriginal(false), [documentId, snapshotVersion]);
343
+ const refresh = useCallback(() => {
344
+ if (!documentId || !onDocumentsChanged) return;
345
+ Promise.resolve(onDocumentsChanged([documentId], "markup")).catch(
346
+ (e) => console.warn("Could not refresh the document after a markup change", e)
347
+ );
348
+ }, [documentId, onDocumentsChanged]);
349
+ const onMarkupChange = useCallback(
350
+ (snapshot) => {
351
+ if (!documentId) return;
352
+ const key = `${documentId}@${shownVersion}`;
353
+ if (countOf(shownVersion) > 0 !== snapshot.count > 0) refresh();
354
+ setLocalCounts((counts) => ({ ...counts, [key]: snapshot.count }));
355
+ },
356
+ [documentId, shownVersion, countOf, refresh]
357
+ );
358
+ const downloadMarkup = useCallback(async () => {
359
+ if (!documentId) return;
360
+ if (currentSigned) {
361
+ notify(SIGNED_LOCKED_REASON, "info");
362
+ return;
363
+ }
364
+ try {
365
+ const { blob, fileName } = await fetchMarkupPdf(
366
+ client,
367
+ documentId,
368
+ snapshotVersion ? snapshotVersion : void 0
369
+ );
370
+ saveFile(blob, fileName);
371
+ } catch (e) {
372
+ notify(e instanceof Error ? e.message : "The markup could not be downloaded", "error");
373
+ }
374
+ }, [client, documentId, snapshotVersion, saveFile, notify, currentSigned]);
375
+ const [legacyCount, setLegacyCount] = useState(0);
376
+ const [migrating, setMigrating] = useState(false);
377
+ const shared = documentData?.shared;
378
+ const loaded = !!documentData;
379
+ const migrate = useCallback(async () => {
380
+ if (!documentId) return;
381
+ const layer = readLegacyLayer(documentId);
382
+ if (!layer) return;
383
+ setMigrating(true);
384
+ try {
385
+ const added = await migrateLegacyLayer(documentId, layer, versions, currentVersion, client);
386
+ setLegacyCount(0);
387
+ setLocalCounts({});
388
+ refresh();
389
+ if (added > 0) {
390
+ notify(
391
+ `${added} annotation${added === 1 ? "" : "s"} from this browser saved to the document`,
392
+ "success",
393
+ {
394
+ description: shared ? "They are now part of the shared markup." : "They are saved with the document, visible only to you."
395
+ }
396
+ );
397
+ }
398
+ } catch (e) {
399
+ notify(
400
+ e instanceof Error ? e.message : "The annotations from this browser could not be saved",
401
+ "error",
402
+ { description: "They are still kept in this browser; open the document again to retry." }
403
+ );
404
+ } finally {
405
+ setMigrating(false);
406
+ }
407
+ }, [client, documentId, versions, currentVersion, refresh, shared, notify]);
408
+ useEffect(() => {
409
+ if (!documentId || !loaded) return;
410
+ const layer = readLegacyLayer(documentId);
411
+ if (!layer) {
412
+ setLegacyCount(0);
413
+ return;
414
+ }
415
+ if (layer.annotations.length === 0) {
416
+ forgetLegacyLayer(documentId);
417
+ setLegacyCount(0);
418
+ return;
419
+ }
420
+ if (shared) setLegacyCount(layer.annotations.length);
421
+ else void migrate();
422
+ }, [documentId, loaded, shared]);
423
+ const legacyPrompt = legacyCount > 0 && !snapshotVersion ? {
424
+ count: legacyCount,
425
+ busy: migrating,
426
+ add: () => void migrate(),
427
+ discard: () => {
428
+ if (documentId) forgetLegacyLayer(documentId);
429
+ setLegacyCount(0);
430
+ }
431
+ } : null;
432
+ const [copying, setCopying] = useState(false);
433
+ const olderWithMarkup = versionsWithMarkup(versions).filter((v) => v.n !== currentVersion).sort((a, b) => b.n - a.n)[0];
434
+ const olderNote = !snapshotVersion && !hasMarkup && olderWithMarkup ? {
435
+ version: olderWithMarkup.n,
436
+ busy: copying,
437
+ signed: currentSigned,
438
+ copy: () => {
439
+ if (!documentId) return;
440
+ setCopying(true);
441
+ copyOpenThreads(documentId, olderWithMarkup.n, client).then((n) => {
442
+ if (n > 0) {
443
+ setLocalCounts((c) => ({ ...c, [`${documentId}@${currentVersion}`]: n }));
444
+ refresh();
445
+ }
446
+ notify(
447
+ n > 0 ? `${n} open comment thread${n === 1 ? "" : "s"} copied to version ${currentVersion}` : `Version ${olderWithMarkup.n} has no open comments`,
448
+ n > 0 ? "success" : "info",
449
+ // The markup is stored beside the version, so the sealed bytes do not change.
450
+ n > 0 && currentSigned ? { description: SIGNED_UNCHANGED } : void 0
451
+ );
452
+ }).catch(
453
+ (e) => notify(e instanceof Error ? e.message : "The comments could not be copied", "error")
454
+ ).finally(() => setCopying(false));
455
+ }
456
+ } : null;
457
+ return {
458
+ hasMarkup,
459
+ showOriginal,
460
+ setShowOriginal,
461
+ onMarkupChange,
462
+ downloadMarkup,
463
+ legacyPrompt,
464
+ olderNote
465
+ };
466
+ }
467
+
468
+ // src/document-tools/frozen-copy.ts
469
+ var baseName = (fileName) => (fileName || "document").replace(/\.pdf$/i, "");
470
+ function frozenCopyName(fileName, redacted) {
471
+ return `${baseName(fileName)} (${redacted ? "redacted" : "annotated"}).pdf`;
472
+ }
473
+ function redactionLogName(fileName) {
474
+ return `${baseName(fileName)} (redaction log).csv`;
475
+ }
476
+ async function uploadFrozenCopy(upload, bytes, source, redacted) {
477
+ const file = new File([bytes], frozenCopyName(source.fileName, redacted), {
478
+ type: "application/pdf"
479
+ });
480
+ const query = {
481
+ derived_from: source.documentId,
482
+ derived_role: redacted ? "redaction" : "annotated",
483
+ shared: String(source.shared)
484
+ };
485
+ if (source.folder) query.folder = source.folder;
486
+ const response = await upload({ file, query });
487
+ return response?.doc_ext_ids?.[0];
488
+ }
489
+
490
+ // src/document-tools/can-annotate.ts
491
+ function canAnnotate(s) {
492
+ return s.activeTab === "pdf" && s.hasPdf && !s.isImage && !s.isVideo && !s.isAudio && !s.isDownloadOnly && !s.isDraft && !s.isStreaming && !s.isSnapshot && !s.isComparing;
493
+ }
494
+ function useIsOnline() {
495
+ return useSyncExternalStore(
496
+ (onChange) => onlineManager.subscribe(onChange),
497
+ () => onlineManager.isOnline(),
498
+ () => true
499
+ );
500
+ }
501
+ function intentText(signer) {
502
+ return `I, ${signer.name.trim()}, sign this document electronically. I intend this electronic signature to have the same effect as my handwritten signature.`;
503
+ }
504
+ async function sha256Hex(blob) {
505
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(await blob.arrayBuffer()));
506
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
507
+ }
508
+ function toAppearance(box) {
509
+ return { page: box.page - 1, x: box.rect.x, y: box.rect.y, width: box.rect.w, height: box.rect.h };
510
+ }
511
+ var MIN_SIGNATURE_BOX = { width: 0.3, height: 0.07 };
512
+ function isLegibleSignatureBox(rect) {
513
+ return rect.w >= MIN_SIGNATURE_BOX.width && rect.h >= MIN_SIGNATURE_BOX.height;
514
+ }
515
+ var SIGNATURES_PATH = "/v1/document/{document_ext_id}/signatures";
516
+ var SIGNATURES_KEY = ["get", SIGNATURES_PATH];
517
+ function errorDetail(error, fallback) {
518
+ const detail = error?.detail;
519
+ return typeof detail === "string" ? detail : fallback;
520
+ }
521
+ async function fetchDocumentSignatures(client, documentRef) {
522
+ const { docId, version } = parseVersionRef(documentRef);
523
+ const { data, error } = await client.GET(SIGNATURES_PATH, {
524
+ params: { path: { document_ext_id: docId }, ...version ? { query: { version } } : {} }
525
+ });
526
+ if (!data) throw new Error(errorDetail(error, "The signatures could not be read"));
527
+ return data;
528
+ }
529
+ function useDocumentSignatures(documentId, enabled = true) {
530
+ const { client } = useDocumentTools();
531
+ const { docId, version } = parseVersionRef(documentId);
532
+ return useQuery({
533
+ queryKey: [
534
+ ...SIGNATURES_KEY,
535
+ { params: { path: { document_ext_id: docId }, ...version ? { query: { version } } : {} } }
536
+ ],
537
+ queryFn: () => fetchDocumentSignatures(client, documentId),
538
+ enabled: enabled && !!docId,
539
+ staleTime: 6e4
540
+ });
541
+ }
542
+ async function signDocument(client, deploymentDomain, {
543
+ documentId,
544
+ pdfBlob,
545
+ email,
546
+ password,
547
+ signer,
548
+ appearance,
549
+ includeDate = false
550
+ }) {
551
+ const path = { document_ext_id: documentId };
552
+ const body = {
553
+ signer: { name: signer.name },
554
+ ...appearance ? { appearance } : {},
555
+ include_date: includeDate
556
+ };
557
+ const prepared = await client.POST("/v1/document/{document_ext_id}/sign/prepare", {
558
+ params: { path },
559
+ body
560
+ });
561
+ if (!prepared.data) throw new Error(errorDetail(prepared.error, "Could not prepare signing"));
562
+ const { statement, intent, source_sha256, timestamp } = prepared.data;
563
+ if (await sha256Hex(pdfBlob) !== source_sha256) {
564
+ throw new Error("The document changed since it was opened. Reopen it and sign again.");
565
+ }
566
+ if (intent !== intentText(signer)) throw new Error("Signing statement mismatch; not signed.");
567
+ const { signingKeyPair } = await generateUserKeypairs(email, password, deploymentDomain);
568
+ const signed = await client.POST("/v1/document/{document_ext_id}/sign", {
569
+ params: { path },
570
+ body: { ...body, timestamp, signature: signMessage(statement, signingKeyPair.secretKey) }
571
+ });
572
+ if (!signed.data) throw new Error(errorDetail(signed.error, "Signing failed"));
573
+ return signed.data;
574
+ }
575
+ function useSignDocument() {
576
+ const env = useDocumentTools();
577
+ const queryClient = useQueryClient();
578
+ return useMutation({
579
+ mutationFn: (vars) => {
580
+ if (!env.deploymentDomain) throw new Error("Signing is not set up: no deployment domain");
581
+ return signDocument(env.client, env.deploymentDomain, vars);
582
+ },
583
+ onSuccess: async (result) => {
584
+ await env.onDocumentsChanged?.([result.doc_ext_id], "signed");
585
+ await queryClient.invalidateQueries({ queryKey: SIGNATURES_KEY });
586
+ }
587
+ });
588
+ }
589
+ var VERIFY_PATH = "/v1/sign/verify/{reference}";
590
+ var REFERENCE = /^sig-[0-9a-f]{32}$/;
591
+ function isSignatureReference(reference) {
592
+ return !!reference && REFERENCE.test(reference);
593
+ }
594
+ var SignatureVerificationError = class extends Error {
595
+ constructor(message, status) {
596
+ super(message);
597
+ this.status = status;
598
+ this.name = "SignatureVerificationError";
599
+ }
600
+ status;
601
+ };
602
+ var VERIFY_ERRORS = {
603
+ 404: "No signature has this reference.",
604
+ 429: "Too many checks, try again in a minute."
605
+ };
606
+ async function fetchSignatureVerification(client, reference) {
607
+ if (!isSignatureReference(reference)) {
608
+ throw new SignatureVerificationError("This is not a signature reference.");
609
+ }
610
+ const { data, response } = await client.GET(VERIFY_PATH, {
611
+ params: { path: { reference } }
612
+ });
613
+ if (!response.ok || !data) {
614
+ throw new SignatureVerificationError(
615
+ VERIFY_ERRORS[response.status] ?? "The signature could not be checked right now.",
616
+ response.status
617
+ );
618
+ }
619
+ return data;
620
+ }
621
+ function useSignatureVerification(reference) {
622
+ const { client } = useDocumentTools();
623
+ return useQuery({
624
+ queryKey: ["get", VERIFY_PATH, { params: { path: { reference } } }],
625
+ queryFn: () => fetchSignatureVerification(client, reference),
626
+ enabled: !!reference,
627
+ retry: false
628
+ });
629
+ }
630
+ async function matchSignedCopy(file, verification) {
631
+ const hash = await sha256Hex(file);
632
+ if (hash === verification.document_sha256.toLowerCase()) return { kind: "current" };
633
+ const signature = verification.signatures.find((s) => s.sha256.toLowerCase() === hash);
634
+ return signature ? { kind: "earlier", signature } : { kind: "none" };
635
+ }
636
+
637
+ export { DocumentToolsProvider, LEGACY_LAYER_PREFIX, MAX_MERGE_ATTEMPTS, MarkupDownloadError, MarkupStoreError, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, SignatureVerificationError, VERIFY_PATH, addToMarkup, canAnnotate, clientUpload, copyOpenThreads, createMarkupStore, currentHasMarkup, defaultCertificateUrl, downloadBlob, fetchDocumentSignatures, fetchMarkupPdf, fetchSignatureVerification, forgetLegacyLayer, frozenCopyName, intentText, isLegibleSignatureBox, isSignatureReference, isSignedVersion, marksByVersion, matchSignedCopy, migrateLegacyLayer, openThreadsOf, readLegacyLayer, redactionLogName, sha256Hex, signDocument, toAppearance, uploadFrozenCopy, useDocumentMarkup, useDocumentSignatures, useDocumentTools, useIsOnline, useSignDocument, useSignatureVerification, versionsWithMarkup };
638
+ //# sourceMappingURL=index.js.map
639
+ //# sourceMappingURL=index.js.map