@twin.org/auditable-item-graph-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.
Files changed (39) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -0
  3. package/dist/cjs/index.cjs +1606 -0
  4. package/dist/esm/index.mjs +1596 -0
  5. package/dist/types/auditableItemGraphRoutes.d.ts +45 -0
  6. package/dist/types/auditableItemGraphService.d.ts +123 -0
  7. package/dist/types/entities/auditableItemGraphAlias.d.ts +30 -0
  8. package/dist/types/entities/auditableItemGraphChangeset.d.ts +30 -0
  9. package/dist/types/entities/auditableItemGraphEdge.d.ts +30 -0
  10. package/dist/types/entities/auditableItemGraphPatch.d.ts +21 -0
  11. package/dist/types/entities/auditableItemGraphResource.d.ts +26 -0
  12. package/dist/types/entities/auditableItemGraphVertex.d.ts +45 -0
  13. package/dist/types/index.d.ts +11 -0
  14. package/dist/types/models/IAuditableItemGraphServiceConfig.d.ts +5 -0
  15. package/dist/types/models/IAuditableItemGraphServiceContext.d.ts +17 -0
  16. package/dist/types/restEntryPoints.d.ts +2 -0
  17. package/dist/types/schema.d.ts +4 -0
  18. package/docs/changelog.md +5 -0
  19. package/docs/examples.md +1 -0
  20. package/docs/open-api/spec.json +1032 -0
  21. package/docs/reference/classes/AuditableItemGraphAlias.md +61 -0
  22. package/docs/reference/classes/AuditableItemGraphChangeset.md +61 -0
  23. package/docs/reference/classes/AuditableItemGraphEdge.md +61 -0
  24. package/docs/reference/classes/AuditableItemGraphPatch.md +45 -0
  25. package/docs/reference/classes/AuditableItemGraphResource.md +53 -0
  26. package/docs/reference/classes/AuditableItemGraphService.md +289 -0
  27. package/docs/reference/classes/AuditableItemGraphVertex.md +85 -0
  28. package/docs/reference/functions/auditableItemGraphCreate.md +25 -0
  29. package/docs/reference/functions/auditableItemGraphGet.md +25 -0
  30. package/docs/reference/functions/auditableItemGraphList.md +25 -0
  31. package/docs/reference/functions/auditableItemGraphUpdate.md +25 -0
  32. package/docs/reference/functions/generateRestRoutesAuditableItemGraph.md +21 -0
  33. package/docs/reference/functions/initSchema.md +9 -0
  34. package/docs/reference/index.md +29 -0
  35. package/docs/reference/interfaces/IAuditableItemGraphServiceConfig.md +3 -0
  36. package/docs/reference/variables/restEntryPoints.md +3 -0
  37. package/docs/reference/variables/tagsAuditableItemGraph.md +5 -0
  38. package/locales/en.json +19 -0
  39. package/package.json +51 -0
@@ -0,0 +1,1606 @@
1
+ 'use strict';
2
+
3
+ var auditableItemGraphModels = require('@twin.org/auditable-item-graph-models');
4
+ var core = require('@twin.org/core');
5
+ var dataSchemaOrg = require('@twin.org/data-schema-org');
6
+ var web = require('@twin.org/web');
7
+ var dataJsonLd = require('@twin.org/data-json-ld');
8
+ var entity = require('@twin.org/entity');
9
+ var entityStorageModels = require('@twin.org/entity-storage-models');
10
+ var immutableProofModels = require('@twin.org/immutable-proof-models');
11
+
12
+ /**
13
+ * The source used when communicating about these routes.
14
+ */
15
+ const ROUTES_SOURCE = "auditableItemGraphRoutes";
16
+ /**
17
+ * The tag to associate with the routes.
18
+ */
19
+ const tagsAuditableItemGraph = [
20
+ {
21
+ name: "Auditable Item Graph",
22
+ description: "Endpoints which are modelled to access an auditable item graph contract."
23
+ }
24
+ ];
25
+ /**
26
+ * The REST routes for auditable item graph.
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 generateRestRoutesAuditableItemGraph(baseRouteName, componentName) {
32
+ const createRoute = {
33
+ operationId: "auditableItemGraphCreate",
34
+ summary: "Create a new graph vertex",
35
+ tag: tagsAuditableItemGraph[0].name,
36
+ method: "POST",
37
+ path: `${baseRouteName}/`,
38
+ handler: async (httpRequestContext, request) => auditableItemGraphCreate(httpRequestContext, componentName, request),
39
+ requestType: {
40
+ type: "IAuditableItemGraphCreateRequest",
41
+ examples: [
42
+ {
43
+ id: "auditableItemGraphCreateRequestExample",
44
+ request: {
45
+ body: {
46
+ vertexObject: {
47
+ "@context": "http://schema.org/",
48
+ "@type": "Note",
49
+ content: "This is a simple note"
50
+ },
51
+ aliases: [
52
+ {
53
+ id: "bar456",
54
+ aliasObject: {
55
+ "@context": "http://schema.org/",
56
+ "@type": "Note",
57
+ content: "This is a simple note"
58
+ }
59
+ },
60
+ {
61
+ id: "foo321",
62
+ aliasObject: {
63
+ "@context": "http://schema.org/",
64
+ "@type": "Note",
65
+ content: "This is a simple note"
66
+ }
67
+ }
68
+ ],
69
+ resources: [
70
+ {
71
+ id: "resource1",
72
+ resourceObject: {
73
+ "@context": "http://schema.org/",
74
+ "@type": "Note",
75
+ content: "This is a simple note"
76
+ }
77
+ },
78
+ {
79
+ id: "resource2",
80
+ resourceObject: {
81
+ "@context": "http://schema.org/",
82
+ "@type": "Note",
83
+ content: "This is a simple note"
84
+ }
85
+ }
86
+ ],
87
+ edges: [
88
+ {
89
+ id: "edge1",
90
+ edgeRelationship: "frenemy",
91
+ edgeObject: {
92
+ "@context": "http://schema.org/",
93
+ "@type": "Note",
94
+ content: "This is a simple note"
95
+ }
96
+ },
97
+ {
98
+ id: "edge2",
99
+ edgeRelationship: "end",
100
+ edgeObject: {
101
+ "@context": "http://schema.org/",
102
+ "@type": "Note",
103
+ content: "This is a simple note"
104
+ }
105
+ }
106
+ ]
107
+ }
108
+ }
109
+ }
110
+ ]
111
+ },
112
+ responseType: [
113
+ {
114
+ type: "ICreatedResponse",
115
+ examples: [
116
+ {
117
+ id: "auditableItemGraphCreateResponseExample",
118
+ description: "The response when a new graph vertex is created.",
119
+ response: {
120
+ statusCode: web.HttpStatusCode.created,
121
+ headers: {
122
+ [web.HeaderTypes.Location]: "aig:1234567890"
123
+ }
124
+ }
125
+ }
126
+ ]
127
+ }
128
+ ]
129
+ };
130
+ const getRoute = {
131
+ operationId: "auditableItemGraphGet",
132
+ summary: "Get a graph vertex",
133
+ tag: tagsAuditableItemGraph[0].name,
134
+ method: "GET",
135
+ path: `${baseRouteName}/:id`,
136
+ handler: async (httpRequestContext, request) => auditableItemGraphGet(httpRequestContext, componentName, request),
137
+ requestType: {
138
+ type: "IAuditableItemGraphGetRequest",
139
+ examples: [
140
+ {
141
+ id: "auditableItemGraphGetRequestExample",
142
+ request: {
143
+ headers: {
144
+ [web.HeaderTypes.Accept]: web.MimeTypes.Json
145
+ },
146
+ pathParams: {
147
+ id: "aig:1234567890"
148
+ }
149
+ }
150
+ }
151
+ ]
152
+ },
153
+ responseType: [
154
+ {
155
+ type: "IAuditableItemGraphGetResponse",
156
+ examples: [
157
+ {
158
+ id: "auditableItemGraphGetResponseExample",
159
+ response: {
160
+ body: {
161
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
162
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Vertex,
163
+ id: "aig:1234567890",
164
+ dateCreated: "2024-08-22T11:55:16.271Z",
165
+ dateModified: "2024-08-22T11:55:16.271Z",
166
+ vertexObject: {
167
+ "@context": "http://schema.org/",
168
+ "@type": "Note",
169
+ content: "This is a simple note"
170
+ },
171
+ aliases: [
172
+ {
173
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
174
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Alias,
175
+ id: "tst:1234567890",
176
+ dateCreated: "2024-08-22T11:55:16.271Z"
177
+ }
178
+ ]
179
+ }
180
+ }
181
+ }
182
+ ]
183
+ },
184
+ {
185
+ type: "IAuditableItemGraphGetResponse",
186
+ mimeType: web.MimeTypes.JsonLd,
187
+ examples: [
188
+ {
189
+ id: "auditableItemGraphJsonLdGetResponseExample",
190
+ response: {
191
+ headers: {
192
+ [web.HeaderTypes.ContentType]: web.MimeTypes.JsonLd
193
+ },
194
+ body: {
195
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
196
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Vertex,
197
+ id: "aig:1234567890",
198
+ dateCreated: "2024-08-22T11:55:16.271Z",
199
+ dateModified: "2024-08-22T11:55:16.271Z",
200
+ vertexObject: {
201
+ "@context": "http://schema.org/",
202
+ "@type": "Note",
203
+ content: "This is a simple note"
204
+ },
205
+ aliases: [
206
+ {
207
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
208
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Alias,
209
+ dateCreated: "2024-08-22T11:55:16.271Z",
210
+ id: "tst:1234567890"
211
+ }
212
+ ]
213
+ }
214
+ }
215
+ }
216
+ ]
217
+ }
218
+ ]
219
+ };
220
+ const updateRoute = {
221
+ operationId: "auditableItemGraphUpdate",
222
+ summary: "Update a graph vertex",
223
+ tag: tagsAuditableItemGraph[0].name,
224
+ method: "PUT",
225
+ path: `${baseRouteName}/:id`,
226
+ handler: async (httpRequestContext, request) => auditableItemGraphUpdate(httpRequestContext, componentName, request),
227
+ requestType: {
228
+ type: "IAuditableItemGraphUpdateRequest",
229
+ examples: [
230
+ {
231
+ id: "auditableItemGraphUpdateRequestExample",
232
+ request: {
233
+ pathParams: {
234
+ id: "aig:1234567890"
235
+ },
236
+ body: {
237
+ vertexObject: {
238
+ "@context": "http://schema.org/",
239
+ "@type": "Note",
240
+ content: "This is a simple note"
241
+ },
242
+ aliases: [
243
+ {
244
+ id: "bar456",
245
+ aliasObject: {
246
+ "@context": "http://schema.org/",
247
+ "@type": "Note",
248
+ content: "This is a simple note"
249
+ }
250
+ },
251
+ {
252
+ id: "foo321",
253
+ aliasObject: {
254
+ "@context": "http://schema.org/",
255
+ "@type": "Note",
256
+ content: "This is a simple note"
257
+ }
258
+ }
259
+ ],
260
+ resources: [
261
+ {
262
+ id: "resource1",
263
+ resourceObject: {
264
+ "@context": "http://schema.org/",
265
+ "@type": "Note",
266
+ content: "This is a simple note"
267
+ }
268
+ },
269
+ {
270
+ id: "resource2",
271
+ resourceObject: {
272
+ "@context": "http://schema.org/",
273
+ "@type": "Note",
274
+ content: "This is a simple note"
275
+ }
276
+ }
277
+ ],
278
+ edges: [
279
+ {
280
+ id: "edge1",
281
+ edgeRelationship: "frenemy",
282
+ edgeObject: {
283
+ "@context": "http://schema.org/",
284
+ "@type": "Note",
285
+ content: "This is a simple note"
286
+ }
287
+ },
288
+ {
289
+ id: "edge2",
290
+ edgeRelationship: "end",
291
+ edgeObject: {
292
+ "@context": "http://schema.org/",
293
+ "@type": "Note",
294
+ content: "This is a simple note"
295
+ }
296
+ }
297
+ ]
298
+ }
299
+ }
300
+ }
301
+ ]
302
+ },
303
+ responseType: [
304
+ {
305
+ type: "INoContentResponse"
306
+ }
307
+ ]
308
+ };
309
+ const listRoute = {
310
+ operationId: "auditableItemGraphList",
311
+ summary: "Query graph vertices by id or alias",
312
+ tag: tagsAuditableItemGraph[0].name,
313
+ method: "GET",
314
+ path: `${baseRouteName}/`,
315
+ handler: async (httpRequestContext, request) => auditableItemGraphList(httpRequestContext, componentName, request),
316
+ requestType: {
317
+ type: "IAuditableItemGraphListRequest",
318
+ examples: [
319
+ {
320
+ id: "IAuditableItemGraphListAllRequest",
321
+ request: {}
322
+ },
323
+ {
324
+ id: "IAuditableItemGraphListIdRequest",
325
+ request: {
326
+ query: {
327
+ id: "1234567890"
328
+ }
329
+ }
330
+ }
331
+ ]
332
+ },
333
+ responseType: [
334
+ {
335
+ type: "IAuditableItemGraphListResponse",
336
+ examples: [
337
+ {
338
+ id: "auditableItemGraphListResponseExample",
339
+ response: {
340
+ body: {
341
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
342
+ type: auditableItemGraphModels.AuditableItemGraphTypes.VertexList,
343
+ vertices: [
344
+ {
345
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
346
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Vertex,
347
+ id: "0101010101010101010101010101010101010101010101010101010101010101",
348
+ dateCreated: "2024-08-22T11:55:16.271Z",
349
+ aliases: [
350
+ {
351
+ "@context": [
352
+ auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot,
353
+ dataSchemaOrg.SchemaOrgTypes.ContextRoot
354
+ ],
355
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Alias,
356
+ id: "foo4",
357
+ dateCreated: "2024-08-22T11:55:16.271Z"
358
+ }
359
+ ]
360
+ }
361
+ ],
362
+ cursor: "1"
363
+ }
364
+ }
365
+ }
366
+ ]
367
+ },
368
+ {
369
+ type: "IAuditableItemGraphListResponse",
370
+ mimeType: web.MimeTypes.JsonLd,
371
+ examples: [
372
+ {
373
+ id: "auditableItemGraphJsonLdListResponseExample",
374
+ response: {
375
+ headers: {
376
+ [web.HeaderTypes.ContentType]: web.MimeTypes.JsonLd
377
+ },
378
+ body: {
379
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
380
+ type: auditableItemGraphModels.AuditableItemGraphTypes.VertexList,
381
+ vertices: [
382
+ {
383
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
384
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Vertex,
385
+ id: "0101010101010101010101010101010101010101010101010101010101010101",
386
+ dateCreated: "2024-08-22T11:55:16.271Z",
387
+ aliases: [
388
+ {
389
+ "@context": [
390
+ auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot,
391
+ dataSchemaOrg.SchemaOrgTypes.ContextRoot
392
+ ],
393
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Alias,
394
+ id: "foo4",
395
+ dateCreated: "2024-08-22T11:55:16.271Z"
396
+ }
397
+ ]
398
+ }
399
+ ],
400
+ cursor: "1"
401
+ }
402
+ }
403
+ }
404
+ ]
405
+ }
406
+ ]
407
+ };
408
+ return [createRoute, getRoute, updateRoute, listRoute];
409
+ }
410
+ /**
411
+ * Create the graph vertex.
412
+ * @param httpRequestContext The request context for the API.
413
+ * @param componentName The name of the component to use in the routes.
414
+ * @param request The request.
415
+ * @returns The response object with additional http response properties.
416
+ */
417
+ async function auditableItemGraphCreate(httpRequestContext, componentName, request) {
418
+ core.Guards.object(ROUTES_SOURCE, "request", request);
419
+ const component = core.ComponentFactory.get(componentName);
420
+ const id = await component.create(request.body?.vertexObject, request.body?.aliases, request.body?.resources, request.body?.edges, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
421
+ return {
422
+ statusCode: web.HttpStatusCode.created,
423
+ headers: {
424
+ [web.HeaderTypes.Location]: id
425
+ }
426
+ };
427
+ }
428
+ /**
429
+ * Get the graph vertex.
430
+ * @param httpRequestContext The request context for the API.
431
+ * @param componentName The name of the component to use in the routes.
432
+ * @param request The request.
433
+ * @returns The response object with additional http response properties.
434
+ */
435
+ async function auditableItemGraphGet(httpRequestContext, componentName, request) {
436
+ core.Guards.object(ROUTES_SOURCE, "request", request);
437
+ core.Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
438
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.id", request.pathParams.id);
439
+ const mimeType = request.headers?.[web.HeaderTypes.Accept] === web.MimeTypes.JsonLd ? "jsonld" : "json";
440
+ const component = core.ComponentFactory.get(componentName);
441
+ const result = await component.get(request.pathParams.id, {
442
+ includeDeleted: request.query?.includeDeleted,
443
+ includeChangesets: request.query?.includeChangesets,
444
+ verifySignatureDepth: request.query?.verifySignatureDepth
445
+ });
446
+ return {
447
+ headers: {
448
+ [web.HeaderTypes.ContentType]: mimeType === "json" ? web.MimeTypes.Json : web.MimeTypes.JsonLd
449
+ },
450
+ body: result
451
+ };
452
+ }
453
+ /**
454
+ * Update the 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 auditableItemGraphUpdate(httpRequestContext, componentName, request) {
461
+ core.Guards.object(ROUTES_SOURCE, "request", request);
462
+ core.Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
463
+ core.Guards.stringValue(ROUTES_SOURCE, "request.pathParams.id", request.pathParams.id);
464
+ const component = core.ComponentFactory.get(componentName);
465
+ await component.update(request.pathParams.id, request.body?.vertexObject, request.body?.aliases, request.body?.resources, request.body?.edges, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
466
+ return {
467
+ statusCode: web.HttpStatusCode.noContent
468
+ };
469
+ }
470
+ /**
471
+ * Query the graph vertices.
472
+ * @param httpRequestContext The request context for the API.
473
+ * @param componentName The name of the component to use in the routes.
474
+ * @param request The request.
475
+ * @returns The response object with additional http response properties.
476
+ */
477
+ async function auditableItemGraphList(httpRequestContext, componentName, request) {
478
+ core.Guards.object(ROUTES_SOURCE, "request", request);
479
+ core.Guards.object(ROUTES_SOURCE, "request.query", request.query);
480
+ const mimeType = request.headers?.[web.HeaderTypes.Accept] === web.MimeTypes.JsonLd ? "jsonld" : "json";
481
+ const component = core.ComponentFactory.get(componentName);
482
+ const result = await component.query({
483
+ id: request.query?.id,
484
+ idMode: request.query?.idMode
485
+ }, request.query?.orderBy, request.query?.orderByDirection, request.query?.properties?.split(","), request.query?.cursor, request.query?.pageSize);
486
+ return {
487
+ headers: {
488
+ [web.HeaderTypes.ContentType]: mimeType === "json" ? web.MimeTypes.Json : web.MimeTypes.JsonLd
489
+ },
490
+ body: result
491
+ };
492
+ }
493
+
494
+ // Copyright 2024 IOTA Stiftung.
495
+ // SPDX-License-Identifier: Apache-2.0.
496
+ /**
497
+ * Class for performing auditable item graph operations.
498
+ */
499
+ class AuditableItemGraphService {
500
+ /**
501
+ * The namespace for the service.
502
+ */
503
+ static NAMESPACE = "aig";
504
+ /**
505
+ * The namespace for the service changeset.
506
+ */
507
+ static NAMESPACE_CHANGESET = "changeset";
508
+ /**
509
+ * The keys to pick when creating the proof for the stream.
510
+ */
511
+ static _PROOF_KEYS_CHANGESET = [
512
+ "id",
513
+ "vertexId",
514
+ "userIdentity",
515
+ "dateCreated",
516
+ "patches"
517
+ ];
518
+ /**
519
+ * Runtime name for the class.
520
+ */
521
+ CLASS_NAME = "AuditableItemGraphService";
522
+ /**
523
+ * The immutable proof component.
524
+ * @internal
525
+ */
526
+ _immutableProofComponent;
527
+ /**
528
+ * The entity storage for vertices.
529
+ * @internal
530
+ */
531
+ _vertexStorage;
532
+ /**
533
+ * The entity storage for changesets.
534
+ * @internal
535
+ */
536
+ _changesetStorage;
537
+ /**
538
+ * Create a new instance of AuditableItemGraphService.
539
+ * @param options The dependencies for the auditable item graph connector.
540
+ * @param options.config The configuration for the connector.
541
+ * @param options.immutableProofComponentType The immutable proof component type, defaults to "immutable-proof".
542
+ * @param options.vertexEntityStorageType The entity storage for vertices, defaults to "auditable-item-graph-vertex".
543
+ * @param options.changesetEntityStorageType The entity storage for changesets, defaults to "auditable-item-graph-changeset".
544
+ */
545
+ constructor(options) {
546
+ this._immutableProofComponent = core.ComponentFactory.get(options?.immutableProofComponentType ?? "immutable-proof");
547
+ this._vertexStorage = entityStorageModels.EntityStorageConnectorFactory.get(options?.vertexEntityStorageType ?? core.StringHelper.kebabCase("AuditableItemGraphVertex"));
548
+ this._changesetStorage = entityStorageModels.EntityStorageConnectorFactory.get(options?.changesetEntityStorageType ??
549
+ core.StringHelper.kebabCase("AuditableItemGraphChangeset"));
550
+ dataSchemaOrg.SchemaOrgDataTypes.registerRedirects();
551
+ }
552
+ /**
553
+ * Create a new graph vertex.
554
+ * @param vertexObject The object for the vertex as JSON-LD.
555
+ * @param aliases Alternative aliases that can be used to identify the vertex.
556
+ * @param resources The resources attached to the vertex.
557
+ * @param edges The edges connected to the vertex.
558
+ * @param userIdentity The identity to create the auditable item graph operation with.
559
+ * @param nodeIdentity The node identity to include in the auditable item graph.
560
+ * @returns The id of the new graph item.
561
+ */
562
+ async create(vertexObject, aliases, resources, edges, userIdentity, nodeIdentity) {
563
+ core.Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
564
+ core.Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
565
+ try {
566
+ if (core.Is.object(vertexObject)) {
567
+ const validationFailures = [];
568
+ await dataJsonLd.JsonLdHelper.validate(vertexObject, validationFailures);
569
+ core.Validation.asValidationError(this.CLASS_NAME, "vertexObject", validationFailures);
570
+ }
571
+ const id = core.Converter.bytesToHex(core.RandomHelper.generate(32), false);
572
+ const context = {
573
+ now: new Date(Date.now()).toISOString(),
574
+ userIdentity,
575
+ nodeIdentity
576
+ };
577
+ const vertex = {
578
+ id,
579
+ nodeIdentity,
580
+ dateCreated: context.now,
581
+ dateModified: context.now
582
+ };
583
+ const originalEntity = core.ObjectHelper.clone(vertex);
584
+ vertex.vertexObject = vertexObject;
585
+ await this.updateAliasList(context, vertex, aliases);
586
+ await this.updateResourceList(context, vertex, resources);
587
+ await this.updateEdgeList(context, vertex, edges);
588
+ delete originalEntity.aliasIndex;
589
+ await this.addChangeset(context, originalEntity, vertex, true);
590
+ await this._vertexStorage.set({
591
+ ...vertex,
592
+ aliasIndex: vertex.aliases
593
+ ?.map(a => a.id)
594
+ .join("||")
595
+ .toLowerCase()
596
+ });
597
+ return new core.Urn(AuditableItemGraphService.NAMESPACE, id).toString();
598
+ }
599
+ catch (error) {
600
+ throw new core.GeneralError(this.CLASS_NAME, "createFailed", undefined, error);
601
+ }
602
+ }
603
+ /**
604
+ * Get a graph vertex.
605
+ * @param id The id of the vertex to get.
606
+ * @returns The vertex if found.
607
+ * @param options Additional options for the get operation.
608
+ * @param options.includeDeleted Whether to include deleted/updated aliases, resource, edges, defaults to false.
609
+ * @param options.includeChangesets Whether to include the changesets of the vertex, defaults to false.
610
+ * @param options.verifySignatureDepth How many signatures to verify, defaults to "none".
611
+ * @throws NotFoundError if the vertex is not found.
612
+ */
613
+ async get(id, options) {
614
+ core.Guards.stringValue(this.CLASS_NAME, "id", id);
615
+ const urnParsed = core.Urn.fromValidString(id);
616
+ if (urnParsed.namespaceIdentifier() !== AuditableItemGraphService.NAMESPACE) {
617
+ throw new core.GeneralError(this.CLASS_NAME, "namespaceMismatch", {
618
+ namespace: AuditableItemGraphService.NAMESPACE,
619
+ id
620
+ });
621
+ }
622
+ try {
623
+ const vertexId = urnParsed.namespaceSpecific(0);
624
+ const vertexEntity = await this._vertexStorage.get(vertexId);
625
+ if (core.Is.empty(vertexEntity)) {
626
+ throw new core.NotFoundError(this.CLASS_NAME, "vertexNotFound", id);
627
+ }
628
+ const vertexModel = this.vertexEntityToJsonLd(vertexEntity);
629
+ const includeChangesets = options?.includeChangesets ?? false;
630
+ const verifySignatureDepth = options?.verifySignatureDepth ?? "none";
631
+ let verified;
632
+ let changesets;
633
+ if (verifySignatureDepth === auditableItemGraphModels.VerifyDepth.Current ||
634
+ verifySignatureDepth === auditableItemGraphModels.VerifyDepth.All ||
635
+ includeChangesets) {
636
+ const verifyResult = await this.verifyChangesets(vertexModel, verifySignatureDepth);
637
+ verified = verifyResult.verified;
638
+ changesets = verifyResult.changesets;
639
+ }
640
+ if (!(options?.includeDeleted ?? false)) {
641
+ if (core.Is.arrayValue(vertexModel.aliases)) {
642
+ vertexModel.aliases = vertexModel.aliases.filter(a => core.Is.undefined(a.dateDeleted));
643
+ if (vertexModel.aliases.length === 0) {
644
+ delete vertexModel.aliases;
645
+ }
646
+ }
647
+ if (core.Is.arrayValue(vertexModel.resources)) {
648
+ vertexModel.resources = vertexModel.resources.filter(r => core.Is.undefined(r.dateDeleted));
649
+ if (vertexModel.resources.length === 0) {
650
+ delete vertexModel.resources;
651
+ }
652
+ }
653
+ if (core.Is.arrayValue(vertexModel.edges)) {
654
+ vertexModel.edges = vertexModel.edges.filter(r => core.Is.undefined(r.dateDeleted));
655
+ if (vertexModel.edges.length === 0) {
656
+ delete vertexModel.edges;
657
+ }
658
+ }
659
+ }
660
+ if (includeChangesets) {
661
+ vertexModel.changesets = changesets;
662
+ }
663
+ if (verifySignatureDepth !== auditableItemGraphModels.VerifyDepth.None) {
664
+ vertexModel.verified = verified;
665
+ }
666
+ const compacted = await dataJsonLd.JsonLdProcessor.compact(vertexModel, vertexModel["@context"]);
667
+ return compacted;
668
+ }
669
+ catch (error) {
670
+ throw new core.GeneralError(this.CLASS_NAME, "getFailed", undefined, error);
671
+ }
672
+ }
673
+ /**
674
+ * Update a graph vertex.
675
+ * @param id The id of the vertex to update.
676
+ * @param vertexObject The object for the vertex.
677
+ * @param aliases Alternative aliases that can be used to identify the vertex.
678
+ * @param resources The resources attached to the vertex.
679
+ * @param edges The edges connected to the vertex.
680
+ * @param userIdentity The identity to create the auditable item graph operation with.
681
+ * @param nodeIdentity The node identity to include in the auditable item graph.
682
+ * @returns Nothing.
683
+ */
684
+ async update(id, vertexObject, aliases, resources, edges, userIdentity, nodeIdentity) {
685
+ core.Guards.stringValue(this.CLASS_NAME, "id", id);
686
+ core.Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
687
+ core.Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
688
+ const urnParsed = core.Urn.fromValidString(id);
689
+ if (urnParsed.namespaceIdentifier() !== AuditableItemGraphService.NAMESPACE) {
690
+ throw new core.GeneralError(this.CLASS_NAME, "namespaceMismatch", {
691
+ namespace: AuditableItemGraphService.NAMESPACE,
692
+ id
693
+ });
694
+ }
695
+ try {
696
+ const vertexId = urnParsed.namespaceSpecific(0);
697
+ const vertexEntity = await this._vertexStorage.get(vertexId);
698
+ if (core.Is.empty(vertexEntity)) {
699
+ throw new core.NotFoundError(this.CLASS_NAME, "vertexNotFound", id);
700
+ }
701
+ if (core.Is.object(vertexObject)) {
702
+ const validationFailures = [];
703
+ await dataJsonLd.JsonLdHelper.validate(vertexObject, validationFailures);
704
+ core.Validation.asValidationError(this.CLASS_NAME, "vertexObject", validationFailures);
705
+ }
706
+ const context = {
707
+ now: new Date(Date.now()).toISOString(),
708
+ userIdentity,
709
+ nodeIdentity
710
+ };
711
+ delete vertexEntity.aliasIndex;
712
+ const originalEntity = core.ObjectHelper.clone(vertexEntity);
713
+ const newEntity = core.ObjectHelper.clone(vertexEntity);
714
+ newEntity.vertexObject = vertexObject;
715
+ await this.updateAliasList(context, newEntity, aliases);
716
+ await this.updateResourceList(context, newEntity, resources);
717
+ await this.updateEdgeList(context, newEntity, edges);
718
+ const changes = await this.addChangeset(context, originalEntity, newEntity, false);
719
+ if (changes) {
720
+ newEntity.dateModified = context.now;
721
+ await this._vertexStorage.set({
722
+ ...newEntity,
723
+ aliasIndex: newEntity.aliases
724
+ ?.map(a => a.id)
725
+ .join("||")
726
+ .toLowerCase()
727
+ });
728
+ }
729
+ }
730
+ catch (error) {
731
+ throw new core.GeneralError(this.CLASS_NAME, "updateFailed", undefined, error);
732
+ }
733
+ }
734
+ /**
735
+ * Remove the immutable storage for an item.
736
+ * @param id The id of the vertex to get.
737
+ * @param nodeIdentity The node identity to use for vault operations.
738
+ * @returns Nothing.
739
+ * @throws NotFoundError if the vertex is not found.
740
+ */
741
+ async removeImmutable(id, nodeIdentity) {
742
+ core.Guards.stringValue(this.CLASS_NAME, "id", id);
743
+ core.Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
744
+ const urnParsed = core.Urn.fromValidString(id);
745
+ if (urnParsed.namespaceIdentifier() !== AuditableItemGraphService.NAMESPACE) {
746
+ throw new core.GeneralError(this.CLASS_NAME, "namespaceMismatch", {
747
+ namespace: AuditableItemGraphService.NAMESPACE,
748
+ id
749
+ });
750
+ }
751
+ try {
752
+ const vertexId = urnParsed.namespaceSpecific(0);
753
+ const vertexEntity = await this._vertexStorage.get(vertexId);
754
+ if (core.Is.empty(vertexEntity)) {
755
+ throw new core.NotFoundError(this.CLASS_NAME, "vertexNotFound", id);
756
+ }
757
+ let changesetsResult;
758
+ do {
759
+ changesetsResult = await this._changesetStorage.query({
760
+ property: "vertexId",
761
+ value: vertexId,
762
+ comparison: entity.ComparisonOperator.Equals
763
+ }, [
764
+ {
765
+ property: "dateCreated",
766
+ sortDirection: entity.SortDirection.Ascending
767
+ }
768
+ ], undefined, changesetsResult?.cursor);
769
+ for (const changeset of changesetsResult.entities) {
770
+ if (core.Is.stringValue(changeset.proofId)) {
771
+ await this._immutableProofComponent.removeImmutable(changeset.proofId, nodeIdentity);
772
+ delete changeset.proofId;
773
+ await this._changesetStorage.set(changeset);
774
+ }
775
+ }
776
+ } while (core.Is.stringValue(changesetsResult.cursor));
777
+ }
778
+ catch (error) {
779
+ throw new core.GeneralError(this.CLASS_NAME, "removeImmutableFailed", undefined, error);
780
+ }
781
+ }
782
+ /**
783
+ * Query the graph for vertices.
784
+ * @param options The query options.
785
+ * @param options.id The optional id to look for.
786
+ * @param options.idMode Look in id, alias or both, defaults to both.
787
+ * @param orderBy The order for the results, defaults to created.
788
+ * @param orderByDirection The direction for the order, defaults to desc.
789
+ * @param properties The properties to return, if not provided defaults to id, created, aliases and object.
790
+ * @param cursor The cursor to request the next page of entities.
791
+ * @param pageSize The maximum number of entities in a page.
792
+ * @returns The entities, which can be partial if a limited keys list was provided.
793
+ */
794
+ async query(options, orderBy, orderByDirection, properties, cursor, pageSize) {
795
+ try {
796
+ const propertiesToReturn = properties ?? [
797
+ "id",
798
+ "dateCreated",
799
+ "dateModified",
800
+ "aliases",
801
+ "vertexObject"
802
+ ];
803
+ const conditions = [];
804
+ const orderProperty = orderBy ?? "dateCreated";
805
+ const orderDirection = orderByDirection ?? entity.SortDirection.Descending;
806
+ const idOrAlias = options?.id;
807
+ if (core.Is.stringValue(idOrAlias)) {
808
+ const idMode = options?.idMode ?? "both";
809
+ if (idMode === "id" || idMode === "both") {
810
+ conditions.push({
811
+ property: "id",
812
+ comparison: entity.ComparisonOperator.Includes,
813
+ value: idOrAlias
814
+ });
815
+ }
816
+ if (idMode === "alias" || idMode === "both") {
817
+ conditions.push({
818
+ property: "aliasIndex",
819
+ comparison: entity.ComparisonOperator.Includes,
820
+ value: idOrAlias.toLowerCase()
821
+ });
822
+ }
823
+ }
824
+ if (!propertiesToReturn.includes("id")) {
825
+ propertiesToReturn.unshift("id");
826
+ }
827
+ const results = await this._vertexStorage.query(conditions.length > 0
828
+ ? {
829
+ conditions,
830
+ logicalOperator: entity.LogicalOperator.Or
831
+ }
832
+ : undefined, [
833
+ {
834
+ property: orderProperty,
835
+ sortDirection: orderDirection
836
+ }
837
+ ], propertiesToReturn, cursor, pageSize);
838
+ const models = results.entities.map(e => this.vertexEntityToJsonLd(e));
839
+ const vertexList = {
840
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
841
+ type: auditableItemGraphModels.AuditableItemGraphTypes.VertexList,
842
+ vertices: models,
843
+ cursor: results.cursor
844
+ };
845
+ const compacted = await dataJsonLd.JsonLdProcessor.compact(vertexList, vertexList["@context"]);
846
+ return compacted;
847
+ }
848
+ catch (error) {
849
+ throw new core.GeneralError(this.CLASS_NAME, "queryingFailed", undefined, error);
850
+ }
851
+ }
852
+ /**
853
+ * Map the vertex entity to JSON-LD.
854
+ * @param vertexEntity The vertex entity.
855
+ * @returns The model.
856
+ * @internal
857
+ */
858
+ vertexEntityToJsonLd(vertexEntity) {
859
+ const model = {
860
+ "@context": [
861
+ auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot,
862
+ immutableProofModels.ImmutableProofTypes.ContextRoot,
863
+ dataSchemaOrg.SchemaOrgTypes.ContextRoot
864
+ ],
865
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Vertex,
866
+ id: vertexEntity.id,
867
+ dateCreated: vertexEntity.dateCreated,
868
+ dateModified: vertexEntity.dateModified,
869
+ nodeIdentity: vertexEntity.nodeIdentity,
870
+ vertexObject: vertexEntity.vertexObject
871
+ };
872
+ if (core.Is.arrayValue(vertexEntity.aliases)) {
873
+ model.aliases ??= [];
874
+ for (const aliasEntity of vertexEntity.aliases) {
875
+ const aliasModel = {
876
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
877
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Alias,
878
+ id: aliasEntity.id,
879
+ aliasFormat: aliasEntity.aliasFormat,
880
+ dateCreated: aliasEntity.dateCreated,
881
+ dateModified: aliasEntity.dateModified,
882
+ dateDeleted: aliasEntity.dateDeleted,
883
+ aliasObject: aliasEntity.aliasObject
884
+ };
885
+ model.aliases.push(aliasModel);
886
+ }
887
+ }
888
+ if (core.Is.arrayValue(vertexEntity.resources)) {
889
+ model.resources ??= [];
890
+ for (const resourceEntity of vertexEntity.resources) {
891
+ const resourceModel = {
892
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
893
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Resource,
894
+ id: resourceEntity.id,
895
+ dateCreated: resourceEntity.dateCreated,
896
+ dateModified: resourceEntity.dateModified,
897
+ dateDeleted: resourceEntity.dateDeleted,
898
+ resourceObject: resourceEntity.resourceObject
899
+ };
900
+ model.resources.push(resourceModel);
901
+ }
902
+ }
903
+ if (core.Is.arrayValue(vertexEntity.edges)) {
904
+ model.edges ??= [];
905
+ for (const edgeEntity of vertexEntity.edges) {
906
+ const edgeModel = {
907
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
908
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Edge,
909
+ id: edgeEntity.id,
910
+ dateCreated: edgeEntity.dateCreated,
911
+ dateModified: edgeEntity.dateModified,
912
+ dateDeleted: edgeEntity.dateDeleted,
913
+ edgeRelationship: edgeEntity.edgeRelationship,
914
+ edgeObject: edgeEntity.edgeObject
915
+ };
916
+ model.edges.push(edgeModel);
917
+ }
918
+ }
919
+ return model;
920
+ }
921
+ /**
922
+ * Map the changeset entity to a JSON-LD.
923
+ * @param changesetEntity The changeset entity.
924
+ * @returns The model.
925
+ * @internal
926
+ */
927
+ changesetEntityToJsonLd(changesetEntity) {
928
+ const model = {
929
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
930
+ type: auditableItemGraphModels.AuditableItemGraphTypes.Changeset,
931
+ id: changesetEntity.id,
932
+ dateCreated: changesetEntity.dateCreated,
933
+ userIdentity: changesetEntity.userIdentity,
934
+ patches: changesetEntity.patches.map(p => ({
935
+ "@context": [auditableItemGraphModels.AuditableItemGraphTypes.ContextRoot, dataSchemaOrg.SchemaOrgTypes.ContextRoot],
936
+ type: auditableItemGraphModels.AuditableItemGraphTypes.PatchOperation,
937
+ patchOperation: p.op,
938
+ patchPath: p.path,
939
+ patchFrom: p.from,
940
+ patchValue: p.value
941
+ })),
942
+ proofId: changesetEntity.proofId
943
+ };
944
+ return model;
945
+ }
946
+ /**
947
+ * Update the aliases of a vertex model.
948
+ * @param context The context for the operation.
949
+ * @param vertex The vertex.
950
+ * @param aliases The aliases to update.
951
+ * @internal
952
+ */
953
+ async updateAliasList(context, vertex, aliases) {
954
+ const active = vertex.aliases?.filter(a => core.Is.empty(a.dateDeleted)) ?? [];
955
+ // The active aliases that are not in the update list should be marked as deleted.
956
+ if (core.Is.arrayValue(active)) {
957
+ for (const alias of active) {
958
+ if (!aliases?.find(a => a.id === alias.id)) {
959
+ alias.dateDeleted = context.now;
960
+ }
961
+ }
962
+ }
963
+ if (core.Is.arrayValue(aliases)) {
964
+ for (const alias of aliases) {
965
+ await this.updateAlias(context, vertex, alias);
966
+ }
967
+ }
968
+ }
969
+ /**
970
+ * Update an alias in the vertex.
971
+ * @param context The context for the operation.
972
+ * @param vertex The vertex.
973
+ * @param alias The alias.
974
+ * @internal
975
+ */
976
+ async updateAlias(context, vertex, alias) {
977
+ core.Guards.object(this.CLASS_NAME, "alias", alias);
978
+ core.Guards.stringValue(this.CLASS_NAME, "alias.id", alias.id);
979
+ if (core.Is.object(alias.aliasObject)) {
980
+ const validationFailures = [];
981
+ await dataJsonLd.JsonLdHelper.validate(alias.aliasObject, validationFailures);
982
+ core.Validation.asValidationError(this.CLASS_NAME, "alias.aliasObject", validationFailures);
983
+ }
984
+ // Try to find an existing alias with the same id.
985
+ const existing = vertex.aliases?.find(a => a.id === alias.id);
986
+ if (core.Is.empty(existing) || !core.Is.empty(existing?.dateDeleted)) {
987
+ // Did not find a matching item, or found one which is deleted.
988
+ vertex.aliases ??= [];
989
+ const model = {
990
+ id: alias.id,
991
+ aliasFormat: alias.aliasFormat,
992
+ dateCreated: context.now,
993
+ aliasObject: alias.aliasObject
994
+ };
995
+ vertex.aliases.push(model);
996
+ }
997
+ else if (existing.aliasFormat !== alias.aliasFormat ||
998
+ !core.ObjectHelper.equal(existing.aliasObject, alias.aliasObject, false)) {
999
+ // Existing alias found, update the aliasObject.
1000
+ existing.dateModified = context.now;
1001
+ existing.aliasFormat = alias.aliasFormat;
1002
+ existing.aliasObject = alias.aliasObject;
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Update the resources of a vertex.
1007
+ * @param context The context for the operation.
1008
+ * @param vertex The vertex.
1009
+ * @param resources The resources to update.
1010
+ * @internal
1011
+ */
1012
+ async updateResourceList(context, vertex, resources) {
1013
+ const active = vertex.resources?.filter(r => core.Is.empty(r.dateDeleted)) ?? [];
1014
+ // The active resources that are not in the update list should be marked as deleted.
1015
+ if (core.Is.arrayValue(active)) {
1016
+ for (const resource of active) {
1017
+ if (!resources?.find(a => a.id === resource.id)) {
1018
+ resource.dateDeleted = context.now;
1019
+ }
1020
+ }
1021
+ }
1022
+ if (core.Is.arrayValue(resources)) {
1023
+ for (const resource of resources) {
1024
+ await this.updateResource(context, vertex, resource);
1025
+ }
1026
+ }
1027
+ }
1028
+ /**
1029
+ * Add a resource to the vertex.
1030
+ * @param context The context for the operation.
1031
+ * @param vertex The vertex.
1032
+ * @param resource The resource.
1033
+ * @internal
1034
+ */
1035
+ async updateResource(context, vertex, resource) {
1036
+ core.Guards.object(this.CLASS_NAME, "resource", resource);
1037
+ core.Guards.stringValue(this.CLASS_NAME, "resource.id", resource.id);
1038
+ if (core.Is.object(resource.resourceObject)) {
1039
+ const validationFailures = [];
1040
+ await dataJsonLd.JsonLdHelper.validate(resource.resourceObject, validationFailures);
1041
+ core.Validation.asValidationError(this.CLASS_NAME, "resource.resourceObject", validationFailures);
1042
+ }
1043
+ // Try to find an existing resource with the same id.
1044
+ const existing = vertex.resources?.find(r => r.id === resource.id);
1045
+ if (core.Is.empty(existing) || !core.Is.empty(existing?.dateDeleted)) {
1046
+ // Did not find a matching item, or found one which is deleted.
1047
+ vertex.resources ??= [];
1048
+ const model = {
1049
+ id: resource.id,
1050
+ dateCreated: context.now,
1051
+ resourceObject: resource.resourceObject
1052
+ };
1053
+ vertex.resources.push(model);
1054
+ }
1055
+ else if (!core.ObjectHelper.equal(existing.resourceObject, resource.resourceObject, false)) {
1056
+ // Existing resource found, update the resourceObject.
1057
+ existing.dateModified = context.now;
1058
+ existing.resourceObject = resource.resourceObject;
1059
+ }
1060
+ }
1061
+ /**
1062
+ * Update the edges of a vertex.
1063
+ * @param context The context for the operation.
1064
+ * @param vertex The vertex.
1065
+ * @param edges The edges to update.
1066
+ * @internal
1067
+ */
1068
+ async updateEdgeList(context, vertex, edges) {
1069
+ const active = vertex.edges?.filter(e => core.Is.empty(e.dateDeleted)) ?? [];
1070
+ // The active edges that are not in the update list should be marked as deleted.
1071
+ if (core.Is.arrayValue(active)) {
1072
+ for (const edge of active) {
1073
+ if (!edges?.find(a => a.id === edge.id)) {
1074
+ edge.dateDeleted = context.now;
1075
+ }
1076
+ }
1077
+ }
1078
+ if (core.Is.arrayValue(edges)) {
1079
+ for (const edge of edges) {
1080
+ await this.updateEdge(context, vertex, edge);
1081
+ }
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Add an edge to the vertex.
1086
+ * @param context The context for the operation.
1087
+ * @param vertex The vertex.
1088
+ * @param edge The edge.
1089
+ * @internal
1090
+ */
1091
+ async updateEdge(context, vertex, edge) {
1092
+ core.Guards.object(this.CLASS_NAME, "edge", edge);
1093
+ core.Guards.stringValue(this.CLASS_NAME, "edge.id", edge.id);
1094
+ core.Guards.stringValue(this.CLASS_NAME, "edge.edgeRelationship", edge.edgeRelationship);
1095
+ if (core.Is.object(edge.edgeObject)) {
1096
+ const validationFailures = [];
1097
+ await dataJsonLd.JsonLdHelper.validate(edge.edgeObject, validationFailures);
1098
+ core.Validation.asValidationError(this.CLASS_NAME, "edge.edgeObject", validationFailures);
1099
+ }
1100
+ // Try to find an existing edge with the same id.
1101
+ const existing = vertex.edges?.find(r => r.id === edge.id);
1102
+ if (core.Is.empty(existing) || !core.Is.empty(existing?.dateDeleted)) {
1103
+ // Did not find a matching item, or found one which is deleted.
1104
+ vertex.edges ??= [];
1105
+ const model = {
1106
+ id: edge.id,
1107
+ dateCreated: context.now,
1108
+ edgeObject: edge.edgeObject,
1109
+ edgeRelationship: edge.edgeRelationship
1110
+ };
1111
+ vertex.edges.push(model);
1112
+ }
1113
+ else if (existing.edgeRelationship !== edge.edgeRelationship ||
1114
+ !core.ObjectHelper.equal(existing.edgeObject, edge.edgeObject, false)) {
1115
+ // Existing resource found, update the edgeObject.
1116
+ existing.dateModified = context.now;
1117
+ existing.edgeRelationship = edge.edgeRelationship;
1118
+ existing.edgeObject = edge.edgeObject;
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Add a changeset to the vertex and generate the associated verifications.
1123
+ * @param context The context for the operation.
1124
+ * @param original The original vertex.
1125
+ * @param updated The updated vertex.
1126
+ * @param isNew Whether this is a new item.
1127
+ * @returns True if there were changes.
1128
+ * @internal
1129
+ */
1130
+ async addChangeset(context, original, updated, isNew) {
1131
+ const patches = core.JsonHelper.diff(original, updated);
1132
+ // If there is a diff set or this is the first time the item is created.
1133
+ if (patches.length > 0 || isNew) {
1134
+ const changesetEntity = {
1135
+ id: core.Converter.bytesToHex(core.RandomHelper.generate(32), false),
1136
+ vertexId: updated.id,
1137
+ dateCreated: context.now,
1138
+ userIdentity: context.userIdentity,
1139
+ patches,
1140
+ proofId: ""
1141
+ };
1142
+ // Create the JSON-LD object we want to use for the proof
1143
+ // this is a subset of fixed properties from the changeset object.
1144
+ const reducedChangesetJsonLd = await this.changesetEntityToJsonLd({
1145
+ ...core.ObjectHelper.pick(changesetEntity, AuditableItemGraphService._PROOF_KEYS_CHANGESET),
1146
+ id: `${AuditableItemGraphService.NAMESPACE}:${updated.id}:${AuditableItemGraphService.NAMESPACE_CHANGESET}:${changesetEntity.id}`
1147
+ });
1148
+ // Create the proof for the changeset object
1149
+ changesetEntity.proofId = await this._immutableProofComponent.create(reducedChangesetJsonLd, context.userIdentity, context.nodeIdentity);
1150
+ // Link the immutable storage id to the changeset
1151
+ await this._changesetStorage.set(changesetEntity);
1152
+ return true;
1153
+ }
1154
+ return false;
1155
+ }
1156
+ /**
1157
+ * Verify the changesets of a vertex.
1158
+ * @param nodeIdentity The node identity to verify the changesets with.
1159
+ * @param vertex The vertex to verify.
1160
+ * @param verifySignatureDepth How many signatures to verify.
1161
+ * @internal
1162
+ */
1163
+ async verifyChangesets(vertex, verifySignatureDepth) {
1164
+ const changesets = [];
1165
+ let changesetsResult;
1166
+ let verified = true;
1167
+ do {
1168
+ changesetsResult = await this._changesetStorage.query({
1169
+ property: "vertexId",
1170
+ value: vertex.id,
1171
+ comparison: entity.ComparisonOperator.Equals
1172
+ }, [
1173
+ {
1174
+ property: "dateCreated",
1175
+ sortDirection: entity.SortDirection.Ascending
1176
+ }
1177
+ ], undefined, changesetsResult?.cursor);
1178
+ const storedChangesets = changesetsResult.entities;
1179
+ if (core.Is.arrayValue(storedChangesets)) {
1180
+ for (let i = 0; i < storedChangesets.length; i++) {
1181
+ const storedChangeset = storedChangesets[i];
1182
+ const storedChangesetJsonLd = this.changesetEntityToJsonLd(storedChangeset);
1183
+ changesets.push(storedChangesetJsonLd);
1184
+ // If we are verifying all signatures
1185
+ // or this is the last changeset (cursor is empty)
1186
+ // and the changeset has a proofId, then verify the proof.
1187
+ if (verifySignatureDepth === auditableItemGraphModels.VerifyDepth.All ||
1188
+ (verifySignatureDepth === auditableItemGraphModels.VerifyDepth.Current &&
1189
+ !core.Is.stringValue(changesetsResult.cursor) &&
1190
+ i === storedChangesets.length - 1)) {
1191
+ if (!core.Is.stringValue(storedChangeset.proofId)) {
1192
+ verified = false;
1193
+ storedChangesetJsonLd.verification = {
1194
+ "@context": immutableProofModels.ImmutableProofTypes.ContextRoot,
1195
+ type: immutableProofModels.ImmutableProofTypes.ImmutableProofVerification,
1196
+ verified: false,
1197
+ failure: immutableProofModels.ImmutableProofFailure.ProofMissing
1198
+ };
1199
+ }
1200
+ else {
1201
+ // Create the JSON-LD object we want to use for the proof
1202
+ // this is a subset of fixed properties from the changeset object.
1203
+ const reducedChangesetJsonLd = await this.changesetEntityToJsonLd(core.ObjectHelper.pick(storedChangeset, AuditableItemGraphService._PROOF_KEYS_CHANGESET));
1204
+ // Verify the proof for the changeset object
1205
+ storedChangesetJsonLd.verification = await this._immutableProofComponent.verify(storedChangeset.proofId, reducedChangesetJsonLd);
1206
+ if (!storedChangesetJsonLd.verification.verified) {
1207
+ verified = false;
1208
+ }
1209
+ }
1210
+ }
1211
+ }
1212
+ }
1213
+ } while (core.Is.stringValue(changesetsResult.cursor));
1214
+ return {
1215
+ verified,
1216
+ changesets
1217
+ };
1218
+ }
1219
+ }
1220
+
1221
+ // Copyright 2024 IOTA Stiftung.
1222
+ // SPDX-License-Identifier: Apache-2.0.
1223
+ /**
1224
+ * Class describing the auditable item graph alias.
1225
+ */
1226
+ exports.AuditableItemGraphAlias = class AuditableItemGraphAlias {
1227
+ /**
1228
+ * The alternative alias for the vertex.
1229
+ */
1230
+ id;
1231
+ /**
1232
+ * The format of the alias for the vertex.
1233
+ */
1234
+ aliasFormat;
1235
+ /**
1236
+ * The date/time of when the alias was created.
1237
+ */
1238
+ dateCreated;
1239
+ /**
1240
+ * The date/time of when the alias was last modified.
1241
+ */
1242
+ dateModified;
1243
+ /**
1244
+ * The timestamp of when the alias was deleted, as we never actually remove items.
1245
+ */
1246
+ dateDeleted;
1247
+ /**
1248
+ * Object to associate with the alias as JSON-LD.
1249
+ */
1250
+ aliasObject;
1251
+ };
1252
+ __decorate([
1253
+ entity.property({ type: "string" }),
1254
+ __metadata("design:type", String)
1255
+ ], exports.AuditableItemGraphAlias.prototype, "id", void 0);
1256
+ __decorate([
1257
+ entity.property({ type: "string" }),
1258
+ __metadata("design:type", String)
1259
+ ], exports.AuditableItemGraphAlias.prototype, "aliasFormat", void 0);
1260
+ __decorate([
1261
+ entity.property({ type: "string", format: "date-time" }),
1262
+ __metadata("design:type", String)
1263
+ ], exports.AuditableItemGraphAlias.prototype, "dateCreated", void 0);
1264
+ __decorate([
1265
+ entity.property({ type: "string", format: "date-time" }),
1266
+ __metadata("design:type", String)
1267
+ ], exports.AuditableItemGraphAlias.prototype, "dateModified", void 0);
1268
+ __decorate([
1269
+ entity.property({ type: "string", format: "date-time" }),
1270
+ __metadata("design:type", String)
1271
+ ], exports.AuditableItemGraphAlias.prototype, "dateDeleted", void 0);
1272
+ __decorate([
1273
+ entity.property({ type: "object", itemTypeRef: dataJsonLd.JsonLdTypes.NodeObject }),
1274
+ __metadata("design:type", Object)
1275
+ ], exports.AuditableItemGraphAlias.prototype, "aliasObject", void 0);
1276
+ exports.AuditableItemGraphAlias = __decorate([
1277
+ entity.entity()
1278
+ ], exports.AuditableItemGraphAlias);
1279
+
1280
+ // Copyright 2024 IOTA Stiftung.
1281
+ // SPDX-License-Identifier: Apache-2.0.
1282
+ /**
1283
+ * Class describing a set of updates to the vertex.
1284
+ */
1285
+ exports.AuditableItemGraphChangeset = class AuditableItemGraphChangeset {
1286
+ /**
1287
+ * The id of the changeset.
1288
+ */
1289
+ id;
1290
+ /**
1291
+ * The vertex the changeset belongs to.
1292
+ */
1293
+ vertexId;
1294
+ /**
1295
+ * The date/time of when the changeset was created.
1296
+ */
1297
+ dateCreated;
1298
+ /**
1299
+ * The identity of the user who made the changeset.
1300
+ */
1301
+ userIdentity;
1302
+ /**
1303
+ * The patches in the changeset.
1304
+ */
1305
+ patches;
1306
+ /**
1307
+ * The immutable proof id which contains the signature for this changeset.
1308
+ */
1309
+ proofId;
1310
+ };
1311
+ __decorate([
1312
+ entity.property({ type: "string", isPrimary: true }),
1313
+ __metadata("design:type", String)
1314
+ ], exports.AuditableItemGraphChangeset.prototype, "id", void 0);
1315
+ __decorate([
1316
+ entity.property({ type: "string", isSecondary: true }),
1317
+ __metadata("design:type", String)
1318
+ ], exports.AuditableItemGraphChangeset.prototype, "vertexId", void 0);
1319
+ __decorate([
1320
+ entity.property({ type: "string", format: "date-time", sortDirection: entity.SortDirection.Descending }),
1321
+ __metadata("design:type", String)
1322
+ ], exports.AuditableItemGraphChangeset.prototype, "dateCreated", void 0);
1323
+ __decorate([
1324
+ entity.property({ type: "string" }),
1325
+ __metadata("design:type", String)
1326
+ ], exports.AuditableItemGraphChangeset.prototype, "userIdentity", void 0);
1327
+ __decorate([
1328
+ entity.property({ type: "array", itemTypeRef: "AuditableItemGraphPatch" }),
1329
+ __metadata("design:type", Array)
1330
+ ], exports.AuditableItemGraphChangeset.prototype, "patches", void 0);
1331
+ __decorate([
1332
+ entity.property({ type: "string" }),
1333
+ __metadata("design:type", String)
1334
+ ], exports.AuditableItemGraphChangeset.prototype, "proofId", void 0);
1335
+ exports.AuditableItemGraphChangeset = __decorate([
1336
+ entity.entity()
1337
+ ], exports.AuditableItemGraphChangeset);
1338
+
1339
+ // Copyright 2024 IOTA Stiftung.
1340
+ // SPDX-License-Identifier: Apache-2.0.
1341
+ /**
1342
+ * Class describing the auditable item graph edge.
1343
+ */
1344
+ exports.AuditableItemGraphEdge = class AuditableItemGraphEdge {
1345
+ /**
1346
+ * The id of the edge.
1347
+ */
1348
+ id;
1349
+ /**
1350
+ * The date/time of when the edge was created.
1351
+ */
1352
+ dateCreated;
1353
+ /**
1354
+ * The date/time of when the edge was last modified.
1355
+ */
1356
+ dateModified;
1357
+ /**
1358
+ * The timestamp of when the edge was deleted, as we never actually remove items.
1359
+ */
1360
+ dateDeleted;
1361
+ /**
1362
+ * The relationship between the two vertices.
1363
+ */
1364
+ edgeRelationship;
1365
+ /**
1366
+ * Object to associate with the edge as JSON-LD.
1367
+ */
1368
+ edgeObject;
1369
+ };
1370
+ __decorate([
1371
+ entity.property({ type: "string" }),
1372
+ __metadata("design:type", String)
1373
+ ], exports.AuditableItemGraphEdge.prototype, "id", void 0);
1374
+ __decorate([
1375
+ entity.property({ type: "string", format: "date-time" }),
1376
+ __metadata("design:type", String)
1377
+ ], exports.AuditableItemGraphEdge.prototype, "dateCreated", void 0);
1378
+ __decorate([
1379
+ entity.property({ type: "string", format: "date-time" }),
1380
+ __metadata("design:type", String)
1381
+ ], exports.AuditableItemGraphEdge.prototype, "dateModified", void 0);
1382
+ __decorate([
1383
+ entity.property({ type: "string", format: "date-time" }),
1384
+ __metadata("design:type", String)
1385
+ ], exports.AuditableItemGraphEdge.prototype, "dateDeleted", void 0);
1386
+ __decorate([
1387
+ entity.property({ type: "string" }),
1388
+ __metadata("design:type", String)
1389
+ ], exports.AuditableItemGraphEdge.prototype, "edgeRelationship", void 0);
1390
+ __decorate([
1391
+ entity.property({ type: "object", itemTypeRef: dataJsonLd.JsonLdTypes.NodeObject }),
1392
+ __metadata("design:type", Object)
1393
+ ], exports.AuditableItemGraphEdge.prototype, "edgeObject", void 0);
1394
+ exports.AuditableItemGraphEdge = __decorate([
1395
+ entity.entity()
1396
+ ], exports.AuditableItemGraphEdge);
1397
+
1398
+ // Copyright 2024 IOTA Stiftung.
1399
+ // SPDX-License-Identifier: Apache-2.0.
1400
+ /**
1401
+ * Class describing the auditable item graph patches.
1402
+ */
1403
+ exports.AuditableItemGraphPatch = class AuditableItemGraphPatch {
1404
+ /**
1405
+ * The operation for the patch.
1406
+ */
1407
+ op;
1408
+ /**
1409
+ * The path for the patch.
1410
+ */
1411
+ path;
1412
+ /**
1413
+ * The from for the patch.
1414
+ */
1415
+ from;
1416
+ /**
1417
+ * The value for the patch.
1418
+ */
1419
+ value;
1420
+ };
1421
+ __decorate([
1422
+ entity.property({ type: "string" }),
1423
+ __metadata("design:type", String)
1424
+ ], exports.AuditableItemGraphPatch.prototype, "op", void 0);
1425
+ __decorate([
1426
+ entity.property({ type: "string" }),
1427
+ __metadata("design:type", String)
1428
+ ], exports.AuditableItemGraphPatch.prototype, "path", void 0);
1429
+ __decorate([
1430
+ entity.property({ type: "string" }),
1431
+ __metadata("design:type", String)
1432
+ ], exports.AuditableItemGraphPatch.prototype, "from", void 0);
1433
+ __decorate([
1434
+ entity.property({ type: "object" }),
1435
+ __metadata("design:type", Object)
1436
+ ], exports.AuditableItemGraphPatch.prototype, "value", void 0);
1437
+ exports.AuditableItemGraphPatch = __decorate([
1438
+ entity.entity()
1439
+ ], exports.AuditableItemGraphPatch);
1440
+
1441
+ // Copyright 2024 IOTA Stiftung.
1442
+ // SPDX-License-Identifier: Apache-2.0.
1443
+ /**
1444
+ * Class describing the auditable item graph vertex resource.
1445
+ */
1446
+ exports.AuditableItemGraphResource = class AuditableItemGraphResource {
1447
+ /**
1448
+ * The id of the resource.
1449
+ */
1450
+ id;
1451
+ /**
1452
+ * The date/time of when the resource was created.
1453
+ */
1454
+ dateCreated;
1455
+ /**
1456
+ * The date/time of when the resource was last modified.
1457
+ */
1458
+ dateModified;
1459
+ /**
1460
+ * The timestamp of when the resource was deleted, as we never actually remove items.
1461
+ */
1462
+ dateDeleted;
1463
+ /**
1464
+ * Object to associate with the resource as JSON-LD.
1465
+ */
1466
+ resourceObject;
1467
+ };
1468
+ __decorate([
1469
+ entity.property({ type: "string", isPrimary: true }),
1470
+ __metadata("design:type", String)
1471
+ ], exports.AuditableItemGraphResource.prototype, "id", void 0);
1472
+ __decorate([
1473
+ entity.property({ type: "string", format: "date-time" }),
1474
+ __metadata("design:type", String)
1475
+ ], exports.AuditableItemGraphResource.prototype, "dateCreated", void 0);
1476
+ __decorate([
1477
+ entity.property({ type: "string", format: "date-time" }),
1478
+ __metadata("design:type", String)
1479
+ ], exports.AuditableItemGraphResource.prototype, "dateModified", void 0);
1480
+ __decorate([
1481
+ entity.property({ type: "string", format: "date-time" }),
1482
+ __metadata("design:type", String)
1483
+ ], exports.AuditableItemGraphResource.prototype, "dateDeleted", void 0);
1484
+ __decorate([
1485
+ entity.property({ type: "object", itemTypeRef: dataJsonLd.JsonLdTypes.NodeObject }),
1486
+ __metadata("design:type", Object)
1487
+ ], exports.AuditableItemGraphResource.prototype, "resourceObject", void 0);
1488
+ exports.AuditableItemGraphResource = __decorate([
1489
+ entity.entity()
1490
+ ], exports.AuditableItemGraphResource);
1491
+
1492
+ // Copyright 2024 IOTA Stiftung.
1493
+ // SPDX-License-Identifier: Apache-2.0.
1494
+ /**
1495
+ * Class describing the auditable item graph vertex.
1496
+ */
1497
+ exports.AuditableItemGraphVertex = class AuditableItemGraphVertex {
1498
+ /**
1499
+ * The id of the vertex.
1500
+ */
1501
+ id;
1502
+ /**
1503
+ * The identity of the node which controls the vertex.
1504
+ */
1505
+ nodeIdentity;
1506
+ /**
1507
+ * The date/time of when the vertex was created.
1508
+ */
1509
+ dateCreated;
1510
+ /**
1511
+ * The date/time of when the vertex was last modified.
1512
+ */
1513
+ dateModified;
1514
+ /**
1515
+ * Combined alias index for the vertex used for querying.
1516
+ */
1517
+ aliasIndex;
1518
+ /**
1519
+ * Object to associate with the vertex as JSON-LD.
1520
+ */
1521
+ vertexObject;
1522
+ /**
1523
+ * Alternative aliases that can be used to identify the vertex.
1524
+ */
1525
+ aliases;
1526
+ /**
1527
+ * The resources attached to the vertex.
1528
+ */
1529
+ resources;
1530
+ /**
1531
+ * Edges connected to the vertex.
1532
+ */
1533
+ edges;
1534
+ };
1535
+ __decorate([
1536
+ entity.property({ type: "string", isPrimary: true }),
1537
+ __metadata("design:type", String)
1538
+ ], exports.AuditableItemGraphVertex.prototype, "id", void 0);
1539
+ __decorate([
1540
+ entity.property({ type: "string" }),
1541
+ __metadata("design:type", String)
1542
+ ], exports.AuditableItemGraphVertex.prototype, "nodeIdentity", void 0);
1543
+ __decorate([
1544
+ entity.property({ type: "string", format: "date-time", sortDirection: entity.SortDirection.Descending }),
1545
+ __metadata("design:type", String)
1546
+ ], exports.AuditableItemGraphVertex.prototype, "dateCreated", void 0);
1547
+ __decorate([
1548
+ entity.property({ type: "string", format: "date-time", sortDirection: entity.SortDirection.Descending }),
1549
+ __metadata("design:type", String)
1550
+ ], exports.AuditableItemGraphVertex.prototype, "dateModified", void 0);
1551
+ __decorate([
1552
+ entity.property({ type: "string", isSecondary: true }),
1553
+ __metadata("design:type", String)
1554
+ ], exports.AuditableItemGraphVertex.prototype, "aliasIndex", void 0);
1555
+ __decorate([
1556
+ entity.property({ type: "object", itemTypeRef: dataJsonLd.JsonLdTypes.NodeObject }),
1557
+ __metadata("design:type", Object)
1558
+ ], exports.AuditableItemGraphVertex.prototype, "vertexObject", void 0);
1559
+ __decorate([
1560
+ entity.property({ type: "array", itemType: "string" }),
1561
+ __metadata("design:type", Array)
1562
+ ], exports.AuditableItemGraphVertex.prototype, "aliases", void 0);
1563
+ __decorate([
1564
+ entity.property({ type: "array", itemTypeRef: "AuditableItemGraphResource" }),
1565
+ __metadata("design:type", Array)
1566
+ ], exports.AuditableItemGraphVertex.prototype, "resources", void 0);
1567
+ __decorate([
1568
+ entity.property({ type: "array", itemTypeRef: "AuditableItemGraphEdge" }),
1569
+ __metadata("design:type", Array)
1570
+ ], exports.AuditableItemGraphVertex.prototype, "edges", void 0);
1571
+ exports.AuditableItemGraphVertex = __decorate([
1572
+ entity.entity()
1573
+ ], exports.AuditableItemGraphVertex);
1574
+
1575
+ const restEntryPoints = [
1576
+ {
1577
+ name: "auditable-item-graph",
1578
+ defaultBaseRoute: "auditable-item-graph",
1579
+ tags: tagsAuditableItemGraph,
1580
+ generateRoutes: generateRestRoutesAuditableItemGraph
1581
+ }
1582
+ ];
1583
+
1584
+ // Copyright 2024 IOTA Stiftung.
1585
+ // SPDX-License-Identifier: Apache-2.0.
1586
+ /**
1587
+ * Initialize the schema for the auditable item graph entity storage connector.
1588
+ */
1589
+ function initSchema() {
1590
+ entity.EntitySchemaFactory.register("AuditableItemGraphVertex", () => entity.EntitySchemaHelper.getSchema(exports.AuditableItemGraphVertex));
1591
+ entity.EntitySchemaFactory.register("AuditableItemGraphAlias", () => entity.EntitySchemaHelper.getSchema(exports.AuditableItemGraphAlias));
1592
+ entity.EntitySchemaFactory.register("AuditableItemGraphResource", () => entity.EntitySchemaHelper.getSchema(exports.AuditableItemGraphResource));
1593
+ entity.EntitySchemaFactory.register("AuditableItemGraphEdge", () => entity.EntitySchemaHelper.getSchema(exports.AuditableItemGraphEdge));
1594
+ entity.EntitySchemaFactory.register("AuditableItemGraphChangeset", () => entity.EntitySchemaHelper.getSchema(exports.AuditableItemGraphChangeset));
1595
+ entity.EntitySchemaFactory.register("AuditableItemGraphPatch", () => entity.EntitySchemaHelper.getSchema(exports.AuditableItemGraphPatch));
1596
+ }
1597
+
1598
+ exports.AuditableItemGraphService = AuditableItemGraphService;
1599
+ exports.auditableItemGraphCreate = auditableItemGraphCreate;
1600
+ exports.auditableItemGraphGet = auditableItemGraphGet;
1601
+ exports.auditableItemGraphList = auditableItemGraphList;
1602
+ exports.auditableItemGraphUpdate = auditableItemGraphUpdate;
1603
+ exports.generateRestRoutesAuditableItemGraph = generateRestRoutesAuditableItemGraph;
1604
+ exports.initSchema = initSchema;
1605
+ exports.restEntryPoints = restEntryPoints;
1606
+ exports.tagsAuditableItemGraph = tagsAuditableItemGraph;