@twin.org/document-management-service 0.0.2-next.3 → 0.0.3-next.1

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