@ldo/connected-nextgraph 1.0.0-alpha.11

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 (73) hide show
  1. package/LICENSE.txt +21 -0
  2. package/README.md +186 -0
  3. package/dist/cjs/NextGraphConnectedPlugin.js +37 -0
  4. package/dist/cjs/NextGraphConnectedPlugin.js.map +1 -0
  5. package/dist/cjs/createNextGraphLdoDataset.js +13 -0
  6. package/dist/cjs/createNextGraphLdoDataset.js.map +1 -0
  7. package/dist/cjs/index.js +23 -0
  8. package/dist/cjs/index.js.map +1 -0
  9. package/dist/cjs/notifications/NextGraphNotificationMessage.js +3 -0
  10. package/dist/cjs/notifications/NextGraphNotificationMessage.js.map +1 -0
  11. package/dist/cjs/notifications/NextGraphNotificationSubscription.js +15 -0
  12. package/dist/cjs/notifications/NextGraphNotificationSubscription.js.map +1 -0
  13. package/dist/cjs/resources/NextGraphResource.js +163 -0
  14. package/dist/cjs/resources/NextGraphResource.js.map +1 -0
  15. package/dist/cjs/results/NextGraphReadSuccess.js +12 -0
  16. package/dist/cjs/results/NextGraphReadSuccess.js.map +1 -0
  17. package/dist/cjs/types.js +3 -0
  18. package/dist/cjs/types.js.map +1 -0
  19. package/dist/cjs/util/NextGraphNotificationMessage.js +3 -0
  20. package/dist/cjs/util/NextGraphNotificationMessage.js.map +1 -0
  21. package/dist/cjs/util/isNextGraphUri.js +13 -0
  22. package/dist/cjs/util/isNextGraphUri.js.map +1 -0
  23. package/dist/esm/NextGraphConnectedPlugin.js +34 -0
  24. package/dist/esm/NextGraphConnectedPlugin.js.map +1 -0
  25. package/dist/esm/createNextGraphLdoDataset.js +9 -0
  26. package/dist/esm/createNextGraphLdoDataset.js.map +1 -0
  27. package/dist/esm/index.js +7 -0
  28. package/dist/esm/index.js.map +1 -0
  29. package/dist/esm/notifications/NextGraphNotificationMessage.js +2 -0
  30. package/dist/esm/notifications/NextGraphNotificationMessage.js.map +1 -0
  31. package/dist/esm/notifications/NextGraphNotificationSubscription.js +11 -0
  32. package/dist/esm/notifications/NextGraphNotificationSubscription.js.map +1 -0
  33. package/dist/esm/resources/NextGraphResource.js +156 -0
  34. package/dist/esm/resources/NextGraphResource.js.map +1 -0
  35. package/dist/esm/results/NextGraphReadSuccess.js +8 -0
  36. package/dist/esm/results/NextGraphReadSuccess.js.map +1 -0
  37. package/dist/esm/types.js +2 -0
  38. package/dist/esm/types.js.map +1 -0
  39. package/dist/esm/util/NextGraphNotificationMessage.js +2 -0
  40. package/dist/esm/util/NextGraphNotificationMessage.js.map +1 -0
  41. package/dist/esm/util/isNextGraphUri.js +9 -0
  42. package/dist/esm/util/isNextGraphUri.js.map +1 -0
  43. package/dist/types/NextGraphConnectedPlugin.d.ts +22 -0
  44. package/dist/types/NextGraphConnectedPlugin.d.ts.map +1 -0
  45. package/dist/types/createNextGraphLdoDataset.d.ts +3 -0
  46. package/dist/types/createNextGraphLdoDataset.d.ts.map +1 -0
  47. package/dist/types/index.d.ts +7 -0
  48. package/dist/types/index.d.ts.map +1 -0
  49. package/dist/types/notifications/NextGraphNotificationMessage.d.ts +16 -0
  50. package/dist/types/notifications/NextGraphNotificationMessage.d.ts.map +1 -0
  51. package/dist/types/notifications/NextGraphNotificationSubscription.d.ts +9 -0
  52. package/dist/types/notifications/NextGraphNotificationSubscription.d.ts.map +1 -0
  53. package/dist/types/resources/NextGraphResource.d.ts +48 -0
  54. package/dist/types/resources/NextGraphResource.d.ts.map +1 -0
  55. package/dist/types/results/NextGraphReadSuccess.d.ts +6 -0
  56. package/dist/types/results/NextGraphReadSuccess.d.ts.map +1 -0
  57. package/dist/types/types.d.ts +6 -0
  58. package/dist/types/types.d.ts.map +1 -0
  59. package/dist/types/util/NextGraphNotificationMessage.d.ts +16 -0
  60. package/dist/types/util/NextGraphNotificationMessage.d.ts.map +1 -0
  61. package/dist/types/util/isNextGraphUri.d.ts +8 -0
  62. package/dist/types/util/isNextGraphUri.d.ts.map +1 -0
  63. package/package.json +74 -0
  64. package/src/NextGraphConnectedPlugin.ts +87 -0
  65. package/src/createNextGraphLdoDataset.ts +13 -0
  66. package/src/index.ts +10 -0
  67. package/src/notifications/NextGraphNotificationMessage.ts +15 -0
  68. package/src/notifications/NextGraphNotificationSubscription.ts +23 -0
  69. package/src/resources/NextGraphResource.ts +271 -0
  70. package/src/results/NextGraphReadSuccess.ts +6 -0
  71. package/src/types.ts +8 -0
  72. package/src/util/NextGraphNotificationMessage.ts +15 -0
  73. package/src/util/isNextGraphUri.ts +10 -0
@@ -0,0 +1,271 @@
1
+ import type {
2
+ ConnectedContext,
3
+ NotificationSubscription,
4
+ SubscriptionCallbacks,
5
+ } from "@ldo/connected";
6
+ import { UnexpectedResourceError, UpdateSuccess } from "@ldo/connected";
7
+ import {
8
+ Unfetched,
9
+ type ConnectedResult,
10
+ type Resource,
11
+ type ResourceEventEmitter,
12
+ } from "@ldo/connected";
13
+ import type { NextGraphUri } from "../types.js";
14
+ import EventEmitter from "events";
15
+ import type { NextGraphConnectedPlugin } from "../NextGraphConnectedPlugin.js";
16
+ import { changesToSparqlUpdate, type DatasetChanges } from "@ldo/rdf-utils";
17
+ import type { NextGraphNotificationMessage } from "../notifications/NextGraphNotificationMessage.js";
18
+ import type { Dataset, Quad } from "@rdfjs/types";
19
+ import { namedNode, quad as createQuad } from "@rdfjs/data-model";
20
+ import { NextGraphReadSuccess } from "../results/NextGraphReadSuccess.js";
21
+ import { NextGraphNotificationSubscription } from "../notifications/NextGraphNotificationSubscription.js";
22
+ import { parseRdf } from "@ldo/ldo";
23
+ import type { LdoDataset } from "@ldo/ldo";
24
+ import { createDataset } from "@ldo/dataset";
25
+
26
+ export class NextGraphResource
27
+ extends (EventEmitter as new () => ResourceEventEmitter)
28
+ implements Resource<NextGraphUri>
29
+ {
30
+ public readonly uri: NextGraphUri;
31
+ public readonly type = "NextGraphResource" as const;
32
+ public readonly isError = false as const;
33
+ public status: ConnectedResult;
34
+ protected context: ConnectedContext<NextGraphConnectedPlugin[]>;
35
+
36
+ private fetched: boolean = false;
37
+ private loading: boolean = false;
38
+ private present: boolean | undefined = undefined;
39
+
40
+ /**
41
+ * @internal
42
+ * Handles notification subscriptions
43
+ */
44
+ protected notificationSubscription: NotificationSubscription<
45
+ NextGraphConnectedPlugin,
46
+ NextGraphNotificationMessage
47
+ >;
48
+
49
+ constructor(
50
+ uri: NextGraphUri,
51
+ context: ConnectedContext<NextGraphConnectedPlugin[]>,
52
+ ) {
53
+ super();
54
+ this.uri = uri;
55
+ this.status = new Unfetched(this);
56
+ this.context = context;
57
+ this.notificationSubscription = new NextGraphNotificationSubscription(
58
+ this,
59
+ this.onNotification.bind(this),
60
+ this.context,
61
+ );
62
+ }
63
+
64
+ isLoading(): boolean {
65
+ return this.loading;
66
+ }
67
+
68
+ isFetched(): boolean {
69
+ return this.fetched;
70
+ }
71
+
72
+ isUnfetched(): boolean {
73
+ return !this.fetched;
74
+ }
75
+
76
+ isDoingInitialFetch(): boolean {
77
+ return this.loading && !this.fetched;
78
+ }
79
+
80
+ isPresent(): boolean | undefined {
81
+ return this.present;
82
+ }
83
+
84
+ isAbsent(): boolean | undefined {
85
+ return !this.present;
86
+ }
87
+
88
+ isSubscribedToNotifications(): boolean {
89
+ return this.notificationSubscription.isSubscribedToNotifications();
90
+ }
91
+
92
+ private handleThrownError(
93
+ err: unknown,
94
+ ): UnexpectedResourceError<NextGraphResource> {
95
+ const error = UnexpectedResourceError.fromThrown(this, err);
96
+ this.loading = false;
97
+ this.status = error;
98
+ this.emit("update");
99
+ return error;
100
+ }
101
+
102
+ private overwriteQuads(quads: Quad[] | Dataset<Quad>) {
103
+ const dataset = this.context.dataset;
104
+ const graphNode = namedNode(this.uri);
105
+ dataset.deleteMatches(undefined, undefined, undefined, graphNode);
106
+ dataset.addAll(
107
+ quads.map((ngQuad) => {
108
+ return createQuad(
109
+ ngQuad.subject,
110
+ ngQuad.predicate,
111
+ ngQuad.object,
112
+ graphNode,
113
+ );
114
+ }),
115
+ );
116
+ }
117
+
118
+ async read(): Promise<
119
+ NextGraphReadSuccess | UnexpectedResourceError<NextGraphResource>
120
+ > {
121
+ try {
122
+ this.loading = true;
123
+ this.emit("update");
124
+
125
+ // Fetch the data once using construct
126
+ const sparqlResult = await this.context.nextgraph.ng.sparql_query(
127
+ this.context.nextgraph.sessionId,
128
+ `CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <${this.uri}> { ?s ?p ?o } }`,
129
+ undefined,
130
+ this.uri,
131
+ );
132
+ // Update the dataset
133
+ this.overwriteQuads(sparqlResult);
134
+
135
+ // Update statuses
136
+ const result = new NextGraphReadSuccess(this, false);
137
+ this.loading = false;
138
+ this.fetched = true;
139
+ this.present = true;
140
+ this.status = result;
141
+ this.emit("update");
142
+ return result;
143
+ } catch (err) {
144
+ if (err === "RepoNotFound") {
145
+ const result = new NextGraphReadSuccess(this, false);
146
+ this.loading = false;
147
+ this.fetched = true;
148
+ this.present = false;
149
+ this.status = result;
150
+ this.emit("update");
151
+ return result;
152
+ }
153
+ return this.handleThrownError(err);
154
+ }
155
+ }
156
+
157
+ async readIfUnfetched(): Promise<
158
+ NextGraphReadSuccess | UnexpectedResourceError<NextGraphResource>
159
+ > {
160
+ if (this.isFetched()) {
161
+ return new NextGraphReadSuccess(this, true);
162
+ }
163
+ return this.read();
164
+ }
165
+
166
+ async update(
167
+ datasetChanges: DatasetChanges<Quad>,
168
+ ): Promise<
169
+ | UpdateSuccess<NextGraphResource>
170
+ | UnexpectedResourceError<NextGraphResource>
171
+ > {
172
+ this.loading = true;
173
+ this.emit("update");
174
+
175
+ // Optimistically apply updates
176
+ this.context.dataset.bulk(datasetChanges);
177
+
178
+ try {
179
+ // Perform Update with remote
180
+ await this.context.nextgraph.ng.sparql_update(
181
+ this.context.nextgraph.sessionId,
182
+ await changesToSparqlUpdate(datasetChanges),
183
+ this.uri,
184
+ );
185
+ return new UpdateSuccess(this);
186
+ } catch (err) {
187
+ // Revert data on error
188
+ this.context.dataset.bulk({
189
+ added: datasetChanges.removed,
190
+ removed: datasetChanges.added,
191
+ });
192
+ return this.handleThrownError(err);
193
+ }
194
+ }
195
+
196
+ private async notificationToQuads(
197
+ notificationString: string,
198
+ ): Promise<Dataset<Quad>> {
199
+ const rawTriples = JSON.parse(notificationString);
200
+ const triples = (
201
+ await Promise.all<LdoDataset>(
202
+ rawTriples.map(async (rawTriple) =>
203
+ parseRdf(`${rawTriple}.`, { baseIRI: this.uri }),
204
+ ),
205
+ )
206
+ ).reduce((agg, ldoDataset) => {
207
+ ldoDataset.forEach((quad) => {
208
+ agg.add(
209
+ createQuad(
210
+ quad.subject,
211
+ quad.predicate,
212
+ quad.object,
213
+ namedNode(this.uri),
214
+ ),
215
+ );
216
+ });
217
+ return agg;
218
+ }, createDataset());
219
+ return triples;
220
+ }
221
+
222
+ protected async onNotification(response: NextGraphNotificationMessage) {
223
+ if (response.V0.State) {
224
+ if (!response.V0.State.graph) {
225
+ this.overwriteQuads([]);
226
+ return;
227
+ }
228
+ const json_str = new TextDecoder().decode(
229
+ response.V0.State.graph.triples,
230
+ );
231
+ const triples = await this.notificationToQuads(json_str);
232
+ this.overwriteQuads(triples);
233
+ } else if (response.V0.Patch?.graph) {
234
+ const insertsString = new TextDecoder().decode(
235
+ response.V0.Patch.graph.inserts,
236
+ );
237
+ const removesString = new TextDecoder().decode(
238
+ response.V0.Patch.graph.removes,
239
+ );
240
+
241
+ const [added, removed] = await Promise.all(
242
+ [insertsString, removesString].map(async (str) => {
243
+ return this.notificationToQuads(str);
244
+ }),
245
+ );
246
+
247
+ this.context.dataset.bulk({
248
+ added,
249
+ removed,
250
+ });
251
+ }
252
+ }
253
+
254
+ async subscribeToNotifications(
255
+ callbacks?: SubscriptionCallbacks<NextGraphNotificationMessage>,
256
+ ): Promise<string> {
257
+ return await this.notificationSubscription.subscribeToNotifications(
258
+ callbacks,
259
+ );
260
+ }
261
+
262
+ unsubscribeFromNotifications(subscriptionId: string): Promise<void> {
263
+ return this.notificationSubscription.unsubscribeFromNotification(
264
+ subscriptionId,
265
+ );
266
+ }
267
+
268
+ unsubscribeFromAllNotifications(): Promise<void> {
269
+ return this.notificationSubscription.unsubscribeFromAllNotifications();
270
+ }
271
+ }
@@ -0,0 +1,6 @@
1
+ import { ReadSuccess } from "@ldo/connected";
2
+ import type { NextGraphResource } from "../resources/NextGraphResource.js";
3
+
4
+ export class NextGraphReadSuccess extends ReadSuccess<NextGraphResource> {
5
+ type = "nextGraphReadSuccess" as const;
6
+ }
package/src/types.ts ADDED
@@ -0,0 +1,8 @@
1
+ export type NextGraphUriPrefix = `did:ng`;
2
+
3
+ /**
4
+ * A NextGraph is a URI that is valid in the NextGraph ecosystem
5
+ */
6
+ // The & {} allows for alias preservation
7
+ // eslint-disable-next-line @typescript-eslint/ban-types
8
+ export type NextGraphUri = `${NextGraphUriPrefix}${string}` & {};
@@ -0,0 +1,15 @@
1
+ export interface NextGraphNotificationMessage {
2
+ V0: {
3
+ State: {
4
+ graph: {
5
+ triples: AllowSharedBufferSource;
6
+ };
7
+ };
8
+ Patch: {
9
+ graph: {
10
+ inserts: AllowSharedBufferSource;
11
+ removes: AllowSharedBufferSource;
12
+ };
13
+ };
14
+ };
15
+ }
@@ -0,0 +1,10 @@
1
+ import type { NextGraphUri } from "../types.js";
2
+
3
+ /**
4
+ * Checks if a provided string is a leaf URI
5
+ * @param uri - the string to check
6
+ * @returns true if the string is a leaf URI
7
+ */
8
+ export function isNextGraphUri(uri: string): uri is NextGraphUri {
9
+ return uri.startsWith("did:ng");
10
+ }