@coasys/ad4m 0.10.1-rc9-dev → 0.10.1-release-candidate-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 (61) hide show
  1. package/lib/index.cjs +3179 -811
  2. package/lib/index.js +3171 -807
  3. package/lib/src/Literal.js +4 -1
  4. package/lib/src/ai/AIClient.d.ts +1 -1
  5. package/lib/src/ai/AIClient.js +6 -6
  6. package/lib/src/ai/AIResolver.d.ts +1 -1
  7. package/lib/src/ai/AIResolver.js +7 -4
  8. package/lib/src/index.d.ts +4 -3
  9. package/lib/src/index.js +4 -3
  10. package/lib/src/model/Ad4mModel.d.ts +609 -0
  11. package/lib/src/model/Ad4mModel.js +1048 -0
  12. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  13. package/lib/src/{subject → model}/Subject.js +18 -18
  14. package/lib/src/model/decorators.d.ts +502 -0
  15. package/lib/src/model/decorators.js +683 -0
  16. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
  17. package/lib/src/neighbourhood/NeighbourhoodClient.js +16 -10
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
  19. package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
  20. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  21. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +31 -0
  22. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
  23. package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
  24. package/lib/src/perspectives/PerspectiveClient.d.ts +18 -11
  25. package/lib/src/perspectives/PerspectiveClient.js +116 -49
  26. package/lib/src/perspectives/PerspectiveProxy.d.ts +471 -54
  27. package/lib/src/perspectives/PerspectiveProxy.js +579 -64
  28. package/lib/src/perspectives/PerspectiveResolver.d.ts +23 -9
  29. package/lib/src/perspectives/PerspectiveResolver.js +140 -46
  30. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  31. package/lib/src/runtime/RuntimeClient.js +48 -0
  32. package/lib/src/runtime/RuntimeResolver.d.ts +24 -0
  33. package/lib/src/runtime/RuntimeResolver.js +117 -0
  34. package/lib/src/schema.gql +25 -11
  35. package/lib/src/typeDefs.js +25 -11
  36. package/package.json +2 -1
  37. package/src/Literal.ts +4 -1
  38. package/src/ai/AIClient.ts +6 -6
  39. package/src/ai/AIResolver.ts +6 -3
  40. package/src/index.ts +4 -3
  41. package/src/model/Ad4mModel.ts +1206 -0
  42. package/src/{subject → model}/Subject.ts +16 -16
  43. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  44. package/src/neighbourhood/NeighbourhoodClient.ts +16 -10
  45. package/src/neighbourhood/NeighbourhoodProxy.test.ts +45 -0
  46. package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
  47. package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
  48. package/src/perspectives/PerspectiveClient.ts +122 -51
  49. package/src/perspectives/PerspectiveProxy.ts +642 -77
  50. package/src/perspectives/PerspectiveResolver.ts +126 -23
  51. package/src/runtime/RuntimeClient.ts +52 -1
  52. package/src/runtime/RuntimeResolver.ts +77 -0
  53. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  54. package/lib/src/subject/SDNADecorators.js +0 -360
  55. package/lib/src/subject/SubjectEntity.d.ts +0 -110
  56. package/lib/src/subject/SubjectEntity.js +0 -288
  57. package/src/subject/SubjectEntity.ts +0 -336
  58. package/yarn-error.log +0 -90
  59. /package/lib/src/{subject → model}/util.d.ts +0 -0
  60. /package/lib/src/{subject → model}/util.js +0 -0
  61. /package/src/{subject → model}/util.ts +0 -0
@@ -4,12 +4,205 @@ import { LinkQuery } from "./LinkQuery";
4
4
  import { PerspectiveHandle, PerspectiveState } from './PerspectiveHandle'
5
5
  import { Perspective } from "./Perspective";
6
6
  import { Literal } from "../Literal";
7
- import { Subject } from "../subject/Subject";
7
+ import { Subject } from "../model/Subject";
8
8
  import { ExpressionRendered } from "../expression/Expression";
9
- import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../subject/util";
9
+ import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../model/util";
10
10
  import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
11
11
  import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
12
12
  import { AIClient } from "../ai/AIClient";
13
+ import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
14
+ import { gql } from "@apollo/client/core";
15
+ import { AllInstancesResult } from "../model/Ad4mModel";
16
+
17
+ type QueryCallback = (result: AllInstancesResult) => void;
18
+
19
+ // Generic subscription interface that matches Apollo's Subscription
20
+ interface Unsubscribable {
21
+ unsubscribe(): void;
22
+ }
23
+
24
+ /** Proxy object for a subscribed Prolog query that provides real-time updates
25
+ *
26
+ * This class handles:
27
+ * - Keeping the subscription alive by sending periodic keepalive signals
28
+ * - Managing callbacks for result updates
29
+ * - Subscribing to query updates via GraphQL subscriptions
30
+ * - Maintaining the latest query result
31
+ * - Ensuring subscription is fully initialized before allowing access
32
+ *
33
+ * The subscription will remain active as long as keepalive signals are sent.
34
+ * Make sure to call dispose() when you're done with the subscription to clean up
35
+ * resources and stop keepalive signals.
36
+ *
37
+ * The subscription goes through an initialization process where it waits for the first
38
+ * result to come through the subscription channel. You can await the `initialized`
39
+ * promise to ensure the subscription is ready. The initialization will timeout after
40
+ * 30 seconds if no result is received.
41
+ *
42
+ * Example usage:
43
+ * ```typescript
44
+ * const subscription = await perspective.subscribeInfer("my_query(X)");
45
+ * // At this point the subscription is already initialized since subscribeInfer waits
46
+ *
47
+ * // Set up callback for future updates
48
+ * const removeCallback = subscription.onResult(result => {
49
+ * console.log("New result:", result);
50
+ * });
51
+ *
52
+ * // Later: clean up
53
+ * subscription.dispose();
54
+ * ```
55
+ */
56
+ export class QuerySubscriptionProxy {
57
+ #uuid: string;
58
+ #subscriptionId: string;
59
+ #client: PerspectiveClient;
60
+ #callbacks: Set<QueryCallback>;
61
+ #keepaliveTimer: number;
62
+ #unsubscribe?: () => void;
63
+ #latestResult: AllInstancesResult;
64
+ #disposed: boolean = false;
65
+ #initialized: Promise<boolean>;
66
+ #initTimeoutId?: NodeJS.Timeout;
67
+
68
+ /** Creates a new query subscription
69
+ * @param uuid - The UUID of the perspective
70
+ * @param subscriptionId - The ID returned by the subscription mutation
71
+ * @param initialResult - The initial query result
72
+ * @param client - The PerspectiveClient instance to use for communication
73
+ */
74
+ constructor(uuid: string, subscriptionId: string, initialResult: AllInstancesResult, client: PerspectiveClient) {
75
+ this.#uuid = uuid;
76
+ this.#subscriptionId = subscriptionId;
77
+ this.#client = client;
78
+ this.#callbacks = new Set();
79
+ this.#latestResult = initialResult;
80
+
81
+ this.#initialized = new Promise<boolean>((resolve, reject) => {
82
+ // Add timeout to prevent hanging promises
83
+ this.#initTimeoutId = setTimeout(() => {
84
+ reject(new Error('Subscription initialization timed out after 30 seconds'));
85
+ }, 30000); // 30 seconds timeout
86
+
87
+ // Subscribe to query updates
88
+ this.#unsubscribe = this.#client.subscribeToQueryUpdates(
89
+ this.#subscriptionId,
90
+ (result) => {
91
+ if (this.#initTimeoutId) {
92
+ clearTimeout(this.#initTimeoutId);
93
+ this.#initTimeoutId = undefined;
94
+ }
95
+ resolve(true);
96
+ this.#latestResult = result;
97
+ this.#notifyCallbacks(result);
98
+ }
99
+ );
100
+ });
101
+
102
+ // Start keepalive loop using platform-agnostic setTimeout
103
+ const keepaliveLoop = async () => {
104
+ if (this.#disposed) return;
105
+
106
+ try {
107
+ await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
108
+ } catch (e) {
109
+ console.error('Error in keepalive:', e);
110
+ }
111
+
112
+ // Schedule next keepalive if not disposed
113
+ if (!this.#disposed) {
114
+ this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
115
+ }
116
+ };
117
+
118
+ // Start the first keepalive loop
119
+ this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
120
+ }
121
+
122
+ /** Promise that resolves when the subscription has received its first result
123
+ * through the subscription channel. This ensures the subscription is fully
124
+ * set up before allowing access to results or updates.
125
+ *
126
+ * The promise will reject if no result is received within 30 seconds.
127
+ *
128
+ * Note: You typically don't need to await this directly since the subscription
129
+ * creation methods (like subscribeInfer) already wait for initialization.
130
+ */
131
+ get initialized(): Promise<boolean> {
132
+ return this.#initialized;
133
+ }
134
+
135
+ /** Get the latest query result
136
+ *
137
+ * This returns the most recent result from the query, which could be either:
138
+ * - The initial result from when the subscription was created
139
+ * - The latest update received through the subscription
140
+ *
141
+ * @returns The latest query result as a string (usually a JSON array of bindings)
142
+ */
143
+ get result(): AllInstancesResult {
144
+ return this.#latestResult;
145
+ }
146
+
147
+ /** Add a callback that will be called whenever new results arrive
148
+ *
149
+ * The callback will be called immediately with the current result,
150
+ * and then again each time the query results change.
151
+ *
152
+ * @param callback - Function that takes a result string and processes it
153
+ * @returns A function that can be called to remove this callback
154
+ *
155
+ * Example:
156
+ * ```typescript
157
+ * const removeCallback = subscription.onResult(result => {
158
+ * const bindings = JSON.parse(result);
159
+ * console.log("New bindings:", bindings);
160
+ * });
161
+ *
162
+ * // Later: stop receiving updates
163
+ * removeCallback();
164
+ * ```
165
+ */
166
+ onResult(callback: QueryCallback): () => void {
167
+ this.#callbacks.add(callback);
168
+ return () => this.#callbacks.delete(callback);
169
+ }
170
+
171
+ /** Internal method to notify all callbacks of a new result */
172
+ #notifyCallbacks(result: AllInstancesResult) {
173
+ for (const callback of this.#callbacks) {
174
+ try {
175
+ callback(result);
176
+ } catch (e) {
177
+ console.error('Error in query subscription callback:', e);
178
+ }
179
+ }
180
+ }
181
+
182
+ /** Clean up the subscription and stop keepalive signals
183
+ *
184
+ * This method:
185
+ * 1. Stops the keepalive timer
186
+ * 2. Unsubscribes from GraphQL subscription updates
187
+ * 3. Clears all registered callbacks
188
+ * 4. Cleans up any pending initialization timeout
189
+ *
190
+ * After calling this method, the subscription is no longer active and
191
+ * will not receive any more updates. The instance should be discarded.
192
+ */
193
+ dispose() {
194
+ this.#disposed = true;
195
+ clearTimeout(this.#keepaliveTimer);
196
+ if (this.#unsubscribe) {
197
+ this.#unsubscribe();
198
+ }
199
+ if (this.#initTimeoutId) {
200
+ clearTimeout(this.#initTimeoutId);
201
+ this.#initTimeoutId = undefined;
202
+ }
203
+ this.#callbacks.clear();
204
+ }
205
+ }
13
206
 
14
207
  type PerspectiveListenerTypes = "link-added" | "link-removed" | "link-updated"
15
208
 
@@ -19,26 +212,59 @@ interface Parameter {
19
212
  value: string
20
213
  }
21
214
 
22
- /** Perspective UI proxy object
23
- *
24
- * Convenience object for UIs to interact with a perspective.
25
- * It is created by some of the methods in the PerspectiveClient class and includes
26
- * a reference to the PerspectiveClient object that created it.
215
+ /**
216
+ * PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs
217
+ * that store and organize links between expressions.
218
+ *
219
+ * A Perspective is fundamentally a collection of links (subject-predicate-object triples) that represent an agent's view
220
+ * of their digital world. Through PerspectiveProxy, you can:
221
+ * - Add, remove, and query links
222
+ * - Work with Social DNA (subject classes and flows)
223
+ * - Subscribe to real-time updates
224
+ * - Share perspectives as Neighbourhoods
225
+ * - Execute Prolog queries for complex graph patterns
226
+ *
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * // Create and work with links
231
+ * const perspective = await ad4m.perspective.add("My Space");
232
+ * await perspective.add({
233
+ * source: "did:key:alice",
234
+ * predicate: "knows",
235
+ * target: "did:key:bob"
236
+ * });
237
+ *
238
+ * // Query links
239
+ * const friends = await perspective.get({
240
+ * source: "did:key:alice",
241
+ * predicate: "knows"
242
+ * });
243
+ *
244
+ * // Use Social DNA
245
+ * await perspective.addSdna(todoClass, "subject_class");
246
+ * const todo = await perspective.createSubject("Todo", "expression://123");
247
+ *
248
+ * // Subscribe to changes
249
+ * perspective.addListener("link-added", (link) => {
250
+ * console.log("New link added:", link);
251
+ * });
252
+ * ```
27
253
  */
28
254
  export class PerspectiveProxy {
29
- /** Unique ID of the perspective */
255
+ /** Unique identifier of this perspective */
30
256
  uuid: string;
31
257
 
32
- /** Given name of the perspective */
258
+ /** Human-readable name of this perspective */
33
259
  name: string;
34
260
 
35
- /** If the perspective is shared as a Neighbourhood, this is the Neighbourhood URL */
261
+ /** If this perspective is shared as a Neighbourhood, this is its URL */
36
262
  sharedUrl: string|null;
37
263
 
38
- /** If the perspective is shared as a Neighbourhood, this is the Neighbourhood Expression */
264
+ /** If this perspective is shared, this contains the Neighbourhood metadata */
39
265
  neighbourhood: NeighbourhoodExpression|null;
40
266
 
41
- /** Returns the state of the perspective **/
267
+ /** Current sync state if this perspective is shared */
42
268
  state: PerspectiveState|null;
43
269
 
44
270
  #handle: PerspectiveHandle
@@ -48,6 +274,10 @@ export class PerspectiveProxy {
48
274
  #perspectiveLinkUpdatedCallbacks: LinkCallback[]
49
275
  #perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]
50
276
 
277
+ /**
278
+ * Creates a new PerspectiveProxy instance.
279
+ * Note: Don't create this directly, use ad4m.perspective.add() instead.
280
+ */
51
281
  constructor(handle: PerspectiveHandle, ad4m: PerspectiveClient) {
52
282
  this.#perspectiveLinkAddedCallbacks = []
53
283
  this.#perspectiveLinkRemovedCallbacks = []
@@ -66,64 +296,270 @@ export class PerspectiveProxy {
66
296
  this.#client.addPerspectiveSyncStateChangeListener(this.#handle.uuid, this.#perspectiveSyncStateChangeCallbacks)
67
297
  }
68
298
 
69
- async executeAction(actions, expression, parameters: Parameter[]) {
70
- return await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters))
299
+ /**
300
+ * Executes a set of actions on an expression with optional parameters.
301
+ * Used internally by Social DNA flows and subject class operations.
302
+ *
303
+ * Actions are specified as an array of commands that modify links in the perspective.
304
+ * Each action is an object with the following format:
305
+ * ```typescript
306
+ * {
307
+ * action: "addLink" | "removeLink" | "setSingleTarget" | "collectionSetter",
308
+ * source: string, // Usually "this" to reference the current expression
309
+ * predicate: string, // The predicate URI
310
+ * target: string // The target value or "value" for parameters
311
+ * }
312
+ * ```
313
+ *
314
+ * Available commands:
315
+ * - `addLink`: Creates a new link
316
+ * - `removeLink`: Removes an existing link
317
+ * - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one
318
+ * - `collectionSetter`: Special command for setting collection properties
319
+ *
320
+ * When used with parameters, the special value "value" in the target field will be
321
+ * replaced with the actual parameter value.
322
+ *
323
+ * @example
324
+ * ```typescript
325
+ * // Add a state link and remove an old one
326
+ * await perspective.executeAction([
327
+ * {
328
+ * action: "addLink",
329
+ * source: "this",
330
+ * predicate: "todo://state",
331
+ * target: "todo://doing"
332
+ * },
333
+ * {
334
+ * action: "removeLink",
335
+ * source: "this",
336
+ * predicate: "todo://state",
337
+ * target: "todo://ready"
338
+ * }
339
+ * ], "expression://123");
340
+ *
341
+ * // Set a property using a parameter
342
+ * await perspective.executeAction([
343
+ * {
344
+ * action: "setSingleTarget",
345
+ * source: "this",
346
+ * predicate: "todo://title",
347
+ * target: "value"
348
+ * }
349
+ * ], "expression://123", [
350
+ * { name: "title", value: "New Title" }
351
+ * ]);
352
+ * ```
353
+ *
354
+ * @param actions - Array of action objects to execute
355
+ * @param expression - Target expression address (replaces "this" in actions)
356
+ * @param parameters - Optional parameters that replace "value" in actions
357
+ * @param batchId - Optional batch ID to group this operation with others
358
+ */
359
+ async executeAction(actions, expression, parameters: Parameter[], batchId?: string) {
360
+ return await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
71
361
  }
72
362
 
73
- /** Returns all the links of this perspective that matches the LinkQuery */
363
+ /**
364
+ * Retrieves links from the perspective that match the given query.
365
+ *
366
+ * @param query - Query parameters to filter links
367
+ * @returns Array of matching LinkExpressions
368
+ *
369
+ * @example
370
+ * ```typescript
371
+ * // Get all links where Alice knows someone
372
+ * const links = await perspective.get({
373
+ * source: "did:key:alice",
374
+ * predicate: "knows"
375
+ * });
376
+ *
377
+ * // Get all comments on a post
378
+ * const comments = await perspective.get({
379
+ * source: "post://123",
380
+ * predicate: "comment"
381
+ * });
382
+ * ```
383
+ */
74
384
  async get(query: LinkQuery): Promise<LinkExpression[]> {
75
385
  return await this.#client.queryLinks(this.#handle.uuid, query)
76
386
  }
77
387
 
78
- /** Runs a Prolog query on the perspective's Prolog engine */
388
+ /**
389
+ * Executes a Prolog query against the perspective's knowledge base.
390
+ * This is a powerful way to find complex patterns in the graph.
391
+ *
392
+ * @param query - Prolog query string
393
+ * @returns Query results or false if no results
394
+ *
395
+ * @example
396
+ * ```typescript
397
+ * // Find friends of friends
398
+ * const results = await perspective.infer(`
399
+ * triple(A, "knows", B),
400
+ * triple(B, "knows", C),
401
+ * A \= C
402
+ * `);
403
+ *
404
+ * // Find all active todos
405
+ * const todos = await perspective.infer(`
406
+ * instance(Todo, "Todo"),
407
+ * property_getter("Todo", Todo, "state", "active")
408
+ * `);
409
+ * ```
410
+ */
79
411
  async infer(query: string): Promise<any> {
80
412
  return await this.#client.queryProlog(this.#handle.uuid, query)
81
413
  }
82
414
 
83
- /** Adds a link to this perspective */
84
- async add(link: Link, status: LinkStatus = 'shared'): Promise<LinkExpression> {
85
- return await this.#client.addLink(this.#handle.uuid, link, status)
415
+ /**
416
+ * Adds a new link to the perspective.
417
+ *
418
+ * @param link - The link to add
419
+ * @param status - Whether the link should be shared in a Neighbourhood
420
+ * @param batchId - Optional batch ID to group this operation with others
421
+ * @returns The created LinkExpression
422
+ *
423
+ * @example
424
+ * ```typescript
425
+ * // Add a simple relationship
426
+ * await perspective.add({
427
+ * source: "did:key:alice",
428
+ * predicate: "follows",
429
+ * target: "did:key:bob"
430
+ * });
431
+ *
432
+ * // Add a local-only link
433
+ * await perspective.add({
434
+ * source: "note://123",
435
+ * predicate: "tag",
436
+ * target: "private"
437
+ * }, "local");
438
+ * ```
439
+ */
440
+ async add(link: Link, status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression> {
441
+ return await this.#client.addLink(this.#handle.uuid, link, status, batchId)
86
442
  }
87
443
 
88
- /** Adds multiple links to this perspective **/
89
- async addLinks(links: Link[], status: LinkStatus = 'shared'): Promise<LinkExpression[]> {
90
- return await this.#client.addLinks(this.#handle.uuid, links, status)
444
+ /**
445
+ * Adds multiple links to the perspective in a single operation.
446
+ * More efficient than adding links one by one.
447
+ *
448
+ * @param links - Array of links to add
449
+ * @param status - Whether the links should be shared
450
+ * @param batchId - Optional batch ID to group this operation with others
451
+ * @returns Array of created LinkExpressions
452
+ */
453
+ async addLinks(links: Link[], status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression[]> {
454
+ return await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
91
455
  }
92
456
 
93
- /** Removes multiple links from this perspective **/
94
- async removeLinks(links: LinkExpressionInput[]): Promise<LinkExpression[]> {
95
- return await this.#client.removeLinks(this.#handle.uuid, links)
457
+ /**
458
+ * Removes multiple links from the perspective.
459
+ *
460
+ * @param links - Array of links to remove
461
+ * @param batchId - Optional batch ID to group this operation with others
462
+ * @returns Array of removed LinkExpressions
463
+ */
464
+ async removeLinks(links: LinkExpressionInput[], batchId?: string): Promise<LinkExpression[]> {
465
+ return await this.#client.removeLinks(this.#handle.uuid, links, batchId)
96
466
  }
97
467
 
98
- /** Adds and removes multiple links from this perspective **/
468
+ /**
469
+ * Applies a set of link mutations (adds and removes) in a single operation.
470
+ * Useful for atomic updates to the perspective.
471
+ *
472
+ * @param mutations - Object containing links to add and remove
473
+ * @param status - Whether new links should be shared
474
+ * @returns Object containing results of the mutations
475
+ */
99
476
  async linkMutations(mutations: LinkMutations, status: LinkStatus = 'shared'): Promise<LinkExpressionMutations> {
100
477
  return await this.#client.linkMutations(this.#handle.uuid, mutations, status)
101
478
  }
102
479
 
103
- /** Adds a linkExpression to this perspective */
104
- async addLinkExpression(link: LinkExpression, status: LinkStatus = 'shared'): Promise<LinkExpression> {
105
- return await this.#client.addLinkExpression(this.#handle.uuid, link, status)
480
+ /**
481
+ * Adds a pre-signed LinkExpression to the perspective.
482
+ *
483
+ * @param link - The signed LinkExpression to add
484
+ * @param status - Whether the link should be shared
485
+ * @param batchId - Optional batch ID to group this operation with others
486
+ * @returns The added LinkExpression
487
+ */
488
+ async addLinkExpression(link: LinkExpression, status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression> {
489
+ return await this.#client.addLinkExpression(this.#handle.uuid, link, status, batchId)
490
+ }
491
+
492
+ /**
493
+ * Updates an existing link with new data.
494
+ *
495
+ * @param oldLink - The existing link to update
496
+ * @param newLink - The new link data
497
+ * @param batchId - Optional batch ID to group this operation with others
498
+ */
499
+ async update(oldLink: LinkExpressionInput, newLink: Link, batchId?: string): Promise<LinkExpression> {
500
+ return await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
106
501
  }
107
502
 
108
- async update(oldLink: LinkExpressionInput, newLink: Link) {
109
- return await this.#client.updateLink(this.#handle.uuid, oldLink, newLink)
503
+ /**
504
+ * Removes a link from the perspective.
505
+ *
506
+ * @param link - The link to remove
507
+ * @param batchId - Optional batch ID to group this operation with others
508
+ */
509
+ async remove(link: LinkExpressionInput, batchId?: string): Promise<boolean> {
510
+ return await this.#client.removeLink(this.#handle.uuid, link, batchId)
110
511
  }
111
512
 
112
- async remove(link: LinkExpressionInput) {
113
- return await this.#client.removeLink(this.#handle.uuid, link)
513
+ /** Creates a new batch for grouping operations */
514
+ async createBatch(): Promise<string> {
515
+ return await this.#client.createBatch(this.#handle.uuid)
114
516
  }
115
517
 
518
+ /** Commits a batch of operations */
519
+ async commitBatch(batchId: string): Promise<LinkExpressionMutations> {
520
+ return await this.#client.commitBatch(this.#handle.uuid, batchId)
521
+
522
+
523
+ }
524
+ /**
525
+ * Retrieves and renders an Expression referenced in this perspective.
526
+ *
527
+ * @param expressionURI - URI of the Expression to retrieve
528
+ * @returns The rendered Expression
529
+ */
116
530
  async getExpression(expressionURI: string): Promise<ExpressionRendered> {
117
531
  return await this.#client.getExpression(expressionURI)
118
532
  }
119
533
 
534
+ /**
535
+ * Creates a new Expression in the specified Language.
536
+ *
537
+ * @param content - Content for the new Expression
538
+ * @param languageAddress - Address of the Language to use
539
+ * @returns URI of the created Expression
540
+ */
120
541
  async createExpression(content: any, languageAddress: string): Promise<string> {
121
542
  return await this.#client.createExpression(content, languageAddress)
122
543
  }
123
544
 
124
- /** Adds a link listener
125
- * @param type Can be 'link-added' or 'link-removed'
126
- * @param cb Callback function that is called when a link is added to the perspective
545
+ /**
546
+ * Subscribes to link changes in the perspective.
547
+ *
548
+ * @param type - Type of change to listen for
549
+ * @param cb - Callback function
550
+ *
551
+ * @example
552
+ * ```typescript
553
+ * // Listen for new links
554
+ * perspective.addListener("link-added", (link) => {
555
+ * console.log("New link:", link);
556
+ * });
557
+ *
558
+ * // Listen for removed links
559
+ * perspective.addListener("link-removed", (link) => {
560
+ * console.log("Link removed:", link);
561
+ * });
562
+ * ```
127
563
  */
128
564
  async addListener(type: PerspectiveListenerTypes, cb: LinkCallback) {
129
565
  if (type === 'link-added') {
@@ -135,17 +571,27 @@ export class PerspectiveProxy {
135
571
  }
136
572
  }
137
573
 
138
- /** Adds a sync state listener
139
- * @param cb Callback function that is called when the sync state of the perspective changes
140
- * @returns A function that can be called to remove the listener
574
+ /**
575
+ * Subscribes to sync state changes if this perspective is shared.
576
+ *
577
+ * @param cb - Callback function
578
+ *
579
+ * @example
580
+ * ```typescript
581
+ * perspective.addSyncStateChangeListener((state) => {
582
+ * console.log("Sync state:", state);
583
+ * });
584
+ * ```
141
585
  */
142
586
  async addSyncStateChangeListener(cb: SyncStateChangeCallback) {
143
587
  this.#perspectiveSyncStateChangeCallbacks.push(cb)
144
588
  }
145
589
 
146
- /** Removes a previously added link listener
147
- * @param type Can be 'link-added' or 'link-removed'
148
- * @param cb Callback function that is called when a link is added to the perspective
590
+ /**
591
+ * Unsubscribes from link changes.
592
+ *
593
+ * @param type - Type of change to stop listening for
594
+ * @param cb - The callback function to remove
149
595
  */
150
596
  async removeListener(type: PerspectiveListenerTypes, cb: LinkCallback) {
151
597
  if (type === 'link-added') {
@@ -163,15 +609,21 @@ export class PerspectiveProxy {
163
609
  }
164
610
  }
165
611
 
166
-
167
- /** Create and return a snapshot of this perspective
168
- * A snapshot is a rendered Perspectie object that contains all the links of the perspective.
612
+ /**
613
+ * Creates a snapshot of the current perspective state.
614
+ * Useful for backup or sharing.
615
+ *
616
+ * @returns Perspective object containing all links
169
617
  */
170
618
  async snapshot(): Promise<Perspective> {
171
619
  return this.#client.snapshotByUUID(this.#handle.uuid)
172
620
  }
173
621
 
174
- /** Take and load all the links from the given snapshot */
622
+ /**
623
+ * Loads a perspective snapshot, replacing current content.
624
+ *
625
+ * @param snapshot - Perspective snapshot to load
626
+ */
175
627
  async loadSnapshot(snapshot: Perspective) {
176
628
  //Clean the input data from __typename
177
629
  const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));
@@ -185,11 +637,21 @@ export class PerspectiveProxy {
185
637
  }
186
638
  }
187
639
 
188
- /** Convenience function to get the target of the first link that matches the given query
189
- * This makes sense when the query is expected to return only one link
190
- * and the target of that link is what you are looking for.
191
- *
192
- * Works best together with @member setSingelTarget()
640
+ /**
641
+ * Gets a single target value matching a query.
642
+ * Useful when you expect only one result.
643
+ *
644
+ * @param query - Query to find the target
645
+ * @returns Target value or void if not found
646
+ *
647
+ * @example
648
+ * ```typescript
649
+ * // Get a user's name
650
+ * const name = await perspective.getSingleTarget({
651
+ * source: "did:key:alice",
652
+ * predicate: "name"
653
+ * });
654
+ * ```
193
655
  */
194
656
  async getSingleTarget(query: LinkQuery): Promise<string|void> {
195
657
  delete query.target
@@ -200,12 +662,21 @@ export class PerspectiveProxy {
200
662
  return null
201
663
  }
202
664
 
203
- /** Convenience function to ensure there is only one link with given source and predicate
204
- * This function will remove all links with the same source and predicate as the given link,
205
- * and then add the given link.
206
- * This ensures there is only one target for the given source and predicate.
207
- *
208
- * Works best together with @member getSingleTarget()
665
+ /**
666
+ * Sets a single target value, removing any existing targets.
667
+ *
668
+ * @param link - Link defining the new target
669
+ * @param status - Whether the link should be shared
670
+ *
671
+ * @example
672
+ * ```typescript
673
+ * // Set a user's status
674
+ * await perspective.setSingleTarget({
675
+ * source: "did:key:alice",
676
+ * predicate: "status",
677
+ * target: "online"
678
+ * });
679
+ * ```
209
680
  */
210
681
  async setSingleTarget(link: Link, status: LinkStatus = 'shared') {
211
682
  const query = new LinkQuery({source: link.source, predicate: link.predicate})
@@ -293,7 +764,7 @@ export class PerspectiveProxy {
293
764
  }
294
765
  }
295
766
 
296
- async stringOrTemplateObjectToSubjectClass<T>(subjectClass: T): Promise<string> {
767
+ async stringOrTemplateObjectToSubjectClassName<T>(subjectClass: T): Promise<string> {
297
768
  if(typeof subjectClass === "string")
298
769
  return subjectClass
299
770
  else {
@@ -307,28 +778,58 @@ export class PerspectiveProxy {
307
778
  }
308
779
  }
309
780
 
310
- /** Creates a new subject instance by running its (SDNA defined) constructor,
311
- * which means adding links around the given expression address so that it
312
- * conforms to the given subject class.
313
- *
781
+ /**
782
+ * Creates a new subject instance of the given subject class
783
+ *
314
784
  * @param subjectClass Either a string with the name of the subject class, or an object
315
- * with the properties of the subject class. In the latter case, the first subject class
316
- * that matches the given properties will be used.
785
+ * with the properties of the subject class.
317
786
  * @param exprAddr The address of the expression to be turned into a subject instance
787
+ * @param initialValues Optional initial values for properties. If provided, these will be
788
+ * merged with constructor actions for better performance.
789
+ * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
790
+ * instead of the subject proxy since the subject won't exist until the batch is committed.
791
+ * @returns A proxy object for the created subject, or just the expression address if in batch mode
318
792
  */
319
- async createSubject<T>(subjectClass: T, exprAddr: string): Promise<T> {
793
+ async createSubject<T, B extends string | undefined = undefined>(
794
+ subjectClass: T,
795
+ exprAddr: string,
796
+ initialValues?: Record<string, any>,
797
+ batchId?: B
798
+ ): Promise<B extends undefined ? T : string> {
320
799
  let className: string;
321
800
 
322
801
  if(typeof subjectClass === "string") {
323
- className = subjectClass
324
-
325
- await this.#client.createSubject(this.#handle.uuid, JSON.stringify({className}), exprAddr);
802
+ className = subjectClass;
803
+ await this.#client.createSubject(
804
+ this.#handle.uuid,
805
+ JSON.stringify({
806
+ className,
807
+ initialValues
808
+ }),
809
+ exprAddr,
810
+ initialValues ? JSON.stringify(initialValues) : undefined,
811
+ batchId
812
+ );
326
813
  } else {
327
- let query = this.buildQueryFromTemplate(subjectClass as object)
328
- await this.#client.createSubject(this.#handle.uuid, JSON.stringify({query}), exprAddr);
814
+ let query = this.buildQueryFromTemplate(subjectClass as object);
815
+ await this.#client.createSubject(
816
+ this.#handle.uuid,
817
+ JSON.stringify({
818
+ query,
819
+ initialValues
820
+ }),
821
+ exprAddr,
822
+ initialValues ? JSON.stringify(initialValues) : undefined,
823
+ batchId
824
+ );
825
+ }
826
+
827
+ // Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed
828
+ if (batchId) {
829
+ return exprAddr as B extends undefined ? T : string;
329
830
  }
330
831
 
331
- return this.getSubjectProxy(exprAddr, subjectClass)
832
+ return this.getSubjectProxy(exprAddr, subjectClass) as Promise<B extends undefined ? T : string>;
332
833
  }
333
834
 
334
835
  async getSubjectData<T>(subjectClass: T, exprAddr: string): Promise<T> {
@@ -346,16 +847,18 @@ export class PerspectiveProxy {
346
847
  * with the properties of the subject class. In the latter case, the first subject class
347
848
  * that matches the given properties will be used.
348
849
  * @param exprAddr The address of the expression to be turned into a subject instance
850
+ * @param batchId Optional batch ID for grouping operations. If provided, the removal will be part of the batch
851
+ * and won't be executed until the batch is committed.
349
852
  */
350
- async removeSubject<T>(subjectClass: T, exprAddr: string) {
351
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
853
+ async removeSubject<T>(subjectClass: T, exprAddr: string, batchId?: string) {
854
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
352
855
  let result = await this.infer(`subject_class("${className}", C), destructor(C, Actions)`)
353
856
  if(!result.length) {
354
- throw "No constructor found for given subject class: " + className
857
+ throw "No destructor found for given subject class: " + className
355
858
  }
356
859
 
357
860
  let actions = result.map(x => eval(x.Actions))
358
- await this.executeAction(actions[0], exprAddr, undefined)
861
+ await this.executeAction(actions[0], exprAddr, undefined, batchId)
359
862
  }
360
863
 
361
864
  /** Checks if the given expression is a subject instance of the given subject class
@@ -365,7 +868,7 @@ export class PerspectiveProxy {
365
868
  * that matches the given properties will be used.
366
869
  */
367
870
  async isSubjectInstance<T>(expression: string, subjectClass: T): Promise<boolean> {
368
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
871
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
369
872
  let isInstance = false;
370
873
  const maxAttempts = 5;
371
874
  let attempts = 0;
@@ -392,7 +895,7 @@ export class PerspectiveProxy {
392
895
  if(!await this.isSubjectInstance(base, subjectClass)) {
393
896
  throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`
394
897
  }
395
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
898
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
396
899
  let subject = new Subject(this, base, className)
397
900
  await subject.init()
398
901
  return subject as unknown as T
@@ -572,8 +1075,70 @@ export class PerspectiveProxy {
572
1075
  return this.#client.getNeighbourhoodProxy(this.#handle.uuid)
573
1076
  }
574
1077
 
1078
+ /**
1079
+ * Returns a proxy object for working with AI capabilities.
1080
+ *
1081
+ * @returns AIClient instance
1082
+ *
1083
+ * @example
1084
+ * ```typescript
1085
+ * // Use AI to analyze perspective content
1086
+ * const summary = await perspective.ai.summarize();
1087
+ *
1088
+ * // Generate new content
1089
+ * const suggestion = await perspective.ai.suggest("next action");
1090
+ * ```
1091
+ */
575
1092
  get ai(): AIClient {
576
1093
  return this.#client.aiClient
577
1094
  }
578
1095
 
1096
+ /**
1097
+ * Creates a subscription for a Prolog query that updates in real-time.
1098
+ *
1099
+ * This method:
1100
+ * 1. Creates the subscription on the Rust side
1101
+ * 2. Sets up the subscription callback
1102
+ * 3. Waits for the initial result to come through the subscription channel
1103
+ * 4. Returns a fully initialized QuerySubscriptionProxy
1104
+ *
1105
+ * The returned subscription is guaranteed to be ready to receive updates,
1106
+ * as this method waits for the initialization process to complete.
1107
+ *
1108
+ * @param query - Prolog query string
1109
+ * @returns Initialized QuerySubscriptionProxy instance
1110
+ *
1111
+ * @example
1112
+ * ```typescript
1113
+ * // Subscribe to active todos
1114
+ * const subscription = await perspective.subscribeInfer(`
1115
+ * instance(Todo, "Todo"),
1116
+ * property_getter("Todo", Todo, "state", "active")
1117
+ * `);
1118
+ *
1119
+ * // Subscription is already initialized here
1120
+ * console.log("Initial result:", subscription.result);
1121
+ *
1122
+ * // Set up callback for future updates
1123
+ * subscription.onResult((todos) => {
1124
+ * console.log("Active todos:", todos);
1125
+ * });
1126
+ * ```
1127
+ */
1128
+ async subscribeInfer(query: string): Promise<QuerySubscriptionProxy> {
1129
+ // Start the subscription on the Rust side first to get the real subscription ID
1130
+ const result = await this.#client.subscribeQuery(this.uuid, query);
1131
+ const subscriptionProxy = new QuerySubscriptionProxy(
1132
+ this.uuid,
1133
+ result.subscriptionId,
1134
+ result.result,
1135
+ this.#client
1136
+ );
1137
+
1138
+ // Wait for the initial result
1139
+ await subscriptionProxy.initialized;
1140
+
1141
+ return subscriptionProxy;
1142
+ }
1143
+
579
1144
  }