@arbidocs/react 0.4.70 → 0.4.72

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 (75) hide show
  1. package/README.md +6 -4
  2. package/dist/ProductionDialog-BRrZ5Lj5.d.cts +84 -0
  3. package/dist/ProductionDialog-DUC9BXWS.d.ts +84 -0
  4. package/dist/annotations/freeze/index.cjs +45 -1100
  5. package/dist/annotations/freeze/index.cjs.map +1 -1
  6. package/dist/annotations/freeze/index.d.cts +2 -85
  7. package/dist/annotations/freeze/index.d.ts +2 -85
  8. package/dist/annotations/freeze/index.js +4 -1084
  9. package/dist/annotations/freeze/index.js.map +1 -1
  10. package/dist/annotations/index.cjs +48 -48
  11. package/dist/annotations/index.d.cts +3 -51
  12. package/dist/annotations/index.d.ts +3 -51
  13. package/dist/annotations/index.js +2 -2
  14. package/dist/artifacts/index.cjs +9 -9
  15. package/dist/artifacts/index.js +2 -2
  16. package/dist/bundle-BnCSbHy2.d.cts +85 -0
  17. package/dist/bundle-BnCSbHy2.d.ts +85 -0
  18. package/dist/bundle-N2JIJ2T6.js +4 -0
  19. package/dist/bundle-N2JIJ2T6.js.map +1 -0
  20. package/dist/bundle-T6BEVYHE.cjs +13 -0
  21. package/dist/bundle-T6BEVYHE.cjs.map +1 -0
  22. package/dist/{chunk-7CL7QHT6.cjs → chunk-GE5TAR7Y.cjs} +26 -25
  23. package/dist/chunk-GE5TAR7Y.cjs.map +1 -0
  24. package/dist/{chunk-3QF5DNAP.js → chunk-IHTBAY57.js} +3 -3
  25. package/dist/{chunk-3QF5DNAP.js.map → chunk-IHTBAY57.js.map} +1 -1
  26. package/dist/{chunk-ZMTLGO3K.cjs → chunk-IIT7DMQL.cjs} +6 -2
  27. package/dist/chunk-IIT7DMQL.cjs.map +1 -0
  28. package/dist/{chunk-SYPUFZGA.js → chunk-IQ5TYPVU.js} +4 -3
  29. package/dist/chunk-IQ5TYPVU.js.map +1 -0
  30. package/dist/{chunk-ULU5LEWF.cjs → chunk-L2PXZWJM.cjs} +25 -25
  31. package/dist/{chunk-ULU5LEWF.cjs.map → chunk-L2PXZWJM.cjs.map} +1 -1
  32. package/dist/{chunk-V4CXOPLB.js → chunk-MHCN7OST.js} +19 -7
  33. package/dist/{chunk-V4CXOPLB.js.map → chunk-MHCN7OST.js.map} +1 -1
  34. package/dist/{chunk-BTRIS3HY.cjs → chunk-QJRP2LLQ.cjs} +19 -6
  35. package/dist/chunk-QJRP2LLQ.cjs.map +1 -0
  36. package/dist/chunk-QJXFRP5R.cjs +1103 -0
  37. package/dist/chunk-QJXFRP5R.cjs.map +1 -0
  38. package/dist/{chunk-J4MX2W4H.js → chunk-WBYNKFUO.js} +6 -3
  39. package/dist/chunk-WBYNKFUO.js.map +1 -0
  40. package/dist/{chunk-LQ5YHB7W.cjs → chunk-WYZJLZ67.cjs} +6 -4
  41. package/dist/chunk-WYZJLZ67.cjs.map +1 -0
  42. package/dist/{chunk-WS6DF5X4.js → chunk-YNNAJJ5Z.js} +6 -4
  43. package/dist/chunk-YNNAJJ5Z.js.map +1 -0
  44. package/dist/chunk-ZJMUNGOY.js +1088 -0
  45. package/dist/chunk-ZJMUNGOY.js.map +1 -0
  46. package/dist/document-tools/index.cjs +226 -11
  47. package/dist/document-tools/index.cjs.map +1 -1
  48. package/dist/document-tools/index.d.cts +139 -9
  49. package/dist/document-tools/index.d.ts +139 -9
  50. package/dist/document-tools/index.js +207 -9
  51. package/dist/document-tools/index.js.map +1 -1
  52. package/dist/{index-BWv_FKi3.d.cts → index-BVMBElCu.d.cts} +82 -1
  53. package/dist/{index-BWv_FKi3.d.ts → index-BVMBElCu.d.ts} +82 -1
  54. package/dist/index.cjs +688 -369
  55. package/dist/index.cjs.map +1 -1
  56. package/dist/index.d.cts +208 -4
  57. package/dist/index.d.ts +208 -4
  58. package/dist/index.js +313 -11
  59. package/dist/index.js.map +1 -1
  60. package/dist/ui/index.cjs +137 -133
  61. package/dist/ui/index.d.cts +1 -1
  62. package/dist/ui/index.d.ts +1 -1
  63. package/dist/ui/index.js +2 -2
  64. package/dist/viewers/index.cjs +2 -2
  65. package/dist/viewers/index.js +1 -1
  66. package/package.json +4 -3
  67. package/dist/chunk-7CL7QHT6.cjs.map +0 -1
  68. package/dist/chunk-BTRIS3HY.cjs.map +0 -1
  69. package/dist/chunk-J4MX2W4H.js.map +0 -1
  70. package/dist/chunk-LQ5YHB7W.cjs.map +0 -1
  71. package/dist/chunk-SYPUFZGA.js.map +0 -1
  72. package/dist/chunk-WS6DF5X4.js.map +0 -1
  73. package/dist/chunk-ZMTLGO3K.cjs.map +0 -1
  74. package/dist/store-CqkkD7Ho.d.cts +0 -35
  75. package/dist/store-D1nhbkgk.d.ts +0 -35
@@ -1,7 +1,8 @@
1
1
  import * as React from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { ArbiClient, components } from '@arbidocs/client';
4
- import { A as AnnotationStore } from '../store-D1nhbkgk.js';
3
+ import { ArbiClient, operations, components } from '@arbidocs/client';
4
+ import { P as ProductionChoices, A as AnnotationStore } from '../ProductionDialog-DUC9BXWS.js';
5
+ import { a as BundleFile, b as BundleIndexEntry } from '../bundle-BnCSbHy2.js';
5
6
  import { A as Annotation, b as AnnotationLayer } from '../model-DIwXRuGC.js';
6
7
  import * as _tanstack_react_query from '@tanstack/react-query';
7
8
 
@@ -31,14 +32,27 @@ type DocumentChange =
31
32
  | 'signed'
32
33
  /** A new document was made from it (a frozen copy). The ids are the NEW documents. */
33
34
  | 'copy';
35
+ /**
36
+ * The `/v1/document/upload` query, typed from the API schema: `derived_from` is a list (a
37
+ * production set is derived from every document in it), `shared` a boolean.
38
+ */
39
+ type DocumentUploadQuery = NonNullable<operations['upload_documents']['parameters']['query']>;
34
40
  interface DocumentUploadRequest {
35
41
  file: File;
36
42
  /** `/v1/document/upload` query: `derived_from`, `derived_role`, `shared`, `folder`. */
37
- query: Record<string, string>;
43
+ query: DocumentUploadQuery;
38
44
  }
45
+ /**
46
+ * The upload query as a URL query string, for a host that posts the upload itself (an XHR with
47
+ * progress): a list repeats its key (`derived_from=a&derived_from=b`), empty values are left out.
48
+ */
49
+ declare function uploadQueryString(query: DocumentUploadQuery): string;
39
50
  interface DocumentToolsEnvironment {
40
51
  client: DocumentToolsClient;
41
- /** The deployment domain the user's keys are derived for. Needed for signing. */
52
+ /**
53
+ * The deployment domain the user's keys are derived for. Needed for signing. Default: the one
54
+ * the enclosing `<ArbiProvider>`'s `Arbi` computes (`arbi.getDeploymentDomain()`), if any.
55
+ */
42
56
  deploymentDomain?: string;
43
57
  /** The signed-in user; marks are authored as "You" without one, and signing is unavailable. */
44
58
  user?: DocumentToolsUser | null;
@@ -60,8 +74,10 @@ interface DocumentToolsEnvironment {
60
74
  /** Email a document (offered once it is signed). Omitted: no "Email it". */
61
75
  emailDocument?: (documentRef: string) => void;
62
76
  /**
63
- * The public page that checks a signature (the certificate), when the backend did not return
64
- * one. Default: `/verify/{reference}` on this origin.
77
+ * The public page that checks a signature (the certificate) in this app. When given, "View
78
+ * certificate" opens it in preference to the backend's `certificate_url` (which is on the
79
+ * deployment domain, like the link embedded in the signed PDF). Without it: the backend's
80
+ * `certificate_url`, else `/verify/{reference}` on this origin.
65
81
  */
66
82
  certificateUrl?: (reference: string) => string;
67
83
  }
@@ -72,22 +88,136 @@ interface ResolvedDocumentToolsEnvironment extends DocumentToolsEnvironment {
72
88
  uploadDocument: (request: DocumentUploadRequest) => Promise<{
73
89
  doc_ext_ids?: string[];
74
90
  } | undefined>;
75
- certificateUrl: (reference: string) => string;
76
91
  }
77
92
  /** Save a blob through a temporary `<a download>`. */
78
93
  declare function downloadBlob(blob: Blob, fileName: string): void;
79
94
  /** The default upload: multipart `files` to `/v1/document/upload` through the API client. */
80
95
  declare function clientUpload(client: DocumentToolsClient): ({ file, query }: DocumentUploadRequest) => Promise<{
81
- doc_ext_ids?: string[];
96
+ doc_ext_ids?: string[] | undefined;
97
+ version?: number | null | undefined;
98
+ batch_id?: string | null | undefined;
99
+ skipped?: {
100
+ file_name: string;
101
+ reason: string;
102
+ }[] | undefined;
82
103
  } | undefined>;
83
104
  declare function defaultCertificateUrl(reference: string): string;
105
+ /**
106
+ * Where "View certificate" goes for a signature: the host's `certificateUrl(reference)` when it
107
+ * gives one, else the `certificate_url` the backend returned, else `/verify/{reference}` here.
108
+ */
109
+ declare function certificateLink(signature: {
110
+ reference: string;
111
+ certificate_url?: string | null;
112
+ }, certificateUrl?: (reference: string) => string): string;
84
113
  interface DocumentToolsProviderProps extends DocumentToolsEnvironment {
85
114
  children: ReactNode;
86
115
  }
87
116
  declare function DocumentToolsProvider({ children, ...env }: DocumentToolsProviderProps): React.JSX.Element;
117
+ /** The host's environment, or `null` outside a `<DocumentToolsProvider>`. */
118
+ declare function useOptionalDocumentTools(): ResolvedDocumentToolsEnvironment | null;
88
119
  /** The host's environment; throws outside a `<DocumentToolsProvider>`. */
89
120
  declare function useDocumentTools(): ResolvedDocumentToolsEnvironment;
90
121
 
122
+ /**
123
+ * A document's bytes, through the host's API client: the PDF the viewer and the tools draw on
124
+ * (`/view`: the file itself for a PDF, its PDF rendering for a Word or text file) and the stored
125
+ * file (`/download`). Either takes a document id or a version reference `doc-…@v{n}`.
126
+ */
127
+
128
+ interface DocumentFetchOptions {
129
+ /** The version to fetch. Default: the one `documentRef` names, else the current version. */
130
+ version?: number | null;
131
+ signal?: AbortSignal;
132
+ }
133
+ /** A document's bytes could not be fetched; `status` is the HTTP status. */
134
+ declare class DocumentFetchError extends Error {
135
+ readonly status: number;
136
+ constructor(message: string, status: number);
137
+ }
138
+ /**
139
+ * The PDF of a document version: `GET /v1/document/{id}/view?version=` with
140
+ * `Accept: application/pdf`. Throws a {@link DocumentFetchError} when there is none (yet).
141
+ */
142
+ declare function fetchDocumentPdf(client: DocumentToolsClient, documentRef: string, options?: DocumentFetchOptions): Promise<Blob>;
143
+ /** The stored file of a document version, as uploaded: `GET /v1/document/{id}/download`. */
144
+ declare function fetchDocumentFile(client: DocumentToolsClient, documentRef: string, options?: DocumentFetchOptions): Promise<Blob>;
145
+
146
+ /**
147
+ * Production sets: number the selected documents with Bates labels (optionally a QR code back to
148
+ * each document and an index page) and save the result back to the workspace. The dialog is
149
+ * `ProductionSetDialog` in `@arbidocs/blocks/document-tools`; this is its data side.
150
+ *
151
+ * A PDF is numbered as stored (`/download`). Any other document is numbered through its PDF
152
+ * rendition (`/view`, what the viewer shows for a Word or text file); one without a rendition is
153
+ * left out. Saved results are new documents derived from their sources (role `production`) in a
154
+ * Productions folder, shared with the workspace only if every source is. The originals never
155
+ * change.
156
+ *
157
+ * pdf-lib (the numbering) is loaded only when a production is built, so importing this module
158
+ * stays as light as the rest of the document tools.
159
+ */
160
+
161
+ /** The fields of a document record (`DocResponse`) a production uses. */
162
+ type ProductionSource = Pick<components['schemas']['DocResponse'], 'external_id' | 'file_name' | 'file_type' | 'shared'> & {
163
+ doc_metadata?: {
164
+ title?: string | null;
165
+ } | null;
166
+ };
167
+ declare const PRODUCTIONS_FOLDER = "Productions";
168
+ declare const isPdfDocument: (doc: ProductionSource) => boolean;
169
+ /** True for a document with no PDF version to number (media, archives and the like). */
170
+ declare const hasNoRendition: (doc: ProductionSource) => boolean;
171
+ /** The name a document goes by in the dialog and the index: its title, else its file name. */
172
+ declare const productionDocumentName: (doc: ProductionSource) => string;
173
+ /**
174
+ * The PDF to number for `doc`: the file itself, or the PDF version of anything else. `null` when a
175
+ * non-PDF has no PDF version (yet), so it is left out; a PDF that cannot be downloaded throws.
176
+ */
177
+ declare function fetchProductionPdf(client: DocumentToolsClient, doc: ProductionSource): Promise<Uint8Array | null>;
178
+ /** "Production ACME-000001-ACME-000042": names the files and folder of one production. */
179
+ declare function productionTitle(firstLabel: string, lastLabel: string): string;
180
+ /** Where a production is saved: the Productions folder, or a folder of its own per document. */
181
+ declare function productionFolder(title: string, merged: boolean): string;
182
+ /** In the workspace a per-document file says which range it holds, beside its original. */
183
+ declare function productionFileName(file: BundleFile, title: string): string;
184
+ /** The `index.csv` of a per-document production: every document with its file and range. */
185
+ declare function productionIndexCsv(index: readonly BundleIndexEntry[]): string;
186
+ interface ProductionUpload {
187
+ name: string;
188
+ bytes: Uint8Array;
189
+ /** The documents this file was made from. */
190
+ sources: ProductionSource[];
191
+ }
192
+ /** Save each file as a new workspace document derived from its sources; returns the new ids. */
193
+ declare function saveProductionFiles(upload: NonNullable<DocumentToolsEnvironment['uploadDocument']>, files: readonly ProductionUpload[], folder: string): Promise<string[]>;
194
+ interface BuildProductionOptions {
195
+ /** The link a document's QR code opens (the document in the host app). */
196
+ documentUrl: (documentId: string) => string;
197
+ /** Who produced the set; recorded in a merged file's metadata. */
198
+ author?: string;
199
+ onProgress?: (done: number, total: number) => void;
200
+ }
201
+ interface BuiltProduction {
202
+ title: string;
203
+ merged: boolean;
204
+ /** The numbered files: one merged PDF (named after its range), or one per document (+ index). */
205
+ files: BundleFile[];
206
+ index: BundleIndexEntry[];
207
+ /** The documents numbered, in order. */
208
+ included: ProductionSource[];
209
+ /** Documents left out because they have no PDF version yet. */
210
+ noRendition: ProductionSource[];
211
+ /** The files as they are saved to the workspace, each with the documents it was made from. */
212
+ uploads: ProductionUpload[];
213
+ folder: string;
214
+ }
215
+ /**
216
+ * Fetch each document's PDF (in `choices.order`) and number the set. Throws when none of the
217
+ * documents has a PDF version, or when a PDF cannot be fetched.
218
+ */
219
+ declare function buildProduction(client: DocumentToolsClient, documents: readonly ProductionSource[], choices: ProductionChoices, options: BuildProductionOptions): Promise<BuiltProduction>;
220
+
91
221
  /**
92
222
  * The annotation store for a document version's MARKUP on the server: `GET`/`PUT
93
223
  * /v1/document/{id}/markup`. The server keeps the marks as native PDF annotations in an encrypted
@@ -389,4 +519,4 @@ type CopyMatch = {
389
519
  /** Compare a file with the signed PDF and its signed revisions. Hashed here; nothing is uploaded. */
390
520
  declare function matchSignedCopy(file: Blob, verification: Pick<SignatureVerification, 'document_sha256' | 'signatures'>): Promise<CopyMatch>;
391
521
 
392
- export { type AnnotatableState, type CopyMatch, type DocumentChange, type DocumentToolsClient, type DocumentToolsEnvironment, type DocumentToolsNoticeKind, type DocumentToolsNoticeOptions, type DocumentToolsNotify, DocumentToolsProvider, type DocumentToolsProviderProps, type DocumentToolsUser, type DocumentUploadRequest, type FrozenCopySource, LEGACY_LAYER_PREFIX, type LegacyPrompt, MAX_MERGE_ATTEMPTS, type MarkupDocument, MarkupDownloadError, type MarkupSnapshot, type MarkupStore, MarkupStoreError, type MarkupStoreOptions, type OlderMarkupNote, type ResolvedDocumentToolsEnvironment, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, type SignDocumentResponse, type SignDocumentVars, type SignatureAppearance, type SignatureRecord, type SignatureStatusResponse, type SignatureVerification, SignatureVerificationError, type SignerDetails, VERIFY_PATH, type VerifiedSignature, type VersionInfo, 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 };
522
+ export { type AnnotatableState, type BuildProductionOptions, type BuiltProduction, type CopyMatch, type DocumentChange, DocumentFetchError, type DocumentFetchOptions, type DocumentToolsClient, type DocumentToolsEnvironment, type DocumentToolsNoticeKind, type DocumentToolsNoticeOptions, type DocumentToolsNotify, DocumentToolsProvider, type DocumentToolsProviderProps, type DocumentToolsUser, type DocumentUploadQuery, type DocumentUploadRequest, type FrozenCopySource, LEGACY_LAYER_PREFIX, type LegacyPrompt, MAX_MERGE_ATTEMPTS, type MarkupDocument, MarkupDownloadError, type MarkupSnapshot, type MarkupStore, MarkupStoreError, type MarkupStoreOptions, type OlderMarkupNote, PRODUCTIONS_FOLDER, type ProductionSource, type ProductionUpload, type ResolvedDocumentToolsEnvironment, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, type SignDocumentResponse, type SignDocumentVars, type SignatureAppearance, type SignatureRecord, type SignatureStatusResponse, type SignatureVerification, SignatureVerificationError, type SignerDetails, VERIFY_PATH, type VerifiedSignature, type VersionInfo, addToMarkup, buildProduction, canAnnotate, certificateLink, clientUpload, copyOpenThreads, createMarkupStore, currentHasMarkup, defaultCertificateUrl, downloadBlob, fetchDocumentFile, fetchDocumentPdf, fetchDocumentSignatures, fetchMarkupPdf, fetchProductionPdf, fetchSignatureVerification, forgetLegacyLayer, frozenCopyName, hasNoRendition, intentText, isLegibleSignatureBox, isPdfDocument, isSignatureReference, isSignedVersion, marksByVersion, matchSignedCopy, migrateLegacyLayer, openThreadsOf, productionDocumentName, productionFileName, productionFolder, productionIndexCsv, productionTitle, readLegacyLayer, redactionLogName, saveProductionFiles, sha256Hex, signDocument, toAppearance, uploadFrozenCopy, uploadQueryString, useDocumentMarkup, useDocumentSignatures, useDocumentTools, useIsOnline, useOptionalDocumentTools, useSignDocument, useSignatureVerification, versionsWithMarkup };
@@ -1,10 +1,11 @@
1
+ import { mergeLayers, AnnotationStoreOfflineError } from '../chunk-IHTBAY57.js';
2
+ import { parseLayer, emptyLayer, LAYER_SCHEMA_VERSION } from '../chunk-COWZGCL5.js';
1
3
  import { parseVersionRef } from '../chunk-HKUD2NZN.js';
2
4
  import '../chunk-G6FHNURH.js';
3
5
  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 { useDeploymentDomain } from '../chunk-WBYNKFUO.js';
7
+ import '../chunk-YNNAJJ5Z.js';
6
8
  import '../chunk-QRCMKEE6.js';
7
- import '../chunk-WS6DF5X4.js';
8
9
  import '../chunk-47CCGUWR.js';
9
10
  import '../chunk-SN5YV6FF.js';
10
11
  import { createContext, useMemo, useContext, useState, useCallback, useEffect, useSyncExternalStore } from 'react';
@@ -12,6 +13,14 @@ import { jsx } from 'react/jsx-runtime';
12
13
  import { onlineManager, useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
13
14
  import { generateUserKeypairs, signMessage } from '@arbidocs/client';
14
15
 
16
+ function uploadQueryString(query) {
17
+ const params = new URLSearchParams();
18
+ for (const [key, value] of Object.entries(query)) {
19
+ if (value === null || value === void 0) continue;
20
+ for (const item of Array.isArray(value) ? value : [value]) params.append(key, String(item));
21
+ }
22
+ return params.toString();
23
+ }
15
24
  function downloadBlob(blob, fileName) {
16
25
  const url = URL.createObjectURL(blob);
17
26
  const a = document.createElement("a");
@@ -28,8 +37,9 @@ function clientUpload(client) {
28
37
  formData.append("files", file);
29
38
  const { data, response } = await client.POST("/v1/document/upload", {
30
39
  params: { query },
40
+ // The schema types the multipart body as `{ files: string[] }`; the FormData is sent as is.
31
41
  body: formData,
32
- bodySerializer: (body) => body
42
+ bodySerializer: () => formData
33
43
  });
34
44
  if (!response.ok) throw new Error(`Upload failed with status ${response.status}`);
35
45
  return data;
@@ -39,8 +49,13 @@ function defaultCertificateUrl(reference) {
39
49
  const origin = typeof location === "undefined" ? "" : location.origin;
40
50
  return `${origin}/verify/${encodeURIComponent(reference)}`;
41
51
  }
52
+ function certificateLink(signature, certificateUrl) {
53
+ if (certificateUrl) return certificateUrl(signature.reference);
54
+ return signature.certificate_url || defaultCertificateUrl(signature.reference);
55
+ }
42
56
  var DocumentToolsContext = createContext(null);
43
57
  function DocumentToolsProvider({ children, ...env }) {
58
+ const arbiDeploymentDomain = useDeploymentDomain();
44
59
  const {
45
60
  client,
46
61
  deploymentDomain,
@@ -56,7 +71,7 @@ function DocumentToolsProvider({ children, ...env }) {
56
71
  const value = useMemo(
57
72
  () => ({
58
73
  client,
59
- deploymentDomain,
74
+ deploymentDomain: deploymentDomain ?? arbiDeploymentDomain,
60
75
  user,
61
76
  openDocument,
62
77
  onDocumentsChanged,
@@ -65,11 +80,12 @@ function DocumentToolsProvider({ children, ...env }) {
65
80
  }),
66
81
  saveFile: saveFile ?? downloadBlob,
67
82
  uploadDocument: uploadDocument ?? clientUpload(client),
68
- certificateUrl: certificateUrl ?? defaultCertificateUrl
83
+ certificateUrl
69
84
  }),
70
85
  [
71
86
  client,
72
87
  deploymentDomain,
88
+ arbiDeploymentDomain,
73
89
  user,
74
90
  notify,
75
91
  openDocument,
@@ -82,12 +98,194 @@ function DocumentToolsProvider({ children, ...env }) {
82
98
  );
83
99
  return /* @__PURE__ */ jsx(DocumentToolsContext.Provider, { value, children });
84
100
  }
101
+ function useOptionalDocumentTools() {
102
+ return useContext(DocumentToolsContext);
103
+ }
85
104
  function useDocumentTools() {
86
105
  const env = useContext(DocumentToolsContext);
87
106
  if (!env) throw new Error("The document tools must be used within a <DocumentToolsProvider>");
88
107
  return env;
89
108
  }
90
109
 
110
+ // src/document-tools/document-pdf.ts
111
+ var DocumentFetchError = class extends Error {
112
+ status;
113
+ constructor(message, status) {
114
+ super(message);
115
+ this.name = "DocumentFetchError";
116
+ this.status = status;
117
+ }
118
+ };
119
+ async function fetchDocumentBytes(client, endpoint, documentRef, options, headers, what) {
120
+ const ref = parseVersionRef(documentRef);
121
+ const version = options.version ?? ref.version;
122
+ const { data, response } = await client.GET(endpoint, {
123
+ params: { path: { document_ext_id: ref.docId }, query: version ? { version } : {} },
124
+ headers,
125
+ parseAs: "blob",
126
+ signal: options.signal
127
+ });
128
+ if (!response.ok || !(data instanceof Blob)) {
129
+ throw new DocumentFetchError(
130
+ `${what} could not be loaded (${response.status})`,
131
+ response.status
132
+ );
133
+ }
134
+ return data;
135
+ }
136
+ function fetchDocumentPdf(client, documentRef, options = {}) {
137
+ return fetchDocumentBytes(
138
+ client,
139
+ "/v1/document/{document_ext_id}/view",
140
+ documentRef,
141
+ options,
142
+ { Accept: "application/pdf" },
143
+ "The PDF"
144
+ );
145
+ }
146
+ function fetchDocumentFile(client, documentRef, options = {}) {
147
+ return fetchDocumentBytes(
148
+ client,
149
+ "/v1/document/{document_ext_id}/download",
150
+ documentRef,
151
+ options,
152
+ {},
153
+ "The file"
154
+ );
155
+ }
156
+
157
+ // src/document-tools/production.ts
158
+ var PRODUCTIONS_FOLDER = "Productions";
159
+ var extensionOf = (fileName) => {
160
+ const name = (fileName ?? "").toLowerCase();
161
+ const dot = name.lastIndexOf(".");
162
+ return dot < 0 ? "" : name.slice(dot + 1);
163
+ };
164
+ var NO_RENDITION_EXTENSIONS = new Set(
165
+ [
166
+ // images
167
+ "jpg jpeg png gif bmp tiff tif webp heic",
168
+ // video and audio
169
+ "mp4 mpeg mpg webm mov avi mkv mp3 wav m4a aac ogg flac",
170
+ // archives, binaries, design files
171
+ "zip rar 7z tar gz exe bin dmg iso apk msi dll so psd ai sketch"
172
+ ].join(" ").split(" ")
173
+ );
174
+ var isPdfDocument = (doc) => /pdf/i.test(doc.file_type ?? "") || extensionOf(doc.file_name) === "pdf";
175
+ var hasNoRendition = (doc) => !isPdfDocument(doc) && NO_RENDITION_EXTENSIONS.has(extensionOf(doc.file_name));
176
+ var productionDocumentName = (doc) => doc.doc_metadata?.title || doc.file_name || doc.external_id;
177
+ var isPdfBytes = (bytes) => bytes.length > 4 && String.fromCharCode(...bytes.subarray(0, 5)) === "%PDF-";
178
+ async function fetchProductionPdf(client, doc) {
179
+ const pdf = isPdfDocument(doc);
180
+ let blob;
181
+ try {
182
+ blob = await (pdf ? fetchDocumentFile : fetchDocumentPdf)(client, doc.external_id);
183
+ } catch (e) {
184
+ if (!pdf && e instanceof DocumentFetchError) return null;
185
+ throw e;
186
+ }
187
+ const bytes = new Uint8Array(await blob.arrayBuffer());
188
+ return pdf || isPdfBytes(bytes) ? bytes : null;
189
+ }
190
+ var safeName = (name) => name.replace(/[\\/:*?"<>|]+/g, "_").trim();
191
+ function productionTitle(firstLabel, lastLabel) {
192
+ return safeName(`Production ${firstLabel}-${lastLabel}`);
193
+ }
194
+ function productionFolder(title, merged) {
195
+ return merged ? PRODUCTIONS_FOLDER : `${PRODUCTIONS_FOLDER}/${title}`;
196
+ }
197
+ function productionFileName(file, title) {
198
+ if (!file.firstLabel) return `${title} index.pdf`;
199
+ return `${file.name.replace(/\.pdf$/i, "")} (${file.firstLabel}-${file.lastLabel}).pdf`;
200
+ }
201
+ var csvCell = (value) => `"${String(value).replace(/"/g, '""')}"`;
202
+ function productionIndexCsv(index) {
203
+ const rows = index.map(
204
+ (e) => [e.documentId, e.name, e.file, e.pages, e.firstLabel, e.lastLabel].map(csvCell).join(",")
205
+ );
206
+ return ["document_id,name,file,pages,first_label,last_label", ...rows].join("\n");
207
+ }
208
+ async function saveProductionFiles(upload, files, folder) {
209
+ const ids = [];
210
+ for (const file of files) {
211
+ const query = {
212
+ derived_from: file.sources.map((doc) => doc.external_id),
213
+ derived_role: "production",
214
+ shared: file.sources.every((doc) => doc.shared),
215
+ folder
216
+ };
217
+ const response = await upload({
218
+ file: new File([file.bytes], file.name, { type: "application/pdf" }),
219
+ query
220
+ });
221
+ ids.push(...response?.doc_ext_ids ?? []);
222
+ }
223
+ return ids;
224
+ }
225
+ async function buildProduction(client, documents, choices, options) {
226
+ const byId = new Map(documents.map((doc) => [doc.external_id, doc]));
227
+ const included = [];
228
+ const noRendition = [];
229
+ const items = [];
230
+ for (const doc of choices.order.flatMap((id) => byId.get(id) ?? [])) {
231
+ const bytes = await fetchProductionPdf(client, doc);
232
+ if (!bytes) {
233
+ noRendition.push(doc);
234
+ continue;
235
+ }
236
+ included.push(doc);
237
+ items.push({
238
+ name: productionDocumentName(doc),
239
+ documentId: doc.external_id,
240
+ bytes,
241
+ qrUrl: options.documentUrl(doc.external_id)
242
+ });
243
+ }
244
+ if (items.length === 0) {
245
+ throw new Error("None of these documents has a PDF version to number yet.");
246
+ }
247
+ const { buildBundle } = await import('../bundle-N2JIJ2T6.js');
248
+ const result = await buildBundle(items, {
249
+ layout: choices.layout,
250
+ bates: {
251
+ prefix: choices.prefix,
252
+ start: choices.start,
253
+ digits: choices.digits,
254
+ corner: choices.corner
255
+ },
256
+ qr: choices.qr,
257
+ // The QR code sits in the bottom corner the label is not in.
258
+ qrCorner: choices.corner.endsWith("left") ? "bottom-right" : "bottom-left",
259
+ indexPage: choices.indexPage,
260
+ author: options.author,
261
+ onProgress: options.onProgress
262
+ });
263
+ const title = productionTitle(
264
+ result.index[0].firstLabel,
265
+ result.index[result.index.length - 1].lastLabel
266
+ );
267
+ const merged = choices.layout === "merged";
268
+ const files = merged ? [{ ...result.files[0], name: `${title}.pdf` }] : result.files;
269
+ const sourceOf = new Map(result.index.map((e) => [e.file, byId.get(e.documentId)]));
270
+ const uploads = files.map((file) => ({
271
+ name: merged ? file.name : productionFileName(file, title),
272
+ bytes: file.bytes,
273
+ // The merged file (and a separate index) is made from every document; each per-document
274
+ // file from its own.
275
+ sources: merged || !sourceOf.has(file.name) ? included : [sourceOf.get(file.name)]
276
+ }));
277
+ return {
278
+ title,
279
+ merged,
280
+ files,
281
+ index: result.index,
282
+ included,
283
+ noRendition,
284
+ uploads,
285
+ folder: productionFolder(title, merged)
286
+ };
287
+ }
288
+
91
289
  // src/document-tools/markup-store.ts
92
290
  var MAX_MERGE_ATTEMPTS = 5;
93
291
  var KEEPALIVE_LIMIT = 6e4;
@@ -478,9 +676,9 @@ async function uploadFrozenCopy(upload, bytes, source, redacted) {
478
676
  type: "application/pdf"
479
677
  });
480
678
  const query = {
481
- derived_from: source.documentId,
679
+ derived_from: [source.documentId],
482
680
  derived_role: redacted ? "redaction" : "annotated",
483
- shared: String(source.shared)
681
+ shared: source.shared
484
682
  };
485
683
  if (source.folder) query.folder = source.folder;
486
684
  const response = await upload({ file, query });
@@ -634,6 +832,6 @@ async function matchSignedCopy(file, verification) {
634
832
  return signature ? { kind: "earlier", signature } : { kind: "none" };
635
833
  }
636
834
 
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 };
835
+ export { DocumentFetchError, DocumentToolsProvider, LEGACY_LAYER_PREFIX, MAX_MERGE_ATTEMPTS, MarkupDownloadError, MarkupStoreError, PRODUCTIONS_FOLDER, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, SignatureVerificationError, VERIFY_PATH, addToMarkup, buildProduction, canAnnotate, certificateLink, clientUpload, copyOpenThreads, createMarkupStore, currentHasMarkup, defaultCertificateUrl, downloadBlob, fetchDocumentFile, fetchDocumentPdf, fetchDocumentSignatures, fetchMarkupPdf, fetchProductionPdf, fetchSignatureVerification, forgetLegacyLayer, frozenCopyName, hasNoRendition, intentText, isLegibleSignatureBox, isPdfDocument, isSignatureReference, isSignedVersion, marksByVersion, matchSignedCopy, migrateLegacyLayer, openThreadsOf, productionDocumentName, productionFileName, productionFolder, productionIndexCsv, productionTitle, readLegacyLayer, redactionLogName, saveProductionFiles, sha256Hex, signDocument, toAppearance, uploadFrozenCopy, uploadQueryString, useDocumentMarkup, useDocumentSignatures, useDocumentTools, useIsOnline, useOptionalDocumentTools, useSignDocument, useSignatureVerification, versionsWithMarkup };
638
836
  //# sourceMappingURL=index.js.map
639
837
  //# sourceMappingURL=index.js.map