@twin.org/document-management-service 0.0.1-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,1015 @@
1
+ import { AuditableItemGraphTypes, AuditableItemGraphContexts } from '@twin.org/auditable-item-graph-models';
2
+ import { Guards, ComponentFactory, Converter, Coerce, Is, BaseError, GeneralError, Urn, NotFoundError, ObjectHelper } from '@twin.org/core';
3
+ import { DocumentTypes, DocumentContexts } from '@twin.org/document-management-models';
4
+ import { SchemaOrgContexts, SchemaOrgDataTypes } from '@twin.org/standards-schema-org';
5
+ import { UneceDocumentCodes } from '@twin.org/standards-unece';
6
+ import { HttpStatusCode, HeaderTypes, MimeTypes } from '@twin.org/web';
7
+ import { AttestationContexts } from '@twin.org/attestation-models';
8
+ import { BlobStorageContexts } from '@twin.org/blob-storage-models';
9
+ import { Sha256 } from '@twin.org/crypto';
10
+ import { JsonLdProcessor } from '@twin.org/data-json-ld';
11
+
12
+ /**
13
+ * The source used when communicating about these routes.
14
+ */
15
+ const ROUTES_SOURCE = "documentManagementStorageRoutes";
16
+ /**
17
+ * The tag to associate with the routes.
18
+ */
19
+ const tagsDocumentManagement = [
20
+ {
21
+ name: "Document Management",
22
+ description: "Endpoints which are modelled to access a document management contract."
23
+ }
24
+ ];
25
+ /**
26
+ * The REST routes for document management.
27
+ * @param baseRouteName Prefix to prepend to the paths.
28
+ * @param componentName The name of the component to use in the routes stored in the ComponentFactory.
29
+ * @returns The generated routes.
30
+ */
31
+ function generateRestRoutesDocumentManagement(baseRouteName, componentName) {
32
+ const documentManagementCreateRoute = {
33
+ operationId: "DocumentManagementSet",
34
+ summary: "Store a document in an auditable item graph vertex and add its content to blob storage.",
35
+ tag: tagsDocumentManagement[0].name,
36
+ method: "POST",
37
+ path: `${baseRouteName}/`,
38
+ handler: async (httpRequestContext, request) => documentManagementCreate(httpRequestContext, componentName, request),
39
+ requestType: {
40
+ type: "IDocumentManagementCreateRequest",
41
+ examples: [
42
+ {
43
+ id: "DocumentManagementCreateRequestExample",
44
+ request: {
45
+ body: {
46
+ documentId: "2721000",
47
+ documentIdFormat: "bol",
48
+ documentCode: UneceDocumentCodes.BillOfLading,
49
+ blob: "SGVsbG8gV29ybGQ=",
50
+ annotationObject: {
51
+ "@context": "https://schema.org",
52
+ "@type": "DigitalDocument",
53
+ name: "myfile.pdf"
54
+ },
55
+ createAttestation: true
56
+ }
57
+ }
58
+ }
59
+ ]
60
+ },
61
+ responseType: [
62
+ {
63
+ type: "ICreatedResponse",
64
+ examples: [
65
+ {
66
+ id: "DocumentManagementCreateResponseExample",
67
+ response: {
68
+ statusCode: HttpStatusCode.created,
69
+ headers: {
70
+ [HeaderTypes.Location]: "aig:123456"
71
+ }
72
+ }
73
+ }
74
+ ]
75
+ }
76
+ ]
77
+ };
78
+ const documentManagementUpdateRoute = {
79
+ operationId: "DocumentManagementUpdate",
80
+ summary: "Update a document in an auditable item graph vertex and add its content to blob storage.",
81
+ tag: tagsDocumentManagement[0].name,
82
+ method: "PUT",
83
+ path: `${baseRouteName}/:auditableItemGraphDocumentId`,
84
+ handler: async (httpRequestContext, request) => documentManagementUpdate(httpRequestContext, componentName, request),
85
+ requestType: {
86
+ type: "IDocumentManagementUpdateRequest",
87
+ examples: [
88
+ {
89
+ id: "DocumentManagementUpdateRequestExample",
90
+ request: {
91
+ pathParams: {
92
+ auditableItemGraphDocumentId: "aig:123456"
93
+ },
94
+ body: {
95
+ blob: "SGVsbG8gV29ybGQ=",
96
+ annotationObject: {
97
+ "@context": "https://schema.org",
98
+ "@type": "DigitalDocument",
99
+ name: "myfile.pdf"
100
+ }
101
+ }
102
+ }
103
+ }
104
+ ]
105
+ },
106
+ responseType: [
107
+ {
108
+ type: "INoContentResponse",
109
+ examples: [
110
+ {
111
+ id: "DocumentManagementCreateResponseExample",
112
+ response: {
113
+ statusCode: HttpStatusCode.noContent
114
+ }
115
+ }
116
+ ]
117
+ }
118
+ ]
119
+ };
120
+ const documentManagementGetRoute = {
121
+ operationId: "DocumentManagementGet",
122
+ summary: "Get the data for a document from document management",
123
+ tag: tagsDocumentManagement[0].name,
124
+ method: "GET",
125
+ path: `${baseRouteName}/:auditableItemGraphDocumentId`,
126
+ handler: async (httpRequestContext, request) => documentManagementGet(httpRequestContext, componentName, request),
127
+ requestType: {
128
+ type: "IDocumentManagementGetRequest",
129
+ examples: [
130
+ {
131
+ id: "DocumentManagementGetRequestExample",
132
+ request: {
133
+ pathParams: {
134
+ auditableItemGraphDocumentId: "aig:123456"
135
+ }
136
+ }
137
+ }
138
+ ]
139
+ },
140
+ responseType: [
141
+ {
142
+ type: "IDocumentManagementGetResponse",
143
+ examples: [
144
+ {
145
+ id: "DocumentManagementGetResponseExample",
146
+ response: {
147
+ body: {
148
+ "@context": [DocumentContexts.ContextRoot, DocumentContexts.ContextRootCommon],
149
+ type: DocumentTypes.DocumentList,
150
+ documents: [
151
+ {
152
+ "@context": [
153
+ DocumentContexts.ContextRoot,
154
+ DocumentContexts.ContextRootCommon,
155
+ SchemaOrgContexts.ContextRoot
156
+ ],
157
+ type: DocumentTypes.Document,
158
+ id: "2721000:0",
159
+ documentId: "2721000",
160
+ documentIdFormat: "bol",
161
+ documentCode: UneceDocumentCodes.BillOfLading,
162
+ documentRevision: 0,
163
+ blobStorageId: "blob-memory:c57d94b088f4c6d2cb32ded014813d0c786aa00134c8ee22f84b1e2545602a70",
164
+ blobHash: "sha256:123456",
165
+ dateCreated: "2024-01-01T00:00:00Z",
166
+ annotationObject: {
167
+ "@context": "https://schema.org",
168
+ "@type": "DigitalDocument",
169
+ name: "myfile.pdf"
170
+ },
171
+ nodeIdentity: "did:entity-storage:0x6363636363636363636363636363636363636363636363636363636363636363",
172
+ userIdentity: "did:entity-storage:0x6363636363636363636363636363636363636363636363636363636363636363"
173
+ }
174
+ ]
175
+ }
176
+ }
177
+ }
178
+ ]
179
+ },
180
+ {
181
+ type: "IDocumentManagementGetResponse",
182
+ mimeType: MimeTypes.JsonLd,
183
+ examples: [
184
+ {
185
+ id: "DocumentManagementGetResponseExample",
186
+ response: {
187
+ body: {
188
+ "@context": [DocumentContexts.ContextRoot, DocumentContexts.ContextRootCommon],
189
+ type: DocumentTypes.DocumentList,
190
+ documents: [
191
+ {
192
+ "@context": [
193
+ DocumentContexts.ContextRoot,
194
+ DocumentContexts.ContextRootCommon,
195
+ SchemaOrgContexts.ContextRoot
196
+ ],
197
+ type: DocumentTypes.Document,
198
+ id: "2721000:0",
199
+ documentId: "2721000",
200
+ documentIdFormat: "bol",
201
+ documentCode: UneceDocumentCodes.BillOfLading,
202
+ documentRevision: 0,
203
+ blobStorageId: "blob-memory:c57d94b088f4c6d2cb32ded014813d0c786aa00134c8ee22f84b1e2545602a70",
204
+ blobHash: "sha256:123456",
205
+ dateCreated: "2024-01-01T00:00:00Z",
206
+ annotationObject: {
207
+ "@context": "https://schema.org",
208
+ "@type": "DigitalDocument",
209
+ name: "myfile.pdf"
210
+ },
211
+ nodeIdentity: "did:entity-storage:0x6363636363636363636363636363636363636363636363636363636363636363",
212
+ userIdentity: "did:entity-storage:0x6363636363636363636363636363636363636363636363636363636363636363"
213
+ }
214
+ ]
215
+ }
216
+ }
217
+ }
218
+ ]
219
+ },
220
+ {
221
+ type: "INotFoundResponse"
222
+ }
223
+ ]
224
+ };
225
+ const documentManagementRemoveRoute = {
226
+ operationId: "DocumentManagementRemove",
227
+ summary: "Remove an document from an auditable item graph vertex",
228
+ tag: tagsDocumentManagement[0].name,
229
+ method: "DELETE",
230
+ path: `${baseRouteName}/:auditableItemGraphDocumentId/:revision`,
231
+ handler: async (httpRequestContext, request) => documentManagementRemove(httpRequestContext, componentName, request),
232
+ requestType: {
233
+ type: "IDocumentManagementRemoveRequest",
234
+ examples: [
235
+ {
236
+ id: "DocumentManagementRemoveRequestExample",
237
+ request: {
238
+ pathParams: {
239
+ auditableItemGraphDocumentId: "aig:1234",
240
+ revision: "1"
241
+ }
242
+ }
243
+ }
244
+ ]
245
+ },
246
+ responseType: [
247
+ {
248
+ type: "INoContentResponse"
249
+ },
250
+ {
251
+ type: "INotFoundResponse"
252
+ }
253
+ ]
254
+ };
255
+ const documentManagementQueryRoute = {
256
+ operationId: "DocumentManagementQuery",
257
+ summary: "Query the items from an auditable item graph vertex",
258
+ tag: tagsDocumentManagement[0].name,
259
+ method: "GET",
260
+ path: `${baseRouteName}/`,
261
+ handler: async (httpRequestContext, request) => documentManagementQuery(httpRequestContext, componentName, request),
262
+ requestType: {
263
+ type: "IDocumentManagementQueryRequest",
264
+ examples: [
265
+ {
266
+ id: "DocumentManagementQueryRequestExample",
267
+ request: {
268
+ query: {
269
+ documentId: "2721000"
270
+ }
271
+ }
272
+ }
273
+ ]
274
+ },
275
+ responseType: [
276
+ {
277
+ type: "IDocumentManagementQueryResponse",
278
+ examples: [
279
+ {
280
+ id: "DocumentManagementQueryResponseExample",
281
+ response: {
282
+ body: {
283
+ "@context": [AuditableItemGraphContexts.ContextRoot],
284
+ type: AuditableItemGraphTypes.VertexList,
285
+ vertices: [
286
+ {
287
+ "@context": [
288
+ AuditableItemGraphContexts.ContextRoot,
289
+ AuditableItemGraphContexts.ContextRootCommon
290
+ ],
291
+ id: "aig:c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7",
292
+ type: AuditableItemGraphTypes.Vertex,
293
+ dateCreated: "2024-08-22T04:13:20.000Z",
294
+ aliases: [
295
+ {
296
+ "@context": [AuditableItemGraphContexts.ContextRoot],
297
+ id: "test-id-0",
298
+ type: AuditableItemGraphTypes.Alias,
299
+ dateCreated: "2024-08-22T04:13:20.000Z"
300
+ }
301
+ ],
302
+ resources: [
303
+ {
304
+ "@context": AuditableItemGraphContexts.ContextRoot,
305
+ type: AuditableItemGraphTypes.Resource,
306
+ dateCreated: "2024-08-22T04:13:20.000Z",
307
+ resourceObject: {
308
+ "@context": [
309
+ "https://schema.twindev.org/documents/",
310
+ "https://schema.twindev.org/common/",
311
+ "https://schema.org"
312
+ ],
313
+ type: "Document",
314
+ id: "test-id-0:0",
315
+ documentId: "test-id-0",
316
+ documentCode: "unece:DocumentCodeList#705",
317
+ documentRevision: 0,
318
+ annotationObject: {
319
+ "@context": "https://schema.org",
320
+ type: "DigitalDocument",
321
+ name: "bill-of-lading"
322
+ },
323
+ blobHash: "sha256:E3Duqrp6bHojSx+CzDttAToAiP1eFkCDAPBbKLABVGM=",
324
+ blobStorageId: "blob:memory:1370eeaaba7a6c7a234b1f82cc3b6d013a0088fd5e16408300f05b28b0015463",
325
+ dateCreated: "2024-08-22T04:13:20.000Z",
326
+ nodeIdentity: "did:entity-storage:0x0101010101010101010101010101010101010101010101010101010101010101",
327
+ userIdentity: "did:entity-storage:0x0404040404040404040404040404040404040404040404040404040404040404"
328
+ }
329
+ }
330
+ ]
331
+ }
332
+ ]
333
+ }
334
+ }
335
+ }
336
+ ]
337
+ }
338
+ ]
339
+ };
340
+ return [
341
+ documentManagementCreateRoute,
342
+ documentManagementUpdateRoute,
343
+ documentManagementGetRoute,
344
+ documentManagementRemoveRoute,
345
+ documentManagementQueryRoute
346
+ ];
347
+ }
348
+ /**
349
+ * Create a document as an auditable item graph vertex.
350
+ * @param httpRequestContext The request context for the API.
351
+ * @param componentName The name of the component to use in the routes.
352
+ * @param request The request.
353
+ * @returns The response object with additional http response properties.
354
+ */
355
+ async function documentManagementCreate(httpRequestContext, componentName, request) {
356
+ Guards.object(ROUTES_SOURCE, "request", request);
357
+ Guards.object(ROUTES_SOURCE, "request.body", request.body);
358
+ Guards.stringBase64(ROUTES_SOURCE, "request.body.blob", request.body.blob);
359
+ const component = ComponentFactory.get(componentName);
360
+ const id = await component.create(request.body.documentId, request.body.documentIdFormat, request.body.documentCode, Converter.base64ToBytes(request.body.blob), request.body.annotationObject, request.body.auditableItemGraphEdges, {
361
+ createAttestation: request.body.createAttestation,
362
+ addAlias: request.body.addAlias,
363
+ aliasAnnotationObject: request.body.aliasAnnotationObject
364
+ }, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
365
+ return {
366
+ statusCode: HttpStatusCode.created,
367
+ headers: {
368
+ location: id
369
+ }
370
+ };
371
+ }
372
+ /**
373
+ * Get the document from the auditable item graph vertex.
374
+ * @param httpRequestContext The request context for the API.
375
+ * @param componentName The name of the component to use in the routes.
376
+ * @param request The request.
377
+ * @returns The response object with additional http response properties.
378
+ */
379
+ async function documentManagementGet(httpRequestContext, componentName, request) {
380
+ Guards.object(ROUTES_SOURCE, "request", request);
381
+ Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
382
+ Guards.stringValue(ROUTES_SOURCE, "request.pathParams.auditableItemGraphDocumentId", request.pathParams.auditableItemGraphDocumentId);
383
+ const mimeType = request.headers?.[HeaderTypes.Accept] === MimeTypes.JsonLd ? "jsonld" : "json";
384
+ const component = ComponentFactory.get(componentName);
385
+ const result = await component.get(request.pathParams.auditableItemGraphDocumentId, {
386
+ includeBlobStorageMetadata: Coerce.boolean(request.query?.includeBlobStorageMetadata),
387
+ includeBlobStorageData: Coerce.boolean(request.query?.includeBlobStorageData),
388
+ includeAttestation: Coerce.boolean(request.query?.includeAttestation),
389
+ includeRemoved: Coerce.boolean(request.query?.includeRemoved)
390
+ }, request.query?.cursor, Coerce.integer(request.query?.pageSize), httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
391
+ return {
392
+ headers: {
393
+ [HeaderTypes.ContentType]: mimeType === "json" ? MimeTypes.Json : MimeTypes.JsonLd
394
+ },
395
+ body: result
396
+ };
397
+ }
398
+ /**
399
+ * UPdate the document from the auditable item graph vertex.
400
+ * @param httpRequestContext The request context for the API.
401
+ * @param componentName The name of the component to use in the routes.
402
+ * @param request The request.
403
+ * @returns The response object with additional http response properties.
404
+ */
405
+ async function documentManagementUpdate(httpRequestContext, componentName, request) {
406
+ Guards.object(ROUTES_SOURCE, "request", request);
407
+ Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
408
+ Guards.stringValue(ROUTES_SOURCE, "request.pathParams.auditableItemGraphDocumentId", request.pathParams.auditableItemGraphDocumentId);
409
+ const component = ComponentFactory.get(componentName);
410
+ await component.update(request.pathParams.auditableItemGraphDocumentId, Is.stringValue(request.body.blob) ? Converter.base64ToBytes(request.body.blob) : undefined, request.body.annotationObject, request.body.auditableItemGraphEdges, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
411
+ return {
412
+ statusCode: HttpStatusCode.noContent
413
+ };
414
+ }
415
+ /**
416
+ * Remove the document from the auditable item graph vertex.
417
+ * @param httpRequestContext The request context for the API.
418
+ * @param componentName The name of the component to use in the routes.
419
+ * @param request The request.
420
+ * @returns The response object with additional http response properties.
421
+ */
422
+ async function documentManagementRemove(httpRequestContext, componentName, request) {
423
+ Guards.object(ROUTES_SOURCE, "request", request);
424
+ Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
425
+ Guards.stringValue(ROUTES_SOURCE, "request.pathParams.auditableItemGraphDocumentId", request.pathParams.auditableItemGraphDocumentId);
426
+ const revision = Coerce.number(request.pathParams.revision);
427
+ Guards.integer(ROUTES_SOURCE, "request.pathParams.revision", revision);
428
+ const component = ComponentFactory.get(componentName);
429
+ await component.removeRevision(request.pathParams.auditableItemGraphDocumentId, revision, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
430
+ return {
431
+ statusCode: HttpStatusCode.noContent
432
+ };
433
+ }
434
+ /**
435
+ * Query the documents from an auditable item graph vertex.
436
+ * @param httpRequestContext The request context for the API.
437
+ * @param componentName The name of the component to use in the routes.
438
+ * @param request The request.
439
+ * @returns The response object with additional http response properties.
440
+ */
441
+ async function documentManagementQuery(httpRequestContext, componentName, request) {
442
+ Guards.object(ROUTES_SOURCE, "request", request);
443
+ Guards.object(ROUTES_SOURCE, "request.query", request.query);
444
+ Guards.stringValue(ROUTES_SOURCE, "request.query.documentId", request.query.documentId);
445
+ const mimeType = request.headers?.[HeaderTypes.Accept] === MimeTypes.JsonLd ? "jsonld" : "json";
446
+ const component = ComponentFactory.get(componentName);
447
+ const result = await component.query(request.query.documentId, request.query?.cursor, Coerce.integer(request.query?.pageSize), httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
448
+ return {
449
+ headers: {
450
+ [HeaderTypes.ContentType]: mimeType === "json" ? MimeTypes.Json : MimeTypes.JsonLd
451
+ },
452
+ body: result
453
+ };
454
+ }
455
+
456
+ /**
457
+ * Service for performing document management operations.
458
+ */
459
+ class DocumentManagementService {
460
+ /**
461
+ * The namespace supported by the document management service.
462
+ */
463
+ static NAMESPACE = "documents";
464
+ /**
465
+ * Runtime name for the class.
466
+ */
467
+ CLASS_NAME = "DocumentManagementService";
468
+ /**
469
+ * The component for the auditable item graph.
470
+ * @internal
471
+ */
472
+ _auditableItemGraphComponent;
473
+ /**
474
+ * The connector for the blob component.
475
+ * @internal
476
+ */
477
+ _blobStorageComponent;
478
+ /**
479
+ * The connector for the attestation.
480
+ * @internal
481
+ */
482
+ _attestationComponent;
483
+ /**
484
+ * Create a new instance of DocumentManagementService.
485
+ * @param options The options for the service.
486
+ */
487
+ constructor(options) {
488
+ this._auditableItemGraphComponent = ComponentFactory.get(options?.auditableItemGraphComponentType ?? "auditable-item-graph");
489
+ this._blobStorageComponent = ComponentFactory.get(options?.blobStorageComponentType ?? "blob-storage");
490
+ this._attestationComponent = ComponentFactory.get(options?.attestationComponentType ?? "attestation");
491
+ SchemaOrgDataTypes.registerRedirects();
492
+ }
493
+ /**
494
+ * Store a document as an auditable item graph vertex and add its content to blob storage.
495
+ * If the document id already exists and the blob data is different a new revision will be created.
496
+ * For any other changes the current revision will be updated.
497
+ * @param documentId The document id to create.
498
+ * @param documentIdFormat The format of the document identifier.
499
+ * @param documentCode The code for the document type.
500
+ * @param blob The data to create the document with.
501
+ * @param annotationObject Additional information to associate with the document.
502
+ * @param auditableItemGraphEdges The auditable item graph vertices to connect the document to.
503
+ * @param options Additional options for the set operation.
504
+ * @param options.createAttestation Flag to create an attestation for the document, defaults to false.
505
+ * @param options.addAlias Flag to add the document id as an alias to the aig vertex, defaults to true.
506
+ * @param options.aliasAnnotationObject Annotation object for the alias.
507
+ * @param userIdentity The identity to perform the auditable item graph operation with.
508
+ * @param nodeIdentity The node identity to use for vault operations.
509
+ * @returns The auditable item graph vertex created for the document including its revision.
510
+ */
511
+ async create(documentId, documentIdFormat, documentCode, blob, annotationObject, auditableItemGraphEdges, options, userIdentity, nodeIdentity) {
512
+ Guards.stringValue(this.CLASS_NAME, "documentId", documentId);
513
+ Guards.arrayOneOf(this.CLASS_NAME, "documentCode", documentCode, Object.values(UneceDocumentCodes));
514
+ Guards.uint8Array(this.CLASS_NAME, "blob", blob);
515
+ Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
516
+ Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
517
+ try {
518
+ // Get the connected vertices first, if one fails we abort the create
519
+ const connectedVertices = {};
520
+ if (Is.arrayValue(auditableItemGraphEdges)) {
521
+ for (const edge of auditableItemGraphEdges) {
522
+ connectedVertices[edge.id] = await this._auditableItemGraphComponent.get(edge.id);
523
+ }
524
+ }
525
+ const documentVertex = {};
526
+ if (options?.addAlias ?? true) {
527
+ documentVertex.aliases ??= [];
528
+ documentVertex.aliases.push({
529
+ "@context": AuditableItemGraphContexts.ContextRoot,
530
+ type: AuditableItemGraphTypes.Alias,
531
+ id: documentId,
532
+ aliasFormat: documentIdFormat,
533
+ annotationObject: options?.aliasAnnotationObject
534
+ });
535
+ }
536
+ // Add the blob to blob storage
537
+ const blobStorageId = await this._blobStorageComponent.create(Converter.bytesToBase64(blob), undefined, undefined, undefined, undefined, userIdentity, nodeIdentity);
538
+ const currentRevision = {
539
+ "@context": [
540
+ DocumentContexts.ContextRoot,
541
+ DocumentContexts.ContextRootCommon,
542
+ SchemaOrgContexts.ContextRoot
543
+ ],
544
+ type: DocumentTypes.Document,
545
+ id: `${documentId}:0`,
546
+ documentId,
547
+ documentIdFormat,
548
+ documentCode,
549
+ documentRevision: 0,
550
+ annotationObject,
551
+ blobHash: this.generateBlobHash(blob),
552
+ blobStorageId,
553
+ dateCreated: new Date(Date.now()).toISOString(),
554
+ nodeIdentity,
555
+ userIdentity
556
+ };
557
+ if (options?.createAttestation ?? false) {
558
+ currentRevision.attestationId = await this.createAttestation(currentRevision, userIdentity, nodeIdentity);
559
+ }
560
+ // Add the new revision in to the vertex
561
+ documentVertex.resources ??= [];
562
+ documentVertex.resources.push({
563
+ "@context": AuditableItemGraphContexts.ContextRoot,
564
+ type: AuditableItemGraphTypes.Resource,
565
+ resourceObject: currentRevision
566
+ });
567
+ // Add the edges from the document to the items
568
+ this.updateEdges(documentVertex, auditableItemGraphEdges);
569
+ // And create the vertex
570
+ const vertexId = await this._auditableItemGraphComponent.create(documentVertex, userIdentity, nodeIdentity);
571
+ // Now add the edges to the connected vertices
572
+ await this.updateConnectedEdges(connectedVertices, vertexId, [], auditableItemGraphEdges, documentId, documentIdFormat, userIdentity, nodeIdentity);
573
+ return vertexId;
574
+ }
575
+ catch (error) {
576
+ if (BaseError.someErrorName(error, "NotFoundError")) {
577
+ throw error;
578
+ }
579
+ throw new GeneralError(this.CLASS_NAME, "createFailed", undefined, error);
580
+ }
581
+ }
582
+ /**
583
+ * Update a document as an auditable item graph vertex and add its content to blob storage.
584
+ * If the blob data is different a new revision will be created.
585
+ * For any other changes the current revision will be updated.
586
+ * @param auditableItemGraphDocumentId The auditable item graph vertex id which contains the document.
587
+ * @param blob The data to update the document with.
588
+ * @param annotationObject Additional information to associate with the document.
589
+ * @param auditableItemGraphEdges The auditable item graph vertices to connect the document to, if undefined retains current connections.
590
+ * @param userIdentity The identity to perform the auditable item graph operation with.
591
+ * @param nodeIdentity The node identity to use for vault operations.
592
+ * @returns Nothing.
593
+ */
594
+ async update(auditableItemGraphDocumentId, blob, annotationObject, auditableItemGraphEdges, userIdentity, nodeIdentity) {
595
+ Urn.guard(this.CLASS_NAME, "auditableItemGraphDocumentId", auditableItemGraphDocumentId);
596
+ Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
597
+ Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
598
+ try {
599
+ const documentVertex = await this._auditableItemGraphComponent.get(auditableItemGraphDocumentId);
600
+ if (Is.empty(documentVertex.resources)) {
601
+ throw new NotFoundError(this.CLASS_NAME, "documentRevisionNone");
602
+ }
603
+ const documents = await this.getDocumentsFromVertex(documentVertex);
604
+ const latestRevision = documents.documents[0];
605
+ if (Is.empty(latestRevision)) {
606
+ throw new NotFoundError(this.CLASS_NAME, "documentRevisionNone");
607
+ }
608
+ // If auditableItemGraphEdges is undefined we are not updating the edges
609
+ // an empty array can be passed to remove all edges
610
+ const connectedVertices = {};
611
+ if (Is.array(auditableItemGraphEdges)) {
612
+ // Get the updated connected vertices first, if one fails we abort the update
613
+ for (const edge of auditableItemGraphEdges) {
614
+ connectedVertices[edge.id] = await this._auditableItemGraphComponent.get(edge.id);
615
+ }
616
+ // Also get the current edges in case some need disconnecting
617
+ if (Is.arrayValue(documents.edges)) {
618
+ for (const edgeId of documents.edges) {
619
+ // If we haven't retrieved the edge then it must be one that needs removing
620
+ if (Is.empty(connectedVertices[edgeId])) {
621
+ connectedVertices[edgeId] = await this._auditableItemGraphComponent.get(edgeId);
622
+ }
623
+ }
624
+ }
625
+ }
626
+ let updatedVertex = false;
627
+ // If the blob is set and its hash has changed then we create a new revision
628
+ if (Is.uint8Array(blob)) {
629
+ const newBlobHash = this.generateBlobHash(blob);
630
+ if (latestRevision.blobHash !== newBlobHash) {
631
+ // Add the blob to blob storage
632
+ const blobStorageId = await this._blobStorageComponent.create(Converter.bytesToBase64(blob), undefined, undefined, undefined, undefined, userIdentity, nodeIdentity);
633
+ const newRevision = ObjectHelper.clone(latestRevision);
634
+ newRevision.documentRevision++;
635
+ newRevision.id = `${newRevision.documentId}:${newRevision.documentRevision}`;
636
+ newRevision.blobHash = newBlobHash;
637
+ newRevision.blobStorageId = blobStorageId;
638
+ newRevision.annotationObject = annotationObject;
639
+ if (Is.stringValue(latestRevision.attestationId)) {
640
+ newRevision.attestationId = await this.createAttestation(newRevision, userIdentity, nodeIdentity);
641
+ }
642
+ documentVertex.resources.push({
643
+ "@context": AuditableItemGraphContexts.ContextRoot,
644
+ type: AuditableItemGraphTypes.Resource,
645
+ resourceObject: newRevision
646
+ });
647
+ updatedVertex = true;
648
+ }
649
+ }
650
+ // If the blob wasn't updated but the annotation object has then update the current revision
651
+ // instead of creating a new one
652
+ if (!updatedVertex &&
653
+ !ObjectHelper.equal(latestRevision.annotationObject, annotationObject)) {
654
+ updatedVertex = true;
655
+ latestRevision.annotationObject = annotationObject;
656
+ latestRevision.dateModified = new Date(Date.now()).toISOString();
657
+ }
658
+ const existingEdgeIds = documentVertex.edges?.map(e => e.id) ?? [];
659
+ // Update the edges from the document to the items
660
+ const edgesUpdated = this.updateEdges(documentVertex, auditableItemGraphEdges);
661
+ if (edgesUpdated) {
662
+ updatedVertex = true;
663
+ }
664
+ if (updatedVertex) {
665
+ await this._auditableItemGraphComponent.update(documentVertex, userIdentity, nodeIdentity);
666
+ }
667
+ if (edgesUpdated) {
668
+ await this.updateConnectedEdges(connectedVertices, auditableItemGraphDocumentId, existingEdgeIds, auditableItemGraphEdges, latestRevision.documentId, latestRevision.documentIdFormat, userIdentity, nodeIdentity);
669
+ }
670
+ }
671
+ catch (error) {
672
+ if (BaseError.someErrorName(error, "NotFoundError")) {
673
+ throw error;
674
+ }
675
+ throw new GeneralError(this.CLASS_NAME, "updateFailed", undefined, error);
676
+ }
677
+ }
678
+ /**
679
+ * Get a document using it's auditable item graph vertex id and optional revision.
680
+ * @param auditableItemGraphDocumentId The auditable item graph vertex id which contains the document.
681
+ * @param options Additional options for the get operation.
682
+ * @param options.includeBlobStorageMetadata Flag to include the blob storage metadata for the document, defaults to false.
683
+ * @param options.includeBlobStorageData Flag to include the blob storage data for the document, defaults to false.
684
+ * @param options.includeAttestation Flag to include the attestation information for the document, defaults to false.
685
+ * @param options.includeRemoved Flag to include deleted documents, defaults to false.
686
+ * @param cursor The cursor to get the next chunk of revisions.
687
+ * @param pageSize Page size of items to return, defaults to 1 so only most recent is returned.
688
+ * @param userIdentity The identity to perform the auditable item graph operation with.
689
+ * @param nodeIdentity The node identity to use for vault operations.
690
+ * @returns The documents and revisions if requested, ordered by revision descending, cursor is set if there are more document revisions.
691
+ */
692
+ async get(auditableItemGraphDocumentId, options, cursor, pageSize, userIdentity, nodeIdentity) {
693
+ Urn.guard(this.CLASS_NAME, "auditableItemGraphDocumentId", auditableItemGraphDocumentId);
694
+ try {
695
+ const documentVertex = await this._auditableItemGraphComponent.get(auditableItemGraphDocumentId, { includeDeleted: options?.includeRemoved });
696
+ // Populate the document and revisions with the options set
697
+ const documents = await this.getDocumentsFromVertex(documentVertex, options, cursor, pageSize, userIdentity, nodeIdentity);
698
+ return JsonLdProcessor.compact(documents, documents["@context"]);
699
+ }
700
+ catch (error) {
701
+ if (BaseError.someErrorName(error, "NotFoundError")) {
702
+ throw error;
703
+ }
704
+ throw new GeneralError(this.CLASS_NAME, "getFailed", undefined, error);
705
+ }
706
+ }
707
+ /**
708
+ * Remove an auditable item graph vertex using it's id.
709
+ * The document dateDeleted will be set, but can still be queried with the includeRemoved flag.
710
+ * @param auditableItemGraphDocumentId The auditable item graph vertex id which contains the document.
711
+ * @param revision The revision of the document to remove.
712
+ * @param userIdentity The identity to perform the auditable item graph operation with.
713
+ * @param nodeIdentity The node identity to use for vault operations.
714
+ * @returns Nothing.
715
+ */
716
+ async removeRevision(auditableItemGraphDocumentId, revision, userIdentity, nodeIdentity) {
717
+ Urn.guard(this.CLASS_NAME, "auditableItemGraphDocumentId", auditableItemGraphDocumentId);
718
+ Guards.number(this.CLASS_NAME, "revision", revision);
719
+ try {
720
+ const documentVertex = await this._auditableItemGraphComponent.get(auditableItemGraphDocumentId);
721
+ if (Is.empty(documentVertex.resources)) {
722
+ throw new NotFoundError(this.CLASS_NAME, "documentRevisionNone");
723
+ }
724
+ const docRevisionIndex = documentVertex.resources.findIndex(d => d.resourceObject?.documentRevision === revision);
725
+ if (docRevisionIndex === -1) {
726
+ throw new NotFoundError(this.CLASS_NAME, "documentRevisionNotFound", revision.toString());
727
+ }
728
+ documentVertex.resources.splice(docRevisionIndex, 1);
729
+ await this._auditableItemGraphComponent.update(documentVertex, userIdentity, nodeIdentity);
730
+ }
731
+ catch (error) {
732
+ if (BaseError.someErrorName(error, "NotFoundError")) {
733
+ throw error;
734
+ }
735
+ throw new GeneralError(this.CLASS_NAME, "removeRevisionFailed", undefined, error);
736
+ }
737
+ }
738
+ /**
739
+ * Find all the document with a specific id.
740
+ * @param documentId The document id to find in the graph.
741
+ * @param cursor The cursor to get the next chunk of documents.
742
+ * @param pageSize The page size to get the next chunk of documents.
743
+ * @param userIdentity The identity to perform the auditable item graph operation with.
744
+ * @param nodeIdentity The node identity to use for vault operations.
745
+ * @returns The graph vertices that contain documents referencing the specified document id.
746
+ */
747
+ async query(documentId, cursor, pageSize, userIdentity, nodeIdentity) {
748
+ Guards.stringValue(this.CLASS_NAME, "documentId", documentId);
749
+ try {
750
+ return this._auditableItemGraphComponent.query({
751
+ id: documentId,
752
+ idMode: "both",
753
+ resourceTypes: [DocumentTypes.Document]
754
+ }, undefined, undefined, undefined, ["id", "dateCreated", "dateModified", "aliases", "annotationObject", "resources", "edges"], cursor, pageSize);
755
+ }
756
+ catch (error) {
757
+ if (BaseError.someErrorName(error, "NotFoundError")) {
758
+ throw error;
759
+ }
760
+ throw new GeneralError(this.CLASS_NAME, "queryFailed", undefined, error);
761
+ }
762
+ }
763
+ /**
764
+ * Update the edges of the document vertex.
765
+ * @param documentVertex The document vertex to update.
766
+ * @param auditableItemGraphEdges The list of edges to use.
767
+ * @returns True if the edges were updated.
768
+ * @internal
769
+ */
770
+ updateEdges(documentVertex, auditableItemGraphEdges) {
771
+ let changed = false;
772
+ const existingEdgeIds = documentVertex.edges?.map(e => e.id) ?? [];
773
+ if (Is.array(auditableItemGraphEdges)) {
774
+ for (const aigEdge of auditableItemGraphEdges) {
775
+ const existingIndex = existingEdgeIds.indexOf(aigEdge.id);
776
+ if (existingIndex !== -1) {
777
+ // If the edge already exists then we don't need to add it again
778
+ // We just need to remove it from the list of existing ids
779
+ // any remaining after this loop will be need to be removed
780
+ existingEdgeIds.splice(existingIndex, 1);
781
+ }
782
+ else {
783
+ const vertexEdge = {
784
+ "@context": AuditableItemGraphContexts.ContextRoot,
785
+ type: AuditableItemGraphTypes.Edge,
786
+ id: aigEdge.id,
787
+ edgeRelationships: ["document"]
788
+ };
789
+ documentVertex.edges ??= [];
790
+ documentVertex.edges?.push(vertexEdge);
791
+ changed = true;
792
+ }
793
+ }
794
+ // Anything left in the existingEdgeIds array means they need to be removed
795
+ if (existingEdgeIds.length > 0 && Is.array(documentVertex.edges)) {
796
+ for (const existingEdgeId of existingEdgeIds) {
797
+ const existingIndex = documentVertex.edges.findIndex(e => e.id === existingEdgeId);
798
+ if (existingIndex !== -1) {
799
+ documentVertex.edges.splice(existingIndex, 1);
800
+ changed = true;
801
+ }
802
+ }
803
+ }
804
+ }
805
+ return changed;
806
+ }
807
+ /**
808
+ * Update the edges.
809
+ * @param connectedVertices The connected vertices for the edges.
810
+ * @param auditableItemGraphDocumentId The document id to use.
811
+ * @param documentVertex The document vertex to update.
812
+ * @param auditableItemGraphEdges The list of edges to use.
813
+ * @param documentId The document identifier.
814
+ * @param documentIdFormat The format of the document identifier.
815
+ * @param userIdentity The identity to perform the auditable item graph operation with.
816
+ * @param nodeIdentity The node identity to use for vault operations.
817
+ * @internal
818
+ */
819
+ async updateConnectedEdges(connectedVertices, auditableItemGraphDocumentId, existingEdgeIds, auditableItemGraphEdges, documentId, documentIdFormat, userIdentity, nodeIdentity) {
820
+ if (Is.array(auditableItemGraphEdges)) {
821
+ for (const aigEdge of auditableItemGraphEdges) {
822
+ const connected = connectedVertices[aigEdge.id];
823
+ if (!Is.empty(connected)) {
824
+ let updatedConnected = false;
825
+ const existingIndex = existingEdgeIds.indexOf(aigEdge.id);
826
+ if (existingIndex !== -1) {
827
+ // If the edge already exists we remove it from the list of existing ids
828
+ // any remaining after this loop will be need to be disconnected
829
+ existingEdgeIds.splice(existingIndex, 1);
830
+ }
831
+ // Add the edge with the document vertex id if it doesn't already exist
832
+ const hasEdge = connected.edges?.some(e => e.id === auditableItemGraphDocumentId);
833
+ if (!hasEdge) {
834
+ const vertexEdge = {
835
+ "@context": AuditableItemGraphContexts.ContextRoot,
836
+ type: AuditableItemGraphTypes.Edge,
837
+ id: auditableItemGraphDocumentId,
838
+ edgeRelationships: ["document"]
839
+ };
840
+ connected.edges ??= [];
841
+ connected.edges?.push(vertexEdge);
842
+ updatedConnected = true;
843
+ }
844
+ // Add alias with the document id if option flag is set and it doesn't already exist
845
+ if (aigEdge.addAlias) {
846
+ const alias = connected.aliases?.find(a => a.id === documentId);
847
+ if (Is.empty(alias)) {
848
+ // No existing alias, so create one
849
+ const vertexAlias = {
850
+ "@context": AuditableItemGraphContexts.ContextRoot,
851
+ type: AuditableItemGraphTypes.Alias,
852
+ id: documentId,
853
+ aliasFormat: documentIdFormat,
854
+ annotationObject: aigEdge.aliasAnnotationObject
855
+ };
856
+ connected.aliases ??= [];
857
+ connected.aliases?.push(vertexAlias);
858
+ updatedConnected = true;
859
+ }
860
+ else if (!ObjectHelper.equal(alias.annotationObject, aigEdge.aliasAnnotationObject) ||
861
+ documentIdFormat !== alias.aliasFormat) {
862
+ // The alias already exists, but the format or annotation object has changed
863
+ alias.annotationObject = aigEdge.aliasAnnotationObject;
864
+ alias.aliasFormat = documentIdFormat;
865
+ updatedConnected = true;
866
+ }
867
+ }
868
+ if (updatedConnected) {
869
+ await this._auditableItemGraphComponent.update(connected, userIdentity, nodeIdentity);
870
+ }
871
+ }
872
+ }
873
+ }
874
+ // Anything left in the existingEdgeIds array means they need to be removed
875
+ if (existingEdgeIds.length > 0) {
876
+ for (const existingEdgeId of existingEdgeIds) {
877
+ const connected = connectedVertices[existingEdgeId];
878
+ if (!Is.empty(connected)) {
879
+ let updatedConnected = false;
880
+ // Remove the edge from the connected vertex
881
+ if (Is.arrayValue(connected.edges)) {
882
+ const existingIndex = connected.edges.findIndex(e => e.id === auditableItemGraphDocumentId);
883
+ if (existingIndex !== -1) {
884
+ connected.edges.splice(existingIndex, 1);
885
+ updatedConnected = true;
886
+ }
887
+ }
888
+ // Remove the alias from the connected vertex
889
+ if (Is.arrayValue(connected.aliases)) {
890
+ const existingIndex = connected.aliases.findIndex(e => e.id === documentId);
891
+ if (existingIndex !== -1) {
892
+ connected.aliases.splice(existingIndex, 1);
893
+ updatedConnected = true;
894
+ }
895
+ }
896
+ if (updatedConnected) {
897
+ await this._auditableItemGraphComponent.update(connected, userIdentity, nodeIdentity);
898
+ }
899
+ }
900
+ }
901
+ }
902
+ }
903
+ /**
904
+ * Generate a hash for the blob data.
905
+ * @param blob The blob data to hash.
906
+ * @returns The hash.
907
+ * @internal
908
+ */
909
+ generateBlobHash(blob) {
910
+ return `sha256:${Converter.bytesToBase64(Sha256.sum256(blob))}`;
911
+ }
912
+ /**
913
+ * Get the documents from the auditable item graph vertex.
914
+ * @param documentVertex The vertex containing the documents.
915
+ * @param options Additional options for the get operation.
916
+ * @param options.includeBlobStorageMetadata Flag to include the blob storage metadata for the document, defaults to false.
917
+ * @param options.includeBlobStorageData Flag to include the blob storage data for the document, defaults to false.
918
+ * @param options.includeAttestation Flag to include the attestation information for the document, defaults to false.
919
+ * @param options.includeRemoved Flag to include deleted documents, defaults to false.
920
+ * @param cursor The cursor to get the next chunk of revisions.
921
+ * @param pageSize Page size of items to return, defaults to 1 so only most recent is returned.
922
+ * @param userIdentity The identity to perform the auditable item graph operation with.
923
+ * @param nodeIdentity The node identity to use for vault operations.
924
+ * @returns The finalised list of documents.
925
+ * @internal
926
+ */
927
+ async getDocumentsFromVertex(documentVertex, options, cursor, pageSize, userIdentity, nodeIdentity) {
928
+ const docList = {
929
+ "@context": [
930
+ DocumentContexts.ContextRoot,
931
+ DocumentContexts.ContextRootCommon,
932
+ SchemaOrgContexts.ContextRoot
933
+ ],
934
+ type: DocumentTypes.DocumentList,
935
+ documents: []
936
+ };
937
+ if (Is.arrayValue(documentVertex.resources)) {
938
+ // Sort by newest revision first
939
+ documentVertex.resources.sort((a, b) => (Coerce.number(b.resourceObject?.documentRevision) ?? 0) -
940
+ (Coerce.number(a.resourceObject?.documentRevision) ?? 0));
941
+ const startIndex = Coerce.integer(cursor) ?? 0;
942
+ const endIndex = Math.min(startIndex + (pageSize ?? 1), documentVertex.resources.length);
943
+ const slicedResources = documentVertex.resources.slice(startIndex, endIndex);
944
+ docList.cursor =
945
+ documentVertex.resources.length > endIndex ? (endIndex + 1).toString() : undefined;
946
+ const includeBlobStorageMetadata = options?.includeBlobStorageMetadata ?? false;
947
+ const includeBlobStorageData = options?.includeBlobStorageData ?? false;
948
+ const includeAttestation = options?.includeAttestation ?? false;
949
+ for (let i = 0; i < slicedResources.length; i++) {
950
+ const document = slicedResources[i].resourceObject;
951
+ if (Is.object(document)) {
952
+ docList.documents.push(document);
953
+ if (includeBlobStorageMetadata || includeBlobStorageData) {
954
+ const blobEntry = await this._blobStorageComponent.get(document.blobStorageId, includeBlobStorageData, userIdentity, nodeIdentity);
955
+ document.blobStorageEntry = blobEntry;
956
+ if (!docList["@context"].includes(BlobStorageContexts.ContextRoot)) {
957
+ docList["@context"].push(BlobStorageContexts.ContextRoot);
958
+ }
959
+ }
960
+ if (includeAttestation && Is.stringValue(document.attestationId)) {
961
+ const attestationInformation = await this._attestationComponent.get(document.attestationId);
962
+ document.attestationInformation = attestationInformation;
963
+ if (!docList["@context"].includes(AttestationContexts.ContextRoot)) {
964
+ docList["@context"].push(AttestationContexts.ContextRoot);
965
+ }
966
+ }
967
+ }
968
+ }
969
+ }
970
+ if (Is.arrayValue(documentVertex.edges)) {
971
+ docList.edges ??= [];
972
+ for (const edge of documentVertex.edges) {
973
+ if (Is.object(edge)) {
974
+ docList.edges.push(edge.id);
975
+ }
976
+ }
977
+ }
978
+ return docList;
979
+ }
980
+ /**
981
+ * Create an attestation for the document.
982
+ * @param document The document to create the attestation for.
983
+ * @param userIdentity The identity to perform the attestation operation with.
984
+ * @param nodeIdentity The node identity to perform attestation operation with.
985
+ * @returns The attestation identifier.
986
+ */
987
+ async createAttestation(document, userIdentity, nodeIdentity) {
988
+ const documentAttestation = {
989
+ "@context": [
990
+ DocumentContexts.ContextRoot,
991
+ DocumentContexts.ContextRootCommon,
992
+ SchemaOrgContexts.ContextRoot
993
+ ],
994
+ type: DocumentTypes.DocumentAttestation,
995
+ id: document.id,
996
+ documentId: document.documentId,
997
+ documentCode: document.documentCode,
998
+ documentRevision: document.documentRevision,
999
+ dateCreated: document.dateCreated,
1000
+ blobHash: document.blobHash
1001
+ };
1002
+ return this._attestationComponent.create(documentAttestation, undefined, userIdentity, nodeIdentity);
1003
+ }
1004
+ }
1005
+
1006
+ const restEntryPoints = [
1007
+ {
1008
+ name: "document-management",
1009
+ defaultBaseRoute: "document-management",
1010
+ tags: tagsDocumentManagement,
1011
+ generateRoutes: generateRestRoutesDocumentManagement
1012
+ }
1013
+ ];
1014
+
1015
+ export { DocumentManagementService, documentManagementCreate, documentManagementGet, documentManagementQuery, documentManagementRemove, documentManagementUpdate, generateRestRoutesDocumentManagement, restEntryPoints, tagsDocumentManagement };