@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-3

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 (115) hide show
  1. package/lib/index.cjs +2377 -849
  2. package/lib/index.js +2354 -846
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +5 -1
  5. package/lib/src/agent/AgentClient.js +48 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/index.d.ts +0 -1
  8. package/lib/src/index.js +0 -1
  9. package/lib/src/language/Language.d.ts +26 -176
  10. package/lib/src/language/Language.js +28 -2
  11. package/lib/src/model/Ad4mModel.d.ts +52 -28
  12. package/lib/src/model/Ad4mModel.js +255 -118
  13. package/lib/src/model/Ad4mModel.test.js +1727 -537
  14. package/lib/src/model/ModelQueryBuilder.d.ts +67 -34
  15. package/lib/src/model/ModelQueryBuilder.js +208 -79
  16. package/lib/src/model/Subject.js +6 -6
  17. package/lib/src/model/decorators.d.ts +14 -8
  18. package/lib/src/model/decorators.js +41 -14
  19. package/lib/src/model/hydration-batch.d.ts +34 -0
  20. package/lib/src/model/hydration-batch.js +147 -0
  21. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  22. package/lib/src/model/hydration-batching.test.js +456 -0
  23. package/lib/src/model/hydration.d.ts +4 -3
  24. package/lib/src/model/hydration.js +365 -86
  25. package/lib/src/model/index.d.ts +4 -1
  26. package/lib/src/model/index.js +4 -1
  27. package/lib/src/model/json-schema.js +2 -2
  28. package/lib/src/model/query-cache.d.ts +30 -0
  29. package/lib/src/model/query-cache.js +66 -0
  30. package/lib/src/model/query-cache.test.d.ts +1 -0
  31. package/lib/src/model/query-cache.test.js +43 -0
  32. package/lib/src/model/query-common.d.ts +1 -1
  33. package/lib/src/model/query-common.js +1 -1
  34. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  35. package/lib/src/model/query-sparql-batch.js +260 -0
  36. package/lib/src/model/query-sparql.d.ts +124 -0
  37. package/lib/src/model/query-sparql.js +767 -0
  38. package/lib/src/model/query-sparql.test.d.ts +1 -0
  39. package/lib/src/model/query-sparql.test.js +495 -0
  40. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +12 -9
  41. package/lib/src/model/{surreal-utils.js → query-utils.js} +43 -27
  42. package/lib/src/model/relation-filtering.test.js +15 -15
  43. package/lib/src/model/sdna.js +1 -1
  44. package/lib/src/model/shacl-gen.js +42 -18
  45. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  46. package/lib/src/model/subscription-delta.test.js +180 -0
  47. package/lib/src/model/subscription-pool.d.ts +39 -0
  48. package/lib/src/model/subscription-pool.js +165 -0
  49. package/lib/src/model/types.d.ts +52 -4
  50. package/lib/src/model/types.js +1 -1
  51. package/lib/src/perspectives/PerspectiveClient.d.ts +3 -17
  52. package/lib/src/perspectives/PerspectiveClient.js +42 -66
  53. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  54. package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
  55. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -30
  56. package/lib/src/perspectives/PerspectiveProxy.js +239 -177
  57. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  58. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  59. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  60. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  61. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  62. package/lib/src/runtime/RuntimeResolver.js +56 -0
  63. package/lib/src/schema.gql +11 -1
  64. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  65. package/lib/src/shacl/SHACLFlow.js +9 -9
  66. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  67. package/lib/src/shacl/SHACLShape.js +38 -38
  68. package/lib/src/typeDefs.js +11 -1
  69. package/lib/src/utils.d.ts +6 -6
  70. package/lib/src/utils.js +6 -6
  71. package/package.json +1 -1
  72. package/src/Ad4mClient.test.ts +56 -1
  73. package/src/Literal.test.ts +10 -5
  74. package/src/Literal.ts +6 -5
  75. package/src/agent/AgentClient.ts +53 -1
  76. package/src/expression/ExpressionRef.ts +2 -2
  77. package/src/index.ts +0 -1
  78. package/src/language/Language.ts +55 -231
  79. package/src/model/Ad4mModel.test.ts +1709 -572
  80. package/src/model/Ad4mModel.ts +274 -120
  81. package/src/model/ModelQueryBuilder.ts +234 -87
  82. package/src/model/Subject.ts +6 -6
  83. package/src/model/decorators.ts +51 -22
  84. package/src/model/hydration-batch.ts +205 -0
  85. package/src/model/hydration-batching.test.ts +563 -0
  86. package/src/model/hydration.ts +349 -84
  87. package/src/model/index.ts +4 -1
  88. package/src/model/json-schema.ts +2 -2
  89. package/src/model/query-cache.test.ts +54 -0
  90. package/src/model/query-cache.ts +79 -0
  91. package/src/model/query-common.ts +1 -1
  92. package/src/model/query-sparql-batch.ts +301 -0
  93. package/src/model/query-sparql.test.ts +568 -0
  94. package/src/model/query-sparql.ts +820 -0
  95. package/src/model/{surreal-utils.ts → query-utils.ts} +44 -27
  96. package/src/model/relation-filtering.test.ts +15 -15
  97. package/src/model/sdna.ts +1 -1
  98. package/src/model/shacl-gen.ts +42 -17
  99. package/src/model/subscription-delta.test.ts +207 -0
  100. package/src/model/subscription-pool.ts +211 -0
  101. package/src/model/types.ts +53 -4
  102. package/src/perspectives/PerspectiveClient.test.ts +204 -0
  103. package/src/perspectives/PerspectiveClient.ts +41 -68
  104. package/src/perspectives/PerspectiveProxy.ts +244 -181
  105. package/src/perspectives/PerspectiveResolver.ts +0 -8
  106. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  107. package/src/runtime/RuntimeResolver.ts +43 -0
  108. package/src/shacl/SHACLFlow.ts +9 -9
  109. package/src/shacl/SHACLShape.ts +39 -39
  110. package/src/utils.ts +6 -6
  111. package/lib/src/model/query-surreal.d.ts +0 -44
  112. package/lib/src/model/query-surreal.js +0 -249
  113. package/src/language/LanguageContext.ts +0 -37
  114. package/src/model/query-surreal.ts +0 -280
  115. package/tsconfig-browser.json +0 -82
@@ -9,13 +9,13 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
12
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
13
13
  import { Link } from "../links/Links";
14
14
  import { LinkQuery } from "./LinkQuery";
15
15
  import { Literal } from "../Literal";
16
16
  import { Subject } from "../model/Subject";
17
17
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
18
- import { escapeSurrealString } from "../utils";
18
+ import { getCachedResult, setCachedResult, invalidatePerspectiveCache } from "../model/query-cache";
19
19
  import { SHACLShape } from "../shacl/SHACLShape";
20
20
  import { SHACLFlow } from "../shacl/SHACLFlow";
21
21
  /** Proxy object for a subscribed Prolog query that provides real-time updates
@@ -72,7 +72,6 @@ export class QuerySubscriptionProxy {
72
72
  _QuerySubscriptionProxy_initReject.set(this, void 0);
73
73
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
74
74
  _QuerySubscriptionProxy_query.set(this, void 0);
75
- this.isSurrealDB = false;
76
75
  __classPrivateFieldSet(this, _QuerySubscriptionProxy_uuid, uuid, "f");
77
76
  __classPrivateFieldSet(this, _QuerySubscriptionProxy_query, query, "f");
78
77
  __classPrivateFieldSet(this, _QuerySubscriptionProxy_client, client, "f");
@@ -103,12 +102,7 @@ export class QuerySubscriptionProxy {
103
102
  try {
104
103
  // Initialize the query subscription
105
104
  let initialResult;
106
- if (this.isSurrealDB) {
107
- initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
108
- }
109
- else {
110
- initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
111
- }
105
+ initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
112
106
  __classPrivateFieldSet(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
113
107
  // Process the initial result immediately for fast UX
114
108
  if (initialResult.result) {
@@ -161,12 +155,7 @@ export class QuerySubscriptionProxy {
161
155
  if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f"))
162
156
  return;
163
157
  try {
164
- if (this.isSurrealDB) {
165
- await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
166
- }
167
- else {
168
- await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
169
- }
158
+ await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
170
159
  }
171
160
  catch (e) {
172
161
  console.error('Error in keepalive:', e);
@@ -273,14 +262,8 @@ export class QuerySubscriptionProxy {
273
262
  }
274
263
  // Tell the backend to dispose of the subscription
275
264
  if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
276
- if (this.isSurrealDB) {
277
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"))
278
- .catch(e => console.error('Error disposing surreal query subscription:', e));
279
- }
280
- else {
281
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"))
282
- .catch(e => console.error('Error disposing query subscription:', e));
283
- }
265
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"))
266
+ .catch(e => console.error('Error disposing query subscription:', e));
284
267
  }
285
268
  }
286
269
  }
@@ -345,6 +328,12 @@ export class PerspectiveProxy {
345
328
  _PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);
346
329
  _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
347
330
  _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
331
+ _PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()
332
+ /**
333
+ * Creates a new PerspectiveProxy instance.
334
+ * Note: Don't create this directly, use ad4m.perspective.add() instead.
335
+ */
336
+ );
348
337
  __classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
349
338
  __classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
350
339
  __classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
@@ -362,6 +351,21 @@ export class PerspectiveProxy {
362
351
  __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
363
352
  __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
364
353
  }
354
+ /** Update the proxy's internal handle and public fields in-place.
355
+ * Keeps the same object reference so all holders see the update. */
356
+ updateHandle(handle) {
357
+ if (handle.uuid !== __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid) {
358
+ throw new Error(`PerspectiveProxy.updateHandle: UUID mismatch — proxy is bound to "${__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid}" but received handle with UUID "${handle.uuid}". ` +
359
+ `This would silently diverge from listeners registered under the original UUID.`);
360
+ }
361
+ __classPrivateFieldSet(this, _PerspectiveProxy_handle, handle, "f");
362
+ this.uuid = handle.uuid;
363
+ this.name = handle.name;
364
+ this.owners = handle.owners;
365
+ this.sharedUrl = handle.sharedUrl;
366
+ this.neighbourhood = handle.neighbourhood;
367
+ this.state = handle.state;
368
+ }
365
369
  /**
366
370
  * Escapes special regex characters in a string to prevent ReDoS attacks
367
371
  * and regex injection when building dynamic regular expressions.
@@ -435,7 +439,9 @@ export class PerspectiveProxy {
435
439
  * @param batchId - Optional batch ID to group this operation with others
436
440
  */
437
441
  async executeAction(actions, expression, parameters, batchId) {
438
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
442
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
443
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
444
+ return result;
439
445
  }
440
446
  /**
441
447
  * Retrieves links from the perspective that match the given query.
@@ -488,34 +494,28 @@ export class PerspectiveProxy {
488
494
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
489
495
  }
490
496
  /**
491
- * Executes a SurrealQL query against the perspective's link cache.
492
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
497
+ * Executes a SPARQL query against the perspective's link cache.
498
+ * This allows powerful SQL-like queries on the link data stored in SPARQL.
493
499
  *
494
500
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
495
501
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
496
502
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
497
503
  *
498
- * @param query - SurrealQL query string (read-only operations only)
504
+ * @param query - SPARQL query string (read-only operations only)
499
505
  * @returns Query results as parsed JSON
500
506
  *
501
- * @example
502
- * ```typescript
503
- * // Get all links
504
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
505
- *
506
- * // Filter links by predicate
507
- * const follows = await perspective.querySurrealDB(
508
- * "SELECT * FROM link WHERE predicate = 'follows'"
509
- * );
510
- *
511
- * // Complex aggregation query
512
- * const stats = await perspective.querySurrealDB(
513
- * "SELECT predicate, count() as total FROM link GROUP BY predicate"
514
- * );
515
- * ```
507
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
508
+ *
509
+ * @param query - SPARQL query string
510
+ * @returns Query results as parsed JSON
516
511
  */
517
- async querySurrealDB(query) {
518
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
512
+ async querySparql(query) {
513
+ const cached = getCachedResult(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
514
+ if (cached !== undefined)
515
+ return cached;
516
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
517
+ setCachedResult(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query, result);
518
+ return result;
519
519
  }
520
520
  /**
521
521
  * Adds a new link to the perspective.
@@ -543,7 +543,9 @@ export class PerspectiveProxy {
543
543
  * ```
544
544
  */
545
545
  async add(link, status = 'shared', batchId) {
546
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
546
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
547
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
548
+ return result;
547
549
  }
548
550
  /**
549
551
  * Adds multiple links to the perspective in a single operation.
@@ -555,7 +557,9 @@ export class PerspectiveProxy {
555
557
  * @returns Array of created LinkExpressions
556
558
  */
557
559
  async addLinks(links, status = 'shared', batchId) {
558
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
560
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
561
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
562
+ return result;
559
563
  }
560
564
  /**
561
565
  * Removes multiple links from the perspective.
@@ -565,7 +569,9 @@ export class PerspectiveProxy {
565
569
  * @returns Array of removed LinkExpressions
566
570
  */
567
571
  async removeLinks(links, batchId) {
568
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
572
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
573
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
574
+ return result;
569
575
  }
570
576
  /**
571
577
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -576,7 +582,9 @@ export class PerspectiveProxy {
576
582
  * @returns Object containing results of the mutations
577
583
  */
578
584
  async linkMutations(mutations, status = 'shared') {
579
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
585
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
586
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
587
+ return result;
580
588
  }
581
589
  /**
582
590
  * Adds a pre-signed LinkExpression to the perspective.
@@ -597,7 +605,9 @@ export class PerspectiveProxy {
597
605
  * @param batchId - Optional batch ID to group this operation with others
598
606
  */
599
607
  async update(oldLink, newLink, batchId) {
600
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
608
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
609
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
610
+ return result;
601
611
  }
602
612
  /**
603
613
  * Removes a link from the perspective.
@@ -606,7 +616,9 @@ export class PerspectiveProxy {
606
616
  * @param batchId - Optional batch ID to group this operation with others
607
617
  */
608
618
  async remove(link, batchId) {
609
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
619
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
620
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
621
+ return result;
610
622
  }
611
623
  /** Creates a new batch for grouping operations */
612
624
  async createBatch() {
@@ -614,7 +626,9 @@ export class PerspectiveProxy {
614
626
  }
615
627
  /** Commits a batch of operations */
616
628
  async commitBatch(batchId) {
617
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
629
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
630
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
631
+ return result;
618
632
  }
619
633
  /**
620
634
  * Retrieves and renders an Expression referenced in this perspective.
@@ -989,6 +1003,13 @@ export class PerspectiveProxy {
989
1003
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
990
1004
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
991
1005
  }
1006
+ /**
1007
+ * Adds a subject class to the perspective.
1008
+ * Alias for addSdna() with sdnaType='subject_class'.
1009
+ */
1010
+ async addSubjectClass(name, shaclJson) {
1011
+ return this.addSdna(name, '', 'subject_class', shaclJson);
1012
+ }
992
1013
  /**
993
1014
  * **Recommended way to add SDNA schemas.**
994
1015
  *
@@ -1020,7 +1041,7 @@ export class PerspectiveProxy {
1020
1041
  // Serialize shape to links
1021
1042
  const shapeLinks = shape.toLinks();
1022
1043
  // Create name -> shape mapping links
1023
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1044
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1024
1045
  const allLinks = [
1025
1046
  ...shapeLinks.map(l => new Link({
1026
1047
  source: l.source,
@@ -1046,7 +1067,7 @@ export class PerspectiveProxy {
1046
1067
  */
1047
1068
  async getShacl(name) {
1048
1069
  // Find the shape URI from the name mapping
1049
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1070
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1050
1071
  const shapeUriLinks = await this.get(new LinkQuery({
1051
1072
  source: nameMapping.toUrl(),
1052
1073
  predicate: "ad4m://shacl_shape_uri"
@@ -1055,22 +1076,25 @@ export class PerspectiveProxy {
1055
1076
  return null;
1056
1077
  }
1057
1078
  const shapeUri = shapeUriLinks[0].data.target;
1058
- const escapedShapeUri = escapeSurrealString(shapeUri);
1059
1079
  // First get property shape URIs so we can query everything in one go
1060
1080
  const propertyLinks = await this.get(new LinkQuery({
1061
1081
  source: shapeUri,
1062
1082
  predicate: "sh://property"
1063
1083
  }));
1064
- // Build a single surreal query that fetches all relevant links
1084
+ // Fetch all links from the shape and its property shapes
1065
1085
  const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
1066
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
1067
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
1068
- const result = await this.querySurrealDB(query);
1069
- const shapeLinks = (result || []).map((r) => ({
1070
- source: r.source,
1071
- predicate: r.predicate,
1072
- target: r.target
1073
- }));
1086
+ const allLinks = [];
1087
+ for (const uri of sourceUris) {
1088
+ const links = await this.get(new LinkQuery({ source: uri }));
1089
+ for (const l of links) {
1090
+ allLinks.push({
1091
+ source: l.data.source,
1092
+ predicate: l.data.predicate,
1093
+ target: l.data.target
1094
+ });
1095
+ }
1096
+ }
1097
+ const shapeLinks = allLinks;
1074
1098
  return SHACLShape.fromLinks(shapeLinks, shapeUri);
1075
1099
  }
1076
1100
  /**
@@ -1172,19 +1196,20 @@ export class PerspectiveProxy {
1172
1196
  return null;
1173
1197
  }
1174
1198
  const flowUri = flowUriLinks[0].data.target;
1175
- const escapedFlowUri = escapeSurrealString(flowUri);
1176
1199
  // Compute alternate prefix for state/transition URIs
1177
1200
  const alternatePrefix = flowUri.endsWith('Flow')
1178
1201
  ? flowUri.slice(0, -4) + '.'
1179
1202
  : flowUri + '.';
1180
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
1181
- // Single surreal query to get all flow-related links
1182
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri = '${escapedFlowUri}' OR string::starts_with(in.uri, '${escapedAltPrefix}')`;
1183
- const result = await this.querySurrealDB(query);
1184
- const flowLinks = (result || []).map((r) => ({
1185
- source: r.source,
1186
- predicate: r.predicate,
1187
- target: r.target
1203
+ // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
1204
+ const sparqlQuery = `SELECT ?s ?p ?o WHERE {
1205
+ ?s ?p ?o .
1206
+ FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
1207
+ }`;
1208
+ const sparqlResult = await this.querySparql(sparqlQuery);
1209
+ const flowLinks = (sparqlResult || []).map((r) => ({
1210
+ source: r.s,
1211
+ predicate: r.p,
1212
+ target: r.o
1188
1213
  }));
1189
1214
  return SHACLFlow.fromLinks(flowLinks, flowUri);
1190
1215
  }
@@ -1293,8 +1318,8 @@ export class PerspectiveProxy {
1293
1318
  const links = await this.get(new LinkQuery({ predicate }));
1294
1319
  for (const link of links) {
1295
1320
  if (shapePattern.test(link.data.source)) {
1296
- // Parse actions from literal://string:{json}
1297
- const prefix = "literal://string:";
1321
+ // Parse actions from literal:string:{json}
1322
+ const prefix = "literal:string:";
1298
1323
  if (link.data.target.startsWith(prefix)) {
1299
1324
  const jsonStr = link.data.target.slice(prefix.length);
1300
1325
  // Decode URL-encoded JSON if needed, with fallback for raw % characters
@@ -1350,35 +1375,20 @@ export class PerspectiveProxy {
1350
1375
  }
1351
1376
  // If no required triples, any expression with links is an instance
1352
1377
  if (metadata.requiredTriples.length === 0) {
1353
- const escapedExpression = escapeSurrealString(expression);
1354
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
1355
- const result = await this.querySurrealDB(checkQuery);
1356
- const count = result[0]?.count ?? 0;
1357
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1358
- return countValue > 0;
1378
+ const links = await this.get(new LinkQuery({ source: expression }));
1379
+ return links.length > 0;
1359
1380
  }
1360
1381
  // Check if the expression has all required triples (predicate + optional exact target)
1361
1382
  for (const triple of metadata.requiredTriples) {
1362
- const escapedExpression = escapeSurrealString(expression);
1363
- const escapedPredicate = escapeSurrealString(triple.predicate);
1364
- let checkQuery;
1383
+ let query;
1365
1384
  if (triple.target) {
1366
- // Flag: must match both predicate AND exact target value
1367
- const escapedTarget = escapeSurrealString(triple.target);
1368
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1385
+ query = new LinkQuery({ source: expression, predicate: triple.predicate, target: triple.target });
1369
1386
  }
1370
1387
  else {
1371
- // Property: just check predicate exists
1372
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
1388
+ query = new LinkQuery({ source: expression, predicate: triple.predicate });
1373
1389
  }
1374
- const result = await this.querySurrealDB(checkQuery);
1375
- if (!result || result.length === 0) {
1376
- return false;
1377
- }
1378
- const count = result[0]?.count ?? 0;
1379
- // Handle potential object response like {Int: 0}
1380
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1381
- if (countValue === 0) {
1390
+ const links = await this.get(query);
1391
+ if (!links || links.length === 0) {
1382
1392
  return false;
1383
1393
  }
1384
1394
  }
@@ -1406,6 +1416,10 @@ export class PerspectiveProxy {
1406
1416
  * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
1407
1417
  * Retrieves the SHACL shape and extracts metadata for instance queries.
1408
1418
  */
1419
+ async getSubjectClassMetadata(className) {
1420
+ return this.getSubjectClassMetadataFromSDNA(className);
1421
+ }
1422
+ /** @deprecated Use getSubjectClassMetadata() */
1409
1423
  async getSubjectClassMetadataFromSDNA(className) {
1410
1424
  try {
1411
1425
  // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
@@ -1460,33 +1474,55 @@ export class PerspectiveProxy {
1460
1474
  }
1461
1475
  }
1462
1476
  /**
1463
- * Generates a SurrealDB query to find instances based on class metadata.
1477
+ * Generates a SPARQL query to find instances based on class metadata.
1478
+ */
1479
+ /**
1480
+ * Finds all instances matching subject class metadata by querying links.
1481
+ * Returns base URIs of matching instances.
1464
1482
  */
1465
- generateSurrealInstanceQuery(metadata) {
1483
+ async findInstancesByMetadata(metadata) {
1466
1484
  if (metadata.requiredTriples.length === 0) {
1467
- // No required triples - any node with links is an instance
1468
- return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
1485
+ // No required triples - return all unique sources that have any link
1486
+ const allLinks = await this.get(new LinkQuery({}));
1487
+ const sources = new Set(allLinks.map(l => l.data.source));
1488
+ return Array.from(sources).map(s => ({ base: s }));
1469
1489
  }
1470
- // Generate WHERE conditions for each required triple (predicate + optional exact target)
1471
- const whereConditions = metadata.requiredTriples.map(triple => {
1472
- const escapedPredicate = escapeSurrealString(triple.predicate);
1473
- if (triple.target) {
1474
- // Flag: must match both predicate AND exact target value
1475
- const escapedTarget = escapeSurrealString(triple.target);
1476
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
1477
- }
1478
- else {
1479
- // Property: just check predicate exists
1480
- return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
1490
+ // Use first required triple to get candidate set, then filter by rest
1491
+ const first = metadata.requiredTriples[0];
1492
+ let query;
1493
+ if (first.target) {
1494
+ query = new LinkQuery({ predicate: first.predicate, target: first.target });
1495
+ }
1496
+ else {
1497
+ query = new LinkQuery({ predicate: first.predicate });
1498
+ }
1499
+ const candidateLinks = await this.get(query);
1500
+ let candidates = [...new Set(candidateLinks.map(l => l.data.source))];
1501
+ // Filter by remaining required triples
1502
+ for (let i = 1; i < metadata.requiredTriples.length; i++) {
1503
+ const triple = metadata.requiredTriples[i];
1504
+ const remaining = [];
1505
+ for (const expr of candidates) {
1506
+ let q;
1507
+ if (triple.target) {
1508
+ q = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
1509
+ }
1510
+ else {
1511
+ q = new LinkQuery({ source: expr, predicate: triple.predicate });
1512
+ }
1513
+ const links = await this.get(q);
1514
+ if (links.length > 0)
1515
+ remaining.push(expr);
1481
1516
  }
1482
- }).join(' AND ');
1483
- return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
1517
+ candidates = remaining;
1518
+ }
1519
+ return candidates.map(c => ({ base: c }));
1484
1520
  }
1485
1521
  /**
1486
- * Gets a property value using SurrealDB when Prolog fails.
1522
+ * Gets a property value using SPARQL when Prolog fails.
1487
1523
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1488
1524
  */
1489
- async getPropertyValueViaSurreal(baseExpression, className, propertyName) {
1525
+ async getPropertyValueViaSparql(baseExpression, className, propertyName) {
1490
1526
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1491
1527
  if (!metadata) {
1492
1528
  return undefined;
@@ -1495,14 +1531,11 @@ export class PerspectiveProxy {
1495
1531
  if (!propMeta) {
1496
1532
  return undefined;
1497
1533
  }
1498
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1499
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1500
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
1501
- const result = await this.querySurrealDB(query);
1502
- if (!result || result.length === 0) {
1534
+ const links = await this.get(new LinkQuery({ source: baseExpression, predicate: propMeta.predicate }));
1535
+ if (!links || links.length === 0) {
1503
1536
  return undefined;
1504
1537
  }
1505
- const value = result[0].value;
1538
+ const value = links[0].data.target;
1506
1539
  // Handle expression resolution if needed
1507
1540
  if (propMeta.resolveLanguage && value) {
1508
1541
  try {
@@ -1521,11 +1554,11 @@ export class PerspectiveProxy {
1521
1554
  return value;
1522
1555
  }
1523
1556
  /**
1524
- * Gets relation values using SurrealDB when Prolog fails.
1557
+ * Gets relation values using SPARQL when Prolog fails.
1525
1558
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1526
1559
  * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
1527
1560
  */
1528
- async getRelationValuesViaSurreal(baseExpression, className, relationName) {
1561
+ async getRelationValuesViaSparql(baseExpression, className, relationName) {
1529
1562
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1530
1563
  if (!metadata) {
1531
1564
  return [];
@@ -1534,14 +1567,13 @@ export class PerspectiveProxy {
1534
1567
  if (!relMeta) {
1535
1568
  return [];
1536
1569
  }
1537
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1538
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1539
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
1540
- const result = await this.querySurrealDB(query);
1541
- if (!result || result.length === 0) {
1570
+ const links = await this.get(new LinkQuery({ source: baseExpression, predicate: relMeta.predicate }));
1571
+ if (!links || links.length === 0) {
1542
1572
  return [];
1543
1573
  }
1544
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1574
+ // Sort by timestamp ascending
1575
+ links.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
1576
+ let values = links.map(l => l.data.target).filter(v => v !== "" && v !== '');
1545
1577
  // Apply condition filtering if present
1546
1578
  if (relMeta.condition && values.length > 0) {
1547
1579
  try {
@@ -1551,13 +1583,28 @@ export class PerspectiveProxy {
1551
1583
  .replace(/\$perspective/g, `'${this.uuid}'`)
1552
1584
  .replace(/\$base/g, `'${baseExpression}'`)
1553
1585
  .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
1554
- // If condition starts with WHERE, wrap in array length check
1555
- if (condition.trim().startsWith('WHERE')) {
1556
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
1586
+ // Parse condition to extract link query parameters
1587
+ // Conditions typically look like: WHERE in.uri = 'X' AND predicate = 'Y' AND out.uri = 'Z'
1588
+ // or: array::len(SELECT * FROM link WHERE ...) > 0
1589
+ // Convert to queryLinks calls
1590
+ const sourceMatch = condition.match(/in\.uri\s*=\s*'([^']+)'/);
1591
+ const predicateMatch = condition.match(/predicate\s*=\s*'([^']+)'/);
1592
+ const targetMatch = condition.match(/out\.uri\s*=\s*'([^']+)'/);
1593
+ if (sourceMatch || predicateMatch || targetMatch) {
1594
+ const linkQuery = {};
1595
+ if (sourceMatch)
1596
+ linkQuery.source = sourceMatch[1];
1597
+ if (predicateMatch)
1598
+ linkQuery.predicate = predicateMatch[1];
1599
+ if (targetMatch)
1600
+ linkQuery.target = targetMatch[1];
1601
+ const matchingLinks = await this.get(new LinkQuery(linkQuery));
1602
+ if (matchingLinks.length > 0) {
1603
+ filteredValues.push(value);
1604
+ }
1557
1605
  }
1558
- const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
1559
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
1560
- if (isTrue) {
1606
+ else {
1607
+ // Can't parse condition, include by default
1561
1608
  filteredValues.push(value);
1562
1609
  }
1563
1610
  }
@@ -1585,7 +1632,7 @@ export class PerspectiveProxy {
1585
1632
  return values;
1586
1633
  }
1587
1634
  /**
1588
- * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
1635
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SPARQL queries.
1589
1636
  * This avoids N+1 query problems by checking all values at once.
1590
1637
  */
1591
1638
  async batchCheckSubjectInstances(expressions, metadata) {
@@ -1594,30 +1641,31 @@ export class PerspectiveProxy {
1594
1641
  }
1595
1642
  // If no required triples, check which expressions have any links
1596
1643
  if (metadata.requiredTriples.length === 0) {
1597
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1598
- const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
1599
- const result = await this.querySurrealDB(checkQuery);
1600
- return result.map(r => r.uri);
1644
+ const results = [];
1645
+ for (const expr of expressions) {
1646
+ const links = await this.get(new LinkQuery({ source: expr }));
1647
+ if (links.length > 0)
1648
+ results.push(expr);
1649
+ }
1650
+ return results;
1601
1651
  }
1602
- // For each required triple, build a query that finds matching expressions
1652
+ // For each required triple, find which expressions match
1603
1653
  const validExpressionSets = [];
1604
1654
  for (const triple of metadata.requiredTriples) {
1605
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1606
- const escapedPredicate = escapeSurrealString(triple.predicate);
1607
- let checkQuery;
1608
- if (triple.target) {
1609
- // Flag: must match both predicate AND exact target value
1610
- const escapedTarget = escapeSurrealString(triple.target);
1611
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1612
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1613
- }
1614
- else {
1615
- // Property: just check predicate exists
1616
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1617
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
1655
+ const matchingExprs = new Set();
1656
+ for (const expr of expressions) {
1657
+ let query;
1658
+ if (triple.target) {
1659
+ query = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
1660
+ }
1661
+ else {
1662
+ query = new LinkQuery({ source: expr, predicate: triple.predicate });
1663
+ }
1664
+ const links = await this.get(query);
1665
+ if (links.length > 0)
1666
+ matchingExprs.add(expr);
1618
1667
  }
1619
- const result = await this.querySurrealDB(checkQuery);
1620
- validExpressionSets.push(new Set(result.map(r => r.uri)));
1668
+ validExpressionSets.push(matchingExprs);
1621
1669
  }
1622
1670
  // Find intersection: expressions that passed ALL required triple checks
1623
1671
  if (validExpressionSets.length === 0) {
@@ -1670,13 +1718,12 @@ export class PerspectiveProxy {
1670
1718
  let instances = [];
1671
1719
  for (let className of classes) {
1672
1720
  //console.log(`getAllSubjectInstances: Processing class ${className}`);
1673
- // Query SDNA for metadata, then query SurrealDB for instances
1721
+ // Query SDNA for metadata, then query SPARQL for instances
1674
1722
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1675
1723
  //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
1676
1724
  if (metadata) {
1677
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1678
- const results = await this.querySurrealDB(surrealQuery);
1679
- // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
1725
+ const results = await this.findInstancesByMetadata(metadata);
1726
+ // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);
1680
1727
  for (const result of results || []) {
1681
1728
  //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
1682
1729
  try {
@@ -1723,11 +1770,10 @@ export class PerspectiveProxy {
1723
1770
  }
1724
1771
  let instances = [];
1725
1772
  for (let className of classes) {
1726
- // Query SDNA for metadata, then query SurrealDB for instances
1773
+ // Query SDNA for metadata, then query SPARQL for instances
1727
1774
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1728
1775
  if (metadata) {
1729
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1730
- const results = await this.querySurrealDB(surrealQuery);
1776
+ const results = await this.findInstancesByMetadata(metadata);
1731
1777
  for (const result of results || []) {
1732
1778
  try {
1733
1779
  let subject = new Subject(this, result.base, className);
@@ -1772,15 +1818,16 @@ export class PerspectiveProxy {
1772
1818
  if (properties.length === 0 && relations.length === 0) {
1773
1819
  return null;
1774
1820
  }
1775
- // Single SurrealDB query to find all classes and their properties/relations
1776
- const query = `SELECT
1777
- in.uri AS shape_source,
1778
- predicate,
1779
- out.uri AS target
1780
- FROM link
1781
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
1782
- const results = await this.querySurrealDB(query);
1783
- if (!results || results.length === 0)
1821
+ // Query links for class shapes using queryLinks
1822
+ const typeLinks = await this.get(new LinkQuery({ predicate: 'rdf://type', target: 'ad4m://SubjectClass' }));
1823
+ const propLinks = await this.get(new LinkQuery({ predicate: 'sh://property' }));
1824
+ const collLinks = await this.get(new LinkQuery({ predicate: 'sh://collection' }));
1825
+ const results = [
1826
+ ...typeLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
1827
+ ...propLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
1828
+ ...collLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
1829
+ ];
1830
+ if (results.length === 0)
1784
1831
  return null;
1785
1832
  // Build a map of className -> { properties, relations }
1786
1833
  const classShapes = new Map();
@@ -1878,8 +1925,15 @@ export class PerspectiveProxy {
1878
1925
  * static generateSDNA() function and adds it to the perspective's SDNA.
1879
1926
  */
1880
1927
  async ensureSDNASubjectClass(jsClass) {
1928
+ return this.ensureSubjectClass(jsClass);
1929
+ }
1930
+ /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
1931
+ async ensureSubjectClass(jsClass) {
1881
1932
  // Get the class name from the JS class
1882
1933
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
1934
+ // Skip if already registered for this perspective instance
1935
+ if (__classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
1936
+ return;
1883
1937
  // Note: Duplicate checking is handled on the Rust side in add_sdna
1884
1938
  // Generate SHACL SDNA (Prolog-free)
1885
1939
  if (!jsClass.generateSHACL) {
@@ -1892,6 +1946,14 @@ export class PerspectiveProxy {
1892
1946
  // Pass SHACL JSON to backend (Prolog-free)
1893
1947
  // Backend stores SHACL links directly
1894
1948
  await this.addSdna(className, '', 'subject_class', shaclJson);
1949
+ // Mark as registered for this perspective instance
1950
+ __classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(className);
1951
+ }
1952
+ /** Clear the per-instance ensured subject class cache.
1953
+ * Call this after wiping a perspective's links so that
1954
+ * subsequent register() calls re-add SHACL definitions. */
1955
+ clearEnsuredSubjectClasses() {
1956
+ __classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").clear();
1895
1957
  }
1896
1958
  getNeighbourhoodProxy() {
1897
1959
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
@@ -1961,7 +2023,7 @@ export class PerspectiveProxy {
1961
2023
  return subscriptionProxy;
1962
2024
  }
1963
2025
  /**
1964
- * Creates a subscription for a SurrealQL query that updates in real-time.
2026
+ * Creates a subscription for a SPARQL query that updates in real-time.
1965
2027
  *
1966
2028
  * This method:
1967
2029
  * 1. Creates the subscription on the Rust side
@@ -1976,12 +2038,12 @@ export class PerspectiveProxy {
1976
2038
  * when dispose() is called. Make sure to call dispose() when you're done to
1977
2039
  * prevent memory leaks and ensure proper cleanup of resources.
1978
2040
  *
1979
- * @param query - SurrealQL query string
2041
+ /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
2042
+ * @param query - Query string
1980
2043
  * @returns Initialized QuerySubscriptionProxy instance
1981
2044
  */
1982
- async subscribeSurrealDB(query) {
2045
+ async subscribeQuery(query) {
1983
2046
  const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
1984
- subscriptionProxy.isSurrealDB = true;
1985
2047
  // Start the subscription on the Rust side first to get the real subscription ID
1986
2048
  await subscriptionProxy.subscribe();
1987
2049
  // Wait for the initial result
@@ -1989,4 +2051,4 @@ export class PerspectiveProxy {
1989
2051
  return subscriptionProxy;
1990
2052
  }
1991
2053
  }
1992
- _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
2054
+ _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();