@twin.org/document-management-service 0.0.2-next.4 → 0.0.3-next.10

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.
@@ -0,0 +1,621 @@
1
+ import { AuditableItemGraphContexts, AuditableItemGraphTypes } from "@twin.org/auditable-item-graph-models";
2
+ import { BlobStorageContexts } from "@twin.org/blob-storage-models";
3
+ import { ContextIdKeys, ContextIdStore } from "@twin.org/context";
4
+ import { BaseError, Coerce, ComponentFactory, Converter, GeneralError, Guards, Is, NotFoundError, ObjectHelper, Urn } from "@twin.org/core";
5
+ import { IntegrityAlgorithm, IntegrityHelper, Sha256 } from "@twin.org/crypto";
6
+ import { JsonLdProcessor } from "@twin.org/data-json-ld";
7
+ import { DocumentContexts, DocumentTypes } from "@twin.org/document-management-models";
8
+ import { SchemaOrgContexts, SchemaOrgDataTypes, SchemaOrgTypes } from "@twin.org/standards-schema-org";
9
+ import { UneceDocumentCodeList } from "@twin.org/standards-unece";
10
+ /**
11
+ * Service for performing document management operations.
12
+ */
13
+ export class DocumentManagementService {
14
+ /**
15
+ * Runtime name for the class.
16
+ */
17
+ static CLASS_NAME = "DocumentManagementService";
18
+ /**
19
+ * The component for the auditable item graph.
20
+ * @internal
21
+ */
22
+ _auditableItemGraphComponent;
23
+ /**
24
+ * The connector for the blob component.
25
+ * @internal
26
+ */
27
+ _blobStorageComponent;
28
+ /**
29
+ * The connector for the attestation.
30
+ * @internal
31
+ */
32
+ _attestationComponent;
33
+ /**
34
+ * The connector for the data processing.
35
+ * @internal
36
+ */
37
+ _dataProcessingComponent;
38
+ /**
39
+ * Create a new instance of DocumentManagementService.
40
+ * @param options The options for the service.
41
+ */
42
+ constructor(options) {
43
+ this._auditableItemGraphComponent = ComponentFactory.get(options?.auditableItemGraphComponentType ?? "auditable-item-graph");
44
+ this._blobStorageComponent = ComponentFactory.get(options?.blobStorageComponentType ?? "blob-storage");
45
+ this._attestationComponent = ComponentFactory.get(options?.attestationComponentType ?? "attestation");
46
+ this._dataProcessingComponent = ComponentFactory.get(options?.dataProcessingComponentType ?? "data-processing");
47
+ SchemaOrgDataTypes.registerRedirects();
48
+ }
49
+ /**
50
+ * Returns the class name of the component.
51
+ * @returns The class name of the component.
52
+ */
53
+ className() {
54
+ return DocumentManagementService.CLASS_NAME;
55
+ }
56
+ /**
57
+ * Store a document as an auditable item graph vertex and add its content to blob storage.
58
+ * If the document id already exists and the blob data is different a new revision will be created.
59
+ * For any other changes the current revision will be updated.
60
+ * @param documentId The document id to create.
61
+ * @param documentIdFormat The format of the document identifier.
62
+ * @param documentCode The code for the document type.
63
+ * @param blob The data to create the document with.
64
+ * @param annotationObject Additional information to associate with the document.
65
+ * @param auditableItemGraphEdges The auditable item graph vertices to connect the document to.
66
+ * @param options Additional options for the set operation.
67
+ * @param options.createAttestation Flag to create an attestation for the document, defaults to false.
68
+ * @param options.addAlias Flag to add the document id as an alias to the aig vertex, defaults to true.
69
+ * @param options.aliasAnnotationObject Annotation object for the alias.
70
+ * @returns The auditable item graph vertex created for the document including its revision.
71
+ */
72
+ async create(documentId, documentIdFormat, documentCode, blob, annotationObject, auditableItemGraphEdges, options) {
73
+ Guards.stringValue(DocumentManagementService.CLASS_NAME, "documentId", documentId);
74
+ Guards.arrayOneOf(DocumentManagementService.CLASS_NAME, "documentCode", documentCode, Object.values(UneceDocumentCodeList));
75
+ Guards.uint8Array(DocumentManagementService.CLASS_NAME, "blob", blob);
76
+ const contextIds = await ContextIdStore.getContextIds();
77
+ try {
78
+ // Get the connected vertices first, if one fails we abort the create
79
+ const connectedVertices = {};
80
+ if (Is.arrayValue(auditableItemGraphEdges)) {
81
+ for (const edge of auditableItemGraphEdges) {
82
+ connectedVertices[edge.targetId] = await this._auditableItemGraphComponent.get(edge.targetId);
83
+ }
84
+ }
85
+ const documentVertex = {};
86
+ if (options?.addAlias ?? true) {
87
+ documentVertex.aliases ??= [];
88
+ documentVertex.aliases.push({
89
+ "@context": AuditableItemGraphContexts.Context,
90
+ type: AuditableItemGraphTypes.Alias,
91
+ id: documentId,
92
+ aliasFormat: documentIdFormat,
93
+ annotationObject: options?.aliasAnnotationObject
94
+ });
95
+ }
96
+ // Add the blob to blob storage
97
+ const blobStorageId = await this._blobStorageComponent.create(Converter.bytesToBase64(blob));
98
+ const currentRevision = {
99
+ "@context": [
100
+ SchemaOrgContexts.Context,
101
+ DocumentContexts.Context,
102
+ DocumentContexts.ContextCommon
103
+ ],
104
+ type: DocumentTypes.Document,
105
+ id: this.createDocumentId(documentId, 0),
106
+ documentId,
107
+ documentIdFormat,
108
+ documentCode,
109
+ documentRevision: 0,
110
+ annotationObject,
111
+ integrity: IntegrityHelper.generate(IntegrityAlgorithm.Sha256, blob),
112
+ blobStorageId,
113
+ dateCreated: new Date(Date.now()).toISOString(),
114
+ organizationIdentity: contextIds?.[ContextIdKeys.Organization],
115
+ userIdentity: contextIds?.[ContextIdKeys.User]
116
+ };
117
+ if (options?.createAttestation ?? false) {
118
+ currentRevision.attestationId = await this.createAttestation(currentRevision);
119
+ }
120
+ // Add the new revision in to the vertex
121
+ documentVertex.resources ??= [];
122
+ documentVertex.resources.push({
123
+ "@context": AuditableItemGraphContexts.Context,
124
+ type: AuditableItemGraphTypes.Resource,
125
+ resourceObject: currentRevision
126
+ });
127
+ // Add the edges from the document to the items
128
+ this.updateEdges(documentVertex, auditableItemGraphEdges);
129
+ // And create the vertex
130
+ const vertexId = await this._auditableItemGraphComponent.create(documentVertex);
131
+ // Now add the edges to the connected vertices
132
+ await this.updateConnectedEdges(connectedVertices, vertexId, [], auditableItemGraphEdges, documentId, documentIdFormat);
133
+ return vertexId;
134
+ }
135
+ catch (error) {
136
+ if (BaseError.someErrorName(error, "NotFoundError")) {
137
+ throw error;
138
+ }
139
+ throw new GeneralError(DocumentManagementService.CLASS_NAME, "createFailed", undefined, error);
140
+ }
141
+ }
142
+ /**
143
+ * Update a document as an auditable item graph vertex and add its content to blob storage.
144
+ * If the blob data is different a new revision will be created.
145
+ * For any other changes the current revision will be updated.
146
+ * @param auditableItemGraphDocumentId The auditable item graph vertex id which contains the document.
147
+ * @param blob The data to update the document with.
148
+ * @param annotationObject Additional information to associate with the document.
149
+ * @param auditableItemGraphEdges The auditable item graph vertices to connect the document to, if undefined retains current connections.
150
+ * @returns Nothing.
151
+ */
152
+ async update(auditableItemGraphDocumentId, blob, annotationObject, auditableItemGraphEdges) {
153
+ Urn.guard(DocumentManagementService.CLASS_NAME, "auditableItemGraphDocumentId", auditableItemGraphDocumentId);
154
+ try {
155
+ const documentVertex = await this._auditableItemGraphComponent.get(auditableItemGraphDocumentId, { includeDeleted: true });
156
+ if (Is.empty(documentVertex.resources)) {
157
+ throw new NotFoundError(DocumentManagementService.CLASS_NAME, "documentRevisionNone");
158
+ }
159
+ const documents = await this.getDocumentsFromVertex(documentVertex);
160
+ const latestRevision = documents.entries.itemListElement[0];
161
+ documentVertex.resources = documentVertex.resources.filter(r => Is.empty(r.dateDeleted));
162
+ if (Is.empty(latestRevision)) {
163
+ throw new NotFoundError(DocumentManagementService.CLASS_NAME, "documentRevisionNone");
164
+ }
165
+ // If auditableItemGraphEdges is undefined we are not updating the edges
166
+ // an empty array can be passed to remove all edges
167
+ const connectedVertices = {};
168
+ if (Is.array(auditableItemGraphEdges)) {
169
+ // Get the updated connected vertices first, if one fails we abort the update
170
+ for (const edge of auditableItemGraphEdges) {
171
+ connectedVertices[edge.targetId] = await this._auditableItemGraphComponent.get(edge.targetId);
172
+ }
173
+ // Also get the current edges in case some need disconnecting
174
+ if (Is.arrayValue(documents.entries.edges)) {
175
+ for (const edgeId of documents.entries.edges) {
176
+ // If we haven't retrieved the edge then it must be one that needs removing
177
+ if (Is.empty(connectedVertices[edgeId])) {
178
+ connectedVertices[edgeId] = await this._auditableItemGraphComponent.get(edgeId);
179
+ }
180
+ }
181
+ }
182
+ }
183
+ let updatedVertex = false;
184
+ // If the blob is set and its hash has changed then we create a new revision
185
+ if (Is.uint8Array(blob)) {
186
+ const newIntegrity = IntegrityHelper.generate(IntegrityAlgorithm.Sha256, blob);
187
+ if (latestRevision.integrity !== newIntegrity) {
188
+ // Add the blob to blob storage
189
+ const blobStorageId = await this._blobStorageComponent.create(Converter.bytesToBase64(blob));
190
+ const newRevision = ObjectHelper.clone(latestRevision);
191
+ newRevision.documentRevision++;
192
+ newRevision.id = this.createDocumentId(newRevision.documentId, newRevision.documentRevision);
193
+ newRevision.integrity = newIntegrity;
194
+ newRevision.blobStorageId = blobStorageId;
195
+ newRevision.annotationObject = annotationObject;
196
+ if (Is.stringValue(latestRevision.attestationId)) {
197
+ newRevision.attestationId = await this.createAttestation(newRevision);
198
+ }
199
+ documentVertex.resources.push({
200
+ "@context": AuditableItemGraphContexts.Context,
201
+ type: AuditableItemGraphTypes.Resource,
202
+ resourceObject: newRevision
203
+ });
204
+ updatedVertex = true;
205
+ }
206
+ }
207
+ // If the blob wasn't updated but the annotation object has then update the current revision
208
+ // instead of creating a new one
209
+ if (!updatedVertex &&
210
+ !ObjectHelper.equal(latestRevision.annotationObject, annotationObject)) {
211
+ updatedVertex = true;
212
+ latestRevision.annotationObject = annotationObject;
213
+ latestRevision.dateModified = new Date(Date.now()).toISOString();
214
+ }
215
+ const existingEdgeIds = documentVertex.edges?.map(e => e.targetId) ?? [];
216
+ // Update the edges from the document to the items
217
+ const edgesUpdated = this.updateEdges(documentVertex, auditableItemGraphEdges);
218
+ if (edgesUpdated) {
219
+ updatedVertex = true;
220
+ }
221
+ if (updatedVertex) {
222
+ await this._auditableItemGraphComponent.update(documentVertex);
223
+ }
224
+ if (edgesUpdated) {
225
+ await this.updateConnectedEdges(connectedVertices, auditableItemGraphDocumentId, existingEdgeIds, auditableItemGraphEdges, latestRevision.documentId, latestRevision.documentIdFormat);
226
+ }
227
+ }
228
+ catch (error) {
229
+ if (BaseError.someErrorName(error, "NotFoundError")) {
230
+ throw error;
231
+ }
232
+ throw new GeneralError(DocumentManagementService.CLASS_NAME, "updateFailed", undefined, error);
233
+ }
234
+ }
235
+ /**
236
+ * Get a document using it's auditable item graph vertex id and optional revision.
237
+ * @param auditableItemGraphDocumentId The auditable item graph vertex id which contains the document.
238
+ * @param options Additional options for the get operation.
239
+ * @param options.includeBlobStorageMetadata Flag to include the blob storage metadata for the document, defaults to false.
240
+ * @param options.includeBlobStorageData Flag to include the blob storage data for the document, defaults to false.
241
+ * @param options.includeAttestation Flag to include the attestation information for the document, defaults to false.
242
+ * @param options.includeRemoved Flag to include deleted documents, defaults to false.
243
+ * @param options.extractRuleGroupId If provided will extract data from the document using the specified rule group id.
244
+ * @param options.extractMimeType By default extraction will auto detect the mime type of the document, this can be used to override the detection.
245
+ * @param cursor The cursor to get the next chunk of revisions.
246
+ * @param limit Limit the number of items to return, defaults to 1 so only most recent is returned.
247
+ * @returns The documents and revisions if requested, ordered by revision descending, cursor is set if there are more document revisions.
248
+ */
249
+ async get(auditableItemGraphDocumentId, options, cursor, limit) {
250
+ Urn.guard(DocumentManagementService.CLASS_NAME, "auditableItemGraphDocumentId", auditableItemGraphDocumentId);
251
+ try {
252
+ const documentVertex = await this._auditableItemGraphComponent.get(auditableItemGraphDocumentId, { includeDeleted: options?.includeRemoved });
253
+ // Populate the document and revisions with the options set
254
+ const documents = await this.getDocumentsFromVertex(documentVertex, options, cursor, limit);
255
+ const result = await JsonLdProcessor.compact(documents.entries, documents.entries["@context"]);
256
+ return {
257
+ entries: result,
258
+ cursor: documents.cursor
259
+ };
260
+ }
261
+ catch (error) {
262
+ if (BaseError.someErrorName(error, "NotFoundError")) {
263
+ throw error;
264
+ }
265
+ throw new GeneralError(DocumentManagementService.CLASS_NAME, "getFailed", undefined, error);
266
+ }
267
+ }
268
+ /**
269
+ * Get a document revision using it's auditable item graph vertex id.
270
+ * @param auditableItemGraphDocumentId The auditable item graph vertex id which contains the document.
271
+ * @param revision The revision id for the document.
272
+ * @param options Additional options for the get operation.
273
+ * @param options.includeBlobStorageMetadata Flag to include the blob storage metadata for the document, defaults to false.
274
+ * @param options.includeBlobStorageData Flag to include the blob storage data for the document, defaults to false.
275
+ * @param options.includeAttestation Flag to include the attestation information for the document, defaults to false.
276
+ * @param options.extractRuleGroupId If provided will extract data from the document using the specified rule group id.
277
+ * @param options.extractMimeType By default extraction will auto detect the mime type of the document, this can be used to override the detection.
278
+ * @returns The documents and revisions if requested, ordered by revision descending, cursor is set if there are more document revisions.
279
+ */
280
+ async getRevision(auditableItemGraphDocumentId, revision, options) {
281
+ Urn.guard(DocumentManagementService.CLASS_NAME, "auditableItemGraphDocumentId", auditableItemGraphDocumentId);
282
+ Guards.integer(DocumentManagementService.CLASS_NAME, "revision", revision);
283
+ try {
284
+ const documentVertex = await this._auditableItemGraphComponent.get(auditableItemGraphDocumentId, { includeDeleted: true });
285
+ if (Is.empty(documentVertex.resources)) {
286
+ throw new NotFoundError(DocumentManagementService.CLASS_NAME, "documentRevisionNone");
287
+ }
288
+ documentVertex.resources = documentVertex.resources.filter(d => d.resourceObject?.documentRevision === revision);
289
+ if (documentVertex.resources.length === 0) {
290
+ throw new NotFoundError(DocumentManagementService.CLASS_NAME, "documentRevisionNotFound", revision.toString());
291
+ }
292
+ // Populate the document and revisions with the options set
293
+ const docList = await this.getDocumentsFromVertex(documentVertex, options);
294
+ const result = await JsonLdProcessor.compact(docList.entries.itemListElement[0], docList.entries.itemListElement[0]["@context"]);
295
+ return result;
296
+ }
297
+ catch (error) {
298
+ if (BaseError.someErrorName(error, "NotFoundError")) {
299
+ throw error;
300
+ }
301
+ throw new GeneralError(DocumentManagementService.CLASS_NAME, "getRevisionFailed", undefined, error);
302
+ }
303
+ }
304
+ /**
305
+ * Remove an auditable item graph vertex using it's id.
306
+ * The document dateDeleted will be set, but can still be queried with the includeRemoved flag.
307
+ * @param auditableItemGraphDocumentId The auditable item graph vertex id which contains the document.
308
+ * @param revision The revision of the document to remove.
309
+ * @returns Nothing.
310
+ */
311
+ async removeRevision(auditableItemGraphDocumentId, revision) {
312
+ Urn.guard(DocumentManagementService.CLASS_NAME, "auditableItemGraphDocumentId", auditableItemGraphDocumentId);
313
+ Guards.number(DocumentManagementService.CLASS_NAME, "revision", revision);
314
+ try {
315
+ const documentVertex = await this._auditableItemGraphComponent.get(auditableItemGraphDocumentId);
316
+ if (Is.empty(documentVertex.resources)) {
317
+ throw new NotFoundError(DocumentManagementService.CLASS_NAME, "documentRevisionNone");
318
+ }
319
+ const docRevisionIndex = documentVertex.resources.findIndex(d => d.resourceObject?.documentRevision === revision);
320
+ if (docRevisionIndex === -1) {
321
+ throw new NotFoundError(DocumentManagementService.CLASS_NAME, "documentRevisionNotFound", revision.toString());
322
+ }
323
+ documentVertex.resources.splice(docRevisionIndex, 1);
324
+ await this._auditableItemGraphComponent.update(documentVertex);
325
+ }
326
+ catch (error) {
327
+ if (BaseError.someErrorName(error, "NotFoundError")) {
328
+ throw error;
329
+ }
330
+ throw new GeneralError(DocumentManagementService.CLASS_NAME, "removeRevisionFailed", undefined, error);
331
+ }
332
+ }
333
+ /**
334
+ * Find all the document with a specific id.
335
+ * @param documentId The document id to find in the graph.
336
+ * @param cursor The cursor to get the next chunk of documents.
337
+ * @param limit The limit to get the next chunk of documents.
338
+ * @returns The graph vertices that contain documents referencing the specified document id.
339
+ */
340
+ async query(documentId, cursor, limit) {
341
+ Guards.stringValue(DocumentManagementService.CLASS_NAME, "documentId", documentId);
342
+ try {
343
+ const result = await this._auditableItemGraphComponent.query({
344
+ id: documentId,
345
+ idMode: "both",
346
+ resourceTypes: [DocumentTypes.Document]
347
+ }, undefined, undefined, undefined, ["id", "dateCreated", "dateModified", "aliases", "annotationObject", "resources", "edges"], cursor, limit);
348
+ return result;
349
+ }
350
+ catch (error) {
351
+ if (BaseError.someErrorName(error, "NotFoundError")) {
352
+ throw error;
353
+ }
354
+ throw new GeneralError(DocumentManagementService.CLASS_NAME, "queryFailed", undefined, error);
355
+ }
356
+ }
357
+ /**
358
+ * Update the edges of the document vertex.
359
+ * @param documentVertex The document vertex to update.
360
+ * @param auditableItemGraphEdges The list of edges to use.
361
+ * @returns True if the edges were updated.
362
+ * @internal
363
+ */
364
+ updateEdges(documentVertex, auditableItemGraphEdges) {
365
+ let changed = false;
366
+ const existingEdgeIds = documentVertex.edges?.map(e => e.targetId) ?? [];
367
+ if (Is.array(auditableItemGraphEdges)) {
368
+ for (const aigEdge of auditableItemGraphEdges) {
369
+ const existingIndex = existingEdgeIds.indexOf(aigEdge.targetId);
370
+ if (existingIndex !== -1) {
371
+ // If the edge already exists then we don't need to add it again
372
+ // We just need to remove it from the list of existing ids
373
+ // any remaining after this loop will be need to be removed
374
+ existingEdgeIds.splice(existingIndex, 1);
375
+ }
376
+ else {
377
+ const vertexEdge = {
378
+ "@context": AuditableItemGraphContexts.Context,
379
+ type: AuditableItemGraphTypes.Edge,
380
+ targetId: aigEdge.targetId,
381
+ edgeRelationships: ["document"]
382
+ };
383
+ documentVertex.edges ??= [];
384
+ documentVertex.edges?.push(vertexEdge);
385
+ changed = true;
386
+ }
387
+ }
388
+ // Anything left in the existingEdgeIds array means they need to be removed
389
+ if (existingEdgeIds.length > 0 && Is.array(documentVertex.edges)) {
390
+ for (const existingEdgeId of existingEdgeIds) {
391
+ const existingIndex = documentVertex.edges.findIndex(e => e.targetId === existingEdgeId);
392
+ if (existingIndex !== -1) {
393
+ documentVertex.edges.splice(existingIndex, 1);
394
+ changed = true;
395
+ }
396
+ }
397
+ }
398
+ }
399
+ return changed;
400
+ }
401
+ /**
402
+ * Update the edges.
403
+ * @param connectedVertices The connected vertices for the edges.
404
+ * @param auditableItemGraphDocumentId The document id to use.
405
+ * @param documentVertex The document vertex to update.
406
+ * @param auditableItemGraphEdges The list of edges to use.
407
+ * @param documentId The document identifier.
408
+ * @param documentIdFormat The format of the document identifier.
409
+ * @internal
410
+ */
411
+ async updateConnectedEdges(connectedVertices, auditableItemGraphDocumentId, existingEdgeIds, auditableItemGraphEdges, documentId, documentIdFormat) {
412
+ if (Is.array(auditableItemGraphEdges)) {
413
+ for (const aigEdge of auditableItemGraphEdges) {
414
+ const connected = connectedVertices[aigEdge.targetId];
415
+ if (!Is.empty(connected)) {
416
+ let updatedConnected = false;
417
+ const existingIndex = existingEdgeIds.indexOf(aigEdge.targetId);
418
+ if (existingIndex !== -1) {
419
+ // If the edge already exists we remove it from the list of existing ids
420
+ // any remaining after this loop will be need to be disconnected
421
+ existingEdgeIds.splice(existingIndex, 1);
422
+ }
423
+ // Add the edge with the document vertex id if it doesn't already exist
424
+ const hasEdge = connected.edges?.some(e => e.targetId === auditableItemGraphDocumentId);
425
+ if (!hasEdge) {
426
+ const vertexEdge = {
427
+ "@context": AuditableItemGraphContexts.Context,
428
+ type: AuditableItemGraphTypes.Edge,
429
+ targetId: auditableItemGraphDocumentId,
430
+ edgeRelationships: ["document"]
431
+ };
432
+ connected.edges ??= [];
433
+ connected.edges?.push(vertexEdge);
434
+ updatedConnected = true;
435
+ }
436
+ // Add alias with the document id if option flag is set and it doesn't already exist
437
+ if (aigEdge.addAlias) {
438
+ const alias = connected.aliases?.find(a => a.id === documentId);
439
+ if (Is.empty(alias)) {
440
+ // No existing alias, so create one
441
+ const vertexAlias = {
442
+ "@context": AuditableItemGraphContexts.Context,
443
+ type: AuditableItemGraphTypes.Alias,
444
+ id: documentId,
445
+ aliasFormat: documentIdFormat,
446
+ annotationObject: aigEdge.aliasAnnotationObject
447
+ };
448
+ connected.aliases ??= [];
449
+ connected.aliases?.push(vertexAlias);
450
+ updatedConnected = true;
451
+ }
452
+ else if (!ObjectHelper.equal(alias.annotationObject, aigEdge.aliasAnnotationObject) ||
453
+ documentIdFormat !== alias.aliasFormat) {
454
+ // The alias already exists, but the format or annotation object has changed
455
+ alias.annotationObject = aigEdge.aliasAnnotationObject;
456
+ alias.aliasFormat = documentIdFormat;
457
+ updatedConnected = true;
458
+ }
459
+ }
460
+ if (updatedConnected) {
461
+ await this._auditableItemGraphComponent.update(connected);
462
+ }
463
+ }
464
+ }
465
+ }
466
+ // Anything left in the existingEdgeIds array means they need to be removed
467
+ if (existingEdgeIds.length > 0) {
468
+ for (const existingEdgeId of existingEdgeIds) {
469
+ const connected = connectedVertices[existingEdgeId];
470
+ if (!Is.empty(connected)) {
471
+ let updatedConnected = false;
472
+ // Remove the edge from the connected vertex
473
+ if (Is.arrayValue(connected.edges)) {
474
+ const existingIndex = connected.edges.findIndex(e => e.targetId === auditableItemGraphDocumentId);
475
+ if (existingIndex !== -1) {
476
+ connected.edges.splice(existingIndex, 1);
477
+ updatedConnected = true;
478
+ }
479
+ }
480
+ // Remove the alias from the connected vertex
481
+ if (Is.arrayValue(connected.aliases)) {
482
+ const existingIndex = connected.aliases.findIndex(e => e.id === documentId);
483
+ if (existingIndex !== -1) {
484
+ connected.aliases.splice(existingIndex, 1);
485
+ updatedConnected = true;
486
+ }
487
+ }
488
+ if (updatedConnected) {
489
+ await this._auditableItemGraphComponent.update(connected);
490
+ }
491
+ }
492
+ }
493
+ }
494
+ }
495
+ /**
496
+ * Get the documents from the auditable item graph vertex.
497
+ * @param documentVertex The vertex containing the documents.
498
+ * @param options Additional options for the get operation.
499
+ * @param options.includeBlobStorageMetadata Flag to include the blob storage metadata for the document, defaults to false.
500
+ * @param options.includeBlobStorageData Flag to include the blob storage data for the document, defaults to false.
501
+ * @param options.includeAttestation Flag to include the attestation information for the document, defaults to false.
502
+ * @param options.extractRuleGroupId If provided will extract data from the document using the specified rule group id.
503
+ * @param options.extractMimeType By default extraction will auto detect the mime type of the document, this can be used to override the detection.
504
+ * @param cursor The cursor to get the next chunk of revisions.
505
+ * @param limit Limit the number of items to return, defaults to 1 so only most recent is returned.
506
+ * @returns The finalised list of documents.
507
+ * @internal
508
+ */
509
+ async getDocumentsFromVertex(documentVertex, options, cursor, limit) {
510
+ const docList = {
511
+ "@context": [
512
+ SchemaOrgContexts.Context,
513
+ DocumentContexts.Context,
514
+ DocumentContexts.ContextCommon
515
+ ],
516
+ type: SchemaOrgTypes.ItemList,
517
+ [SchemaOrgTypes.ItemListElement]: []
518
+ };
519
+ let nextCursor;
520
+ if (Is.arrayValue(documentVertex.resources)) {
521
+ // Sort by newest revision first
522
+ documentVertex.resources.sort((a, b) => (Coerce.number(b.resourceObject?.documentRevision) ?? 0) -
523
+ (Coerce.number(a.resourceObject?.documentRevision) ?? 0));
524
+ const startIndex = Coerce.integer(cursor) ?? 0;
525
+ const endIndex = Math.min(startIndex + (limit ?? 1), documentVertex.resources.length);
526
+ const slicedResources = documentVertex.resources.slice(startIndex, endIndex);
527
+ nextCursor = documentVertex.resources.length > endIndex ? endIndex.toString() : undefined;
528
+ const includeBlobStorageMetadata = options?.includeBlobStorageMetadata ?? false;
529
+ const includeBlobStorageData = options?.includeBlobStorageData ?? false;
530
+ const includeAttestation = options?.includeAttestation ?? false;
531
+ const extractData = Is.stringValue(options?.extractRuleGroupId);
532
+ for (let i = 0; i < slicedResources.length; i++) {
533
+ const document = slicedResources[i].resourceObject;
534
+ if (Is.object(document)) {
535
+ document.dateDeleted = slicedResources[i].dateDeleted;
536
+ docList[SchemaOrgTypes.ItemListElement].push(document);
537
+ const blobRequired = includeBlobStorageMetadata || includeBlobStorageData;
538
+ if (blobRequired || extractData) {
539
+ const blobEntry = await this._blobStorageComponent.get(document.blobStorageId, {
540
+ includeContent: includeBlobStorageData || extractData
541
+ });
542
+ if (blobRequired) {
543
+ document.blobStorageEntry = blobEntry;
544
+ if (Is.object(document.blobStorageEntry)) {
545
+ ObjectHelper.propertyDelete(document.blobStorageEntry, "@context");
546
+ }
547
+ if (!docList["@context"].includes(BlobStorageContexts.Context)) {
548
+ docList["@context"].push(BlobStorageContexts.Context);
549
+ }
550
+ }
551
+ if (Is.stringValue(options?.extractRuleGroupId) && Is.stringValue(blobEntry.blob)) {
552
+ const binaryBlob = Converter.base64ToBytes(blobEntry.blob);
553
+ document.extractedData = await this._dataProcessingComponent.extract(options.extractRuleGroupId, binaryBlob, undefined, options?.extractMimeType);
554
+ }
555
+ // If we have the blob data due to extraction but we weren't asked for it
556
+ // then we remove it from the document
557
+ if (!blobRequired) {
558
+ delete document.blobStorageEntry;
559
+ }
560
+ else if (!includeBlobStorageData) {
561
+ delete document.blobStorageEntry?.blob;
562
+ }
563
+ }
564
+ if (includeAttestation && Is.stringValue(document.attestationId)) {
565
+ const attestationInformation = await this._attestationComponent.get(document.attestationId);
566
+ document.attestationInformation = attestationInformation;
567
+ if (Is.object(document.attestationInformation)) {
568
+ ObjectHelper.propertyDelete(document.attestationInformation, "@context");
569
+ }
570
+ }
571
+ }
572
+ }
573
+ }
574
+ if (Is.arrayValue(documentVertex.edges)) {
575
+ docList.edges ??= [];
576
+ for (const edge of documentVertex.edges) {
577
+ if (Is.object(edge)) {
578
+ docList.edges.push(edge.targetId);
579
+ }
580
+ }
581
+ }
582
+ return {
583
+ entries: docList,
584
+ cursor: nextCursor
585
+ };
586
+ }
587
+ /**
588
+ * Create an attestation for the document.
589
+ * @param document The document to create the attestation for.
590
+ * @returns The attestation identifier.
591
+ */
592
+ async createAttestation(document) {
593
+ const documentAttestation = {
594
+ "@context": [
595
+ SchemaOrgContexts.Context,
596
+ DocumentContexts.Context,
597
+ DocumentContexts.ContextCommon
598
+ ],
599
+ type: DocumentTypes.DocumentAttestation,
600
+ id: document.id,
601
+ documentId: document.documentId,
602
+ documentCode: document.documentCode,
603
+ documentRevision: document.documentRevision,
604
+ dateCreated: document.dateCreated,
605
+ integrity: document.integrity
606
+ };
607
+ return this._attestationComponent.create(documentAttestation);
608
+ }
609
+ /**
610
+ * Create a document id from the document id and revision.
611
+ * @param documentId The document id to create.
612
+ * @param revision The revision of the document.
613
+ * @returns The document id.
614
+ * @internal
615
+ */
616
+ createDocumentId(documentId, revision) {
617
+ const documentIdHash = Converter.bytesToBase64Url(Sha256.sum256(Converter.utf8ToBytes(documentId)));
618
+ return `document:${documentIdHash}:${revision}`;
619
+ }
620
+ }
621
+ //# sourceMappingURL=documentManagementService.js.map