@coasys/ad4m 0.12.0-rc1-dev.1 → 0.12.0-rc1-dev.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 (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6046
  3. package/lib/index.js +5977 -6040
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2799
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3249
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -1,22 +1,8 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
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;
13
- import { Link } from "../links/Links";
14
1
  import { LinkQuery } from "./LinkQuery";
15
2
  import { Literal } from "../Literal";
16
- import { Subject } from "../model/Subject";
3
+ import { collectionAdderToName, collectionRemoverToName, collectionSetterToName, collectionToAdderName, collectionToRemoverName, collectionToSetterName, propertyNameToSetterName, } from "../model/util";
4
+ import { getPropertiesMetadata, getRelationsMetadata, } from "../model/decorators";
17
5
  import { escapeSurrealString } from "../utils";
18
- import { SHACLShape } from "../shacl/SHACLShape";
19
- import { SHACLFlow } from "../shacl/SHACLFlow";
20
6
  /** Proxy object for a subscribed Prolog query that provides real-time updates
21
7
  *
22
8
  * This class handles:
@@ -57,137 +43,116 @@ export class QuerySubscriptionProxy {
57
43
  * @param client - The PerspectiveClient instance to use for communication
58
44
  */
59
45
  constructor(uuid, query, client) {
60
- _QuerySubscriptionProxy_instances.add(this);
61
- _QuerySubscriptionProxy_uuid.set(this, void 0);
62
- _QuerySubscriptionProxy_subscriptionId.set(this, void 0);
63
- _QuerySubscriptionProxy_client.set(this, void 0);
64
- _QuerySubscriptionProxy_callbacks.set(this, void 0);
65
- _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
66
- _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
67
- _QuerySubscriptionProxy_latestResult.set(this, void 0);
68
- _QuerySubscriptionProxy_disposed.set(this, false);
69
- _QuerySubscriptionProxy_initialized.set(this, void 0);
70
- _QuerySubscriptionProxy_initResolve.set(this, void 0);
71
- _QuerySubscriptionProxy_initReject.set(this, void 0);
72
- _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
73
- _QuerySubscriptionProxy_query.set(this, void 0);
74
- this.isSurrealDB = false;
75
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_uuid, uuid, "f");
76
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_query, query, "f");
77
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_client, client, "f");
78
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
79
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, null, "f");
46
+ this._disposed = false;
47
+ // Prevent Vue / Proxy-based reactivity systems from wrapping this instance.
48
+ // QuerySubscriptionProxy manages its own internal state via #private fields
49
+ // and callbacks; wrapping it in a Proxy breaks WeakMap-based private field access.
50
+ this._uuid = uuid;
51
+ this._query = query;
52
+ this._client = client;
53
+ this._callbacks = new Set();
54
+ this._latestResult = null;
80
55
  // Create the promise once and store its resolve/reject
81
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
82
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
83
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, reject, "f");
84
- }), "f");
56
+ this._initialized = new Promise((resolve, reject) => {
57
+ this._initResolve = resolve;
58
+ this._initReject = reject;
59
+ });
85
60
  }
86
61
  async subscribe() {
87
62
  // Clean up previous subscription attempt if retrying
88
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
89
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
90
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, undefined, "f");
63
+ if (this._unsubscribe) {
64
+ this._unsubscribe();
65
+ this._unsubscribe = undefined;
91
66
  }
92
67
  // Clear any existing timeout
93
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
94
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
95
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
68
+ if (this._initTimeoutId) {
69
+ clearTimeout(this._initTimeoutId);
70
+ this._initTimeoutId = undefined;
96
71
  }
97
72
  // Clear any existing keepalive timer to prevent accumulation
98
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f")) {
99
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
100
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, "f");
73
+ if (this._keepaliveTimer) {
74
+ clearTimeout(this._keepaliveTimer);
75
+ this._keepaliveTimer = undefined;
101
76
  }
102
77
  try {
103
78
  // Initialize the query subscription
104
79
  let initialResult;
105
- if (this.isSurrealDB) {
106
- initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
107
- }
108
- else {
109
- initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
110
- }
111
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
80
+ initialResult = await this._client.subscribeQuery(this._uuid, this._query);
81
+ this._subscriptionId = initialResult.subscriptionId;
112
82
  // Process the initial result immediately for fast UX
113
83
  if (initialResult.result) {
114
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
115
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
84
+ this._latestResult = initialResult.result;
85
+ this._notifyCallbacks(initialResult.result);
116
86
  }
117
87
  else {
118
- console.warn('⚠️ No initial result returned from subscribeQuery!');
88
+ console.warn("⚠️ No initial result returned from subscribeQuery!");
119
89
  }
120
90
  // Set up timeout for retry
121
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
122
- console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
91
+ this._initTimeoutId = setTimeout(() => {
92
+ console.error("Subscription initialization timed out after 30 seconds. Resubscribing...");
123
93
  // Recursively retry subscription, catching any errors
124
- this.subscribe().catch(error => {
125
- console.error('Error during subscription retry after timeout:', error);
94
+ this.subscribe().catch((error) => {
95
+ console.error("Error during subscription retry after timeout:", error);
126
96
  });
127
- }, 30000), "f");
97
+ }, 30000);
128
98
  // Subscribe to query updates
129
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
99
+ this._unsubscribe = this._client.subscribeToQueryUpdates(this._subscriptionId, (updateResult) => {
130
100
  // Clear timeout on first message
131
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
132
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
133
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
101
+ if (this._initTimeoutId) {
102
+ clearTimeout(this._initTimeoutId);
103
+ this._initTimeoutId = undefined;
134
104
  }
135
105
  // Resolve the initialization promise (only resolves once)
136
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initResolve, "f")) {
137
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
138
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
139
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f");
106
+ if (this._initResolve) {
107
+ this._initResolve(true);
108
+ this._initResolve = undefined; // Prevent double-resolve
109
+ this._initReject = undefined;
140
110
  }
141
111
  // Skip duplicate init messages
142
- if (updateResult.isInit && __classPrivateFieldGet(this, _QuerySubscriptionProxy_latestResult, "f"))
112
+ if (updateResult.isInit && this._latestResult)
143
113
  return;
144
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
145
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
146
- }), "f");
114
+ this._latestResult = updateResult;
115
+ this._notifyCallbacks(updateResult);
116
+ });
147
117
  }
148
118
  catch (error) {
149
- console.error('Error setting up subscription:', error);
119
+ console.error("Error setting up subscription:", error);
150
120
  // Reject the promise if this is the first attempt
151
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initReject, "f")) {
152
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_initReject, "f").call(this, error);
153
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
154
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f");
121
+ if (this._initReject) {
122
+ this._initReject(error);
123
+ this._initResolve = undefined;
124
+ this._initReject = undefined;
155
125
  }
156
126
  throw error; // Re-throw so caller knows it failed
157
127
  }
158
128
  // Start keepalive loop using platform-agnostic setTimeout
159
129
  const keepaliveLoop = async () => {
160
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f"))
130
+ if (this._disposed)
161
131
  return;
162
132
  try {
163
- if (this.isSurrealDB) {
164
- await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
165
- }
166
- else {
167
- await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
168
- }
133
+ await this._client.keepAliveQuery(this._uuid, this._subscriptionId);
169
134
  }
170
135
  catch (e) {
171
- console.error('Error in keepalive:', e);
136
+ console.error("Error in keepalive:", e);
172
137
  // try to reinitialize the subscription
173
- console.log('Reinitializing subscription for query:', __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
138
+ console.log("Reinitializing subscription for query:", this._query);
174
139
  try {
175
140
  await this.subscribe();
176
- console.log('Subscription reinitialized');
141
+ console.log("Subscription reinitialized");
177
142
  }
178
143
  catch (resubscribeError) {
179
- console.error('Error during resubscription from keepalive:', resubscribeError);
144
+ console.error("Error during resubscription from keepalive:", resubscribeError);
180
145
  // Don't schedule another keepalive on resubscribe failure
181
146
  return;
182
147
  }
183
148
  }
184
149
  // Schedule next keepalive if not disposed
185
- if (!__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f")) {
186
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
150
+ if (!this._disposed) {
151
+ this._keepaliveTimer = setTimeout(keepaliveLoop, 30000);
187
152
  }
188
153
  };
189
154
  // Start the first keepalive loop
190
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
155
+ this._keepaliveTimer = setTimeout(keepaliveLoop, 30000);
191
156
  }
192
157
  /** Get the subscription ID for this query subscription
193
158
  *
@@ -198,7 +163,7 @@ export class QuerySubscriptionProxy {
198
163
  * @returns The subscription ID string
199
164
  */
200
165
  get id() {
201
- return __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f");
166
+ return this._subscriptionId;
202
167
  }
203
168
  /** Promise that resolves when the subscription has received its first result
204
169
  * through the subscription channel. This ensures the subscription is fully
@@ -212,7 +177,7 @@ export class QuerySubscriptionProxy {
212
177
  * creation methods (like subscribeInfer) already wait for initialization.
213
178
  */
214
179
  get initialized() {
215
- return __classPrivateFieldGet(this, _QuerySubscriptionProxy_initialized, "f");
180
+ return this._initialized;
216
181
  }
217
182
  /** Get the latest query result
218
183
  *
@@ -223,7 +188,7 @@ export class QuerySubscriptionProxy {
223
188
  * @returns The latest query result as a string (usually a JSON array of bindings)
224
189
  */
225
190
  get result() {
226
- return __classPrivateFieldGet(this, _QuerySubscriptionProxy_latestResult, "f");
191
+ return this._latestResult;
227
192
  }
228
193
  /** Add a callback that will be called whenever new results arrive
229
194
  *
@@ -245,8 +210,19 @@ export class QuerySubscriptionProxy {
245
210
  * ```
246
211
  */
247
212
  onResult(callback) {
248
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
249
- return () => __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
213
+ this._callbacks.add(callback);
214
+ return () => this._callbacks.delete(callback);
215
+ }
216
+ /** Internal method to notify all callbacks of a new result */
217
+ _notifyCallbacks(result) {
218
+ for (const callback of this._callbacks) {
219
+ try {
220
+ callback(result);
221
+ }
222
+ catch (e) {
223
+ console.error("Error in query subscription callback:", e);
224
+ }
225
+ }
250
226
  }
251
227
  /** Clean up the subscription and stop keepalive signals
252
228
  *
@@ -260,39 +236,24 @@ export class QuerySubscriptionProxy {
260
236
  * will not receive any more updates. The instance should be discarded.
261
237
  */
262
238
  dispose() {
263
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_disposed, true, "f");
264
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
265
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
266
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
239
+ this._disposed = true;
240
+ clearTimeout(this._keepaliveTimer);
241
+ if (this._unsubscribe) {
242
+ this._unsubscribe();
267
243
  }
268
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").clear();
269
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
270
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
271
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
244
+ this._callbacks.clear();
245
+ if (this._initTimeoutId) {
246
+ clearTimeout(this._initTimeoutId);
247
+ this._initTimeoutId = undefined;
272
248
  }
273
249
  // Tell the backend to dispose of the subscription
274
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
275
- if (this.isSurrealDB) {
276
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"))
277
- .catch(e => console.error('Error disposing surreal query subscription:', e));
278
- }
279
- else {
280
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"))
281
- .catch(e => console.error('Error disposing query subscription:', e));
282
- }
250
+ if (this._subscriptionId) {
251
+ this._client
252
+ .disposeQuerySubscription(this._uuid, this._subscriptionId)
253
+ .catch((e) => console.error("Error disposing query subscription:", e));
283
254
  }
284
255
  }
285
256
  }
286
- _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
287
- for (const callback of __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f")) {
288
- try {
289
- callback(result);
290
- }
291
- catch (e) {
292
- console.error('Error in query subscription callback:', e);
293
- }
294
- }
295
- };
296
257
  /**
297
258
  * PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs
298
259
  * that store and organize links between expressions.
@@ -332,34 +293,159 @@ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscripti
332
293
  * });
333
294
  * ```
334
295
  */
296
+ /** Local (unexported) helper – was previously `core/src/model/Subject.ts` */
297
+ class Subject {
298
+ constructor(perspective, baseExpression, subjectClassName) {
299
+ this._baseExpression = baseExpression;
300
+ this._subjectClassName = subjectClassName;
301
+ this._perspective = perspective;
302
+ }
303
+ get baseExpression() {
304
+ return this._baseExpression;
305
+ }
306
+ async init() {
307
+ let isInstance = await this._perspective.isSubjectInstance(this._baseExpression, this._subjectClassName);
308
+ if (!isInstance) {
309
+ throw `Not a valid subject instance of ${this._subjectClassName} for ${this._baseExpression}`;
310
+ }
311
+ let results = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property(C, Property)`);
312
+ let properties = results.map((result) => result.Property);
313
+ for (let p of properties) {
314
+ await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property_resolve(C, "${p}")`);
315
+ Object.defineProperty(this, p, {
316
+ configurable: true,
317
+ get: async () => {
318
+ try {
319
+ return await this._perspective.getPropertyValueViaSurreal(this._baseExpression, this._subjectClassName, p);
320
+ }
321
+ catch (err) {
322
+ console.warn(`Failed to get property ${p} via SurrealDB:`, err);
323
+ return undefined;
324
+ }
325
+ },
326
+ });
327
+ }
328
+ const setters = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property_setter(C, Property, Setter)`);
329
+ for (let setter of setters ? setters : []) {
330
+ if (setter) {
331
+ const property = setter.Property;
332
+ const actions = eval(setter.Setter);
333
+ const resolveLanguageResults = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property_resolve_language(C, "${property}", Language)`);
334
+ let resolveLanguage;
335
+ if (resolveLanguageResults && resolveLanguageResults.length > 0) {
336
+ resolveLanguage = resolveLanguageResults[0].Language;
337
+ }
338
+ this[propertyNameToSetterName(property)] = async (value) => {
339
+ if (resolveLanguage) {
340
+ value = await this._perspective.createExpression(value, resolveLanguage);
341
+ }
342
+ await this._perspective.executeAction(actions, this._baseExpression, [
343
+ { name: "value", value },
344
+ ]);
345
+ };
346
+ }
347
+ }
348
+ let results2 = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection(C, Collection)`);
349
+ if (!results2)
350
+ results2 = [];
351
+ let collections = results2.map((result) => result.Collection);
352
+ for (let c of collections) {
353
+ Object.defineProperty(this, c, {
354
+ configurable: true,
355
+ get: async () => {
356
+ try {
357
+ return await this._perspective.getCollectionValuesViaSurreal(this._baseExpression, this._subjectClassName, c);
358
+ }
359
+ catch (err) {
360
+ console.warn(`Failed to get collection ${c} via SurrealDB:`, err);
361
+ return [];
362
+ }
363
+ },
364
+ });
365
+ }
366
+ let adders = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection_adder(C, Collection, Adder)`);
367
+ if (!adders)
368
+ adders = [];
369
+ for (let adder of adders) {
370
+ if (adder) {
371
+ const collection = adder.Collection;
372
+ const actions = eval(adder.Adder);
373
+ this[collectionToAdderName(collection)] = async (value) => {
374
+ if (Array.isArray(value)) {
375
+ await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [
376
+ { name: "value", value: v },
377
+ ])));
378
+ }
379
+ else {
380
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }]);
381
+ }
382
+ };
383
+ }
384
+ }
385
+ let removers = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection_remover(C, Collection, Remover)`);
386
+ if (!removers)
387
+ removers = [];
388
+ for (let remover of removers) {
389
+ if (remover) {
390
+ const collection = remover.Collection;
391
+ const actions = eval(remover.Remover);
392
+ this[collectionToRemoverName(collection)] = async (value) => {
393
+ if (Array.isArray(value)) {
394
+ await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [
395
+ { name: "value", value: v },
396
+ ])));
397
+ }
398
+ else {
399
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }]);
400
+ }
401
+ };
402
+ }
403
+ }
404
+ let collectionSetters = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection_setter(C, Collection, Setter)`);
405
+ if (!collectionSetters)
406
+ collectionSetters = [];
407
+ for (let collectionSetter of collectionSetters) {
408
+ if (collectionSetter) {
409
+ const collection = collectionSetter.Collection;
410
+ const actions = eval(collectionSetter.Setter);
411
+ this[collectionToSetterName(collection)] = async (value) => {
412
+ if (Array.isArray(value)) {
413
+ await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: "value", value: v })));
414
+ }
415
+ else {
416
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }]);
417
+ }
418
+ };
419
+ }
420
+ }
421
+ }
422
+ }
335
423
  export class PerspectiveProxy {
336
424
  /**
337
425
  * Creates a new PerspectiveProxy instance.
338
426
  * Note: Don't create this directly, use ad4m.perspective.add() instead.
339
427
  */
340
428
  constructor(handle, ad4m) {
341
- _PerspectiveProxy_handle.set(this, void 0);
342
- _PerspectiveProxy_client.set(this, void 0);
343
- _PerspectiveProxy_perspectiveLinkAddedCallbacks.set(this, void 0);
344
- _PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);
345
- _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
346
- _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
347
- __classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
348
- __classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
349
- __classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
350
- __classPrivateFieldSet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, [], "f");
351
- __classPrivateFieldSet(this, _PerspectiveProxy_handle, handle, "f");
352
- __classPrivateFieldSet(this, _PerspectiveProxy_client, ad4m, "f");
353
- this.uuid = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid;
354
- this.name = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").name;
355
- this.owners = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").owners;
356
- this.sharedUrl = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").sharedUrl;
357
- this.neighbourhood = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").neighbourhood;
358
- this.state = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").state;
359
- __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkAddedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f"));
360
- __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkRemovedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f"));
361
- __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
362
- __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
429
+ // Prevent Vue (and other Proxy-based reactivity systems) from wrapping this
430
+ // instance. PerspectiveProxy manages its own internal state via subscriptions
431
+ // and #private fields; wrapping it in a Proxy breaks WeakMap-based private
432
+ // field access (TypeError: Cannot read private member).
433
+ this._perspectiveLinkAddedCallbacks = [];
434
+ this._perspectiveLinkRemovedCallbacks = [];
435
+ this._perspectiveLinkUpdatedCallbacks = [];
436
+ this._perspectiveSyncStateChangeCallbacks = [];
437
+ this._handle = handle;
438
+ this._client = ad4m;
439
+ this.uuid = this._handle.uuid;
440
+ this.name = this._handle.name;
441
+ this.owners = this._handle.owners;
442
+ this.sharedUrl = this._handle.sharedUrl;
443
+ this.neighbourhood = this._handle.neighbourhood;
444
+ this.state = this._handle.state;
445
+ this._client.addPerspectiveLinkAddedListener(this._handle.uuid, this._perspectiveLinkAddedCallbacks);
446
+ this._client.addPerspectiveLinkRemovedListener(this._handle.uuid, this._perspectiveLinkRemovedCallbacks);
447
+ this._client.addPerspectiveLinkUpdatedListener(this._handle.uuid, this._perspectiveLinkUpdatedCallbacks);
448
+ this._client.addPerspectiveSyncStateChangeListener(this._handle.uuid, this._perspectiveSyncStateChangeCallbacks);
363
449
  }
364
450
  /**
365
451
  * Escapes special regex characters in a string to prevent ReDoS attacks
@@ -371,7 +457,7 @@ export class PerspectiveProxy {
371
457
  * @private
372
458
  */
373
459
  escapeRegExp(str) {
374
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
460
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
375
461
  }
376
462
  /**
377
463
  * Executes a set of actions on an expression with optional parameters.
@@ -381,7 +467,7 @@ export class PerspectiveProxy {
381
467
  * Each action is an object with the following format:
382
468
  * ```typescript
383
469
  * {
384
- * action: "addLink" | "removeLink" | "setSingleTarget" | "collectionSetter",
470
+ * action: "addLink" | "removeLink" | "setSingleTarget" | "relationSetter",
385
471
  * source: string, // Usually "this" to reference the current expression
386
472
  * predicate: string, // The predicate URI
387
473
  * target: string // The target value or "value" for parameters
@@ -392,7 +478,7 @@ export class PerspectiveProxy {
392
478
  * - `addLink`: Creates a new link
393
479
  * - `removeLink`: Removes an existing link
394
480
  * - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one
395
- * - `collectionSetter`: Special command for setting collection properties
481
+ * - `relationSetter`: Special command for bulk-setting a relation (clears existing links, then adds new ones)
396
482
  *
397
483
  * When used with parameters, the special value "value" in the target field will be
398
484
  * replaced with the actual parameter value.
@@ -434,7 +520,7 @@ export class PerspectiveProxy {
434
520
  * @param batchId - Optional batch ID to group this operation with others
435
521
  */
436
522
  async executeAction(actions, expression, parameters, batchId) {
437
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
523
+ return await this._client.executeCommands(this._handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
438
524
  }
439
525
  /**
440
526
  * Retrieves links from the perspective that match the given query.
@@ -458,7 +544,7 @@ export class PerspectiveProxy {
458
544
  * ```
459
545
  */
460
546
  async get(query) {
461
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
547
+ return await this._client.queryLinks(this._handle.uuid, query);
462
548
  }
463
549
  /**
464
550
  * Executes a Prolog query against the perspective's knowledge base.
@@ -484,7 +570,7 @@ export class PerspectiveProxy {
484
570
  * ```
485
571
  */
486
572
  async infer(query) {
487
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
573
+ return await this._client.queryProlog(this._handle.uuid, query);
488
574
  }
489
575
  /**
490
576
  * Executes a SurrealQL query against the perspective's link cache.
@@ -514,7 +600,7 @@ export class PerspectiveProxy {
514
600
  * ```
515
601
  */
516
602
  async querySurrealDB(query) {
517
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
603
+ return await this._client.querySurrealDB(this._handle.uuid, query);
518
604
  }
519
605
  /**
520
606
  * Adds a new link to the perspective.
@@ -541,8 +627,8 @@ export class PerspectiveProxy {
541
627
  * }, "local");
542
628
  * ```
543
629
  */
544
- async add(link, status = 'shared', batchId) {
545
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
630
+ async add(link, status = "shared", batchId) {
631
+ return await this._client.addLink(this._handle.uuid, link, status, batchId);
546
632
  }
547
633
  /**
548
634
  * Adds multiple links to the perspective in a single operation.
@@ -553,8 +639,8 @@ export class PerspectiveProxy {
553
639
  * @param batchId - Optional batch ID to group this operation with others
554
640
  * @returns Array of created LinkExpressions
555
641
  */
556
- async addLinks(links, status = 'shared', batchId) {
557
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
642
+ async addLinks(links, status = "shared", batchId) {
643
+ return await this._client.addLinks(this._handle.uuid, links, status, batchId);
558
644
  }
559
645
  /**
560
646
  * Removes multiple links from the perspective.
@@ -564,7 +650,7 @@ export class PerspectiveProxy {
564
650
  * @returns Array of removed LinkExpressions
565
651
  */
566
652
  async removeLinks(links, batchId) {
567
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
653
+ return await this._client.removeLinks(this._handle.uuid, links, batchId);
568
654
  }
569
655
  /**
570
656
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -574,29 +660,29 @@ export class PerspectiveProxy {
574
660
  * @param status - Whether new links should be shared
575
661
  * @returns Object containing results of the mutations
576
662
  */
577
- async linkMutations(mutations, status = 'shared') {
578
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
663
+ async linkMutations(mutations, status = "shared") {
664
+ return await this._client.linkMutations(this._handle.uuid, mutations, status);
579
665
  }
580
666
  /**
581
- * Adds a pre-signed LinkExpression to the perspective.
582
- *
583
- * @param link - The signed LinkExpression to add
584
- * @param status - Whether the link should be shared
585
- * @param batchId - Optional batch ID to group this operation with others
586
- * @returns The added LinkExpression
587
- */
588
- async addLinkExpression(link, status = 'shared', batchId) {
589
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
667
+ * Adds a pre-signed LinkExpression to the perspective.
668
+ *
669
+ * @param link - The signed LinkExpression to add
670
+ * @param status - Whether the link should be shared
671
+ * @param batchId - Optional batch ID to group this operation with others
672
+ * @returns The added LinkExpression
673
+ */
674
+ async addLinkExpression(link, status = "shared", batchId) {
675
+ return await this._client.addLinkExpression(this._handle.uuid, link, status, batchId);
590
676
  }
591
677
  /**
592
- * Updates an existing link with new data.
593
- *
594
- * @param oldLink - The existing link to update
595
- * @param newLink - The new link data
596
- * @param batchId - Optional batch ID to group this operation with others
597
- */
678
+ * Updates an existing link with new data.
679
+ *
680
+ * @param oldLink - The existing link to update
681
+ * @param newLink - The new link data
682
+ * @param batchId - Optional batch ID to group this operation with others
683
+ */
598
684
  async update(oldLink, newLink, batchId) {
599
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
685
+ return await this._client.updateLink(this._handle.uuid, oldLink, newLink, batchId);
600
686
  }
601
687
  /**
602
688
  * Removes a link from the perspective.
@@ -605,15 +691,15 @@ export class PerspectiveProxy {
605
691
  * @param batchId - Optional batch ID to group this operation with others
606
692
  */
607
693
  async remove(link, batchId) {
608
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
694
+ return await this._client.removeLink(this._handle.uuid, link, batchId);
609
695
  }
610
696
  /** Creates a new batch for grouping operations */
611
697
  async createBatch() {
612
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
698
+ return await this._client.createBatch(this._handle.uuid);
613
699
  }
614
700
  /** Commits a batch of operations */
615
701
  async commitBatch(batchId) {
616
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
702
+ return await this._client.commitBatch(this._handle.uuid, batchId);
617
703
  }
618
704
  /**
619
705
  * Retrieves and renders an Expression referenced in this perspective.
@@ -622,7 +708,7 @@ export class PerspectiveProxy {
622
708
  * @returns The rendered Expression
623
709
  */
624
710
  async getExpression(expressionURI) {
625
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getExpression(expressionURI);
711
+ return await this._client.getExpression(expressionURI);
626
712
  }
627
713
  /**
628
714
  * Creates a new Expression in the specified Language.
@@ -632,7 +718,7 @@ export class PerspectiveProxy {
632
718
  * @returns URI of the created Expression
633
719
  */
634
720
  async createExpression(content, languageAddress) {
635
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createExpression(content, languageAddress);
721
+ return await this._client.createExpression(content, languageAddress);
636
722
  }
637
723
  /**
638
724
  * Subscribes to link changes in the perspective.
@@ -654,14 +740,14 @@ export class PerspectiveProxy {
654
740
  * ```
655
741
  */
656
742
  async addListener(type, cb) {
657
- if (type === 'link-added') {
658
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").push(cb);
743
+ if (type === "link-added") {
744
+ this._perspectiveLinkAddedCallbacks.push(cb);
659
745
  }
660
- else if (type === 'link-removed') {
661
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").push(cb);
746
+ else if (type === "link-removed") {
747
+ this._perspectiveLinkRemovedCallbacks.push(cb);
662
748
  }
663
- else if (type === 'link-updated') {
664
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").push(cb);
749
+ else if (type === "link-updated") {
750
+ this._perspectiveLinkUpdatedCallbacks.push(cb);
665
751
  }
666
752
  }
667
753
  /**
@@ -677,7 +763,7 @@ export class PerspectiveProxy {
677
763
  * ```
678
764
  */
679
765
  async addSyncStateChangeListener(cb) {
680
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").push(cb);
766
+ this._perspectiveSyncStateChangeCallbacks.push(cb);
681
767
  }
682
768
  /**
683
769
  * Unsubscribes from link changes.
@@ -686,17 +772,17 @@ export class PerspectiveProxy {
686
772
  * @param cb - The callback function to remove
687
773
  */
688
774
  async removeListener(type, cb) {
689
- if (type === 'link-added') {
690
- const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
691
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
775
+ if (type === "link-added") {
776
+ const index = this._perspectiveLinkAddedCallbacks.indexOf(cb);
777
+ this._perspectiveLinkAddedCallbacks.splice(index, 1);
692
778
  }
693
- else if (type === 'link-removed') {
694
- const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
695
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
779
+ else if (type === "link-removed") {
780
+ const index = this._perspectiveLinkRemovedCallbacks.indexOf(cb);
781
+ this._perspectiveLinkRemovedCallbacks.splice(index, 1);
696
782
  }
697
- else if (type === 'link-updated') {
698
- const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
699
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
783
+ else if (type === "link-updated") {
784
+ const index = this._perspectiveLinkUpdatedCallbacks.indexOf(cb);
785
+ this._perspectiveLinkUpdatedCallbacks.splice(index, 1);
700
786
  }
701
787
  }
702
788
  /**
@@ -706,7 +792,7 @@ export class PerspectiveProxy {
706
792
  * @returns Perspective object containing all links
707
793
  */
708
794
  async snapshot() {
709
- return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").snapshotByUUID(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
795
+ return this._client.snapshotByUUID(this._handle.uuid);
710
796
  }
711
797
  /**
712
798
  * Loads a perspective snapshot, replacing current content.
@@ -717,7 +803,7 @@ export class PerspectiveProxy {
717
803
  //Clean the input data from __typename
718
804
  const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));
719
805
  delete cleanedSnapshot.__typename;
720
- cleanedSnapshot.links.forEach(link => {
806
+ cleanedSnapshot.links.forEach((link) => {
721
807
  delete link.data.__typename;
722
808
  });
723
809
  for (const link of cleanedSnapshot.links) {
@@ -764,8 +850,11 @@ export class PerspectiveProxy {
764
850
  * });
765
851
  * ```
766
852
  */
767
- async setSingleTarget(link, status = 'shared') {
768
- const query = new LinkQuery({ source: link.source, predicate: link.predicate });
853
+ async setSingleTarget(link, status = "shared") {
854
+ const query = new LinkQuery({
855
+ source: link.source,
856
+ predicate: link.predicate,
857
+ });
769
858
  const foundLinks = await this.get(query);
770
859
  const removals = [];
771
860
  for (const l of foundLinks) {
@@ -782,9 +871,9 @@ export class PerspectiveProxy {
782
871
  // Query for all flow registration links
783
872
  const flowLinks = await this.get(new LinkQuery({
784
873
  source: "ad4m://self",
785
- predicate: "ad4m://has_flow"
874
+ predicate: "ad4m://has_flow",
786
875
  }));
787
- return flowLinks.map(l => {
876
+ return flowLinks.map((l) => {
788
877
  try {
789
878
  return Literal.fromUrl(l.data.target).get();
790
879
  }
@@ -811,7 +900,7 @@ export class PerspectiveProxy {
811
900
  const links = await this.get(new LinkQuery({
812
901
  source,
813
902
  predicate: pattern.predicate,
814
- target: pattern.target
903
+ target: pattern.target,
815
904
  }));
816
905
  if (links.length > 0) {
817
906
  available.push(name);
@@ -835,17 +924,17 @@ export class PerspectiveProxy {
835
924
  if (!flow)
836
925
  return [];
837
926
  // Find the state with the matching value
838
- const state = flow.states.find(s => s.value === flowState);
927
+ const state = flow.states.find((s) => s.value === flowState);
839
928
  if (!state)
840
929
  return [];
841
930
  // Query for expressions matching this state's check pattern
842
931
  const pattern = state.stateCheck;
843
932
  const links = await this.get(new LinkQuery({
844
933
  predicate: pattern.predicate,
845
- target: pattern.target
934
+ target: pattern.target,
846
935
  }));
847
936
  // Return the sources (expression addresses) - use source if pattern has no explicit source
848
- return links.map(l => pattern.source ? l.data.target : l.data.source);
937
+ return links.map((l) => (pattern.source ? l.data.target : l.data.source));
849
938
  }
850
939
  /** Returns the given expression's flow state with regard to given Social DNA flow */
851
940
  async flowState(flowName, exprAddr) {
@@ -859,7 +948,7 @@ export class PerspectiveProxy {
859
948
  const links = await this.get(new LinkQuery({
860
949
  source,
861
950
  predicate: pattern.predicate,
862
- target: pattern.target
951
+ target: pattern.target,
863
952
  }));
864
953
  if (links.length > 0)
865
954
  return state.value;
@@ -879,7 +968,7 @@ export class PerspectiveProxy {
879
968
  const links = await this.get(new LinkQuery({
880
969
  source,
881
970
  predicate: pattern.predicate,
882
- target: pattern.target
971
+ target: pattern.target,
883
972
  }));
884
973
  if (links.length > 0) {
885
974
  currentStateName = state.name;
@@ -890,15 +979,15 @@ export class PerspectiveProxy {
890
979
  return [];
891
980
  // Return transitions available from current state
892
981
  return flow.transitions
893
- .filter(t => t.fromState === currentStateName)
894
- .map(t => t.actionName);
982
+ .filter((t) => t.fromState === currentStateName)
983
+ .map((t) => t.actionName);
895
984
  }
896
985
  /** Runs given Social DNA flow action */
897
986
  async runFlowAction(flowName, exprAddr, actionName) {
898
987
  const flow = await this.getFlow(flowName);
899
988
  if (!flow)
900
989
  throw `Flow "${flowName}" not found`;
901
- const transition = flow.transitions.find(t => t.actionName === actionName);
990
+ const transition = flow.transitions.find((t) => t.actionName === actionName);
902
991
  if (!transition)
903
992
  throw `Action "${actionName}" not found in flow "${flowName}"`;
904
993
  await this.executeAction(transition.actions, exprAddr, undefined);
@@ -911,14 +1000,14 @@ export class PerspectiveProxy {
911
1000
  const sdnaPredicates = [
912
1001
  "ad4m://has_subject_class",
913
1002
  "ad4m://has_flow",
914
- "ad4m://has_custom_sdna"
1003
+ "ad4m://has_custom_sdna",
915
1004
  ];
916
1005
  const allSdnaCode = [];
917
1006
  for (const predicate of sdnaPredicates) {
918
1007
  // Find name literals linked from ad4m://self with this predicate
919
1008
  const nameLinks = await this.get(new LinkQuery({
920
1009
  source: "ad4m://self",
921
- predicate: predicate
1010
+ predicate: predicate,
922
1011
  }));
923
1012
  // For each name literal found, get the actual SDNA code
924
1013
  for (const nameLink of nameLinks) {
@@ -926,12 +1015,12 @@ export class PerspectiveProxy {
926
1015
  // Now find the SDNA code linked from this name with predicate "ad4m://sdna"
927
1016
  const sdnaLinks = await this.get(new LinkQuery({
928
1017
  source: nameLiteral,
929
- predicate: "ad4m://sdna"
1018
+ predicate: "ad4m://sdna",
930
1019
  }));
931
1020
  // Extract the SDNA code from each link
932
1021
  for (const sdnaLink of sdnaLinks) {
933
1022
  const code = Literal.fromUrl(sdnaLink.data.target).get();
934
- if (typeof code === 'string') {
1023
+ if (typeof code === "string") {
935
1024
  allSdnaCode.push(code);
936
1025
  }
937
1026
  }
@@ -948,7 +1037,7 @@ export class PerspectiveProxy {
948
1037
  const links = await this.get(new LinkQuery({
949
1038
  source: "ad4m://self",
950
1039
  target: nameLiteral.toUrl(),
951
- predicate: "ad4m://has_subject_class"
1040
+ predicate: "ad4m://has_subject_class",
952
1041
  }));
953
1042
  if (links.length === 0) {
954
1043
  return null;
@@ -956,14 +1045,14 @@ export class PerspectiveProxy {
956
1045
  // Now find the SDNA code linked from this name with predicate "ad4m://sdna"
957
1046
  const sdnaLinks = await this.get(new LinkQuery({
958
1047
  source: nameLiteral.toUrl(),
959
- predicate: "ad4m://sdna"
1048
+ predicate: "ad4m://sdna",
960
1049
  }));
961
1050
  if (sdnaLinks.length === 0) {
962
1051
  return null;
963
1052
  }
964
1053
  // Extract the SDNA code from the first link
965
1054
  const code = Literal.fromUrl(sdnaLinks[0].data.target).get();
966
- return typeof code === 'string' ? code : null;
1055
+ return typeof code === "string" ? code : null;
967
1056
  }
968
1057
  /**
969
1058
  * Adds Social DNA code to the perspective.
@@ -986,7 +1075,7 @@ export class PerspectiveProxy {
986
1075
  * await perspective.addSdna('Recipe', prologCode, 'subject_class');
987
1076
  */
988
1077
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
989
- return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
1078
+ return this._client.addSdna(this._handle.uuid, name, sdnaCode, sdnaType, shaclJson);
990
1079
  }
991
1080
  /**
992
1081
  * **Recommended way to add SDNA schemas.**
@@ -1017,28 +1106,27 @@ export class PerspectiveProxy {
1017
1106
  */
1018
1107
  async addShacl(name, shape) {
1019
1108
  // Serialize shape to links
1020
- const shapeLinks = shape.toLinks();
1021
- // Create name -> shape mapping links
1109
+ const links = shape.toLinks();
1110
+ // Add all links to perspective
1111
+ for (const link of links) {
1112
+ await this.add({
1113
+ source: link.source,
1114
+ predicate: link.predicate,
1115
+ target: link.target,
1116
+ });
1117
+ }
1118
+ // Create a name -> shape mapping link for easy retrieval
1022
1119
  const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1023
- const allLinks = [
1024
- ...shapeLinks.map(l => new Link({
1025
- source: l.source,
1026
- predicate: l.predicate,
1027
- target: l.target
1028
- })),
1029
- new Link({
1030
- source: "ad4m://self",
1031
- predicate: "ad4m://has_shacl",
1032
- target: nameMapping.toUrl()
1033
- }),
1034
- new Link({
1035
- source: nameMapping.toUrl(),
1036
- predicate: "ad4m://shacl_shape_uri",
1037
- target: shape.nodeShapeUri
1038
- })
1039
- ];
1040
- // Batch add all links at once
1041
- await this.addLinks(allLinks);
1120
+ await this.add({
1121
+ source: "ad4m://self",
1122
+ predicate: "ad4m://has_shacl",
1123
+ target: nameMapping.toUrl(),
1124
+ });
1125
+ await this.add({
1126
+ source: nameMapping.toUrl(),
1127
+ predicate: "ad4m://shacl_shape_uri",
1128
+ target: shape.nodeShapeUri,
1129
+ });
1042
1130
  }
1043
1131
  /**
1044
1132
  * Retrieve a SHACL shape by name from this Perspective
@@ -1048,28 +1136,72 @@ export class PerspectiveProxy {
1048
1136
  const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1049
1137
  const shapeUriLinks = await this.get(new LinkQuery({
1050
1138
  source: nameMapping.toUrl(),
1051
- predicate: "ad4m://shacl_shape_uri"
1139
+ predicate: "ad4m://shacl_shape_uri",
1052
1140
  }));
1053
1141
  if (shapeUriLinks.length === 0) {
1054
1142
  return null;
1055
1143
  }
1056
1144
  const shapeUri = shapeUriLinks[0].data.target;
1057
- const escapedShapeUri = escapeSurrealString(shapeUri);
1058
- // First get property shape URIs so we can query everything in one go
1059
- const propertyLinks = await this.get(new LinkQuery({
1145
+ // Get all links that are part of this shape
1146
+ // This includes the shape itself and all its property shapes
1147
+ const shapeLinks = [];
1148
+ // Get shape type and target class
1149
+ const shapeTypeLinks = await this.get(new LinkQuery({
1060
1150
  source: shapeUri,
1061
- predicate: "sh://property"
1151
+ predicate: "rdf://type",
1062
1152
  }));
1063
- // Build a single surreal query that fetches all relevant links
1064
- const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
1065
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
1066
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
1067
- const result = await this.querySurrealDB(query);
1068
- const shapeLinks = (result || []).map((r) => ({
1069
- source: r.source,
1070
- predicate: r.predicate,
1071
- target: r.target
1153
+ shapeLinks.push(...shapeTypeLinks.map((l) => l.data));
1154
+ const targetClassLinks = await this.get(new LinkQuery({
1155
+ source: shapeUri,
1156
+ predicate: "sh://targetClass",
1072
1157
  }));
1158
+ shapeLinks.push(...targetClassLinks.map((l) => l.data));
1159
+ // Get constructor actions
1160
+ const constructorLinks = await this.get(new LinkQuery({
1161
+ source: shapeUri,
1162
+ predicate: "ad4m://constructor",
1163
+ }));
1164
+ shapeLinks.push(...constructorLinks.map((l) => l.data));
1165
+ // Get destructor actions
1166
+ const destructorLinks = await this.get(new LinkQuery({
1167
+ source: shapeUri,
1168
+ predicate: "ad4m://destructor",
1169
+ }));
1170
+ shapeLinks.push(...destructorLinks.map((l) => l.data));
1171
+ // Get property shapes
1172
+ const propertyLinks = await this.get(new LinkQuery({
1173
+ source: shapeUri,
1174
+ predicate: "sh://property",
1175
+ }));
1176
+ for (const propLink of propertyLinks) {
1177
+ shapeLinks.push(propLink.data);
1178
+ // Get all links for this property shape (named URI or blank node)
1179
+ const propShapeId = propLink.data.target;
1180
+ // Query targeted predicates for this property shape to avoid loading all links
1181
+ const expectedPredicates = [
1182
+ "sh://path",
1183
+ "sh://datatype",
1184
+ "sh://nodeKind",
1185
+ "sh://minCount",
1186
+ "sh://maxCount",
1187
+ "ad4m://local",
1188
+ "ad4m://readOnly",
1189
+ "ad4m://resolveLanguage",
1190
+ "ad4m://setter",
1191
+ "ad4m://adder",
1192
+ "ad4m://remover",
1193
+ "rdf://type", // For CollectionShape detection
1194
+ ];
1195
+ for (const predicate of expectedPredicates) {
1196
+ const links = await this.get(new LinkQuery({
1197
+ source: propShapeId,
1198
+ predicate,
1199
+ }));
1200
+ shapeLinks.push(...links.map((l) => l.data));
1201
+ }
1202
+ }
1203
+ // Reconstruct shape from links
1204
+ const { SHACLShape } = await import("../shacl/SHACLShape");
1073
1205
  return SHACLShape.fromLinks(shapeLinks, shapeUri);
1074
1206
  }
1075
1207
  /**
@@ -1078,13 +1210,13 @@ export class PerspectiveProxy {
1078
1210
  async getAllShacl() {
1079
1211
  const nameLinks = await this.get(new LinkQuery({
1080
1212
  source: "ad4m://self",
1081
- predicate: "ad4m://has_shacl"
1213
+ predicate: "ad4m://has_shacl",
1082
1214
  }));
1083
1215
  const shapes = [];
1084
1216
  for (const nameLink of nameLinks) {
1085
1217
  const nameUrl = nameLink.data.target;
1086
1218
  const name = Literal.fromUrl(nameUrl).get();
1087
- const shapeName = name.replace('shacl://', '');
1219
+ const shapeName = name.replace("shacl://", "");
1088
1220
  const shape = await this.getShacl(shapeName);
1089
1221
  if (shape) {
1090
1222
  shapes.push({ name: shapeName, shape });
@@ -1131,28 +1263,28 @@ export class PerspectiveProxy {
1131
1263
  */
1132
1264
  async addFlow(name, flow) {
1133
1265
  // Serialize flow to links
1134
- const flowLinks = flow.toLinks();
1135
- // Create registration and mapping links
1266
+ const links = flow.toLinks();
1267
+ // Add all links to perspective
1268
+ for (const link of links) {
1269
+ await this.add({
1270
+ source: link.source,
1271
+ predicate: link.predicate,
1272
+ target: link.target,
1273
+ });
1274
+ }
1275
+ // Create registration link matching ad4m://has_flow pattern
1136
1276
  const flowNameLiteral = Literal.from(name).toUrl();
1137
- const allLinks = [
1138
- ...flowLinks.map(l => new Link({
1139
- source: l.source,
1140
- predicate: l.predicate,
1141
- target: l.target
1142
- })),
1143
- new Link({
1144
- source: "ad4m://self",
1145
- predicate: "ad4m://has_flow",
1146
- target: flowNameLiteral
1147
- }),
1148
- new Link({
1149
- source: flowNameLiteral,
1150
- predicate: "ad4m://flow_uri",
1151
- target: flow.flowUri
1152
- })
1153
- ];
1154
- // Batch add all links at once
1155
- await this.addLinks(allLinks);
1277
+ await this.add({
1278
+ source: "ad4m://self",
1279
+ predicate: "ad4m://has_flow",
1280
+ target: flowNameLiteral,
1281
+ });
1282
+ // Create mapping from name to flow URI
1283
+ await this.add({
1284
+ source: flowNameLiteral,
1285
+ predicate: "ad4m://flow_uri",
1286
+ target: flow.flowUri,
1287
+ });
1156
1288
  }
1157
1289
  /**
1158
1290
  * Retrieve a Flow definition by name from this Perspective
@@ -1165,26 +1297,45 @@ export class PerspectiveProxy {
1165
1297
  // Find flow URI from name mapping
1166
1298
  const flowUriLinks = await this.get(new LinkQuery({
1167
1299
  source: flowNameLiteral,
1168
- predicate: "ad4m://flow_uri"
1300
+ predicate: "ad4m://flow_uri",
1169
1301
  }));
1170
1302
  if (flowUriLinks.length === 0) {
1171
1303
  return null;
1172
1304
  }
1173
1305
  const flowUri = flowUriLinks[0].data.target;
1174
- const escapedFlowUri = escapeSurrealString(flowUri);
1175
- // Compute alternate prefix for state/transition URIs
1176
- const alternatePrefix = flowUri.endsWith('Flow')
1177
- ? flowUri.slice(0, -4) + '.'
1178
- : flowUri + '.';
1179
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
1180
- // Single surreal query to get all flow-related links
1181
- 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}')`;
1182
- const result = await this.querySurrealDB(query);
1183
- const flowLinks = (result || []).map((r) => ({
1184
- source: r.source,
1185
- predicate: r.predicate,
1186
- target: r.target
1187
- }));
1306
+ // Get all links related to this flow
1307
+ // flowUri format: {namespace}{Name}Flow
1308
+ // State/transition URIs format: {namespace}{Name}.{stateName}
1309
+ // Compute alternate prefix by only replacing trailing "Flow" suffix
1310
+ const alternatePrefix = flowUri.endsWith("Flow")
1311
+ ? flowUri.slice(0, -4) + "." // Remove trailing 'Flow', add '.'
1312
+ : flowUri + ".";
1313
+ // Query flow-related predicates to avoid fetching all links
1314
+ const flowPredicates = [
1315
+ "rdf://type",
1316
+ "ad4m://flowName",
1317
+ "ad4m://flowable",
1318
+ "ad4m://startAction",
1319
+ "ad4m://hasState",
1320
+ "ad4m://hasTransition",
1321
+ "ad4m://stateName",
1322
+ "ad4m://stateValue",
1323
+ "ad4m://stateCheck",
1324
+ "ad4m://actionName",
1325
+ "ad4m://fromState",
1326
+ "ad4m://toState",
1327
+ "ad4m://transitionActions",
1328
+ ];
1329
+ const allLinks = [];
1330
+ for (const predicate of flowPredicates) {
1331
+ const links = await this.get(new LinkQuery({ predicate }));
1332
+ allLinks.push(...links);
1333
+ }
1334
+ const flowLinks = allLinks
1335
+ .map((l) => l.data)
1336
+ .filter((l) => l.source === flowUri || l.source.startsWith(alternatePrefix));
1337
+ // Reconstruct flow from links
1338
+ const { SHACLFlow } = await import("../shacl/SHACLFlow");
1188
1339
  return SHACLFlow.fromLinks(flowLinks, flowUri);
1189
1340
  }
1190
1341
  /** Returns all the Subject classes defined in this perspectives SDNA
@@ -1196,22 +1347,25 @@ export class PerspectiveProxy {
1196
1347
  // Query SHACL class links directly — no need for a separate GraphQL endpoint
1197
1348
  const classLinks = await this.get(new LinkQuery({
1198
1349
  predicate: "rdf://type",
1199
- target: "ad4m://SubjectClass"
1350
+ target: "ad4m://SubjectClass",
1200
1351
  }));
1201
1352
  const classNames = classLinks
1202
- .map(l => {
1353
+ .map((l) => {
1203
1354
  const source = l.data.source;
1204
- // Extract class name from URI like "recipe://Recipe" or "flux://Channel"
1205
- const parts = source.split("://");
1206
- const lastPart = parts[parts.length - 1];
1207
- return lastPart.split('/').pop() || '';
1355
+ // Extract class name from URI like "recipe://RecipeShape" -> "Recipe"
1356
+ const sepIdx = source.indexOf("://");
1357
+ if (sepIdx < 0)
1358
+ return "";
1359
+ const afterScheme = source.substring(sepIdx + 3);
1360
+ const lastPart = afterScheme.split("/").pop() || "";
1361
+ // Strip trailing "Shape" suffix if present
1362
+ return lastPart.endsWith("Shape") ? lastPart.slice(0, -5) : lastPart;
1208
1363
  })
1209
- .filter(name => name.length > 0);
1210
- // Deduplicate
1364
+ .filter((name) => name.length > 0);
1211
1365
  return [...new Set(classNames)];
1212
1366
  }
1213
1367
  catch (e) {
1214
- console.warn('subjectClasses: SHACL lookup failed:', e);
1368
+ console.warn("subjectClasses: SHACL lookup failed:", e);
1215
1369
  return [];
1216
1370
  }
1217
1371
  }
@@ -1245,21 +1399,22 @@ export class PerspectiveProxy {
1245
1399
  let className;
1246
1400
  if (typeof subjectClass === "string") {
1247
1401
  className = subjectClass;
1248
- await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
1402
+ await this._client.createSubject(this._handle.uuid, JSON.stringify({
1249
1403
  className,
1250
- initialValues
1404
+ initialValues,
1251
1405
  }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
1252
1406
  }
1253
1407
  else {
1254
- const obj = subjectClass;
1255
- const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
1256
- || await this.findClassByProperties(obj);
1257
- if (!resolvedClassName) {
1258
- throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
1408
+ const o = subjectClass;
1409
+ const className = o.className ||
1410
+ o.constructor?.className ||
1411
+ o.constructor?.prototype?.className;
1412
+ if (!className) {
1413
+ throw new Error(`createSubject: could not resolve className from subject class object. Ensure the class is decorated with @Model.`);
1259
1414
  }
1260
- await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
1261
- className: resolvedClassName,
1262
- initialValues
1415
+ await this._client.createSubject(this._handle.uuid, JSON.stringify({
1416
+ className,
1417
+ initialValues,
1263
1418
  }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
1264
1419
  }
1265
1420
  // Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed
@@ -1270,15 +1425,16 @@ export class PerspectiveProxy {
1270
1425
  }
1271
1426
  async getSubjectData(subjectClass, exprAddr) {
1272
1427
  if (typeof subjectClass === "string") {
1273
- return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
1428
+ return JSON.parse(await this._client.getSubjectData(this._handle.uuid, JSON.stringify({ className: subjectClass }), exprAddr));
1274
1429
  }
1275
- const obj = subjectClass;
1276
- const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
1277
- || await this.findClassByProperties(obj);
1278
- if (!resolvedClassName) {
1279
- throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
1430
+ const o = subjectClass;
1431
+ const className = o.className ||
1432
+ o.constructor?.className ||
1433
+ o.constructor?.prototype?.className;
1434
+ if (!className) {
1435
+ throw new Error(`getSubjectData: could not resolve className from subject class object. Ensure the class is decorated with @Model.`);
1280
1436
  }
1281
- return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));
1437
+ return JSON.parse(await this._client.getSubjectData(this._handle.uuid, JSON.stringify({ className }), exprAddr));
1282
1438
  }
1283
1439
  /**
1284
1440
  * Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).
@@ -1338,7 +1494,7 @@ export class PerspectiveProxy {
1338
1494
  * @param subjectClass Either a string with the name of the subject class, or an object
1339
1495
  * with the properties of the subject class. In the latter case, the first subject class
1340
1496
  * that matches the given properties will be used.
1341
- */
1497
+ */
1342
1498
  async isSubjectInstance(expression, subjectClass) {
1343
1499
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
1344
1500
  // Get metadata from SHACL links
@@ -1353,7 +1509,9 @@ export class PerspectiveProxy {
1353
1509
  const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
1354
1510
  const result = await this.querySurrealDB(checkQuery);
1355
1511
  const count = result[0]?.count ?? 0;
1356
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1512
+ const countValue = typeof count === "object" && count?.Int !== undefined
1513
+ ? count.Int
1514
+ : count;
1357
1515
  return countValue > 0;
1358
1516
  }
1359
1517
  // Check if the expression has all required triples (predicate + optional exact target)
@@ -1376,7 +1534,9 @@ export class PerspectiveProxy {
1376
1534
  }
1377
1535
  const count = result[0]?.count ?? 0;
1378
1536
  // Handle potential object response like {Int: 0}
1379
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1537
+ const countValue = typeof count === "object" && count?.Int !== undefined
1538
+ ? count.Int
1539
+ : count;
1380
1540
  if (countValue === 0) {
1381
1541
  return false;
1382
1542
  }
@@ -1393,7 +1553,7 @@ export class PerspectiveProxy {
1393
1553
  * that matches the given properties will be used.
1394
1554
  */
1395
1555
  async getSubjectProxy(base, subjectClass) {
1396
- if (!await this.isSubjectInstance(base, subjectClass)) {
1556
+ if (!(await this.isSubjectInstance(base, subjectClass))) {
1397
1557
  throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`;
1398
1558
  }
1399
1559
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
@@ -1402,53 +1562,132 @@ export class PerspectiveProxy {
1402
1562
  return subject;
1403
1563
  }
1404
1564
  /**
1405
- * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
1406
- * Retrieves the SHACL shape and extracts metadata for instance queries.
1565
+ * Extracts subject class metadata from SDNA by parsing the Prolog text.
1566
+ * Parses the instance rule to extract required predicates.
1567
+ * Returns required predicates that define what makes something an instance,
1568
+ * plus a map of property/collection names to their predicates.
1569
+ */
1570
+ /**
1571
+ * Gets subject class metadata from SHACL links (Prolog-free implementation).
1572
+ * Uses the link API directly instead of SurrealDB queries.
1407
1573
  */
1408
1574
  async getSubjectClassMetadataFromSDNA(className) {
1409
1575
  try {
1410
- // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
1411
- const shape = await this.getShacl(className);
1412
- if (!shape) {
1576
+ // Resolve the exact SHACL shape URI from the name mapping to avoid overlapping class name issues
1577
+ const nameMapping = Literal.fromUrl(`literal://string:shacl://${className}`);
1578
+ const shapeUriLinks = await this.get(new LinkQuery({
1579
+ source: nameMapping.toUrl(),
1580
+ predicate: "ad4m://shacl_shape_uri",
1581
+ }));
1582
+ if (shapeUriLinks.length === 0) {
1413
1583
  console.warn(`No SHACL metadata found for ${className}`);
1414
1584
  return null;
1415
1585
  }
1586
+ const shapeUri = shapeUriLinks[0].data.target;
1587
+ // Get the target class URI from the shape
1588
+ const targetClassLinks = await this.get(new LinkQuery({
1589
+ source: shapeUri,
1590
+ predicate: "sh://targetClass",
1591
+ }));
1592
+ if (targetClassLinks.length === 0) {
1593
+ console.warn(`No target class found for SHACL shape ${shapeUri}`);
1594
+ return null;
1595
+ }
1596
+ const classUri = targetClassLinks[0].data.target;
1416
1597
  const requiredPredicates = [];
1417
1598
  const requiredTriples = [];
1418
1599
  const properties = new Map();
1419
1600
  const collections = new Map();
1420
- // Build property/collection maps and track writable predicates from shape properties
1421
- const writablePredicates = new Set();
1422
- for (const prop of shape.properties) {
1423
- if (!prop.path || !prop.name)
1601
+ // Get all property shapes FIRST to know which predicates are from properties vs flags
1602
+ const propertyPredicates = new Set();
1603
+ const readOnlyPredicates = new Set(); // Track which predicates are read-only
1604
+ const propertyLinks = await this.get(new LinkQuery({
1605
+ source: shapeUri,
1606
+ predicate: "sh://property",
1607
+ }));
1608
+ for (const propLink of propertyLinks) {
1609
+ const propUri = propLink.data.target;
1610
+ // Extract property name from URI (e.g., "todo://Todo.title" -> "title")
1611
+ const propNameMatch = propUri.match(/\.([^.]+)$/);
1612
+ if (!propNameMatch)
1424
1613
  continue;
1425
- if (prop.writable) {
1426
- writablePredicates.add(prop.path);
1427
- }
1428
- const isCollection = prop.adder && prop.adder.length > 0;
1429
- if (isCollection) {
1430
- collections.set(prop.name, { predicate: prop.path });
1614
+ const propName = propNameMatch[1];
1615
+ // Get property details
1616
+ const propDetailLinks = await this.get(new LinkQuery({
1617
+ source: propUri,
1618
+ }));
1619
+ let predicate;
1620
+ let resolveLanguage;
1621
+ let isCollection = false;
1622
+ let isReadOnly = false;
1623
+ for (const detail of propDetailLinks) {
1624
+ if (detail.data.predicate === "sh://path") {
1625
+ predicate = detail.data.target;
1626
+ }
1627
+ else if (detail.data.predicate === "ad4m://resolveLanguage") {
1628
+ resolveLanguage = detail.data.target?.replace("literal://string:", "");
1629
+ }
1630
+ else if (detail.data.predicate === "rdf://type" &&
1631
+ detail.data.target === "ad4m://Collection") {
1632
+ isCollection = true;
1633
+ }
1634
+ else if (detail.data.predicate === "ad4m://readOnly" &&
1635
+ detail.data.target === "literal://true") {
1636
+ isReadOnly = true;
1637
+ }
1431
1638
  }
1432
- else {
1433
- properties.set(prop.name, {
1434
- predicate: prop.path,
1435
- resolveLanguage: prop.resolveLanguage
1436
- });
1639
+ if (predicate) {
1640
+ propertyPredicates.add(predicate); // Track predicates that come from properties
1641
+ if (isReadOnly) {
1642
+ readOnlyPredicates.add(predicate); // Track which are read-only
1643
+ }
1644
+ if (isCollection) {
1645
+ collections.set(propName, { predicate });
1646
+ }
1647
+ else {
1648
+ properties.set(propName, { predicate, resolveLanguage });
1649
+ }
1437
1650
  }
1438
1651
  }
1439
- // Extract required predicates/triples from constructor actions
1440
- if (shape.constructor_actions) {
1441
- for (const action of shape.constructor_actions) {
1442
- if (action.predicate) {
1443
- requiredPredicates.push(action.predicate);
1444
- const isWritableProperty = writablePredicates.has(action.predicate);
1445
- if (action.target && action.target !== 'value' && !isWritableProperty) {
1446
- requiredTriples.push({ predicate: action.predicate, target: action.target });
1447
- }
1448
- else {
1449
- requiredTriples.push({ predicate: action.predicate });
1652
+ // Get constructor actions from SHACL shape
1653
+ const constructorLinks = await this.get(new LinkQuery({
1654
+ source: shapeUri,
1655
+ predicate: "ad4m://constructor",
1656
+ }));
1657
+ if (constructorLinks.length > 0) {
1658
+ const constructorTarget = constructorLinks[0].data.target;
1659
+ // Parse constructor actions from literal://string:[{...}]
1660
+ if (constructorTarget &&
1661
+ constructorTarget.startsWith("literal://string:")) {
1662
+ try {
1663
+ const actionsJson = constructorTarget.substring("literal://string:".length);
1664
+ const actions = JSON.parse(actionsJson);
1665
+ for (const action of actions) {
1666
+ if (action.predicate) {
1667
+ requiredPredicates.push(action.predicate);
1668
+ // Flags: fixed target value + in propertyPredicates + IS readOnly -> require exact match
1669
+ // Properties with initial: has target + in propertyPredicates + NOT readOnly -> any value OK
1670
+ // Other: not in propertyPredicates -> require exact match if has target
1671
+ const isWritableProperty = !readOnlyPredicates.has(action.predicate);
1672
+ if (action.target &&
1673
+ action.target !== "value" &&
1674
+ !isWritableProperty) {
1675
+ // Either a flag (readOnly) or not a property at all - require exact target
1676
+ requiredTriples.push({
1677
+ predicate: action.predicate,
1678
+ target: action.target,
1679
+ });
1680
+ }
1681
+ else {
1682
+ // Non-readOnly property with initial value - just require predicate exists
1683
+ requiredTriples.push({ predicate: action.predicate });
1684
+ }
1685
+ }
1450
1686
  }
1451
1687
  }
1688
+ catch (e) {
1689
+ console.warn(`Failed to parse constructor actions for ${className}:`, e);
1690
+ }
1452
1691
  }
1453
1692
  }
1454
1693
  return { requiredPredicates, requiredTriples, properties, collections };
@@ -1467,7 +1706,8 @@ export class PerspectiveProxy {
1467
1706
  return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
1468
1707
  }
1469
1708
  // Generate WHERE conditions for each required triple (predicate + optional exact target)
1470
- const whereConditions = metadata.requiredTriples.map(triple => {
1709
+ const whereConditions = metadata.requiredTriples
1710
+ .map((triple) => {
1471
1711
  const escapedPredicate = escapeSurrealString(triple.predicate);
1472
1712
  if (triple.target) {
1473
1713
  // Flag: must match both predicate AND exact target value
@@ -1478,7 +1718,8 @@ export class PerspectiveProxy {
1478
1718
  // Property: just check predicate exists
1479
1719
  return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
1480
1720
  }
1481
- }).join(' AND ');
1721
+ })
1722
+ .join(" AND ");
1482
1723
  return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
1483
1724
  }
1484
1725
  /**
@@ -1540,7 +1781,7 @@ export class PerspectiveProxy {
1540
1781
  if (!result || result.length === 0) {
1541
1782
  return [];
1542
1783
  }
1543
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1784
+ let values = result.map((r) => r.value).filter((v) => v !== "" && v !== "");
1544
1785
  // Apply condition filtering if present
1545
1786
  if (collMeta.condition && values.length > 0) {
1546
1787
  try {
@@ -1551,11 +1792,14 @@ export class PerspectiveProxy {
1551
1792
  .replace(/\$base/g, `'${baseExpression}'`)
1552
1793
  .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
1553
1794
  // If condition starts with WHERE, wrap in array length check
1554
- if (condition.trim().startsWith('WHERE')) {
1795
+ if (condition.trim().startsWith("WHERE")) {
1555
1796
  condition = `array::len(SELECT * FROM link ${condition}) > 0`;
1556
1797
  }
1557
1798
  const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
1558
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
1799
+ const isTrue = filterResult === true ||
1800
+ (Array.isArray(filterResult) &&
1801
+ filterResult.length > 0 &&
1802
+ filterResult[0] === true);
1559
1803
  if (isTrue) {
1560
1804
  filteredValues.push(value);
1561
1805
  }
@@ -1593,15 +1837,19 @@ export class PerspectiveProxy {
1593
1837
  }
1594
1838
  // If no required triples, check which expressions have any links
1595
1839
  if (metadata.requiredTriples.length === 0) {
1596
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1840
+ const escapedExpressions = expressions
1841
+ .map((e) => `'${escapeSurrealString(e)}'`)
1842
+ .join(", ");
1597
1843
  const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
1598
1844
  const result = await this.querySurrealDB(checkQuery);
1599
- return result.map(r => r.uri);
1845
+ return result.map((r) => r.uri);
1600
1846
  }
1601
1847
  // For each required triple, build a query that finds matching expressions
1602
1848
  const validExpressionSets = [];
1603
1849
  for (const triple of metadata.requiredTriples) {
1604
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1850
+ const escapedExpressions = expressions
1851
+ .map((e) => `'${escapeSurrealString(e)}'`)
1852
+ .join(", ");
1605
1853
  const escapedPredicate = escapeSurrealString(triple.predicate);
1606
1854
  let checkQuery;
1607
1855
  if (triple.target) {
@@ -1616,15 +1864,15 @@ export class PerspectiveProxy {
1616
1864
  checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
1617
1865
  }
1618
1866
  const result = await this.querySurrealDB(checkQuery);
1619
- validExpressionSets.push(new Set(result.map(r => r.uri)));
1867
+ validExpressionSets.push(new Set(result.map((r) => r.uri)));
1620
1868
  }
1621
1869
  // Find intersection: expressions that passed ALL required triple checks
1622
1870
  if (validExpressionSets.length === 0) {
1623
1871
  return expressions;
1624
1872
  }
1625
1873
  const firstSet = validExpressionSets[0];
1626
- const validExpressions = expressions.filter(expr => {
1627
- return validExpressionSets.every(set => set.has(expr));
1874
+ const validExpressions = expressions.filter((expr) => {
1875
+ return validExpressionSets.every((set) => set.has(expr));
1628
1876
  });
1629
1877
  return validExpressions;
1630
1878
  }
@@ -1741,13 +1989,129 @@ export class PerspectiveProxy {
1741
1989
  }
1742
1990
  return instances;
1743
1991
  }
1744
- /**
1745
- * Find a subject class by matching an object's properties/collections against SHACL shapes.
1746
- * Queries SHACL links client-side to find a class whose properties contain all required ones.
1747
- * @returns The matching class name, or null if no match found.
1992
+ buildQueryFromTemplate(obj) {
1993
+ let result;
1994
+ // We need to avoid strict mode for the following intropsective code
1995
+ (function (obj) {
1996
+ // Collect all string properties of the object in a list
1997
+ let properties = [];
1998
+ // Collect all collections of the object in a list
1999
+ let collections = [];
2000
+ // Collect all string properties of the object in a list
2001
+ const _protoProps = getPropertiesMetadata(Object.getPrototypeOf(obj)?.constructor);
2002
+ if (Object.keys(_protoProps).length > 0) {
2003
+ Object.keys(_protoProps).forEach((p) => properties.push(p));
2004
+ }
2005
+ else {
2006
+ properties.push(...Object.keys(obj).filter((key) => !Array.isArray(obj[key])));
2007
+ }
2008
+ // Collect all collections of the object in a list
2009
+ const _protoCols = getRelationsMetadata(Object.getPrototypeOf(obj)?.constructor);
2010
+ if (Object.keys(_protoCols).length > 0) {
2011
+ Object.keys(_protoCols)
2012
+ .filter((key) => key !== "isSubjectInstance")
2013
+ .forEach((c) => {
2014
+ if (!collections.includes(c)) {
2015
+ collections.push(c);
2016
+ }
2017
+ });
2018
+ }
2019
+ else {
2020
+ collections.push(...Object.keys(obj)
2021
+ .filter((key) => Array.isArray(obj[key]))
2022
+ .filter((key) => key !== "isSubjectInstance"));
2023
+ }
2024
+ // Helper: distinguish collection setters (setComments, setLocations, …) from
2025
+ // plain property setters (setName, setState, …) using @HasMany/__collections metadata
2026
+ // rather than the old "setCollection" string prefix.
2027
+ const _collectionsMetadata = getRelationsMetadata(Object.getPrototypeOf(obj)?.constructor ?? obj.constructor);
2028
+ const isRelationSetter = (key) => {
2029
+ if (!key.startsWith("set") || key.length <= 3)
2030
+ return false;
2031
+ const suffix = key.substring(3);
2032
+ const relationKey = suffix.charAt(0).toLowerCase() + suffix.slice(1);
2033
+ return relationKey in _collectionsMetadata;
2034
+ };
2035
+ // Collect all set functions of the object in a list
2036
+ let setFunctions = Object.getOwnPropertyNames(obj).filter((key) => typeof obj[key] === "function" &&
2037
+ key.startsWith("set") &&
2038
+ !isRelationSetter(key));
2039
+ // Add all set functions of the object's prototype to that list
2040
+ setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
2041
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
2042
+ return (descriptor &&
2043
+ typeof descriptor.value === "function" &&
2044
+ key.startsWith("set") &&
2045
+ !isRelationSetter(key));
2046
+ }));
2047
+ // Collect all add functions of the object in a list
2048
+ let addFunctions = Object.getOwnPropertyNames(obj).filter((key) => Object.prototype.hasOwnProperty.call(obj, key) &&
2049
+ typeof obj[key] === "function" &&
2050
+ key.startsWith("add"));
2051
+ // Add all add functions of the object's prototype to that list
2052
+ addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
2053
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
2054
+ return (descriptor &&
2055
+ typeof descriptor.value === "function" &&
2056
+ key.startsWith("add"));
2057
+ }));
2058
+ // Collect all remove functions of the object in a list
2059
+ let removeFunctions = Object.getOwnPropertyNames(obj).filter((key) => Object.prototype.hasOwnProperty.call(obj, key) &&
2060
+ typeof obj[key] === "function" &&
2061
+ key.startsWith("remove"));
2062
+ // Add all remove functions of the object's prototype to that list
2063
+ removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
2064
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
2065
+ return (descriptor &&
2066
+ typeof descriptor.value === "function" &&
2067
+ key.startsWith("remove"));
2068
+ }));
2069
+ // Collect all collection setter functions of the object in a list
2070
+ let setCollectionFunctions = Object.getOwnPropertyNames(obj).filter((key) => Object.prototype.hasOwnProperty.call(obj, key) &&
2071
+ typeof obj[key] === "function" &&
2072
+ key.startsWith("set") &&
2073
+ isRelationSetter(key));
2074
+ // Add all collection setter functions from the object's prototype to that list
2075
+ setCollectionFunctions = setCollectionFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
2076
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
2077
+ return (descriptor &&
2078
+ typeof descriptor.value === "function" &&
2079
+ key.startsWith("set") &&
2080
+ isRelationSetter(key));
2081
+ }));
2082
+ // Construct query to find all subject classes that have the given properties and collections
2083
+ let query = `subject_class(Class, C)`;
2084
+ for (let property of properties) {
2085
+ query += `, property(C, "${property}")`;
2086
+ }
2087
+ for (let collection of collections) {
2088
+ query += `, collection(C, "${collection}")`;
2089
+ }
2090
+ for (let setFunction of setFunctions) {
2091
+ // e.g. "setState" -> "state"
2092
+ let property = setFunction.substring(3);
2093
+ property = property.charAt(0).toLowerCase() + property.slice(1);
2094
+ query += `, property_setter(C, "${property}", _)`;
2095
+ }
2096
+ for (let addFunction of addFunctions) {
2097
+ query += `, collection_adder(C, "${collectionAdderToName(addFunction)}", _)`;
2098
+ }
2099
+ for (let removeFunction of removeFunctions) {
2100
+ query += `, collection_remover(C, "${collectionRemoverToName(removeFunction)}", _)`;
2101
+ }
2102
+ for (let setCollectionFunction of setCollectionFunctions) {
2103
+ query += `, collection_setter(C, "${collectionSetterToName(setCollectionFunction)}", _)`;
2104
+ }
2105
+ query += ".";
2106
+ result = query;
2107
+ })(obj);
2108
+ return result;
2109
+ }
2110
+ /** Finds a single subject class whose SHACL shape matches all properties
2111
+ * and collections present on `obj`. Returns `null` when no match is found.
1748
2112
  */
1749
2113
  async findClassByProperties(obj) {
1750
- // Extract properties and collections from the object
2114
+ // Extract property / collection names from the object or its prototype
1751
2115
  let properties = [];
1752
2116
  let collections = [];
1753
2117
  const proto = Object.getPrototypeOf(obj);
@@ -1755,53 +2119,59 @@ export class PerspectiveProxy {
1755
2119
  properties = Object.keys(proto.__properties);
1756
2120
  }
1757
2121
  else {
1758
- properties = Object.keys(obj).filter(key => !Array.isArray(obj[key]));
2122
+ properties = Object.keys(obj).filter((key) => !Array.isArray(obj[key]));
1759
2123
  }
1760
2124
  if (proto?.__collections) {
1761
- collections = Object.keys(proto.__collections).filter(key => key !== 'isSubjectInstance');
2125
+ collections = Object.keys(proto.__collections).filter((k) => k !== "isSubjectInstance");
1762
2126
  }
1763
2127
  else {
1764
- collections = Object.keys(obj).filter(key => Array.isArray(obj[key]) && key !== 'isSubjectInstance');
2128
+ collections = Object.keys(obj).filter((key) => Array.isArray(obj[key]) && key !== "isSubjectInstance");
1765
2129
  }
1766
- if (properties.length === 0 && collections.length === 0) {
2130
+ if (properties.length === 0 && collections.length === 0)
1767
2131
  return null;
1768
- }
1769
- // Single SurrealDB query to find all classes and their properties/collections
1770
- const query = `SELECT
1771
- in.uri AS shape_source,
1772
- predicate,
1773
- out.uri AS target
1774
- FROM link
1775
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
2132
+ // Single SurrealDB query to fetch all SHACL links at once
2133
+ const query = `SELECT
2134
+ in.uri AS shape_source,
2135
+ predicate,
2136
+ out.uri AS target
2137
+ FROM link
2138
+ WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
1776
2139
  const results = await this.querySurrealDB(query);
1777
2140
  if (!results || results.length === 0)
1778
2141
  return null;
1779
- // Build a map of className -> { properties, collections }
2142
+ // Build className -> { shapeUri, properties[], collections[] }
1780
2143
  const classShapes = new Map();
1781
- // First pass: find all subject classes
1782
2144
  for (const r of results) {
1783
- if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {
2145
+ if (r.predicate === "rdf://type" && r.target === "ad4m://SubjectClass") {
1784
2146
  const source = r.shape_source;
1785
- const sepIdx = source.indexOf('://');
2147
+ const sepIdx = source.indexOf("://");
1786
2148
  if (sepIdx < 0)
1787
2149
  continue;
1788
- const className = source.substring(sepIdx + 3).split('/').pop();
2150
+ let className = source
2151
+ .substring(sepIdx + 3)
2152
+ .split("/")
2153
+ .pop();
1789
2154
  if (!className)
1790
2155
  continue;
1791
- classShapes.set(className, { shapeUri: source, properties: [], collections: [] });
2156
+ if (className.endsWith("Shape"))
2157
+ className = className.slice(0, -5);
2158
+ classShapes.set(className, {
2159
+ shapeUri: source,
2160
+ properties: [],
2161
+ collections: [],
2162
+ });
1792
2163
  }
1793
2164
  }
1794
- // Second pass: collect properties and collections for each class
1795
2165
  for (const r of results) {
1796
- if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {
1797
- // Match shape source to class (e.g., "recipe://RecipeShape" -> "Recipe")
2166
+ if (r.predicate === "sh://property" ||
2167
+ r.predicate === "sh://collection") {
1798
2168
  for (const [className, shape] of classShapes) {
1799
2169
  if (r.shape_source.endsWith(`${className}Shape`)) {
1800
- const dotIdx = r.target.lastIndexOf('.');
2170
+ const dotIdx = r.target.lastIndexOf(".");
1801
2171
  if (dotIdx < 0)
1802
2172
  continue;
1803
2173
  const name = r.target.substring(dotIdx + 1);
1804
- if (r.predicate === 'sh://property') {
2174
+ if (r.predicate === "sh://property") {
1805
2175
  shape.properties.push(name);
1806
2176
  }
1807
2177
  else {
@@ -1811,13 +2181,11 @@ export class PerspectiveProxy {
1811
2181
  }
1812
2182
  }
1813
2183
  }
1814
- // Find a class that has all required properties and collections
1815
2184
  for (const [className, shape] of classShapes) {
1816
- const hasAllProps = properties.every(p => shape.properties.includes(p));
1817
- const hasAllCols = collections.every(c => shape.collections.includes(c));
1818
- if (hasAllProps && hasAllCols) {
2185
+ const hasAllProps = properties.every((p) => shape.properties.includes(p));
2186
+ const hasAllCols = collections.every((c) => shape.collections.includes(c));
2187
+ if (hasAllProps && hasAllCols)
1819
2188
  return className;
1820
- }
1821
2189
  }
1822
2190
  return null;
1823
2191
  }
@@ -1833,20 +2201,21 @@ export class PerspectiveProxy {
1833
2201
  * @param obj The template object
1834
2202
  */
1835
2203
  async subjectClassesByTemplate(obj) {
1836
- // SHACL-based lookup: try property matching first (more precise), fall back to className
2204
+ // Try property-shape matching first (more precise)
1837
2205
  try {
1838
2206
  const match = await this.findClassByProperties(obj);
1839
- if (match) {
2207
+ if (match)
1840
2208
  return [match];
1841
- }
1842
2209
  }
1843
2210
  catch (e) {
1844
- console.warn('subjectClassesByTemplate: property matching failed:', e);
2211
+ console.warn("subjectClassesByTemplate: property matching failed:", e);
1845
2212
  }
1846
- // Fall back to className lookup
2213
+ // Fall back to className lookup against live SHACL links
1847
2214
  try {
1848
- // @ts-ignore - className is added dynamically by decorators
1849
- const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;
2215
+ const o = obj;
2216
+ const className = o.className ||
2217
+ o.constructor?.className ||
2218
+ o.constructor?.prototype?.className;
1850
2219
  if (className) {
1851
2220
  const existingClasses = await this.subjectClasses();
1852
2221
  if (existingClasses.includes(className)) {
@@ -1855,7 +2224,7 @@ export class PerspectiveProxy {
1855
2224
  }
1856
2225
  }
1857
2226
  catch (e) {
1858
- console.warn('subjectClassesByTemplate: className lookup failed:', e);
2227
+ console.warn("subjectClassesByTemplate: className lookup failed:", e);
1859
2228
  }
1860
2229
  return [];
1861
2230
  }
@@ -1875,14 +2244,33 @@ export class PerspectiveProxy {
1875
2244
  }
1876
2245
  // Get SHACL shape (W3C standard + AD4M action definitions)
1877
2246
  const { shape } = jsClass.generateSHACL();
1878
- // Serialize SHACL shape to JSON for Rust backend using SHACLShape.toJSON()
1879
- const shaclJson = JSON.stringify(shape.toJSON());
2247
+ // Serialize SHACL shape to JSON for Rust backend
2248
+ const shaclJson = JSON.stringify({
2249
+ target_class: shape.targetClass,
2250
+ constructor_actions: shape.constructor_actions,
2251
+ destructor_actions: shape.destructor_actions,
2252
+ properties: shape.properties.map((p) => ({
2253
+ path: p.path,
2254
+ name: p.name,
2255
+ datatype: p.datatype,
2256
+ min_count: p.minCount,
2257
+ max_count: p.maxCount,
2258
+ read_only: p.readOnly,
2259
+ local: p.local,
2260
+ resolve_language: p.resolveLanguage,
2261
+ node_kind: p.nodeKind,
2262
+ collection: p.collection,
2263
+ setter: p.setter,
2264
+ adder: p.adder,
2265
+ remover: p.remover,
2266
+ })),
2267
+ });
1880
2268
  // Pass SHACL JSON to backend (Prolog-free)
1881
2269
  // Backend stores SHACL links directly
1882
- await this.addSdna(className, '', 'subject_class', shaclJson);
2270
+ await this.addSdna(className, "", "subject_class", shaclJson);
1883
2271
  }
1884
2272
  getNeighbourhoodProxy() {
1885
- return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
2273
+ return this._client.getNeighbourhoodProxy(this._handle.uuid);
1886
2274
  }
1887
2275
  /**
1888
2276
  * Returns a proxy object for working with AI capabilities.
@@ -1899,7 +2287,7 @@ export class PerspectiveProxy {
1899
2287
  * ```
1900
2288
  */
1901
2289
  get ai() {
1902
- return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").aiClient;
2290
+ return this._client.aiClient;
1903
2291
  }
1904
2292
  /**
1905
2293
  * Creates a subscription for a Prolog query that updates in real-time.
@@ -1941,35 +2329,7 @@ export class PerspectiveProxy {
1941
2329
  * ```
1942
2330
  */
1943
2331
  async subscribeInfer(query) {
1944
- const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
1945
- // Start the subscription on the Rust side first to get the real subscription ID
1946
- await subscriptionProxy.subscribe();
1947
- // Wait for the initial result
1948
- await subscriptionProxy.initialized;
1949
- return subscriptionProxy;
1950
- }
1951
- /**
1952
- * Creates a subscription for a SurrealQL query that updates in real-time.
1953
- *
1954
- * This method:
1955
- * 1. Creates the subscription on the Rust side
1956
- * 2. Sets up the subscription callback
1957
- * 3. Waits for the initial result to come through the subscription channel
1958
- * 4. Returns a fully initialized QuerySubscriptionProxy
1959
- *
1960
- * The returned subscription is guaranteed to be ready to receive updates,
1961
- * as this method waits for the initialization process to complete.
1962
- *
1963
- * The subscription will be automatically cleaned up on both frontend and backend
1964
- * when dispose() is called. Make sure to call dispose() when you're done to
1965
- * prevent memory leaks and ensure proper cleanup of resources.
1966
- *
1967
- * @param query - SurrealQL query string
1968
- * @returns Initialized QuerySubscriptionProxy instance
1969
- */
1970
- async subscribeSurrealDB(query) {
1971
- const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
1972
- subscriptionProxy.isSurrealDB = true;
2332
+ const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, this._client);
1973
2333
  // Start the subscription on the Rust side first to get the real subscription ID
1974
2334
  await subscriptionProxy.subscribe();
1975
2335
  // Wait for the initial result
@@ -1977,4 +2337,3 @@ export class PerspectiveProxy {
1977
2337
  return subscriptionProxy;
1978
2338
  }
1979
2339
  }
1980
- _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();