@ldo/connected-nextgraph 1.0.0-alpha.2

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 (49) hide show
  1. package/LICENSE.txt +21 -0
  2. package/README.md +124 -0
  3. package/dist/NextGraphConnectedPlugin.d.ts +19 -0
  4. package/dist/NextGraphConnectedPlugin.js +38 -0
  5. package/dist/NextGraphConnectedPlugin.js.map +1 -0
  6. package/dist/createNextGraphLdoDataset.d.ts +2 -0
  7. package/dist/createNextGraphLdoDataset.js +13 -0
  8. package/dist/createNextGraphLdoDataset.js.map +1 -0
  9. package/dist/createSolidLdoDataset.d.ts +2 -0
  10. package/dist/createSolidLdoDataset.js +13 -0
  11. package/dist/createSolidLdoDataset.js.map +1 -0
  12. package/dist/index.d.ts +5 -0
  13. package/dist/index.js +22 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/notifications/NextGraphNotificationMessage.d.ts +15 -0
  16. package/dist/notifications/NextGraphNotificationMessage.js +3 -0
  17. package/dist/notifications/NextGraphNotificationMessage.js.map +1 -0
  18. package/dist/notifications/NextGraphNotificationSubscription.d.ts +8 -0
  19. package/dist/notifications/NextGraphNotificationSubscription.js +20 -0
  20. package/dist/notifications/NextGraphNotificationSubscription.js.map +1 -0
  21. package/dist/resources/NextGraphResource.d.ts +40 -0
  22. package/dist/resources/NextGraphResource.js +171 -0
  23. package/dist/resources/NextGraphResource.js.map +1 -0
  24. package/dist/results/NextGraphReadSuccess.d.ts +5 -0
  25. package/dist/results/NextGraphReadSuccess.js +12 -0
  26. package/dist/results/NextGraphReadSuccess.js.map +1 -0
  27. package/dist/results/NoNextGraphStoreError.d.ts +5 -0
  28. package/dist/results/NoNextGraphStoreError.js +12 -0
  29. package/dist/results/NoNextGraphStoreError.js.map +1 -0
  30. package/dist/types.d.ts +2 -0
  31. package/dist/types.js +3 -0
  32. package/dist/types.js.map +1 -0
  33. package/dist/util/NextGraphNotificationMessage.d.ts +15 -0
  34. package/dist/util/NextGraphNotificationMessage.js +3 -0
  35. package/dist/util/NextGraphNotificationMessage.js.map +1 -0
  36. package/dist/util/isNextGraphUri.d.ts +2 -0
  37. package/dist/util/isNextGraphUri.js +8 -0
  38. package/dist/util/isNextGraphUri.js.map +1 -0
  39. package/package.json +61 -0
  40. package/src/NextGraphConnectedPlugin.ts +83 -0
  41. package/src/createNextGraphLdoDataset.ts +13 -0
  42. package/src/index.ts +8 -0
  43. package/src/notifications/NextGraphNotificationMessage.ts +15 -0
  44. package/src/notifications/NextGraphNotificationSubscription.ts +25 -0
  45. package/src/resources/NextGraphResource.ts +275 -0
  46. package/src/results/NextGraphReadSuccess.ts +6 -0
  47. package/src/types.ts +8 -0
  48. package/src/util/NextGraphNotificationMessage.ts +15 -0
  49. package/src/util/isNextGraphUri.ts +10 -0
package/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Jackson Morgan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # `@ldo/connected-nextgraph`
2
+
3
+ The `@ldo/connected-nextgraph` library allows you to integrate [NextGraph](https://nextgraph.org) with the [LDO](https://ldo.js.org) ecosystem. It provides a `ConnectedLdoDataset` that manages RDF data across decentralized NextGraph resources with real-time synchronization and read/write capabilities.
4
+
5
+ ## Installation
6
+
7
+ First, install the required libraries:
8
+
9
+ ```bash
10
+ npm install nextgraph @ldo/connected-nextgraph
11
+ ```
12
+
13
+ ## Usage:
14
+
15
+ ### 1. Setup: Create a ConnectedLdoDataset
16
+
17
+ ```ts
18
+ import { createNextGraphLdoDataset } from "@ldo/connected-nextgraph";
19
+
20
+ // Create the dataset
21
+ const ldoDataset = createNextGraphLdoDataset();
22
+ ```
23
+
24
+ ### 2. Connect to a NextGraph Wallet Session
25
+
26
+ Before you can create or access resources, you need an active session:
27
+
28
+ ```ts
29
+ import ng from "nextgraph";
30
+
31
+ // Open your nextgraph wallet
32
+ const openedWallet = await ng.wallet_open_with_mnemonic_words(
33
+ walletBinary,
34
+ mnemonic,
35
+ [1, 2, 3, 4]
36
+ );
37
+
38
+ // Start a session
39
+ const session = await ng.session_in_memory_start(
40
+ openedWallet.V0.wallet_id,
41
+ openedWallet.V0.personal_site
42
+ );
43
+ ```
44
+
45
+ ---
46
+
47
+ ### 3. Link Your Dataset to the NextGraph Session
48
+
49
+ ```ts
50
+ ldoDataset.setContext("nextgraph", {
51
+ sessionId: session.session_id
52
+ });
53
+ ```
54
+
55
+ ### 4. Create a Resource
56
+
57
+ To create a new resource in your store:
58
+
59
+ ```ts
60
+ const resource = await ldoDataset.createResource("nextgraph");
61
+ if (!resource.isError) {
62
+ console.log("Created resource:", resource.uri);
63
+ }
64
+ ```
65
+
66
+ ### 5. Read and Monitor a Resource**
67
+
68
+ #### Read Existing Resource
69
+
70
+ ```ts
71
+ const resource = ldoDataset.getResource(existingUri);
72
+ const readResult = await resource.read();
73
+
74
+ if (!readResult.isError) {
75
+ console.log("Resource loaded!", readResult.type);
76
+ }
77
+ ```
78
+
79
+ #### Read Only If Unfetched
80
+
81
+ Avoid redundant fetches:
82
+
83
+ ```ts
84
+ const readResult = await resource.readIfUnfetched();
85
+ ```
86
+
87
+ #### Subscribe to Notifications
88
+
89
+ ```ts
90
+ const unsubscribeId = await resource.subscribeToNotifications();
91
+ await resource.unsubscribeFromNotification(unsubscribeId);
92
+ await resource.unsubscribeFromAllNotifications();
93
+ ```
94
+
95
+ ---
96
+
97
+ ### 6. Write Data to a Resource
98
+
99
+ You can write RDF data to a resource using `update()`:
100
+
101
+ ```ts
102
+ import { parseRdf } from "@ldo/ldo";
103
+
104
+ const ttlData = `
105
+ @prefix foaf: <http://xmlns.com/foaf/0.1/> .
106
+ <#spiderman> a foaf:Person ; foaf:name "Spiderman" .
107
+ `;
108
+
109
+ const triples = await parseRdf(ttlData);
110
+
111
+ await resource.update({
112
+ added: triples,
113
+ removed: undefined
114
+ });
115
+ ```
116
+
117
+ ## Sponsorship
118
+ This project was made possible by a grant from NGI Zero Entrust via nlnet. Learn more on the [NLnet project page](https://nlnet.nl/project/SolidUsableApps/).
119
+
120
+ [<img src="https://nlnet.nl/logo/banner.png" alt="nlnet foundation logo" width="300" />](https://nlnet.nl/)
121
+ [<img src="https://nlnet.nl/image/logos/NGI0Entrust_tag.svg" alt="NGI Zero Entrust Logo" width="300" />](https://nlnet.nl/)
122
+
123
+ ## Liscense
124
+ MIT
@@ -0,0 +1,19 @@
1
+ import type { ConnectedContext, ConnectedPlugin } from "@ldo/connected";
2
+ import type { NextGraphUri } from "./types";
3
+ import { NextGraphResource } from "./resources/NextGraphResource";
4
+ export interface NextGraphConnectedContext {
5
+ sessionId?: string;
6
+ protectedStoreId?: string;
7
+ privateStoreId?: string;
8
+ publicStoreId?: string;
9
+ }
10
+ export interface NextGraphCreateResourceOptions {
11
+ storeType?: "public" | "protected" | "private" | "group" | "dialog";
12
+ storeRepo?: string;
13
+ }
14
+ export interface NextGraphConnectedPlugin extends ConnectedPlugin<"nextgraph", NextGraphUri, NextGraphResource, NextGraphConnectedContext, NextGraphCreateResourceOptions> {
15
+ name: "nextgraph";
16
+ getResource: (uri: NextGraphUri, context: ConnectedContext<this[]>) => NextGraphResource;
17
+ createResource(context: ConnectedContext<this[]>): Promise<NextGraphResource>;
18
+ }
19
+ export declare const nextGraphConnectedPlugin: NextGraphConnectedPlugin;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.nextGraphConnectedPlugin = void 0;
7
+ const NextGraphResource_1 = require("./resources/NextGraphResource");
8
+ const nextgraph_1 = __importDefault(require("nextgraph"));
9
+ const isNextGraphUri_1 = require("./util/isNextGraphUri");
10
+ exports.nextGraphConnectedPlugin = {
11
+ name: "nextgraph",
12
+ getResource: function (uri, context) {
13
+ return new NextGraphResource_1.NextGraphResource(uri, context);
14
+ },
15
+ createResource: async function (context, options) {
16
+ const storeType = options?.storeType;
17
+ const storeRepo = options?.storeRepo ??
18
+ (storeType === "protected"
19
+ ? context.nextgraph.protectedStoreId
20
+ : storeType === "public"
21
+ ? context.nextgraph.publicStoreId
22
+ : storeType === "private"
23
+ ? context.nextgraph.privateStoreId
24
+ : undefined);
25
+ const nuri = await nextgraph_1.default.doc_create(context.nextgraph.sessionId, "Graph", "data:graph", "store", storeType, storeRepo);
26
+ const newResource = new NextGraphResource_1.NextGraphResource(nuri, context);
27
+ await newResource.read();
28
+ return newResource;
29
+ },
30
+ isUriValid: function (uri) {
31
+ return (0, isNextGraphUri_1.isNextGraphUri)(uri);
32
+ },
33
+ initialContext: {
34
+ sessionId: undefined,
35
+ },
36
+ types: {},
37
+ };
38
+ //# sourceMappingURL=NextGraphConnectedPlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NextGraphConnectedPlugin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LdoDataset } from "@ldo/connected";
2
+ export declare function createNextGraphLdoDataset(): ConnectedLdoDataset<import("./NextGraphConnectedPlugin").NextGraphConnectedPlugin[]>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNextGraphLdoDataset = void 0;
4
+ const connected_1 = require("@ldo/connected");
5
+ const NextGraphConnectedPlugin_1 = require("./NextGraphConnectedPlugin");
6
+ const dataset_1 = require("@ldo/dataset");
7
+ const subscribable_dataset_1 = require("@ldo/subscribable-dataset");
8
+ function createNextGraphLdoDataset() {
9
+ const nextGraphLdoDataset = new connected_1.ConnectedLdoDataset([NextGraphConnectedPlugin_1.nextGraphConnectedPlugin], (0, dataset_1.createDatasetFactory)(), (0, subscribable_dataset_1.createTransactionDatasetFactory)());
10
+ return nextGraphLdoDataset;
11
+ }
12
+ exports.createNextGraphLdoDataset = createNextGraphLdoDataset;
13
+ //# sourceMappingURL=createNextGraphLdoDataset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createNextGraphLdoDataset.js","sourceRoot":"","sources":["../src/createNextGraphLdoDataset.ts"],"names":[],"mappings":";;;AAAA,8CAAqD;AACrD,yEAAsE;AACtE,0CAAoD;AACpD,oEAA4E;AAE5E,SAAgB,yBAAyB;IACvC,MAAM,mBAAmB,GAAG,IAAI,+BAAmB,CACjD,CAAC,mDAAwB,CAAC,EAC1B,IAAA,8BAAoB,GAAE,EACtB,IAAA,sDAA+B,GAAE,CAClC,CAAC;IACF,OAAO,mBAAmB,CAAC;AAC7B,CAAC;AAPD,8DAOC"}
@@ -0,0 +1,2 @@
1
+ import { ConnectedLdoDataset } from "@ldo/connected";
2
+ export declare function createNextGraphLdoDataset(): ConnectedLdoDataset<import("./NextGraphConnectedPlugin").NextGraphConnectedPlugin[]>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNextGraphLdoDataset = void 0;
4
+ const connected_1 = require("@ldo/connected");
5
+ const NextGraphConnectedPlugin_1 = require("./NextGraphConnectedPlugin");
6
+ const dataset_1 = require("@ldo/dataset");
7
+ const subscribable_dataset_1 = require("@ldo/subscribable-dataset");
8
+ function createNextGraphLdoDataset() {
9
+ const nextGraphLdoDataset = new connected_1.ConnectedLdoDataset([NextGraphConnectedPlugin_1.nextGraphConnectedPlugin], (0, dataset_1.createDatasetFactory)(), (0, subscribable_dataset_1.createTransactionDatasetFactory)());
10
+ return nextGraphLdoDataset;
11
+ }
12
+ exports.createNextGraphLdoDataset = createNextGraphLdoDataset;
13
+ //# sourceMappingURL=createSolidLdoDataset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createSolidLdoDataset.js","sourceRoot":"","sources":["../src/createSolidLdoDataset.ts"],"names":[],"mappings":";;;AAAA,8CAAqD;AACrD,yEAAsE;AACtE,0CAAoD;AACpD,oEAA4E;AAE5E,SAAgB,yBAAyB;IACvC,MAAM,mBAAmB,GAAG,IAAI,+BAAmB,CACjD,CAAC,mDAAwB,CAAC,EAC1B,IAAA,8BAAoB,GAAE,EACtB,IAAA,sDAA+B,GAAE,CAClC,CAAC;IACF,OAAO,mBAAmB,CAAC;AAC7B,CAAC;AAPD,8DAOC"}
@@ -0,0 +1,5 @@
1
+ export * from "./types";
2
+ export * from "./NextGraphConnectedPlugin";
3
+ export * from "./resources/NextGraphResource";
4
+ export * from "./util/isNextGraphUri";
5
+ export * from "./results/NextGraphReadSuccess";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./NextGraphConnectedPlugin"), exports);
19
+ __exportStar(require("./resources/NextGraphResource"), exports);
20
+ __exportStar(require("./util/isNextGraphUri"), exports);
21
+ __exportStar(require("./results/NextGraphReadSuccess"), exports);
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0CAAwB;AACxB,6DAA2C;AAE3C,gEAA8C;AAE9C,wDAAsC;AAEtC,iEAA+C"}
@@ -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,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=NextGraphNotificationMessage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NextGraphNotificationMessage.js","sourceRoot":"","sources":["../../src/notifications/NextGraphNotificationMessage.ts"],"names":[],"mappings":""}
@@ -0,0 +1,8 @@
1
+ import { NotificationSubscription } from "@ldo/connected";
2
+ import type { NextGraphConnectedPlugin } from "../NextGraphConnectedPlugin";
3
+ import type { NextGraphNotificationMessage } from "./NextGraphNotificationMessage";
4
+ export declare class NextGraphNotificationSubscription extends NotificationSubscription<NextGraphConnectedPlugin, NextGraphNotificationMessage> {
5
+ private unsub;
6
+ protected open(): Promise<void>;
7
+ protected close(): Promise<void>;
8
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.NextGraphNotificationSubscription = void 0;
7
+ const connected_1 = require("@ldo/connected");
8
+ const nextgraph_1 = __importDefault(require("nextgraph"));
9
+ class NextGraphNotificationSubscription extends connected_1.NotificationSubscription {
10
+ async open() {
11
+ console.log("THIS WAS OPENED AND IT SHOULDNT BE");
12
+ this.unsub = await nextgraph_1.default.doc_subscribe(this.resource.uri, this.context.nextgraph.sessionId, this.onNotification.bind(this));
13
+ }
14
+ async close() {
15
+ this.unsub?.();
16
+ this.unsub = undefined;
17
+ }
18
+ }
19
+ exports.NextGraphNotificationSubscription = NextGraphNotificationSubscription;
20
+ //# sourceMappingURL=NextGraphNotificationSubscription.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NextGraphNotificationSubscription.js","sourceRoot":"","sources":["../../src/notifications/NextGraphNotificationSubscription.ts"],"names":[],"mappings":";;;;;;AAAA,8CAA0D;AAG1D,0DAA2B;AAE3B,MAAa,iCAAkC,SAAQ,oCAGtD;IAGW,KAAK,CAAC,IAAI;QAClB,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,MAAM,mBAAE,CAAC,aAAa,CACjC,IAAI,CAAC,QAAQ,CAAC,GAAG,EACjB,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,EAChC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/B,CAAC;IACJ,CAAC;IAES,KAAK,CAAC,KAAK;QACnB,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;IACzB,CAAC;CACF;AAnBD,8EAmBC"}
@@ -0,0 +1,40 @@
1
+ import type { ConnectedContext, NotificationSubscription, SubscriptionCallbacks } from "@ldo/connected";
2
+ import { UnexpectedResourceError, UpdateSuccess } from "@ldo/connected";
3
+ import { type ConnectedResult, type Resource, type ResourceEventEmitter } from "@ldo/connected";
4
+ import type { NextGraphUri } from "../types";
5
+ import type { NextGraphConnectedPlugin } from "../NextGraphConnectedPlugin";
6
+ import { type DatasetChanges } from "@ldo/rdf-utils";
7
+ import type { NextGraphNotificationMessage } from "../notifications/NextGraphNotificationMessage";
8
+ import type { Quad } from "@rdfjs/types";
9
+ import { NextGraphReadSuccess } from "../results/NextGraphReadSuccess";
10
+ declare const NextGraphResource_base: new () => ResourceEventEmitter;
11
+ export declare class NextGraphResource extends NextGraphResource_base implements Resource<NextGraphUri> {
12
+ readonly uri: NextGraphUri;
13
+ readonly type: "NextGraphResource";
14
+ readonly isError: false;
15
+ status: ConnectedResult;
16
+ protected context: ConnectedContext<NextGraphConnectedPlugin[]>;
17
+ private fetched;
18
+ private loading;
19
+ private present;
20
+ protected notificationSubscription: NotificationSubscription<NextGraphConnectedPlugin, NextGraphNotificationMessage>;
21
+ constructor(uri: NextGraphUri, context: ConnectedContext<NextGraphConnectedPlugin[]>);
22
+ isLoading(): boolean;
23
+ isFetched(): boolean;
24
+ isUnfetched(): boolean;
25
+ isDoingInitialFetch(): boolean;
26
+ isPresent(): boolean | undefined;
27
+ isAbsent(): boolean | undefined;
28
+ isSubscribedToNotifications(): boolean;
29
+ private handleThrownError;
30
+ private overwriteQuads;
31
+ read(): Promise<NextGraphReadSuccess | UnexpectedResourceError<NextGraphResource>>;
32
+ readIfUnfetched(): Promise<NextGraphReadSuccess | UnexpectedResourceError<NextGraphResource>>;
33
+ update(datasetChanges: DatasetChanges<Quad>): Promise<UpdateSuccess<NextGraphResource> | UnexpectedResourceError<NextGraphResource>>;
34
+ private notificationToQuads;
35
+ protected onNotification(response: NextGraphNotificationMessage): Promise<void>;
36
+ subscribeToNotifications(callbacks?: SubscriptionCallbacks<NextGraphNotificationMessage>): Promise<string>;
37
+ unsubscribeFromNotifications(subscriptionId: string): Promise<void>;
38
+ unsubscribeFromAllNotifications(): Promise<void>;
39
+ }
40
+ export {};
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.NextGraphResource = void 0;
7
+ const connected_1 = require("@ldo/connected");
8
+ const connected_2 = require("@ldo/connected");
9
+ const events_1 = __importDefault(require("events"));
10
+ const nextgraph_1 = __importDefault(require("nextgraph"));
11
+ const rdf_utils_1 = require("@ldo/rdf-utils");
12
+ const data_model_1 = require("@rdfjs/data-model");
13
+ const NextGraphReadSuccess_1 = require("../results/NextGraphReadSuccess");
14
+ const NextGraphNotificationSubscription_1 = require("../notifications/NextGraphNotificationSubscription");
15
+ const ldo_1 = require("@ldo/ldo");
16
+ const dataset_1 = require("@ldo/dataset");
17
+ class NextGraphResource extends events_1.default {
18
+ constructor(uri, context) {
19
+ super();
20
+ this.type = "NextGraphResource";
21
+ this.isError = false;
22
+ this.fetched = false;
23
+ this.loading = false;
24
+ this.present = undefined;
25
+ this.uri = uri;
26
+ this.status = new connected_2.Unfetched(this);
27
+ this.context = context;
28
+ this.notificationSubscription = new NextGraphNotificationSubscription_1.NextGraphNotificationSubscription(this, this.onNotification.bind(this), this.context);
29
+ }
30
+ isLoading() {
31
+ return this.loading;
32
+ }
33
+ isFetched() {
34
+ return this.fetched;
35
+ }
36
+ isUnfetched() {
37
+ return !this.fetched;
38
+ }
39
+ isDoingInitialFetch() {
40
+ return this.loading && !this.fetched;
41
+ }
42
+ isPresent() {
43
+ return this.present;
44
+ }
45
+ isAbsent() {
46
+ return !this.present;
47
+ }
48
+ isSubscribedToNotifications() {
49
+ return this.notificationSubscription.isSubscribedToNotifications();
50
+ }
51
+ handleThrownError(err) {
52
+ const error = connected_1.UnexpectedResourceError.fromThrown(this, err);
53
+ this.loading = false;
54
+ this.status = error;
55
+ this.emit("update");
56
+ return error;
57
+ }
58
+ overwriteQuads(quads) {
59
+ const dataset = this.context.dataset;
60
+ const graphNode = (0, data_model_1.namedNode)(this.uri);
61
+ dataset.deleteMatches(undefined, undefined, undefined, graphNode);
62
+ dataset.addAll(quads.map((ngQuad) => {
63
+ return (0, data_model_1.quad)(ngQuad.subject, ngQuad.predicate, ngQuad.object, graphNode);
64
+ }));
65
+ }
66
+ async read() {
67
+ try {
68
+ this.loading = true;
69
+ this.emit("update");
70
+ await new Promise(async (resolve, reject) => {
71
+ let unsub;
72
+ try {
73
+ unsub = await nextgraph_1.default.doc_subscribe(this.uri, this.context.nextgraph.sessionId, async (response) => {
74
+ if (response.V0.State) {
75
+ unsub();
76
+ await this.onNotification(response);
77
+ resolve();
78
+ }
79
+ });
80
+ }
81
+ catch (err) {
82
+ reject(err);
83
+ }
84
+ });
85
+ const result = new NextGraphReadSuccess_1.NextGraphReadSuccess(this, false);
86
+ this.loading = false;
87
+ this.fetched = true;
88
+ this.present = true;
89
+ this.status = result;
90
+ this.emit("update");
91
+ return result;
92
+ }
93
+ catch (err) {
94
+ if (err === "RepoNotFound") {
95
+ const result = new NextGraphReadSuccess_1.NextGraphReadSuccess(this, false);
96
+ this.loading = false;
97
+ this.fetched = true;
98
+ this.present = false;
99
+ this.status = result;
100
+ this.emit("update");
101
+ return result;
102
+ }
103
+ return this.handleThrownError(err);
104
+ }
105
+ }
106
+ async readIfUnfetched() {
107
+ if (this.isFetched()) {
108
+ return new NextGraphReadSuccess_1.NextGraphReadSuccess(this, true);
109
+ }
110
+ return this.read();
111
+ }
112
+ async update(datasetChanges) {
113
+ this.loading = true;
114
+ this.emit("update");
115
+ this.context.dataset.bulk(datasetChanges);
116
+ try {
117
+ await nextgraph_1.default.sparql_update(this.context.nextgraph.sessionId, await (0, rdf_utils_1.changesToSparqlUpdate)(datasetChanges), this.uri);
118
+ return new connected_1.UpdateSuccess(this);
119
+ }
120
+ catch (err) {
121
+ this.context.dataset.bulk({
122
+ added: datasetChanges.removed,
123
+ removed: datasetChanges.added,
124
+ });
125
+ return this.handleThrownError(err);
126
+ }
127
+ }
128
+ async notificationToQuads(notificationString) {
129
+ const rawTriples = JSON.parse(notificationString);
130
+ const triples = (await Promise.all(rawTriples.map(async (rawTriple) => (0, ldo_1.parseRdf)(`${rawTriple}.`, { baseIRI: this.uri })))).reduce((agg, ldoDataset) => {
131
+ ldoDataset.forEach((quad) => {
132
+ agg.add(quad);
133
+ });
134
+ return agg;
135
+ }, (0, dataset_1.createDataset)());
136
+ return triples;
137
+ }
138
+ async onNotification(response) {
139
+ if (response.V0.State) {
140
+ if (!response.V0.State.graph) {
141
+ this.overwriteQuads([]);
142
+ return;
143
+ }
144
+ const json_str = new TextDecoder().decode(response.V0.State.graph.triples);
145
+ const triples = await this.notificationToQuads(json_str);
146
+ this.overwriteQuads(triples);
147
+ }
148
+ else if (response.V0.Patch?.graph) {
149
+ const insertsString = new TextDecoder().decode(response.V0.Patch.graph.inserts);
150
+ const removesString = new TextDecoder().decode(response.V0.Patch.graph.removes);
151
+ const [added, removed] = await Promise.all([insertsString, removesString].map(async (str) => {
152
+ return this.notificationToQuads(str);
153
+ }));
154
+ this.context.dataset.bulk({
155
+ added,
156
+ removed,
157
+ });
158
+ }
159
+ }
160
+ async subscribeToNotifications(callbacks) {
161
+ return await this.notificationSubscription.subscribeToNotifications(callbacks);
162
+ }
163
+ unsubscribeFromNotifications(subscriptionId) {
164
+ return this.notificationSubscription.unsubscribeFromNotification(subscriptionId);
165
+ }
166
+ unsubscribeFromAllNotifications() {
167
+ return this.notificationSubscription.unsubscribeFromAllNotifications();
168
+ }
169
+ }
170
+ exports.NextGraphResource = NextGraphResource;
171
+ //# sourceMappingURL=NextGraphResource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NextGraphResource.js","sourceRoot":"","sources":["../../src/resources/NextGraphResource.ts"],"names":[],"mappings":";;;;;;AAK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C,CAAC;QACL,CAAC;IACH,CAAC;IAED,KAAK,CAAC,wBAAwB,CAC5B,SAA+D;QAE/D,OAAO,MAAM,IAAI,CAAC,wBAAwB,CAAC,wBAAwB,CACjE,SAAS,CACV,CAAC;IACJ,CAAC;IAED,4BAA4B,CAAC,cAAsB;QACjD,OAAO,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAC9D,cAAc,CACf,CAAC;IACJ,CAAC;IAED,+BAA+B;QAC7B,OAAO,IAAI,CAAC,wBAAwB,CAAC,+BAA+B,EAAE,CAAC;IACzE,CAAC;CACF;AAxPD,8CAwPC"}
@@ -0,0 +1,5 @@
1
+ import { ReadSuccess } from "@ldo/connected";
2
+ import type { NextGraphResource } from "../resources/NextGraphResource";
3
+ export declare class NextGraphReadSuccess extends ReadSuccess<NextGraphResource> {
4
+ type: "nextGraphReadSuccess";
5
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NextGraphReadSuccess = void 0;
4
+ const connected_1 = require("@ldo/connected");
5
+ class NextGraphReadSuccess extends connected_1.ReadSuccess {
6
+ constructor() {
7
+ super(...arguments);
8
+ this.type = "nextGraphReadSuccess";
9
+ }
10
+ }
11
+ exports.NextGraphReadSuccess = NextGraphReadSuccess;
12
+ //# sourceMappingURL=NextGraphReadSuccess.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NextGraphReadSuccess.js","sourceRoot":"","sources":["../../src/results/NextGraphReadSuccess.ts"],"names":[],"mappings":";;;AAAA,8CAA6C;AAG7C,MAAa,oBAAqB,SAAQ,uBAA8B;IAAxE;;QACE,SAAI,GAAG,sBAA+B,CAAC;IACzC,CAAC;CAAA;AAFD,oDAEC"}
@@ -0,0 +1,5 @@
1
+ import { ErrorResult } from "@ldo/connected";
2
+ export declare class NoNextGraphStoreError extends ErrorResult {
3
+ type: "noNextGraphStore";
4
+ constructor(message?: string);
5
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NoNextGraphStoreError = void 0;
4
+ const connected_1 = require("@ldo/connected");
5
+ class NoNextGraphStoreError extends connected_1.ErrorResult {
6
+ constructor(message) {
7
+ super(message ?? "No NextGraph store was provided.");
8
+ this.type = "noNextGraphStore";
9
+ }
10
+ }
11
+ exports.NoNextGraphStoreError = NoNextGraphStoreError;
12
+ //# sourceMappingURL=NoNextGraphStoreError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NoNextGraphStoreError.js","sourceRoot":"","sources":["../../src/results/NoNextGraphStoreError.ts"],"names":[],"mappings":";;;AAAA,8CAA6C;AAE7C,MAAa,qBAAsB,SAAQ,uBAAW;IAEpD,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,IAAI,kCAAkC,CAAC,CAAC;QAFvD,SAAI,GAAG,kBAA2B,CAAC;IAGnC,CAAC;CACF;AALD,sDAKC"}
@@ -0,0 +1,2 @@
1
+ export type NextGraphUriPrefix = `did:ng`;
2
+ export type NextGraphUri = `${NextGraphUriPrefix}${string}` & {};
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -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,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=NextGraphNotificationMessage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NextGraphNotificationMessage.js","sourceRoot":"","sources":["../../src/util/NextGraphNotificationMessage.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ import type { NextGraphUri } from "../types";
2
+ export declare function isNextGraphUri(uri: string): uri is NextGraphUri;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNextGraphUri = void 0;
4
+ function isNextGraphUri(uri) {
5
+ return uri.startsWith("did:ng");
6
+ }
7
+ exports.isNextGraphUri = isNextGraphUri;
8
+ //# sourceMappingURL=isNextGraphUri.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isNextGraphUri.js","sourceRoot":"","sources":["../../src/util/isNextGraphUri.ts"],"names":[],"mappings":";;;AAOA,SAAgB,cAAc,CAAC,GAAW;IACxC,OAAO,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;AAClC,CAAC;AAFD,wCAEC"}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@ldo/connected-nextgraph",
3
+ "version": "1.0.0-alpha.2",
4
+ "description": "A plugin for @ldo/connected to work with the Solid ecosystem.",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "build": "tsc --project tsconfig.build.json",
8
+ "watch": "tsc --watch",
9
+ "test": "npm run test:integration",
10
+ "prepublishOnly": "npm run test && npm run build",
11
+ "lint": "eslint src/** --fix --no-error-on-unmatched-pattern",
12
+ "docs": "typedoc --plugin typedoc-plugin-markdown",
13
+ "start-test-server": "./test/ngd -vv --save-key -l 14400 --base ./test/nextgraph-data",
14
+ "start-integration-test": "jest --coverage",
15
+ "test:integration": "start-server-and-test start-test-server http-get://localhost:14400 start-integration-test"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/o-development/ldobjects.git"
20
+ },
21
+ "author": "Jackson Morgan",
22
+ "license": "MIT",
23
+ "bugs": {
24
+ "url": "https://github.com/o-development/ldobjects/issues"
25
+ },
26
+ "homepage": "https://github.com/o-development/ldobjects/tree/main/packages/solid#readme",
27
+ "devDependencies": {
28
+ "@inrupt/solid-client-authn-core": "^2.2.6",
29
+ "@ldo/cli": "^1.0.0-alpha.2",
30
+ "@rdfjs/data-model": "^1.2.0",
31
+ "@rdfjs/types": "^1.0.1",
32
+ "@solid-notifications/types": "^0.1.2",
33
+ "@solid/community-server": "^7.1.3",
34
+ "cross-env": "^7.0.3",
35
+ "dotenv": "^16.3.1",
36
+ "jest-rdf": "^1.8.0",
37
+ "start-server-and-test": "^2.0.11",
38
+ "ts-node": "^10.9.1",
39
+ "typed-emitter": "^2.1.0",
40
+ "typedoc": "^0.25.4",
41
+ "typedoc-plugin-markdown": "^3.17.1"
42
+ },
43
+ "dependencies": {
44
+ "@ldo/dataset": "^1.0.0-alpha.2",
45
+ "@ldo/ldo": "^1.0.0-alpha.2",
46
+ "@ldo/rdf-utils": "^1.0.0-alpha.2",
47
+ "@solid-notifications/subscription": "^0.1.2",
48
+ "cross-fetch": "^3.1.6",
49
+ "http-link-header": "^1.1.1",
50
+ "nextgraph": "^0.1.1-alpha.7",
51
+ "ws": "^8.18.0"
52
+ },
53
+ "files": [
54
+ "dist",
55
+ "src"
56
+ ],
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "gitHead": "ba5cbcfa79af530258cad3b7ae1478a6673befea"
61
+ }
@@ -0,0 +1,83 @@
1
+ import type { ConnectedContext, ConnectedPlugin } from "@ldo/connected";
2
+ import type { NextGraphUri } from "./types";
3
+ import { NextGraphResource } from "./resources/NextGraphResource";
4
+ import ng from "nextgraph";
5
+ import { isNextGraphUri } from "./util/isNextGraphUri";
6
+
7
+ export interface NextGraphConnectedContext {
8
+ sessionId?: string;
9
+ protectedStoreId?: string;
10
+ privateStoreId?: string;
11
+ publicStoreId?: string;
12
+ }
13
+
14
+ export interface NextGraphCreateResourceOptions {
15
+ storeType?: "public" | "protected" | "private" | "group" | "dialog";
16
+ storeRepo?: string;
17
+ }
18
+
19
+ export interface NextGraphConnectedPlugin
20
+ extends ConnectedPlugin<
21
+ "nextgraph",
22
+ NextGraphUri,
23
+ NextGraphResource,
24
+ NextGraphConnectedContext,
25
+ NextGraphCreateResourceOptions
26
+ > {
27
+ name: "nextgraph";
28
+ getResource: (
29
+ uri: NextGraphUri,
30
+ context: ConnectedContext<this[]>,
31
+ ) => NextGraphResource;
32
+ createResource(context: ConnectedContext<this[]>): Promise<NextGraphResource>;
33
+ }
34
+
35
+ export const nextGraphConnectedPlugin: NextGraphConnectedPlugin = {
36
+ name: "nextgraph",
37
+
38
+ getResource: function (
39
+ uri: NextGraphUri,
40
+ context: ConnectedContext<NextGraphConnectedPlugin[]>,
41
+ ): NextGraphResource {
42
+ return new NextGraphResource(uri, context);
43
+ },
44
+
45
+ createResource: async function (
46
+ context: ConnectedContext<NextGraphConnectedPlugin[]>,
47
+ options?: NextGraphCreateResourceOptions,
48
+ ): Promise<NextGraphResource> {
49
+ const storeType = options?.storeType;
50
+ const storeRepo =
51
+ options?.storeRepo ??
52
+ (storeType === "protected"
53
+ ? context.nextgraph.protectedStoreId
54
+ : storeType === "public"
55
+ ? context.nextgraph.publicStoreId
56
+ : storeType === "private"
57
+ ? context.nextgraph.privateStoreId
58
+ : undefined);
59
+
60
+ const nuri: NextGraphUri = await ng.doc_create(
61
+ context.nextgraph.sessionId,
62
+ "Graph",
63
+ "data:graph",
64
+ "store",
65
+ storeType,
66
+ storeRepo,
67
+ );
68
+ const newResource = new NextGraphResource(nuri, context);
69
+ await newResource.read();
70
+ return newResource;
71
+ },
72
+
73
+ isUriValid: function (uri: string): uri is NextGraphUri {
74
+ return isNextGraphUri(uri);
75
+ },
76
+
77
+ initialContext: {
78
+ sessionId: undefined,
79
+ },
80
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
81
+ // @ts-ignore "Types" only exists for the typing system
82
+ types: {},
83
+ };
@@ -0,0 +1,13 @@
1
+ import { ConnectedLdoDataset } from "@ldo/connected";
2
+ import { nextGraphConnectedPlugin } from "./NextGraphConnectedPlugin";
3
+ import { createDatasetFactory } from "@ldo/dataset";
4
+ import { createTransactionDatasetFactory } from "@ldo/subscribable-dataset";
5
+
6
+ export function createNextGraphLdoDataset() {
7
+ const nextGraphLdoDataset = new ConnectedLdoDataset(
8
+ [nextGraphConnectedPlugin],
9
+ createDatasetFactory(),
10
+ createTransactionDatasetFactory(),
11
+ );
12
+ return nextGraphLdoDataset;
13
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from "./types";
2
+ export * from "./NextGraphConnectedPlugin";
3
+
4
+ export * from "./resources/NextGraphResource";
5
+
6
+ export * from "./util/isNextGraphUri";
7
+
8
+ export * from "./results/NextGraphReadSuccess";
@@ -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,25 @@
1
+ import { NotificationSubscription } from "@ldo/connected";
2
+ import type { NextGraphConnectedPlugin } from "../NextGraphConnectedPlugin";
3
+ import type { NextGraphNotificationMessage } from "./NextGraphNotificationMessage";
4
+ import ng from "nextgraph";
5
+
6
+ export class NextGraphNotificationSubscription extends NotificationSubscription<
7
+ NextGraphConnectedPlugin,
8
+ NextGraphNotificationMessage
9
+ > {
10
+ private unsub: (() => void) | undefined;
11
+
12
+ protected async open(): Promise<void> {
13
+ console.log("THIS WAS OPENED AND IT SHOULDNT BE");
14
+ this.unsub = await ng.doc_subscribe(
15
+ this.resource.uri,
16
+ this.context.nextgraph.sessionId,
17
+ this.onNotification.bind(this),
18
+ );
19
+ }
20
+
21
+ protected async close(): Promise<void> {
22
+ this.unsub?.();
23
+ this.unsub = undefined;
24
+ }
25
+ }
@@ -0,0 +1,275 @@
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";
14
+ import EventEmitter from "events";
15
+ import type { NextGraphConnectedPlugin } from "../NextGraphConnectedPlugin";
16
+ import ng from "nextgraph";
17
+ import { changesToSparqlUpdate, type DatasetChanges } from "@ldo/rdf-utils";
18
+ import type { NextGraphNotificationMessage } from "../notifications/NextGraphNotificationMessage";
19
+ import type { Dataset, Quad } from "@rdfjs/types";
20
+ import { namedNode, quad as createQuad } from "@rdfjs/data-model";
21
+ import { NextGraphReadSuccess } from "../results/NextGraphReadSuccess";
22
+ import { NextGraphNotificationSubscription } from "../notifications/NextGraphNotificationSubscription";
23
+ import { parseRdf } from "@ldo/ldo";
24
+ import type { LdoDataset } from "@ldo/ldo";
25
+ import { createDataset } from "@ldo/dataset";
26
+
27
+ export class NextGraphResource
28
+ extends (EventEmitter as new () => ResourceEventEmitter)
29
+ implements Resource<NextGraphUri>
30
+ {
31
+ public readonly uri: NextGraphUri;
32
+ public readonly type = "NextGraphResource" as const;
33
+ public readonly isError = false as const;
34
+ public status: ConnectedResult;
35
+ protected context: ConnectedContext<NextGraphConnectedPlugin[]>;
36
+
37
+ private fetched: boolean = false;
38
+ private loading: boolean = false;
39
+ private present: boolean | undefined = undefined;
40
+
41
+ /**
42
+ * @internal
43
+ * Handles notification subscriptions
44
+ */
45
+ protected notificationSubscription: NotificationSubscription<
46
+ NextGraphConnectedPlugin,
47
+ NextGraphNotificationMessage
48
+ >;
49
+
50
+ constructor(
51
+ uri: NextGraphUri,
52
+ context: ConnectedContext<NextGraphConnectedPlugin[]>,
53
+ ) {
54
+ super();
55
+ this.uri = uri;
56
+ this.status = new Unfetched(this);
57
+ this.context = context;
58
+ this.notificationSubscription = new NextGraphNotificationSubscription(
59
+ this,
60
+ this.onNotification.bind(this),
61
+ this.context,
62
+ );
63
+ }
64
+
65
+ isLoading(): boolean {
66
+ return this.loading;
67
+ }
68
+
69
+ isFetched(): boolean {
70
+ return this.fetched;
71
+ }
72
+
73
+ isUnfetched(): boolean {
74
+ return !this.fetched;
75
+ }
76
+
77
+ isDoingInitialFetch(): boolean {
78
+ return this.loading && !this.fetched;
79
+ }
80
+
81
+ isPresent(): boolean | undefined {
82
+ return this.present;
83
+ }
84
+
85
+ isAbsent(): boolean | undefined {
86
+ return !this.present;
87
+ }
88
+
89
+ isSubscribedToNotifications(): boolean {
90
+ return this.notificationSubscription.isSubscribedToNotifications();
91
+ }
92
+
93
+ private handleThrownError(
94
+ err: unknown,
95
+ ): UnexpectedResourceError<NextGraphResource> {
96
+ const error = UnexpectedResourceError.fromThrown(this, err);
97
+ this.loading = false;
98
+ this.status = error;
99
+ this.emit("update");
100
+ return error;
101
+ }
102
+
103
+ private overwriteQuads(quads: Quad[] | Dataset<Quad>) {
104
+ const dataset = this.context.dataset;
105
+ const graphNode = namedNode(this.uri);
106
+ dataset.deleteMatches(undefined, undefined, undefined, graphNode);
107
+ dataset.addAll(
108
+ quads.map((ngQuad) => {
109
+ return createQuad(
110
+ ngQuad.subject,
111
+ ngQuad.predicate,
112
+ ngQuad.object,
113
+ graphNode,
114
+ );
115
+ }),
116
+ );
117
+ }
118
+
119
+ async read(): Promise<
120
+ NextGraphReadSuccess | UnexpectedResourceError<NextGraphResource>
121
+ > {
122
+ try {
123
+ this.loading = true;
124
+ this.emit("update");
125
+
126
+ // Fetch the data once using subscribe
127
+ await new Promise<void>(async (resolve, reject) => {
128
+ let unsub: () => void;
129
+ try {
130
+ unsub = await ng.doc_subscribe(
131
+ this.uri,
132
+ this.context.nextgraph.sessionId,
133
+ async (response: NextGraphNotificationMessage) => {
134
+ if (response.V0.State) {
135
+ unsub();
136
+ await this.onNotification(response);
137
+ resolve();
138
+ }
139
+ },
140
+ );
141
+ } catch (err) {
142
+ reject(err);
143
+ }
144
+ });
145
+
146
+ // Update statuses
147
+ const result = new NextGraphReadSuccess(this, false);
148
+ this.loading = false;
149
+ this.fetched = true;
150
+ this.present = true;
151
+ this.status = result;
152
+ this.emit("update");
153
+ return result;
154
+ } catch (err) {
155
+ if (err === "RepoNotFound") {
156
+ const result = new NextGraphReadSuccess(this, false);
157
+ this.loading = false;
158
+ this.fetched = true;
159
+ this.present = false;
160
+ this.status = result;
161
+ this.emit("update");
162
+ return result;
163
+ }
164
+ return this.handleThrownError(err);
165
+ }
166
+ }
167
+
168
+ async readIfUnfetched(): Promise<
169
+ NextGraphReadSuccess | UnexpectedResourceError<NextGraphResource>
170
+ > {
171
+ if (this.isFetched()) {
172
+ return new NextGraphReadSuccess(this, true);
173
+ }
174
+ return this.read();
175
+ }
176
+
177
+ async update(
178
+ datasetChanges: DatasetChanges<Quad>,
179
+ ): Promise<
180
+ | UpdateSuccess<NextGraphResource>
181
+ | UnexpectedResourceError<NextGraphResource>
182
+ > {
183
+ this.loading = true;
184
+ this.emit("update");
185
+
186
+ // Optimistically apply updates
187
+ this.context.dataset.bulk(datasetChanges);
188
+
189
+ try {
190
+ // Perform Update with remote
191
+ await ng.sparql_update(
192
+ this.context.nextgraph.sessionId,
193
+ await changesToSparqlUpdate(datasetChanges),
194
+ this.uri,
195
+ );
196
+ return new UpdateSuccess(this);
197
+ } catch (err) {
198
+ // Revert data on error
199
+ this.context.dataset.bulk({
200
+ added: datasetChanges.removed,
201
+ removed: datasetChanges.added,
202
+ });
203
+ return this.handleThrownError(err);
204
+ }
205
+ }
206
+
207
+ private async notificationToQuads(
208
+ notificationString: string,
209
+ ): Promise<Dataset<Quad>> {
210
+ const rawTriples = JSON.parse(notificationString);
211
+ const triples = (
212
+ await Promise.all<LdoDataset>(
213
+ rawTriples.map(async (rawTriple) =>
214
+ parseRdf(`${rawTriple}.`, { baseIRI: this.uri }),
215
+ ),
216
+ )
217
+ ).reduce((agg, ldoDataset) => {
218
+ ldoDataset.forEach((quad) => {
219
+ agg.add(quad);
220
+ });
221
+ return agg;
222
+ }, createDataset());
223
+ return triples;
224
+ }
225
+
226
+ protected async onNotification(response: NextGraphNotificationMessage) {
227
+ if (response.V0.State) {
228
+ if (!response.V0.State.graph) {
229
+ this.overwriteQuads([]);
230
+ return;
231
+ }
232
+ const json_str = new TextDecoder().decode(
233
+ response.V0.State.graph.triples,
234
+ );
235
+ const triples = await this.notificationToQuads(json_str);
236
+ this.overwriteQuads(triples);
237
+ } else if (response.V0.Patch?.graph) {
238
+ const insertsString = new TextDecoder().decode(
239
+ response.V0.Patch.graph.inserts,
240
+ );
241
+ const removesString = new TextDecoder().decode(
242
+ response.V0.Patch.graph.removes,
243
+ );
244
+
245
+ const [added, removed] = await Promise.all(
246
+ [insertsString, removesString].map(async (str) => {
247
+ return this.notificationToQuads(str);
248
+ }),
249
+ );
250
+
251
+ this.context.dataset.bulk({
252
+ added,
253
+ removed,
254
+ });
255
+ }
256
+ }
257
+
258
+ async subscribeToNotifications(
259
+ callbacks?: SubscriptionCallbacks<NextGraphNotificationMessage>,
260
+ ): Promise<string> {
261
+ return await this.notificationSubscription.subscribeToNotifications(
262
+ callbacks,
263
+ );
264
+ }
265
+
266
+ unsubscribeFromNotifications(subscriptionId: string): Promise<void> {
267
+ return this.notificationSubscription.unsubscribeFromNotification(
268
+ subscriptionId,
269
+ );
270
+ }
271
+
272
+ unsubscribeFromAllNotifications(): Promise<void> {
273
+ return this.notificationSubscription.unsubscribeFromAllNotifications();
274
+ }
275
+ }
@@ -0,0 +1,6 @@
1
+ import { ReadSuccess } from "@ldo/connected";
2
+ import type { NextGraphResource } from "../resources/NextGraphResource";
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";
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
+ }