@coasys/ad4m 0.13.0-test-6 → 0.13.0-test-8

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 (279) hide show
  1. package/lib/index.cjs +1103 -747
  2. package/lib/index.js +1090 -747
  3. package/lib/src/Ad4mClient.d.ts +4 -1
  4. package/lib/src/Ad4mClient.js +2 -2
  5. package/lib/src/agent/AgentClient.js +17 -0
  6. package/lib/src/ai/AIClient.js +1 -1
  7. package/lib/src/apiClient.d.ts +5 -1
  8. package/lib/src/apiClient.js +14 -6
  9. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +7 -0
  10. package/lib/src/generated/rest/AIModelLoadingStatus.js +2 -0
  11. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +3 -0
  12. package/lib/src/generated/rest/AddAgentInfosRequest.js +2 -0
  13. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +6 -0
  14. package/lib/src/generated/rest/AddLinkExpressionRequest.js +1 -0
  15. package/lib/src/generated/rest/AddLinkRequest.d.ts +6 -0
  16. package/lib/src/generated/rest/AddLinkRequest.js +1 -0
  17. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +6 -0
  18. package/lib/src/generated/rest/AddLinksBulkRequest.js +1 -0
  19. package/lib/src/generated/rest/AddSdnaRequest.d.ts +6 -0
  20. package/lib/src/generated/rest/AddSdnaRequest.js +2 -0
  21. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +4 -0
  22. package/lib/src/generated/rest/ApplyTemplateRequest.js +2 -0
  23. package/lib/src/generated/rest/AuthInfoInput.d.ts +10 -0
  24. package/lib/src/generated/rest/AuthInfoInput.js +1 -0
  25. package/lib/src/generated/rest/BroadcastRequest.d.ts +6 -0
  26. package/lib/src/generated/rest/BroadcastRequest.js +1 -0
  27. package/lib/src/generated/rest/CapabilityInput.d.ts +5 -0
  28. package/lib/src/generated/rest/CapabilityInput.js +1 -0
  29. package/lib/src/generated/rest/CommitBatchRequest.d.ts +3 -0
  30. package/lib/src/generated/rest/CommitBatchRequest.js +2 -0
  31. package/lib/src/generated/rest/ComputeLogEntry.d.ts +9 -0
  32. package/lib/src/generated/rest/ComputeLogEntry.js +2 -0
  33. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +4 -0
  34. package/lib/src/generated/rest/CreateExpressionRequest.js +2 -0
  35. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +3 -0
  36. package/lib/src/generated/rest/CreatePerspectiveRequest.js +2 -0
  37. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +6 -0
  38. package/lib/src/generated/rest/CreateSubjectRequest.js +2 -0
  39. package/lib/src/generated/rest/CreateUserRequest.d.ts +4 -0
  40. package/lib/src/generated/rest/CreateUserRequest.js +2 -0
  41. package/lib/src/generated/rest/CreateUserResponse.d.ts +5 -0
  42. package/lib/src/generated/rest/CreateUserResponse.js +2 -0
  43. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +6 -0
  44. package/lib/src/generated/rest/DecoratedExpressionProof.js +2 -0
  45. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +10 -0
  46. package/lib/src/generated/rest/DecoratedLinkExpression.js +1 -0
  47. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +3 -0
  48. package/lib/src/generated/rest/DisposeQueryRequest.js +2 -0
  49. package/lib/src/generated/rest/EmailTestRequest.d.ts +6 -0
  50. package/lib/src/generated/rest/EmailTestRequest.js +2 -0
  51. package/lib/src/generated/rest/EmbedRequest.d.ts +4 -0
  52. package/lib/src/generated/rest/EmbedRequest.js +2 -0
  53. package/lib/src/generated/rest/EntanglementProofInput.d.ts +6 -0
  54. package/lib/src/generated/rest/EntanglementProofInput.js +2 -0
  55. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +4 -0
  56. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +2 -0
  57. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +4 -0
  58. package/lib/src/generated/rest/ExecuteCommandsRequest.js +2 -0
  59. package/lib/src/generated/rest/ExportRequest.d.ts +5 -0
  60. package/lib/src/generated/rest/ExportRequest.js +2 -0
  61. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +3 -0
  62. package/lib/src/generated/rest/ExpressionManyRequest.js +2 -0
  63. package/lib/src/generated/rest/ExpressionProof.d.ts +4 -0
  64. package/lib/src/generated/rest/ExpressionProof.js +2 -0
  65. package/lib/src/generated/rest/ExpressionProofInput.d.ts +6 -0
  66. package/lib/src/generated/rest/ExpressionProofInput.js +2 -0
  67. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +3 -0
  68. package/lib/src/generated/rest/FriendSendMessageRequest.js +2 -0
  69. package/lib/src/generated/rest/FriendsListRequest.d.ts +3 -0
  70. package/lib/src/generated/rest/FriendsListRequest.js +2 -0
  71. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +3 -0
  72. package/lib/src/generated/rest/GenerateAgentRequest.js +2 -0
  73. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +4 -0
  74. package/lib/src/generated/rest/GenerateJwtRequest.js +2 -0
  75. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +4 -0
  76. package/lib/src/generated/rest/GetSubjectDataRequest.js +2 -0
  77. package/lib/src/generated/rest/HostingInfoResponse.d.ts +5 -0
  78. package/lib/src/generated/rest/HostingInfoResponse.js +2 -0
  79. package/lib/src/generated/rest/HostingWalletResponse.d.ts +4 -0
  80. package/lib/src/generated/rest/HostingWalletResponse.js +2 -0
  81. package/lib/src/generated/rest/ImportAgentRequest.d.ts +6 -0
  82. package/lib/src/generated/rest/ImportAgentRequest.js +2 -0
  83. package/lib/src/generated/rest/ImportRequest.d.ts +4 -0
  84. package/lib/src/generated/rest/ImportRequest.js +2 -0
  85. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +3 -0
  86. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +2 -0
  87. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +3 -0
  88. package/lib/src/generated/rest/KeepAliveQueryRequest.js +2 -0
  89. package/lib/src/generated/rest/LanguageMetaInput.d.ts +6 -0
  90. package/lib/src/generated/rest/LanguageMetaInput.js +2 -0
  91. package/lib/src/generated/rest/Link.d.ts +5 -0
  92. package/lib/src/generated/rest/Link.js +2 -0
  93. package/lib/src/generated/rest/LinkExpression.d.ts +10 -0
  94. package/lib/src/generated/rest/LinkExpression.js +1 -0
  95. package/lib/src/generated/rest/LinkExpressionInput.d.ts +10 -0
  96. package/lib/src/generated/rest/LinkExpressionInput.js +1 -0
  97. package/lib/src/generated/rest/LinkInput.d.ts +5 -0
  98. package/lib/src/generated/rest/LinkInput.js +2 -0
  99. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +3 -0
  100. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +2 -0
  101. package/lib/src/generated/rest/LinkMutationRequest.d.ts +12 -0
  102. package/lib/src/generated/rest/LinkMutationRequest.js +1 -0
  103. package/lib/src/generated/rest/LinkMutationResponse.d.ts +9 -0
  104. package/lib/src/generated/rest/LinkMutationResponse.js +1 -0
  105. package/lib/src/generated/rest/LinkMutations.d.ts +6 -0
  106. package/lib/src/generated/rest/LinkMutations.js +1 -0
  107. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +5 -0
  108. package/lib/src/generated/rest/LinkMutationsRequest.js +1 -0
  109. package/lib/src/generated/rest/LinkStatus.d.ts +1 -0
  110. package/lib/src/generated/rest/LinkStatus.js +2 -0
  111. package/lib/src/generated/rest/LinkUpdateInput.d.ts +5 -0
  112. package/lib/src/generated/rest/LinkUpdateInput.js +1 -0
  113. package/lib/src/generated/rest/LockAgentRequest.d.ts +3 -0
  114. package/lib/src/generated/rest/LockAgentRequest.js +2 -0
  115. package/lib/src/generated/rest/LoginUserRequest.d.ts +5 -0
  116. package/lib/src/generated/rest/LoginUserRequest.js +2 -0
  117. package/lib/src/generated/rest/ModelType.d.ts +1 -0
  118. package/lib/src/generated/rest/ModelType.js +2 -0
  119. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +3 -0
  120. package/lib/src/generated/rest/NotificationGrantRequest.js +2 -0
  121. package/lib/src/generated/rest/NotificationInput.d.ts +10 -0
  122. package/lib/src/generated/rest/NotificationInput.js +2 -0
  123. package/lib/src/generated/rest/OpenLinkRequest.d.ts +3 -0
  124. package/lib/src/generated/rest/OpenLinkRequest.js +2 -0
  125. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +3 -0
  126. package/lib/src/generated/rest/PermitCapabilityRequest.js +2 -0
  127. package/lib/src/generated/rest/PerspectiveInput.d.ts +4 -0
  128. package/lib/src/generated/rest/PerspectiveInput.js +1 -0
  129. package/lib/src/generated/rest/PromptRequest.d.ts +4 -0
  130. package/lib/src/generated/rest/PromptRequest.js +2 -0
  131. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +4 -0
  132. package/lib/src/generated/rest/PublicPerspectiveInput.js +1 -0
  133. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +5 -0
  134. package/lib/src/generated/rest/PublishLanguageRequest.js +1 -0
  135. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +6 -0
  136. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +1 -0
  137. package/lib/src/generated/rest/QueryRequest.d.ts +7 -0
  138. package/lib/src/generated/rest/QueryRequest.js +2 -0
  139. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +5 -0
  140. package/lib/src/generated/rest/RemoveLinkRequest.js +1 -0
  141. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +5 -0
  142. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +1 -0
  143. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +4 -0
  144. package/lib/src/generated/rest/RequestCapabilityRequest.js +1 -0
  145. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +3 -0
  146. package/lib/src/generated/rest/RequestPaymentRequest.js +2 -0
  147. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +4 -0
  148. package/lib/src/generated/rest/RequestVerificationRequest.js +2 -0
  149. package/lib/src/generated/rest/ResourceInput.d.ts +4 -0
  150. package/lib/src/generated/rest/ResourceInput.js +2 -0
  151. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +4 -0
  152. package/lib/src/generated/rest/SetDefaultModelRequest.js +1 -0
  153. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +3 -0
  154. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +2 -0
  155. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +3 -0
  156. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +2 -0
  157. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +3 -0
  158. package/lib/src/generated/rest/SetMultiUserRequest.js +2 -0
  159. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +5 -0
  160. package/lib/src/generated/rest/SetOnlineStatusRequest.js +1 -0
  161. package/lib/src/generated/rest/SetStatusRequest.d.ts +3 -0
  162. package/lib/src/generated/rest/SetStatusRequest.js +2 -0
  163. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +4 -0
  164. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +2 -0
  165. package/lib/src/generated/rest/SignMessageRequest.d.ts +3 -0
  166. package/lib/src/generated/rest/SignMessageRequest.js +2 -0
  167. package/lib/src/generated/rest/SignalRequest.d.ts +6 -0
  168. package/lib/src/generated/rest/SignalRequest.js +1 -0
  169. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +3 -0
  170. package/lib/src/generated/rest/SubscribeQueryRequest.js +2 -0
  171. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +4 -0
  172. package/lib/src/generated/rest/SubscribeQueryResponse.js +2 -0
  173. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +3 -0
  174. package/lib/src/generated/rest/TrustedAgentsRequest.js +2 -0
  175. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +4 -0
  176. package/lib/src/generated/rest/UnlockAgentRequest.js +2 -0
  177. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +7 -0
  178. package/lib/src/generated/rest/UpdateLinkRequest.js +1 -0
  179. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +3 -0
  180. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +2 -0
  181. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +5 -0
  182. package/lib/src/generated/rest/UpdateProfileRequest.js +1 -0
  183. package/lib/src/generated/rest/UserStatistics.d.ts +9 -0
  184. package/lib/src/generated/rest/UserStatistics.js +2 -0
  185. package/lib/src/generated/rest/VerificationRequestResult.d.ts +6 -0
  186. package/lib/src/generated/rest/VerificationRequestResult.js +2 -0
  187. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +6 -0
  188. package/lib/src/generated/rest/VerifyEmailRequest.js +2 -0
  189. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +5 -0
  190. package/lib/src/generated/rest/VerifySignatureRequest.js +2 -0
  191. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +3 -0
  192. package/lib/src/generated/rest/WriteSettingsRequest.js +2 -0
  193. package/lib/src/generated/rest/index.d.ts +73 -0
  194. package/lib/src/generated/rest/index.js +8 -0
  195. package/lib/src/generated/rest/routes.d.ts +587 -0
  196. package/lib/src/generated/rest/routes.js +3 -0
  197. package/lib/src/index.d.ts +4 -0
  198. package/lib/src/index.js +4 -0
  199. package/lib/src/model/Ad4mModel.d.ts +30 -21
  200. package/lib/src/model/Ad4mModel.js +93 -316
  201. package/lib/src/model/Ad4mModel.test.js +1536 -535
  202. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  203. package/lib/src/model/ModelQueryBuilder.js +136 -47
  204. package/lib/src/model/Subject.js +6 -6
  205. package/lib/src/model/decorators.d.ts +7 -4
  206. package/lib/src/model/decorators.js +0 -7
  207. package/lib/src/model/hydration-batch.d.ts +34 -0
  208. package/lib/src/model/hydration-batch.js +147 -0
  209. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  210. package/lib/src/model/hydration-batching.test.js +456 -0
  211. package/lib/src/model/query-cache.test.d.ts +1 -0
  212. package/lib/src/model/query-cache.test.js +43 -0
  213. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  214. package/lib/src/model/query-sparql-batch.js +260 -0
  215. package/lib/src/model/query-sparql.d.ts +0 -10
  216. package/lib/src/model/query-sparql.js +10 -15
  217. package/lib/src/model/query-sparql.test.d.ts +1 -0
  218. package/lib/src/model/query-sparql.test.js +230 -0
  219. package/lib/src/model/relation-filtering.test.js +15 -15
  220. package/lib/src/model/shacl-gen.js +120 -47
  221. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  222. package/lib/src/model/subscription-delta.test.js +180 -0
  223. package/lib/src/model/subscription-pool.d.ts +39 -0
  224. package/lib/src/model/subscription-pool.js +165 -0
  225. package/lib/src/model/types.d.ts +140 -4
  226. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  227. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -4
  228. package/lib/src/perspectives/PerspectiveClient.js +22 -6
  229. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  230. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  231. package/lib/src/perspectives/PerspectiveProxy.d.ts +27 -7
  232. package/lib/src/perspectives/PerspectiveProxy.js +60 -12
  233. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +1 -0
  234. package/lib/src/perspectives/PerspectiveProxy.test.js +34 -0
  235. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  236. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  237. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  238. package/lib/src/perspectives/SparqlBindings.js +65 -0
  239. package/lib/src/perspectives/WakerSubscriptionManager.js +5 -4
  240. package/lib/src/restClient.d.ts +52 -0
  241. package/lib/src/restClient.js +227 -0
  242. package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
  243. package/lib/src/runtime/RuntimeResolver.js +197 -4
  244. package/lib/src/schema.gql +27 -1
  245. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  246. package/lib/src/shacl/NodeExpression.js +39 -0
  247. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  248. package/lib/src/shacl/SHACLShape.js +115 -1
  249. package/lib/src/shacl/builders.d.ts +58 -0
  250. package/lib/src/shacl/builders.js +76 -0
  251. package/lib/src/shacl/index.d.ts +36 -0
  252. package/lib/src/shacl/index.js +33 -0
  253. package/package.json +1 -1
  254. package/src/Ad4mClient.ts +7 -2
  255. package/src/agent/AgentClient.ts +23 -0
  256. package/src/ai/AIClient.ts +1 -1
  257. package/src/apiClient.ts +17 -6
  258. package/src/index.ts +4 -0
  259. package/src/model/Ad4mModel.test.ts +274 -72
  260. package/src/model/Ad4mModel.ts +141 -350
  261. package/src/model/ModelQueryBuilder.ts +131 -56
  262. package/src/model/decorators.ts +7 -13
  263. package/src/model/query-sparql.test.ts +35 -19
  264. package/src/model/query-sparql.ts +10 -16
  265. package/src/model/relation-filtering.test.ts +46 -39
  266. package/src/model/shacl-gen.ts +128 -54
  267. package/src/model/shacl-roundtrip.test.ts +197 -0
  268. package/src/model/types-typed-query.test.ts +360 -0
  269. package/src/model/types.ts +196 -4
  270. package/src/perspectives/PerspectiveClient.ts +24 -8
  271. package/src/perspectives/PerspectiveProxy.test.ts +85 -1
  272. package/src/perspectives/PerspectiveProxy.ts +65 -20
  273. package/src/perspectives/SparqlBindings.ts +79 -0
  274. package/src/perspectives/WakerSubscriptionManager.ts +5 -4
  275. package/src/shacl/NodeExpression.ts +54 -0
  276. package/src/shacl/SHACLShape.test.ts +172 -0
  277. package/src/shacl/SHACLShape.ts +173 -1
  278. package/src/shacl/builders.ts +86 -0
  279. package/src/shacl/index.ts +72 -0
package/lib/index.cjs CHANGED
@@ -23,7 +23,7 @@ function nextId() {
23
23
  return String(++_idCounter);
24
24
  }
25
25
  class ApiClient {
26
- constructor(baseUrl, token) {
26
+ constructor(baseUrl, token, webSocketImpl, fetchImpl) {
27
27
  // ── WebSocket RPC core ──────────────────────────────────────────────────
28
28
  this._ws = null;
29
29
  this._wsCallbacks = new Set();
@@ -36,9 +36,15 @@ class ApiClient {
36
36
  this._wsPingTimer = null;
37
37
  this.baseUrl = baseUrl;
38
38
  this.token = token;
39
+ this._webSocketImpl = webSocketImpl;
40
+ this._fetchImpl = fetchImpl;
39
41
  }
40
42
  getBaseUrl() { return this.baseUrl; }
41
43
  getToken() { return this.token; }
44
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
45
+ doFetch(url, init) {
46
+ return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init);
47
+ }
42
48
  setToken(token) {
43
49
  this.token = token;
44
50
  }
@@ -51,7 +57,7 @@ class ApiClient {
51
57
  return tokenParam ? `${wsBase}${path}?${tokenParam}` : `${wsBase}${path}`;
52
58
  }
53
59
  _ensureWs() {
54
- if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) {
60
+ if (this._ws && (this._ws.readyState === 1 /* OPEN */ || this._ws.readyState === 0 /* CONNECTING */)) {
55
61
  return;
56
62
  }
57
63
  // Prevent duplicate connections from concurrent callers
@@ -62,7 +68,8 @@ class ApiClient {
62
68
  this._wsReadyResolve = resolve;
63
69
  });
64
70
  const url = this._getWsUrl();
65
- const ws = new WebSocket(url);
71
+ const WsImpl = this._webSocketImpl ?? WebSocket;
72
+ const ws = new WsImpl(url);
66
73
  this._ws = ws;
67
74
  ws.onopen = () => {
68
75
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
@@ -112,12 +119,13 @@ class ApiClient {
112
119
  // Reset the readiness promise so future calls reconnect
113
120
  this._wsReady = null;
114
121
  // Reject all pending calls
122
+ const hadPendingCalls = this._pendingCalls.size > 0;
115
123
  for (const [id, pending] of this._pendingCalls) {
116
124
  clearTimeout(pending.timer);
117
125
  pending.reject(new RpcError(503, 'WebSocket connection closed'));
118
126
  }
119
127
  this._pendingCalls.clear();
120
- if (!this._wsClosed && (this._wsCallbacks.size > 0 || this._pendingCalls.size > 0)) {
128
+ if (!this._wsClosed && (this._wsCallbacks.size > 0 || hadPendingCalls)) {
121
129
  this._scheduleReconnect();
122
130
  }
123
131
  };
@@ -125,7 +133,7 @@ class ApiClient {
125
133
  _startPing() {
126
134
  this._stopPing();
127
135
  this._wsPingTimer = setInterval(() => {
128
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
136
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
129
137
  this._ws.send(JSON.stringify({ type: 'ping' }));
130
138
  }
131
139
  }, 30000);
@@ -178,7 +186,7 @@ class ApiClient {
178
186
  reject,
179
187
  timer,
180
188
  });
181
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
189
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
182
190
  this._ws.send(JSON.stringify(message));
183
191
  }
184
192
  else {
@@ -955,6 +963,46 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
955
963
  };
956
964
  }
957
965
 
966
+ /**
967
+ * SHACL-AF Node Expressions for property transforms.
968
+ *
969
+ * A `NodeExpression` is a JSON-serializable tree that describes how to transform
970
+ * a resolved property value. Unlike JS lambdas, these are portable, inspectable,
971
+ * and can be executed in the Rust model query engine.
972
+ *
973
+ * Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
974
+ */
975
+ /**
976
+ * Type guard to check if a value is a valid NodeExpression.
977
+ */
978
+ function isNodeExpression(v) {
979
+ if (typeof v !== 'object' || v === null)
980
+ return false;
981
+ const obj = v;
982
+ const type = obj.type;
983
+ switch (type) {
984
+ case 'focus':
985
+ return typeof obj.type === 'string';
986
+ case 'literal':
987
+ return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
988
+ case 'path':
989
+ return typeof obj.predicate === 'string';
990
+ case 'exists':
991
+ return isNodeExpression(obj.expr);
992
+ case 'if':
993
+ return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
994
+ (obj.else === undefined || isNodeExpression(obj.else));
995
+ case 'concat':
996
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
997
+ case 'coalesce':
998
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
999
+ case 'function':
1000
+ return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
1001
+ default:
1002
+ return false;
1003
+ }
1004
+ }
1005
+
958
1006
  /**
959
1007
  * Extract namespace from a URI
960
1008
  * Examples:
@@ -1285,7 +1333,7 @@ class SHACLShape {
1285
1333
  target: `literal:${prop.writable}`
1286
1334
  });
1287
1335
  }
1288
- if (prop.resolveLanguage) {
1336
+ if (prop.resolveLanguage != null) {
1289
1337
  links.push({
1290
1338
  source: propShapeId,
1291
1339
  predicate: "ad4m://resolveLanguage",
@@ -1342,6 +1390,48 @@ class SHACLShape {
1342
1390
  target: `literal:string:${JSON.stringify(prop.in)}`
1343
1391
  });
1344
1392
  }
1393
+ if (prop.relationKind) {
1394
+ links.push({
1395
+ source: propShapeId,
1396
+ predicate: "ad4m://relationKind",
1397
+ target: `literal:string:${prop.relationKind}`
1398
+ });
1399
+ }
1400
+ if (prop.targetClassName) {
1401
+ links.push({
1402
+ source: propShapeId,
1403
+ predicate: "ad4m://targetClassName",
1404
+ target: `literal:string:${prop.targetClassName}`
1405
+ });
1406
+ }
1407
+ if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
1408
+ links.push({
1409
+ source: propShapeId,
1410
+ predicate: "ad4m://whereFilter",
1411
+ target: `literal:string:${JSON.stringify(prop.whereFilter)}`
1412
+ });
1413
+ }
1414
+ if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
1415
+ links.push({
1416
+ source: propShapeId,
1417
+ predicate: "ad4m://wherePredicates",
1418
+ target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
1419
+ });
1420
+ }
1421
+ if (prop.filter !== undefined) {
1422
+ links.push({
1423
+ source: propShapeId,
1424
+ predicate: "ad4m://filter",
1425
+ target: `literal:${prop.filter}`
1426
+ });
1427
+ }
1428
+ if (prop.transform && typeof prop.transform === 'object') {
1429
+ links.push({
1430
+ source: propShapeId,
1431
+ predicate: "ad4m://transform",
1432
+ target: `literal:string:${JSON.stringify(prop.transform)}`
1433
+ });
1434
+ }
1345
1435
  }
1346
1436
  return links;
1347
1437
  }
@@ -1523,6 +1613,60 @@ class SHACLShape {
1523
1613
  // Ignore parse errors
1524
1614
  }
1525
1615
  }
1616
+ const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
1617
+ if (relationKindLink) {
1618
+ const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1619
+ if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
1620
+ prop.relationKind = val;
1621
+ }
1622
+ }
1623
+ const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
1624
+ if (targetClassNameLink) {
1625
+ prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1626
+ }
1627
+ const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
1628
+ if (whereFilterLink) {
1629
+ try {
1630
+ const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1631
+ prop.whereFilter = JSON.parse(jsonStr);
1632
+ }
1633
+ catch (e) {
1634
+ // Ignore parse errors
1635
+ }
1636
+ }
1637
+ const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
1638
+ if (wherePredicatesLink) {
1639
+ try {
1640
+ const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1641
+ prop.wherePredicates = JSON.parse(jsonStr);
1642
+ }
1643
+ catch (e) {
1644
+ // Ignore parse errors
1645
+ }
1646
+ }
1647
+ const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
1648
+ if (filterLink) {
1649
+ let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
1650
+ if (val.startsWith('boolean:'))
1651
+ val = val.substring(8);
1652
+ prop.filter = val === 'true';
1653
+ }
1654
+ const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
1655
+ if (transformLink) {
1656
+ const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1657
+ try {
1658
+ const parsed = JSON.parse(jsonStr);
1659
+ if (!isNodeExpression(parsed)) {
1660
+ throw new Error(`Invalid transform for property ${propShapeId}: ` +
1661
+ `payload is not a valid NodeExpression. Received: ${jsonStr}`);
1662
+ }
1663
+ prop.transform = parsed;
1664
+ }
1665
+ catch (e) {
1666
+ throw new Error(`Failed to deserialize transform for property ${propShapeId}: ` +
1667
+ `${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`);
1668
+ }
1669
+ }
1526
1670
  shape.addProperty(prop);
1527
1671
  }
1528
1672
  return shape;
@@ -1559,6 +1703,12 @@ class SHACLShape {
1559
1703
  conformance_conditions: p.conformanceConditions,
1560
1704
  class: p.class,
1561
1705
  in: p.in,
1706
+ relation_kind: p.relationKind,
1707
+ target_class_name: p.targetClassName,
1708
+ where_filter: p.whereFilter,
1709
+ where_predicates: p.wherePredicates,
1710
+ filter: p.filter,
1711
+ transform: p.transform,
1562
1712
  })),
1563
1713
  constructor_actions: this.constructor_actions,
1564
1714
  destructor_actions: this.destructor_actions,
@@ -1572,6 +1722,11 @@ class SHACLShape {
1572
1722
  ? new SHACLShape(json.node_shape_uri, json.target_class)
1573
1723
  : new SHACLShape(json.target_class);
1574
1724
  for (const p of json.properties || []) {
1725
+ // Validate transform if present
1726
+ if (p.transform && !isNodeExpression(p.transform)) {
1727
+ throw new Error(`Invalid transform for property ${p.name}: ` +
1728
+ `payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`);
1729
+ }
1575
1730
  shape.addProperty({
1576
1731
  path: p.path,
1577
1732
  name: p.name,
@@ -1593,6 +1748,12 @@ class SHACLShape {
1593
1748
  conformanceConditions: p.conformance_conditions,
1594
1749
  class: p.class,
1595
1750
  in: p.in,
1751
+ relationKind: p.relation_kind,
1752
+ targetClassName: p.target_class_name,
1753
+ whereFilter: p.where_filter,
1754
+ wherePredicates: p.where_predicates,
1755
+ filter: p.filter,
1756
+ transform: p.transform,
1596
1757
  });
1597
1758
  }
1598
1759
  if (json.constructor_actions) {
@@ -1610,303 +1771,61 @@ class SHACLShape {
1610
1771
  }
1611
1772
  }
1612
1773
 
1613
- function formatList(list) {
1614
- if (!list?.length) {
1615
- return "";
1616
- }
1617
- if (list.length === 1) {
1618
- return list.toString();
1619
- }
1620
- if (list.length === 2) {
1621
- return list.join(' and ');
1622
- }
1623
- return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
1624
- }
1625
- function capSentence(cap) {
1626
- const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
1627
- const domain = cap.with.domain === "*" ? "" : cap.with.domain;
1628
- const pointers = cap.with.pointers.includes("*")
1629
- ? ["all AD4M data"]
1630
- : cap.with.pointers;
1631
- return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
1632
- }
1633
- /**
1634
- * Escapes a string value for safe use in query strings.
1635
- *
1636
- * @description
1637
- * Prevents SQL injection by properly escaping special characters in string values
1638
- * that will be interpolated into query strings. This handles the most common
1639
- * special characters that could break SQL queries or enable injection attacks.
1640
- *
1641
- * Single quotes, backslashes, and other special characters are escaped using
1642
- * backslash notation, which is the standard escaping mechanism for query.
1643
- *
1644
- * @param value - The string value to escape
1645
- * @returns The escaped string safe for query interpolation (without surrounding quotes)
1646
- *
1647
- * @example
1648
- * ```typescript
1649
- * const userInput = "user's input with 'quotes'";
1650
- * const escaped = escapeQueryString(userInput);
1651
- * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
1652
- * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
1653
- * ```
1654
- */
1655
- function escapeQueryString(value) {
1656
- return value
1657
- .replace(/\\/g, '\\\\') // Backslash -> \\
1658
- .replace(/'/g, "\\'") // Single quote -> \'
1659
- .replace(/"/g, '\\"') // Double quote -> \"
1660
- .replace(/\n/g, '\\n') // Newline -> \n
1661
- .replace(/\r/g, '\\r') // Carriage return -> \r
1662
- .replace(/\t/g, '\\t'); // Tab -> \t
1663
- }
1664
-
1665
- /**
1666
- * Shared query compilation utilities.
1667
- *
1668
- * These functions are used by both the runtime query builder (`Ad4mModel`) and
1669
- * the compile-time SHACL generator (`decorators.ts`).
1670
- *
1671
- * All output uses native SPARQL syntax.
1672
- */
1673
1774
  /**
1674
- * Format a JavaScript value for embedding in a query expression.
1775
+ * SHACL shape generation for AD4M model classes.
1675
1776
  *
1676
- * - Strings are single-quoted with backslash / quote / newline escaping
1677
- * - Numbers and booleans are passed through as-is
1678
- * - Arrays are recursed
1777
+ * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
1778
+ * from a model's property and relation metadata. The heavy lifting used
1779
+ * to live inside the `@Model` decorator closure — it is extracted here so
1780
+ * decorators.ts stays focused on decorator registration logic.
1679
1781
  */
1680
- function formatQueryValue(value) {
1681
- if (typeof value === 'string') {
1682
- // Escape backslashes first, then single quotes and other special characters
1683
- const escaped = value
1684
- .replace(/\\/g, '\\\\') // Backslash -> \\
1685
- .replace(/'/g, "\\'") // Single quote -> \'
1686
- .replace(/"/g, '\\"') // Double quote -> \"
1687
- .replace(/\n/g, '\\n') // Newline -> \n
1688
- .replace(/\r/g, '\\r') // Carriage return -> \r
1689
- .replace(/\t/g, '\\t'); // Tab -> \t
1690
- return `'${escaped}'`;
1691
- }
1692
- else if (typeof value === 'number' || typeof value === 'boolean') {
1693
- return String(value);
1694
- }
1695
- else if (Array.isArray(value)) {
1696
- return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
1697
- }
1698
- else {
1699
- return String(value);
1700
- }
1701
- }
1702
1782
  /**
1703
- * Compile a single Where condition for a property into a SPARQL triple pattern
1704
- * that can be embedded in a getter's WHERE clause.
1705
- *
1706
- * The generated pattern operates on `?target` — e.g.:
1707
- * `?target <pred> <value> .`
1708
- * `FILTER EXISTS { ?target <pred> ?_v0 }`
1783
+ * Build a SHACL shape for a model class.
1709
1784
  *
1710
- * @param predicate - The predicate URI for the property
1711
- * @param condition - The Where condition value
1712
- * @param opts - Optional settings (e.g. `resolveLanguage`)
1713
- * @returns A single SPARQL condition string
1785
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
1786
+ * @param target - The class constructor (used for prototype access,
1787
+ * inheritance chain, and relation target resolution)
1788
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
1789
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
1790
+ * @param conformanceFilterFn - Injected conformance-filter builder
1791
+ * (avoids circular dependency back into decorators.ts)
1714
1792
  */
1715
- function buildWhereCondition(predicate, condition, opts) {
1716
- const escapedPredicate = escapeQueryString(predicate);
1717
- // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
1718
- // For language-resolved properties, we match against the plain URI
1719
- // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
1720
- // For language-resolved properties, values are plain URIs
1721
- const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
1722
- const varSuffix = opts?.varIndex ?? 0;
1723
- function formatValue(v) {
1724
- if (typeof v === 'string') {
1725
- return isLiteral
1726
- ? `<literal:string:${escapeQueryString(v)}>`
1727
- : `<${escapeQueryString(v)}>`;
1793
+ function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
1794
+ const obj = target.prototype;
1795
+ // ── Determine namespace from first property or relation ─────────────
1796
+ let namespace = "ad4m://";
1797
+ // Try properties first
1798
+ if (Object.keys(properties).length > 0) {
1799
+ const firstProp = properties[Object.keys(properties)[0]];
1800
+ if (firstProp.through) {
1801
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
1802
+ if (match) {
1803
+ namespace = match[1];
1804
+ }
1728
1805
  }
1729
- // Numbers/booleans — also stored as literal:string: in AD4M
1730
- return `<literal:string:${v}>`;
1731
1806
  }
1732
- /**
1733
- * For literal properties, generate a FILTER-based match that handles both
1734
- * the raw value and the literal-encoded value. This mirrors the Rust
1735
- * `build_projection_where_patterns` approach which uses:
1736
- * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
1737
- * This is more robust than exact IRI matching because it handles edge cases
1738
- * where the stored format might vary.
1739
- */
1740
- function formatLiteralFilter(varName, v) {
1741
- const raw = escapeQueryString(String(v));
1742
- const encoded = encodeURIComponent(String(v))
1743
- .replace(/!/g, '%21')
1744
- .replace(/'/g, '%27')
1745
- .replace(/\(/g, '%28')
1746
- .replace(/\)/g, '%29')
1747
- .replace(/\*/g, '%2A');
1748
- if (typeof v === 'string') {
1749
- return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
1750
- }
1751
- else if (typeof v === 'number') {
1752
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
1753
- }
1754
- else if (typeof v === 'boolean') {
1755
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
1807
+ // Fall back to relations if no properties
1808
+ else if (Object.keys(allRelationsMeta).length > 0) {
1809
+ const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
1810
+ if (firstRel.predicate) {
1811
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
1812
+ if (match) {
1813
+ namespace = match[1];
1814
+ }
1756
1815
  }
1757
- return `FILTER(STR(${varName}) = "${raw}")`;
1758
1816
  }
1759
- if (Array.isArray(condition)) {
1760
- // Array values → FILTER IN
1761
- if (isLiteral) {
1762
- const varName = `?_wc${varSuffix}`;
1763
- const inValues = condition.flatMap(v => {
1764
- const raw = escapeQueryString(String(v));
1765
- const encoded = encodeURIComponent(String(v))
1766
- .replace(/!/g, '%21').replace(/'/g, '%27')
1767
- .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
1768
- return [`"${raw}"`, `"literal:string:${encoded}"`];
1769
- }).join(', ');
1770
- return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
1771
- }
1772
- const formattedValues = condition.map(formatValue).join(', ');
1773
- return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
1774
- }
1775
- else if (typeof condition === 'object' && condition !== null) {
1776
- // Operator object
1777
- const ops = condition;
1778
- const parts = [];
1779
- if (ops.not !== undefined) {
1780
- if (Array.isArray(ops.not)) {
1781
- const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
1782
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1783
- // so O(N²) behavior is bounded by the number of values for this property.
1784
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
1785
- }
1786
- else {
1787
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1788
- // so O(N²) behavior is bounded by the number of values for this property.
1789
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
1790
- }
1791
- }
1792
- // Comparison operators — ensure property exists
1793
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1794
- ops.lt !== undefined || ops.lte !== undefined ||
1795
- ops.between !== undefined || ops.contains !== undefined;
1796
- if (hasComparisonOps) {
1797
- parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
1798
- }
1799
- return parts.join(' ');
1800
- }
1801
- else {
1802
- // Simple equality
1803
- if (isLiteral) {
1804
- // Use FILTER matching (mirrors Rust build_projection_where_patterns)
1805
- // to handle both raw values and literal-encoded IRIs robustly.
1806
- const varName = `?_wc${varSuffix}`;
1807
- return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
1808
- }
1809
- return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
1810
- }
1811
- }
1812
- /**
1813
- * Compile a full `Where` clause to an array of SPARQL condition strings.
1814
- *
1815
- * When `metadata` is provided, property names are resolved to predicates
1816
- * using the model's property metadata. When `metadata` is `null`, property
1817
- * names are treated as raw predicate URIs.
1818
- *
1819
- * Only handles **regular properties** — special fields (`id`, `author`,
1820
- * `timestamp`) and relation fields are skipped (they are only relevant at
1821
- * runtime query time, not for compile-time getter generation).
1822
- */
1823
- function compileWhereClause(where, metadata) {
1824
- const conditions = [];
1825
- for (const [propertyName, condition] of Object.entries(where)) {
1826
- // Skip special fields that don't apply at compile time
1827
- if (['id', 'author', 'timestamp'].includes(propertyName))
1828
- continue;
1829
- let predicate;
1830
- let resolveLanguage;
1831
- if (metadata) {
1832
- const propMeta = metadata.properties[propertyName];
1833
- if (propMeta) {
1834
- predicate = propMeta.predicate;
1835
- resolveLanguage = propMeta.resolveLanguage;
1836
- }
1837
- else {
1838
- // Property not found in metadata — treat name as raw predicate URI
1839
- predicate = propertyName;
1840
- }
1841
- }
1842
- else {
1843
- // No metadata — treat name as raw predicate URI
1844
- predicate = propertyName;
1845
- }
1846
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
1847
- if (cond) {
1848
- conditions.push(cond);
1849
- }
1850
- }
1851
- return conditions;
1852
- }
1853
-
1854
- /**
1855
- * SHACL shape generation for AD4M model classes.
1856
- *
1857
- * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
1858
- * from a model's property and relation metadata. The heavy lifting used
1859
- * to live inside the `@Model` decorator closure — it is extracted here so
1860
- * decorators.ts stays focused on decorator registration logic.
1861
- */
1862
- /**
1863
- * Build a SHACL shape for a model class.
1864
- *
1865
- * @param subjectName - The model's registered name (from `@Model({ name })`)
1866
- * @param target - The class constructor (used for prototype access,
1867
- * inheritance chain, and relation target resolution)
1868
- * @param properties - Merged property metadata (from `getPropertiesMetadata`)
1869
- * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
1870
- * @param conformanceFilterFn - Injected conformance-filter builder
1871
- * (avoids circular dependency back into decorators.ts)
1872
- */
1873
- function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
1874
- const obj = target.prototype;
1875
- // ── Determine namespace from first property or relation ─────────────
1876
- let namespace = "ad4m://";
1877
- const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
1878
- // Try properties first
1879
- if (Object.keys(properties).length > 0) {
1880
- const firstProp = properties[Object.keys(properties)[0]];
1881
- if (firstProp.through) {
1882
- const match = firstProp.through.match(/^([^:]+:\/\/)/);
1883
- if (match) {
1884
- namespace = match[1];
1885
- }
1886
- }
1887
- }
1888
- // Fall back to relations if no properties
1889
- else if (Object.keys(relations).length > 0) {
1890
- const firstRel = relations[Object.keys(relations)[0]];
1891
- if (firstRel.predicate) {
1892
- const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
1893
- if (match) {
1894
- namespace = match[1];
1895
- }
1896
- }
1897
- }
1898
- // ── Create SHACL shape ──────────────────────────────────────────────
1899
- const shapeUri = `${namespace}${subjectName}Shape`;
1900
- const targetClass = `${namespace}${subjectName}`;
1901
- const shape = new SHACLShape(shapeUri, targetClass);
1902
- // Detect @Model inheritance — if the parent class also has
1903
- // generateSHACL it is itself a @Model and we reference its shape
1904
- // via sh:node so SHACL validators can walk the hierarchy.
1905
- const parentCtor = Object.getPrototypeOf(target);
1906
- if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
1907
- const parentSHACL = parentCtor.generateSHACL();
1908
- if (parentSHACL?.shape?.nodeShapeUri) {
1909
- shape.addParentShape(parentSHACL.shape.nodeShapeUri);
1817
+ // ── Create SHACL shape ──────────────────────────────────────────────
1818
+ const shapeUri = `${namespace}${subjectName}Shape`;
1819
+ const targetClass = `${namespace}${subjectName}`;
1820
+ const shape = new SHACLShape(shapeUri, targetClass);
1821
+ // Detect @Model inheritance — if the parent class also has
1822
+ // generateSHACL it is itself a @Model and we reference its shape
1823
+ // via sh:node so SHACL validators can walk the hierarchy.
1824
+ const parentCtor = Object.getPrototypeOf(target);
1825
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
1826
+ const parentSHACL = parentCtor.generateSHACL();
1827
+ if (parentSHACL?.shape?.nodeShapeUri) {
1828
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
1910
1829
  }
1911
1830
  }
1912
1831
  // ── Constructor / Destructor actions ────────────────────────────────
@@ -1961,9 +1880,19 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1961
1880
  if (propMeta.writable !== undefined) {
1962
1881
  propShape.writable = propMeta.writable;
1963
1882
  }
1964
- if (propMeta.resolveLanguage) {
1883
+ if (propMeta.resolveLanguage != null) {
1965
1884
  propShape.resolveLanguage = propMeta.resolveLanguage;
1966
1885
  }
1886
+ // Explicit getter SPARQL — the executor evaluates this when
1887
+ // hydrating the property, in addition to (or instead of)
1888
+ // reading raw links via `propMeta.through`.
1889
+ if (propMeta.getter) {
1890
+ propShape.getter = propMeta.getter;
1891
+ }
1892
+ // Serializable transform expression (SHACL-AF Node Expression)
1893
+ if (propMeta.transform) {
1894
+ propShape.transform = propMeta.transform;
1895
+ }
1967
1896
  // ── Setter actions ──────────────────────────────────────────────
1968
1897
  if (propMeta.prologSetter) {
1969
1898
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
@@ -2002,63 +1931,82 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2002
1931
  shape.addProperty(propShape);
2003
1932
  }
2004
1933
  // ── Convert relations to SHACL property shapes ─────────────────────
2005
- for (const relName in relations) {
2006
- const relMeta = relations[relName];
2007
- if (!relMeta.predicate)
1934
+ for (const relName in allRelationsMeta) {
1935
+ const relMeta = allRelationsMeta[relName];
1936
+ // Getter-only relations (no `through`) have no real link predicate
1937
+ // but still need a SHACL property entry so the executor can find
1938
+ // the getter expression. Synthesize a deterministic IRI so the
1939
+ // SHACL graph is well-formed; the predicate is never used to match
1940
+ // links because the getter is the sole source of values. Use
1941
+ // slash separators so the result is a valid IRI (colons in the
1942
+ // authority confuse strict SPARQL IRI parsers).
1943
+ if (!relMeta.predicate && !relMeta.getter)
2008
1944
  continue;
1945
+ const synthesizedPath = relMeta.predicate
1946
+ || `ad4m://getter/${subjectName}/${relName}`;
2009
1947
  const relShape = {
2010
1948
  name: relName,
2011
- path: relMeta.predicate,
1949
+ path: synthesizedPath,
2012
1950
  };
2013
1951
  // Relations typically contain IRIs
2014
1952
  relShape.nodeKind = 'IRI';
1953
+ // Encode relation kind so the executor can derive direction and
1954
+ // scalar-vs-collection rendering without consulting the JS class.
1955
+ relShape.relationKind = relMeta.kind;
1956
+ // Scalar relations cap at 1.
1957
+ if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
1958
+ relShape.maxCount = 1;
1959
+ }
1960
+ else if (relMeta.maxCount !== undefined) {
1961
+ relShape.maxCount = relMeta.maxCount;
1962
+ }
1963
+ // Encode opt-out of type filtering (default true; only emit when false).
1964
+ if (relMeta.filter === false) {
1965
+ relShape.filter = false;
1966
+ }
2015
1967
  // AD4M-specific metadata
2016
1968
  if (relMeta.local !== undefined) {
2017
1969
  relShape.local = relMeta.local;
2018
1970
  }
2019
- // Adder action
2020
- relShape.adder = [{
2021
- action: "addLink",
2022
- source: "this",
2023
- predicate: relMeta.predicate,
2024
- target: "value",
2025
- ...(relMeta.local && { local: true })
2026
- }];
2027
- // Remover action
2028
- relShape.remover = [{
2029
- action: "removeLink",
2030
- source: "this",
2031
- predicate: relMeta.predicate,
2032
- target: "value",
2033
- ...(relMeta.local && { local: true })
2034
- }];
1971
+ // Adder / Remover actions — only meaningful for relations backed
1972
+ // by a real link predicate. Getter-only relations are read-only.
1973
+ if (relMeta.predicate) {
1974
+ relShape.adder = [{
1975
+ action: "addLink",
1976
+ source: "this",
1977
+ predicate: relMeta.predicate,
1978
+ target: "value",
1979
+ ...(relMeta.local && { local: true })
1980
+ }];
1981
+ relShape.remover = [{
1982
+ action: "removeLink",
1983
+ source: "this",
1984
+ predicate: relMeta.predicate,
1985
+ target: "value",
1986
+ ...(relMeta.local && { local: true })
1987
+ }];
1988
+ }
2035
1989
  // ── Build Getter (conformance filter) ───────────────────────────
2036
1990
  // Priority chain:
2037
1991
  // 1. Explicit getter string → use verbatim
2038
- // 2. `where` clause → compile DSL to SPARQL getter
2039
- // 3. target + filter !== false → auto-derive from shape
1992
+ // 2. target + filter !== false → auto-derive conformance getter
1993
+ // from the shape. Where-clause filtering is applied as a
1994
+ // post-getter pass via `whereFilter` / `wherePredicates`, which
1995
+ // use `parse_literal_value` and so transparently handle
1996
+ // `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
1997
+ // comparisons can't.
2040
1998
  if (relMeta.getter) {
2041
1999
  relShape.getter = relMeta.getter;
2042
2000
  }
2043
- else if (relMeta.where) {
2044
- try {
2045
- const TargetClass = relMeta.target?.();
2046
- const targetMetadata = TargetClass
2047
- ? TargetClass.getModelMetadata?.() ?? null
2048
- : null;
2049
- const conditions = compileWhereClause(relMeta.where, targetMetadata);
2050
- if (conditions.length > 0) {
2051
- const escapedPredicate = escapeQueryString(relMeta.predicate);
2052
- relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
2053
- }
2054
- }
2055
- catch (e) {
2056
- // Target metadata may not be available yet
2057
- }
2058
- }
2059
- else if (relMeta.target && relMeta.filter !== false) {
2001
+ else if (relMeta.target
2002
+ && relMeta.filter !== false
2003
+ && relMeta.kind !== 'belongsToOne'
2004
+ && relMeta.kind !== 'belongsToMany') {
2060
2005
  // Lazy conformance filter: store deferred reference,
2061
- // resolve on first access via a getter on relShape
2006
+ // resolve on first access via a getter on relShape.
2007
+ // Skipped for reverse relations (belongsTo*) because the
2008
+ // auto-derived getter assumes forward direction; the executor's
2009
+ // `resolve_reverse_relations` already populates these correctly.
2062
2010
  const targetThunk = relMeta.target;
2063
2011
  const predicate = relMeta.predicate;
2064
2012
  let resolved = false;
@@ -2095,6 +2043,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2095
2043
  });
2096
2044
  }
2097
2045
  // ── sh:class — target shape reference ───────────────────────────
2046
+ // Also emit ad4m:targetClassName so the executor can look up the
2047
+ // target class shape through its in-memory cache by bare name.
2098
2048
  if (relMeta.target) {
2099
2049
  try {
2100
2050
  const TargetClass = relMeta.target();
@@ -2102,9 +2052,54 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2102
2052
  if (targetSHACL?.shape?.nodeShapeUri) {
2103
2053
  relShape.class = targetSHACL.shape.nodeShapeUri;
2104
2054
  }
2055
+ if (targetSHACL?.name) {
2056
+ relShape.targetClassName = targetSHACL.name;
2057
+ }
2058
+ else {
2059
+ const targetProto = TargetClass.prototype;
2060
+ if (targetProto?.className) {
2061
+ relShape.targetClassName = targetProto.className;
2062
+ }
2063
+ }
2064
+ }
2065
+ catch (e) {
2066
+ // Target class resolution failed (typically a circular
2067
+ // decorator dependency). Since the executor no longer
2068
+ // receives target metadata over the wire, dropping the
2069
+ // reference here would turn a transient build-time issue
2070
+ // into a permanent broken-include at query time. Log
2071
+ // loudly so the failure is discoverable.
2072
+ console.warn(`[shacl-gen] Failed to resolve target class for relation `
2073
+ + `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
2074
+ }
2075
+ }
2076
+ // ── Where-clause metadata for post-getter filtering ─────────────
2077
+ // The executor uses these to apply where conditions against the
2078
+ // target class without needing the target's ModelMetadata at query time.
2079
+ if (relMeta.where) {
2080
+ relShape.whereFilter = relMeta.where;
2081
+ try {
2082
+ const TargetClass = relMeta.target?.();
2083
+ const targetMetadata = TargetClass
2084
+ ? TargetClass.getModelMetadata?.() ?? null
2085
+ : null;
2086
+ if (targetMetadata?.properties) {
2087
+ const predicates = {};
2088
+ for (const propName of Object.keys(relMeta.where)) {
2089
+ if (['id', 'author', 'timestamp'].includes(propName))
2090
+ continue;
2091
+ const propMeta = targetMetadata.properties[propName];
2092
+ if (propMeta?.predicate) {
2093
+ predicates[propName] = propMeta.predicate;
2094
+ }
2095
+ }
2096
+ if (Object.keys(predicates).length > 0) {
2097
+ relShape.wherePredicates = predicates;
2098
+ }
2099
+ }
2105
2100
  }
2106
2101
  catch (e) {
2107
- // Target class may not be available yet
2102
+ // Target metadata may not be available yet
2108
2103
  }
2109
2104
  }
2110
2105
  shape.addProperty(relShape);
@@ -2122,6 +2117,58 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2122
2117
  };
2123
2118
  }
2124
2119
 
2120
+ function formatList(list) {
2121
+ if (!list?.length) {
2122
+ return "";
2123
+ }
2124
+ if (list.length === 1) {
2125
+ return list.toString();
2126
+ }
2127
+ if (list.length === 2) {
2128
+ return list.join(' and ');
2129
+ }
2130
+ return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
2131
+ }
2132
+ function capSentence(cap) {
2133
+ const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
2134
+ const domain = cap.with.domain === "*" ? "" : cap.with.domain;
2135
+ const pointers = cap.with.pointers.includes("*")
2136
+ ? ["all AD4M data"]
2137
+ : cap.with.pointers;
2138
+ return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
2139
+ }
2140
+ /**
2141
+ * Escapes a string value for safe use in query strings.
2142
+ *
2143
+ * @description
2144
+ * Prevents SQL injection by properly escaping special characters in string values
2145
+ * that will be interpolated into query strings. This handles the most common
2146
+ * special characters that could break SQL queries or enable injection attacks.
2147
+ *
2148
+ * Single quotes, backslashes, and other special characters are escaped using
2149
+ * backslash notation, which is the standard escaping mechanism for query.
2150
+ *
2151
+ * @param value - The string value to escape
2152
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
2153
+ *
2154
+ * @example
2155
+ * ```typescript
2156
+ * const userInput = "user's input with 'quotes'";
2157
+ * const escaped = escapeQueryString(userInput);
2158
+ * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
2159
+ * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
2160
+ * ```
2161
+ */
2162
+ function escapeQueryString(value) {
2163
+ return value
2164
+ .replace(/\\/g, '\\\\') // Backslash -> \\
2165
+ .replace(/'/g, "\\'") // Single quote -> \'
2166
+ .replace(/"/g, '\\"') // Double quote -> \"
2167
+ .replace(/\n/g, '\\n') // Newline -> \n
2168
+ .replace(/\r/g, '\\r') // Carriage return -> \r
2169
+ .replace(/\t/g, '\\t'); // Tab -> \t
2170
+ }
2171
+
2125
2172
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
2126
2173
  const propertyRegistry = new WeakMap();
2127
2174
  /** Registry of relation metadata keyed by constructor → { propName → metadata } */
@@ -2641,15 +2688,8 @@ function resolveRelationArgs(first, second) {
2641
2688
  return opts;
2642
2689
  }
2643
2690
  function HasMany(first, second) {
2644
- const explicitThrough = typeof first === 'function' ? second?.through : first.through;
2645
2691
  const opts = resolveRelationArgs(first, second);
2646
2692
  return function (target, key) {
2647
- if (!explicitThrough && !opts.getter) {
2648
- const className = (target.constructor?.name) ?? 'unknown';
2649
- console.warn(`@HasMany on ${className}.${String(key)} has no 'through' predicate — defaulting to 'ad4m://has_child'. ` +
2650
- `Add { through: 'ad4m://has_child' } to silence this warning, or use a semantic predicate ` +
2651
- `like { through: 'myns://has_${String(key)}' } for efficient targeted queries.`);
2652
- }
2653
2693
  // --- relation registry ---
2654
2694
  const ctor = target.constructor;
2655
2695
  if (!relationRegistry.has(ctor))
@@ -3745,13 +3785,16 @@ class PerspectiveProxy {
3745
3785
  /**
3746
3786
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
3747
3787
  *
3788
+ * The executor resolves the model's shape from the perspective's SHACL
3789
+ * triples (written by `addSdna`). Callers no longer ship shape
3790
+ * metadata with the query; the perspective is the source of truth.
3791
+ *
3748
3792
  * @param className - The model class name (e.g. "Recipe")
3749
3793
  * @param queryJson - Structured query as JSON string
3750
- * @param shapeJson - Optional shape metadata JSON from the model class
3751
3794
  * @returns Object with `instances` array and `totalCount`
3752
3795
  */
3753
- async modelQuery(className, queryJson, shapeJson) {
3754
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3796
+ async modelQuery(className, queryJson) {
3797
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3755
3798
  }
3756
3799
  /**
3757
3800
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -3762,12 +3805,11 @@ class PerspectiveProxy {
3762
3805
  *
3763
3806
  * @param className - The model class name (e.g. "Message")
3764
3807
  * @param instanceIds - Array of instance base expression URIs
3765
- * @param shapeJson - Shape metadata JSON from the model class
3766
3808
  * @param propertyNames - Optional subset of property names to evaluate
3767
3809
  * @returns Map of instance ID → evaluated property values
3768
3810
  */
3769
- async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
3770
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
3811
+ async evaluateGetters(className, instanceIds, propertyNames) {
3812
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
3771
3813
  }
3772
3814
  /**
3773
3815
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
@@ -3779,11 +3821,10 @@ class PerspectiveProxy {
3779
3821
  *
3780
3822
  * @param className - The model class name
3781
3823
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
3782
- * @param shapeJson - Optional shape metadata JSON from the model class
3783
3824
  * @returns Object with `subscriptionId` and initial `result`
3784
3825
  */
3785
- async modelSubscribe(className, queryJson, shapeJson) {
3786
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3826
+ async modelSubscribe(className, queryJson) {
3827
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3787
3828
  }
3788
3829
  /**
3789
3830
  * Adds a new link to the perspective.
@@ -3971,17 +4012,30 @@ class PerspectiveProxy {
3971
4012
  async removeListener(type, cb) {
3972
4013
  if (type === 'link-added') {
3973
4014
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
3974
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
4015
+ if (index >= 0)
4016
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
3975
4017
  }
3976
4018
  else if (type === 'link-removed') {
3977
4019
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
3978
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
4020
+ if (index >= 0)
4021
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
3979
4022
  }
3980
4023
  else if (type === 'link-updated') {
3981
4024
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
3982
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
4025
+ if (index >= 0)
4026
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
3983
4027
  }
3984
4028
  }
4029
+ /** Clean up all subscriptions registered by this proxy.
4030
+ * Call this when the proxy is no longer needed to prevent subscription leaks.
4031
+ * After calling dispose(), the proxy should not be used. */
4032
+ dispose() {
4033
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeAllListeners(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4034
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").length = 0;
4035
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").length = 0;
4036
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").length = 0;
4037
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").length = 0;
4038
+ }
3985
4039
  /**
3986
4040
  * Creates a snapshot of the current perspective state.
3987
4041
  * Useful for backup or sharing.
@@ -4271,6 +4325,40 @@ class PerspectiveProxy {
4271
4325
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
4272
4326
  return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
4273
4327
  }
4328
+ /**
4329
+ * Batch variant of addSdna — registers multiple SDNA entries in a single RPC call.
4330
+ * Acquires the Rust-side mutex once for the entire batch.
4331
+ */
4332
+ async addSdnaAll(entries) {
4333
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdnaBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, entries);
4334
+ }
4335
+ /**
4336
+ * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.
4337
+ * Skips classes already registered on this perspective instance.
4338
+ */
4339
+ async ensureSubjectClasses(jsClasses) {
4340
+ const entries = [];
4341
+ for (const jsClass of jsClasses) {
4342
+ const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
4343
+ if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
4344
+ continue;
4345
+ if (!jsClass.generateSHACL) {
4346
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
4347
+ }
4348
+ const { shape } = jsClass.generateSHACL();
4349
+ entries.push({
4350
+ name: className,
4351
+ sdnaType: 'subject_class',
4352
+ shaclJson: JSON.stringify(shape.toJSON()),
4353
+ });
4354
+ }
4355
+ if (entries.length === 0)
4356
+ return;
4357
+ await this.addSdnaAll(entries);
4358
+ for (const entry of entries) {
4359
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(entry.name);
4360
+ }
4361
+ }
4274
4362
  /**
4275
4363
  * Adds a subject class to the perspective.
4276
4364
  * Alias for addSdna() with sdnaType='subject_class'.
@@ -5378,22 +5466,21 @@ class PerspectiveClient {
5378
5466
  }
5379
5467
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5380
5468
  }
5381
- async modelQuery(uuid, className, queryJson, shapeJson) {
5382
- const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5469
+ async modelQuery(uuid, className, queryJson) {
5470
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
5383
5471
  return JSON.parse(resultJson);
5384
5472
  }
5385
- async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
5473
+ async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5386
5474
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5387
5475
  uuid,
5388
5476
  class_name: className,
5389
5477
  instance_ids: instanceIds,
5390
- shape_json: shapeJson,
5391
5478
  ...(propertyNames && { property_names: propertyNames }),
5392
5479
  });
5393
5480
  return JSON.parse(resultJson);
5394
5481
  }
5395
- async modelSubscribe(uuid, className, queryJson, shapeJson) {
5396
- const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5482
+ async modelSubscribe(uuid, className, queryJson) {
5483
+ const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
5397
5484
  return {
5398
5485
  subscriptionId: response.subscription_id,
5399
5486
  result: JSON.parse(response.result)
@@ -5439,6 +5526,9 @@ class PerspectiveClient {
5439
5526
  async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {
5440
5527
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson });
5441
5528
  }
5529
+ async addSdnaBatch(uuid, entries) {
5530
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || "" })) });
5531
+ }
5442
5532
  async executeCommands(uuid, commands, expression, parameters, batchId) {
5443
5533
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
5444
5534
  }
@@ -5546,7 +5636,21 @@ class PerspectiveClient {
5546
5636
  __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5547
5637
  await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5548
5638
  }
5549
- getNeighbourhoodProxy(uuid) {
5639
+ /** Unsubscribe all link/sync-state listeners registered for the given perspective UUID.
5640
+ * Called by PerspectiveProxy.dispose() to prevent subscription leaks. */
5641
+ removeAllListeners(uuid) {
5642
+ const unsubs = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid);
5643
+ if (unsubs) {
5644
+ for (const fn of unsubs) {
5645
+ try {
5646
+ fn();
5647
+ }
5648
+ catch { }
5649
+ }
5650
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").delete(uuid);
5651
+ }
5652
+ }
5653
+ getNeighbourhoodProxy(uuid) {
5550
5654
  return new NeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveClient_neighbourhoodClient, "f"), uuid);
5551
5655
  }
5552
5656
  async createBatch(uuid) {
@@ -5748,6 +5852,11 @@ class AgentClient {
5748
5852
  const agent = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.get');
5749
5853
  let agentObject = new Agent(agent.did, agent.perspective);
5750
5854
  agentObject.directMessageLanguage = agent.directMessageLanguage;
5855
+ // Auto-set selfDid so event-driven cache invalidation works
5856
+ // without requiring apps to call setSelfDid() manually
5857
+ if (agentObject.did && !__classPrivateFieldGet$7(this, _AgentClient_selfDid, "f")) {
5858
+ __classPrivateFieldSet$7(this, _AgentClient_selfDid, agentObject.did, "f");
5859
+ }
5751
5860
  return agentObject;
5752
5861
  }
5753
5862
  async status() {
@@ -5835,6 +5944,12 @@ class AgentClient {
5835
5944
  const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { publicPerspective: cleanedPerspective });
5836
5945
  const agent = new Agent(a.did, a.perspective);
5837
5946
  agent.directMessageLanguage = a.directMessageLanguage;
5947
+ // Immediately update byDID cache so subsequent byDID() calls
5948
+ // return fresh data without waiting for the subscription event
5949
+ if (agent.did) {
5950
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
5951
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, agent); // fire-and-forget
5952
+ }
5838
5953
  return agent;
5839
5954
  }
5840
5955
  async mutatePublicPerspective(mutations) {
@@ -5859,6 +5974,12 @@ class AgentClient {
5859
5974
  const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { dmLanguage: directMessageLanguage });
5860
5975
  const agent = new Agent(a.did, a.perspective);
5861
5976
  agent.directMessageLanguage = a.directMessageLanguage;
5977
+ // Immediately update byDID cache so subsequent byDID() calls
5978
+ // return fresh data without waiting for the subscription event
5979
+ if (agent.did) {
5980
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
5981
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, agent); // fire-and-forget
5982
+ }
5862
5983
  return agent;
5863
5984
  }
5864
5985
  async addEntanglementProofs(proofs) {
@@ -13754,7 +13875,7 @@ class AIClient {
13754
13875
  // Use slice to get only the relevant portion of the underlying ArrayBuffer
13755
13876
  // (Float32Array may be a view over a larger buffer)
13756
13877
  const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
13757
- const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13878
+ const response = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13758
13879
  method: 'POST',
13759
13880
  headers: {
13760
13881
  'Content-Type': 'application/octet-stream',
@@ -14216,7 +14337,9 @@ function escapeSPARQL(value) {
14216
14337
  .replace(/"/g, '\\"')
14217
14338
  .replace(/\n/g, "\\n")
14218
14339
  .replace(/\r/g, "\\r")
14219
- .replace(/\t/g, "\\t");
14340
+ .replace(/\t/g, "\\t")
14341
+ .replace(/\0/g, "")
14342
+ .replace(/\f/g, "\\u000C");
14220
14343
  }
14221
14344
  /**
14222
14345
  * Format a value as a SPARQL string literal (double-quoted).
@@ -14231,8 +14354,14 @@ function formatSPARQLValue(value) {
14231
14354
  * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
14232
14355
  * All AD4M link source/predicate/target values become IRIs in angle brackets.
14233
14356
  * The Rust SPARQL service transparently transforms these to valid IRI format.
14357
+ *
14358
+ * Rejects characters that would break or inject into a SPARQL IRI token,
14359
+ * matching the Rust-side `validate_iri()` function.
14234
14360
  */
14235
14361
  function iri(value) {
14362
+ if (/[<>{}" ]/.test(value)) {
14363
+ throw new Error(`Invalid IRI component: '${value}'`);
14364
+ }
14236
14365
  return `<${value}>`;
14237
14366
  }
14238
14367
  /**
@@ -14378,21 +14507,8 @@ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
14378
14507
  ?_reifier <ad4m://ontology/timestamp> ?timestamp .
14379
14508
  ${filterClause}
14380
14509
  }
14381
- ${buildSPARQLOrderLimitOffset()}
14382
14510
  `.trim();
14383
14511
  }
14384
- /**
14385
- * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
14386
- *
14387
- * NOTE: The outer SELECT returns multiple rows per instance (one per link),
14388
- * so LIMIT/OFFSET at the outer level would cut off links mid-instance.
14389
- * This function is kept for backward compatibility and always returns "".
14390
- * SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
14391
- * using buildPaginationSubquery().
14392
- */
14393
- function buildSPARQLOrderLimitOffset(_metadata, query) {
14394
- return "";
14395
- }
14396
14512
  /**
14397
14513
  * Build an inner subquery that selects DISTINCT ?source URIs with
14398
14514
  * ORDER BY, LIMIT, and OFFSET applied at the instance level.
@@ -14439,7 +14555,7 @@ function buildPaginationSubquery(joinPatterns, filterExpressions, metadata, quer
14439
14555
  { SELECT DISTINCT ?source${tsSelect} WHERE {${innerJoin}${orderJoinPatterns.join('')}${tsPattern}
14440
14556
  FILTER(isIRI(?source))
14441
14557
  ${innerFilter}
14442
- } GROUP BY ?source ${orderByClause} ${limitClause} ${offsetClause} }\n`;
14558
+ } ${orderByClause} ${limitClause} ${offsetClause} }\n`;
14443
14559
  }
14444
14560
  /**
14445
14561
  * Build SPARQL FILTER expressions from user `where` conditions.
@@ -14835,13 +14951,6 @@ class ModelQueryBuilder {
14835
14951
  this.modelClassName = className;
14836
14952
  return this;
14837
14953
  }
14838
- /**
14839
- * Sets the query engine to use.
14840
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
14841
- */
14842
- engine(_eng) {
14843
- return this;
14844
- }
14845
14954
  /**
14846
14955
  * Executes the query once and returns the results.
14847
14956
  *
@@ -14885,8 +14994,10 @@ class ModelQueryBuilder {
14885
14994
  * ```
14886
14995
  */
14887
14996
  async first() {
14997
+ const savedLimit = this.queryParams.limit;
14888
14998
  this.queryParams.limit = 1;
14889
14999
  const results = await this.get();
15000
+ this.queryParams.limit = savedLimit;
14890
15001
  return results[0] ?? null;
14891
15002
  }
14892
15003
  /**
@@ -14921,16 +15032,17 @@ class ModelQueryBuilder {
14921
15032
  // Clean up any existing subscription
14922
15033
  this.dispose();
14923
15034
  const ctor = this.ctor;
14924
- // Build the model query params (className, queryJson, shapeJson)
14925
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
15035
+ // Build the model query params (className, queryJson). The executor
15036
+ // resolves the shape from the perspective's SHACL triples.
15037
+ const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
14926
15038
  // Register model subscription via Rust — this builds trigger SPARQL internally,
14927
15039
  // registers the subscription, and runs the initial query in one call.
14928
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15040
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
14929
15041
  // Convert JSON instances to model class instances
14930
15042
  const parseResults = (raw) => {
14931
15043
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
14932
15044
  };
14933
- // Parse initial results
15045
+ // Transforms are now applied by the Rust executor during hydration
14934
15046
  const initialResults = parseResults(initialModelResult);
14935
15047
  // Track last emitted result fingerprint to suppress duplicate callbacks
14936
15048
  let lastResultFingerprint = null;
@@ -14945,9 +15057,13 @@ class ModelQueryBuilder {
14945
15057
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
14946
15058
  try {
14947
15059
  const results = parseResults(rawResult);
15060
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
14948
15061
  const fp = buildFingerprint(results);
14949
- if (fp === lastResultFingerprint)
15062
+ if (fp === lastResultFingerprint) {
15063
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
14950
15064
  return;
15065
+ }
15066
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
14951
15067
  lastResultFingerprint = fp;
14952
15068
  callback(results);
14953
15069
  }
@@ -14955,20 +15071,50 @@ class ModelQueryBuilder {
14955
15071
  console.error('Model subscription update parse error:', e);
14956
15072
  }
14957
15073
  });
14958
- // Set up keepalive with failure tracking
14959
- let keepaliveFailures = 0;
14960
- const keepaliveTimer = setInterval(() => {
14961
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
14962
- keepaliveFailures = 0;
14963
- }).catch((e) => {
14964
- keepaliveFailures++;
14965
- console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
14966
- });
14967
- }, 30000);
15074
+ // Set up keepalive with recovery — uses setTimeout loop so we can
15075
+ // break out and resubscribe when the server evicts the subscription.
15076
+ let disposed = false;
15077
+ let keepaliveTimer;
15078
+ let resubscribeAttempts = 0;
15079
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15080
+ const keepaliveLoop = async () => {
15081
+ if (disposed)
15082
+ return;
15083
+ try {
15084
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15085
+ resubscribeAttempts = 0; // Reset on success
15086
+ }
15087
+ catch (e) {
15088
+ console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);
15089
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15090
+ resubscribeAttempts++;
15091
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15092
+ console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15093
+ await new Promise(r => setTimeout(r, backoffMs));
15094
+ try {
15095
+ unsubscribe();
15096
+ await this.subscribe(callback);
15097
+ }
15098
+ catch (resubErr) {
15099
+ console.error('Model subscription resubscribe failed:', resubErr);
15100
+ }
15101
+ }
15102
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15103
+ console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15104
+ }
15105
+ return; // new subscription owns its own keepalive loop
15106
+ }
15107
+ if (!disposed) {
15108
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15109
+ }
15110
+ };
15111
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
14968
15112
  // Store dispose function
14969
15113
  this.currentSubscription = {
14970
15114
  dispose: () => {
14971
- clearInterval(keepaliveTimer);
15115
+ disposed = true;
15116
+ if (keepaliveTimer)
15117
+ clearTimeout(keepaliveTimer);
14972
15118
  unsubscribe();
14973
15119
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
14974
15120
  },
@@ -15041,8 +15187,8 @@ class ModelQueryBuilder {
15041
15187
  // Clean up any existing subscription
15042
15188
  this.dispose();
15043
15189
  const countParams = { ...this.queryParams, limit: 0 };
15044
- const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15045
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15190
+ const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15191
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
15046
15192
  const parseCount = (raw) => {
15047
15193
  const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
15048
15194
  return data.totalCount ?? 0;
@@ -15056,18 +15202,47 @@ class ModelQueryBuilder {
15056
15202
  console.error('Count subscription update parse error:', e);
15057
15203
  }
15058
15204
  });
15059
- let keepaliveFailures = 0;
15060
- const keepaliveTimer = setInterval(() => {
15061
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15062
- keepaliveFailures = 0;
15063
- }).catch((e) => {
15064
- keepaliveFailures++;
15065
- console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15066
- });
15067
- }, 30000);
15205
+ let disposed = false;
15206
+ let keepaliveTimer;
15207
+ let resubscribeAttempts = 0;
15208
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15209
+ const keepaliveLoop = async () => {
15210
+ if (disposed)
15211
+ return;
15212
+ try {
15213
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15214
+ resubscribeAttempts = 0;
15215
+ }
15216
+ catch (e) {
15217
+ console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);
15218
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15219
+ resubscribeAttempts++;
15220
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15221
+ console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15222
+ await new Promise(r => setTimeout(r, backoffMs));
15223
+ try {
15224
+ unsubscribe();
15225
+ await this.countSubscribe(callback);
15226
+ }
15227
+ catch (resubErr) {
15228
+ console.error('Count subscription resubscribe failed:', resubErr);
15229
+ }
15230
+ }
15231
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15232
+ console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15233
+ }
15234
+ return;
15235
+ }
15236
+ if (!disposed) {
15237
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15238
+ }
15239
+ };
15240
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15068
15241
  this.currentSubscription = {
15069
15242
  dispose: () => {
15070
- clearInterval(keepaliveTimer);
15243
+ disposed = true;
15244
+ if (keepaliveTimer)
15245
+ clearTimeout(keepaliveTimer);
15071
15246
  unsubscribe();
15072
15247
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
15073
15248
  },
@@ -15148,8 +15323,8 @@ class ModelQueryBuilder {
15148
15323
  const subscriptionParams = { ...(this.queryParams || {}) };
15149
15324
  delete subscriptionParams.limit;
15150
15325
  delete subscriptionParams.offset;
15151
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15152
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15326
+ const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15327
+ const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
15153
15328
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
15154
15329
  const paginatedQuery = {
15155
15330
  ...(this.queryParams || {}),
@@ -15162,20 +15337,50 @@ class ModelQueryBuilder {
15162
15337
  callback({ results, totalCount, pageSize, pageNumber });
15163
15338
  };
15164
15339
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15340
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
15165
15341
  processResults().catch(e => console.error('Paginate subscription error:', e));
15166
15342
  });
15167
- let keepaliveFailures = 0;
15168
- const keepaliveTimer = setInterval(() => {
15169
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15170
- keepaliveFailures = 0;
15171
- }).catch((e) => {
15172
- keepaliveFailures++;
15173
- console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15174
- });
15175
- }, 30000);
15343
+ let disposed = false;
15344
+ let keepaliveTimer;
15345
+ let resubscribeAttempts = 0;
15346
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15347
+ const keepaliveLoop = async () => {
15348
+ if (disposed)
15349
+ return;
15350
+ try {
15351
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15352
+ resubscribeAttempts = 0;
15353
+ }
15354
+ catch (e) {
15355
+ console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);
15356
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15357
+ resubscribeAttempts++;
15358
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15359
+ console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15360
+ await new Promise(r => setTimeout(r, backoffMs));
15361
+ try {
15362
+ unsubscribe();
15363
+ await this.paginateSubscribe(pageSize, pageNumber, callback);
15364
+ }
15365
+ catch (resubErr) {
15366
+ console.error('Paginate subscription resubscribe failed:', resubErr);
15367
+ }
15368
+ }
15369
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15370
+ console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15371
+ }
15372
+ return;
15373
+ }
15374
+ if (!disposed) {
15375
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15376
+ }
15377
+ };
15378
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15176
15379
  this.currentSubscription = {
15177
15380
  dispose: () => {
15178
- clearInterval(keepaliveTimer);
15381
+ disposed = true;
15382
+ if (keepaliveTimer)
15383
+ clearTimeout(keepaliveTimer);
15179
15384
  unsubscribe();
15180
15385
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
15181
15386
  },
@@ -15218,46 +15423,6 @@ function normalizeValue(value) {
15218
15423
  // ---------------------------------------------------------------------------
15219
15424
  // Helpers for Rust-side include resolution
15220
15425
  // ---------------------------------------------------------------------------
15221
- /**
15222
- * Recursively enrich relation metadata in the shape with target class shapes
15223
- * so the Rust endpoint can resolve includes in-process (no extra GraphQL
15224
- * round-trips per relation).
15225
- */
15226
- function enrichShapeForIncludes(metadata, include, allRelMeta) {
15227
- for (const [relName, includeVal] of Object.entries(include)) {
15228
- if (!includeVal)
15229
- continue;
15230
- const meta = allRelMeta[relName];
15231
- if (!meta?.target)
15232
- continue;
15233
- const TargetClass = meta.target();
15234
- // Deep-copy so we don't mutate the cached metadata
15235
- const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
15236
- // Ensure the relation is in metadata.relations (fallback for edge cases)
15237
- if (!metadata.relations[relName]) {
15238
- metadata.relations[relName] = {
15239
- name: relName,
15240
- predicate: meta.predicate,
15241
- direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
15242
- ? 'reverse'
15243
- : 'forward',
15244
- };
15245
- }
15246
- const rel = metadata.relations[relName];
15247
- rel.kind = meta.kind;
15248
- rel.maxCount = meta.maxCount;
15249
- rel.targetShape = targetMeta;
15250
- rel.targetClassName = targetMeta.className;
15251
- // Recurse for nested includes
15252
- const nested = typeof includeVal === 'object' && includeVal !== null
15253
- ? includeVal.include
15254
- : undefined;
15255
- if (nested) {
15256
- const targetRelMeta = getRelationsMetadata(TargetClass);
15257
- enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
15258
- }
15259
- }
15260
- }
15261
15426
  /**
15262
15427
  * Construct a model class instance from a plain JSON object returned by the
15263
15428
  * Rust endpoint. Recursively converts included relation values (which come
@@ -15302,22 +15467,6 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15302
15467
  }
15303
15468
  instance[key] = value;
15304
15469
  }
15305
- // Apply property transform functions from decorators (only for literal-resolved
15306
- // or no-resolveLanguage properties; non-literal properties are resolved + transformed
15307
- // asynchronously in executeModelQuery).
15308
- try {
15309
- const propsMeta = getPropertiesMetadata(ModelClass);
15310
- for (const [propName, opts] of Object.entries(propsMeta)) {
15311
- const o = opts;
15312
- if (typeof o.transform !== 'function' || !(propName in json))
15313
- continue;
15314
- // Skip non-literal resolveLanguage props — they need async expression resolution first
15315
- if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
15316
- continue;
15317
- instance[propName] = o.transform(instance[propName]);
15318
- }
15319
- }
15320
- catch (_) { /* no metadata available */ }
15321
15470
  // Recursively convert included relation values to class instances
15322
15471
  if (include) {
15323
15472
  const relMeta = getRelationsMetadata(ModelClass);
@@ -15555,8 +15704,8 @@ class Ad4mModel {
15555
15704
  ...(options.getter !== undefined && { getter: options.getter }),
15556
15705
  ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
15557
15706
  ...(options.local !== undefined && { local: options.local }),
15558
- ...(options.transform !== undefined && { transform: options.transform }),
15559
- ...(options.flag !== undefined && { flag: options.flag })
15707
+ ...(options.flag !== undefined && { flag: options.flag }),
15708
+ ...(options.transform !== undefined && { transform: options.transform })
15560
15709
  };
15561
15710
  }
15562
15711
  // Extract relations (relations) from WeakMap registry
@@ -15741,6 +15890,7 @@ class Ad4mModel {
15741
15890
  * • `null` / empty object — skip ALL relations (used by bare
15742
15891
  * subscriptions that don't eagerly load relations).
15743
15892
  */
15893
+ /** @internal */
15744
15894
  takeSnapshot(includedRelations) {
15745
15895
  const ctor = this.constructor;
15746
15896
  const metadata = ctor.getModelMetadata();
@@ -15936,115 +16086,14 @@ class Ad4mModel {
15936
16086
  }
15937
16087
  /**
15938
16088
  * Build the JSON parameters needed for a model query/subscription endpoint.
15939
- * Returns the className, queryJson, and shapeJson that the Rust executor expects.
16089
+ * Returns the className and queryJson that the Rust executor expects.
16090
+ * Shape resolution happens server-side from the perspective's SHACL triples.
15940
16091
  * @internal
15941
16092
  */
15942
16093
  static prepareModelQueryParams(query = {}, classNameOverride) {
15943
- const metadata = this.getModelMetadata();
15944
- const className = classNameOverride || metadata.className;
15945
- const queryInput = {};
15946
- if (query.parent) {
15947
- const parentPredicate = resolveParentPredicate(query.parent, this);
15948
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
15949
- }
15950
- if (query.properties)
15951
- queryInput.properties = query.properties;
15952
- if (query.include)
15953
- queryInput.include = query.include;
15954
- if (query.where)
15955
- queryInput.where = query.where;
15956
- if (query.order) {
15957
- queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
15958
- }
15959
- if (query.offset !== undefined)
15960
- queryInput.offset = query.offset;
15961
- if (query.limit !== undefined)
15962
- queryInput.limit = query.limit;
15963
- if (query.count !== undefined)
15964
- queryInput.count = query.count;
15965
- queryInput.deepQuery = query.deepQuery ?? true;
15966
- if (query.include) {
15967
- const allRelMeta = getRelationsMetadata(this);
15968
- enrichShapeForIncludes(metadata, query.include, allRelMeta);
15969
- }
15970
- // Pre-compute conformance getters for Rust-side evaluation.
15971
- // Where clauses are NOT compiled into getter SPARQL because stored
15972
- // property values are signed expression envelopes (literal:json:...),
15973
- // not simple literal:string:X values. Instead, where clauses are
15974
- // attached as metadata for Rust-side post-evaluation filtering.
15975
- {
15976
- const allRelMeta = getRelationsMetadata(this);
15977
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
15978
- const rel = relMeta;
15979
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
15980
- continue;
15981
- const meta = allRelMeta[relName];
15982
- if (!meta?.target)
15983
- continue;
15984
- try {
15985
- const TargetClass = meta.target();
15986
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
15987
- if (filter) {
15988
- rel.getter = filter.getter;
15989
- }
15990
- // Attach where-clause metadata for Rust-side post-getter filtering
15991
- if (rel.where) {
15992
- try {
15993
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
15994
- if (targetMetadata) {
15995
- const predicates = {};
15996
- for (const propName of Object.keys(rel.where)) {
15997
- if (['id', 'author', 'timestamp'].includes(propName))
15998
- continue;
15999
- const propMeta = targetMetadata.properties[propName];
16000
- if (propMeta?.predicate) {
16001
- predicates[propName] = propMeta.predicate;
16002
- }
16003
- }
16004
- if (Object.keys(predicates).length > 0) {
16005
- rel.whereFilter = rel.where;
16006
- rel.wherePredicates = predicates;
16007
- }
16008
- }
16009
- }
16010
- catch (_) { }
16011
- }
16012
- }
16013
- catch (_) { }
16014
- }
16015
- }
16016
- return {
16017
- className,
16018
- queryJson: JSON.stringify(queryInput),
16019
- shapeJson: JSON.stringify(metadata),
16020
- };
16021
- }
16022
- /**
16023
- * Parse raw model query/subscription result JSON into typed model instances.
16024
- * Used by ModelQueryBuilder to convert subscription updates without circular imports.
16025
- * @internal
16026
- */
16027
- static parseModelResult(perspective, raw, include, properties) {
16028
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
16029
- const arr = data.instances || data;
16030
- if (!Array.isArray(arr))
16031
- return [];
16032
- return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
16033
- }
16034
- // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
16035
- /**
16036
- * Execute a model query via the executor-side endpoint.
16037
- *
16038
- * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
16039
- * with a single RPC to the executor that handles everything in Rust.
16040
- *
16041
- * @internal
16042
- */
16043
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
16044
16094
  const metadata = this.getModelMetadata();
16045
16095
  const className = classNameOverride || metadata.className;
16046
16096
  // Expand includeAll: true to a full IncludeMap covering every forward relation.
16047
- // Done before queryInput is built so all downstream uses of query.include see the expansion.
16048
16097
  if (query.includeAll) {
16049
16098
  const allRelMeta = getRelationsMetadata(this);
16050
16099
  const expanded = {};
@@ -16053,11 +16102,8 @@ class Ad4mModel {
16053
16102
  expanded[relName] = true;
16054
16103
  }
16055
16104
  }
16056
- // Explicit include entries take precedence over the expansion
16057
16105
  query = { ...query, include: { ...expanded, ...query.include } };
16058
16106
  }
16059
- // Build the query input that the Rust endpoint expects.
16060
- // Convert the TS Query type to the executor's ModelQueryInput format.
16061
16107
  const queryInput = {};
16062
16108
  if (query.parent) {
16063
16109
  const parentPredicate = resolveParentPredicate(query.parent, this);
@@ -16081,19 +16127,23 @@ class Ad4mModel {
16081
16127
  if (Object.keys(normalIncludes).length > 0)
16082
16128
  queryInput.include = normalIncludes;
16083
16129
  if (Object.keys(projections).length > 0) {
16084
- // Enrich projections with target shapes so Rust can apply where clause filtering
16130
+ // Tag each projection with its target class name so the executor can
16131
+ // resolve the target shape through its in-memory cache when applying
16132
+ // projection where-clause filters.
16085
16133
  const allRelMeta = getRelationsMetadata(this);
16086
16134
  for (const [, proj] of Object.entries(projections)) {
16087
16135
  const relMeta = allRelMeta[proj.from];
16088
- if (!proj.targetShape && relMeta?.target) {
16136
+ if (!proj.targetClassName && relMeta?.target) {
16089
16137
  try {
16090
16138
  const TargetClass = relMeta.target();
16091
16139
  const targetMeta = TargetClass.getModelMetadata?.();
16092
- if (targetMeta) {
16093
- proj.targetShape = targetMeta;
16140
+ if (targetMeta?.className) {
16141
+ proj.targetClassName = targetMeta.className;
16094
16142
  }
16095
16143
  }
16096
- catch (_) { /* target class may not be available */ }
16144
+ catch (e) {
16145
+ console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e);
16146
+ }
16097
16147
  }
16098
16148
  }
16099
16149
  queryInput.projections = projections;
@@ -16102,7 +16152,6 @@ class Ad4mModel {
16102
16152
  if (query.where)
16103
16153
  queryInput.where = query.where;
16104
16154
  if (query.order) {
16105
- // Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
16106
16155
  queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
16107
16156
  }
16108
16157
  if (query.offset !== undefined)
@@ -16112,113 +16161,52 @@ class Ad4mModel {
16112
16161
  if (query.count !== undefined)
16113
16162
  queryInput.count = query.count;
16114
16163
  queryInput.deepQuery = query.deepQuery ?? true;
16115
- // Enrich relation metadata with target class shapes for Rust-side
16116
- // include resolution. This eliminates per-relation GraphQL round-trips
16117
- // by letting the Rust endpoint resolve includes in-process.
16118
- if (queryInput.include) {
16119
- const allRelMeta = getRelationsMetadata(this);
16120
- enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
16121
- }
16122
- // ── Pre-compute conformance getters for Rust-side evaluation ──────
16123
- // For each relation with a target class and filter !== false, compute
16124
- // the conformance getter SPARQL so Rust can evaluate it in-process
16125
- // (eliminating N × querySparql round-trips per instance).
16126
- // When a relation has a `where` clause, compile the where conditions
16127
- // into the getter SPARQL so Rust applies them during evaluation.
16128
- {
16129
- const allRelMeta = getRelationsMetadata(this);
16130
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16131
- const rel = relMeta;
16132
- if (rel.getter)
16133
- continue; // explicit getter already set
16134
- if (rel.direction === 'reverse')
16135
- continue; // reverse relations use reverse link lookup
16136
- if (rel.filter === false)
16137
- continue; // opt-out of conformance filtering
16138
- const meta = allRelMeta[relName];
16139
- if (!meta?.target)
16140
- continue;
16141
- try {
16142
- const TargetClass = meta.target();
16143
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16144
- if (filter) {
16145
- rel.getter = filter.getter;
16146
- }
16147
- // Attach where-clause metadata for Rust-side post-getter filtering.
16148
- // Property values are signed expression envelopes (literal:json:...)
16149
- // and cannot be matched by SPARQL FILTER on the raw IRI.
16150
- if (rel.where) {
16151
- try {
16152
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16153
- if (targetMetadata) {
16154
- const predicates = {};
16155
- for (const propName of Object.keys(rel.where)) {
16156
- if (['id', 'author', 'timestamp'].includes(propName))
16157
- continue;
16158
- const propMeta = targetMetadata.properties[propName];
16159
- if (propMeta?.predicate) {
16160
- predicates[propName] = propMeta.predicate;
16161
- }
16162
- }
16163
- if (Object.keys(predicates).length > 0) {
16164
- rel.whereFilter = rel.where;
16165
- rel.wherePredicates = predicates;
16166
- }
16167
- }
16168
- }
16169
- catch (_) { /* target metadata unavailable */ }
16170
- }
16171
- }
16172
- catch (e) {
16173
- // Target class may not be available; skip silently
16174
- }
16175
- }
16176
- }
16177
- // Send shape metadata to the executor so it knows the model structure.
16178
- // This is more reliable than reading SHACL from the store because
16179
- // the TS decorators are the definitive source of truth.
16180
- const shapeJson = JSON.stringify(metadata);
16181
- const queryJson = JSON.stringify(queryInput);
16182
- const result = await perspective.modelQuery(className, queryJson, shapeJson);
16164
+ // Conformance getters, where filters, and target shapes for includes
16165
+ // are all resolved by the executor from the perspective's SHACL triples
16166
+ // — no client-side pre-computation is needed any more.
16167
+ return {
16168
+ className,
16169
+ queryJson: JSON.stringify(queryInput),
16170
+ metadata,
16171
+ };
16172
+ }
16173
+ /**
16174
+ * Parse raw model query/subscription result JSON into typed model instances.
16175
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
16176
+ * @internal
16177
+ */
16178
+ static parseModelResult(perspective, raw, include, properties) {
16179
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
16180
+ const arr = data.instances || data;
16181
+ if (!Array.isArray(arr))
16182
+ return [];
16183
+ return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
16184
+ }
16185
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
16186
+ /**
16187
+ * Execute a model query via the executor-side endpoint.
16188
+ *
16189
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
16190
+ * with a single RPC to the executor that handles everything in Rust.
16191
+ *
16192
+ * @internal
16193
+ */
16194
+ static async executeModelQuery(perspective, query = {}, classNameOverride) {
16195
+ // Delegate query input building to the shared prepareModelQueryParams
16196
+ // helper. The executor resolves the shape from SHACL server-side.
16197
+ const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16198
+ const result = await perspective.modelQuery(className, queryJson);
16183
16199
  // Convert JSON instances to model class instances, recursively constructing
16184
16200
  // class instances for any included relations resolved by Rust.
16185
16201
  const instances = result.instances.map((json) => {
16186
16202
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
16187
16203
  });
16188
- // Resolve non-literal expressions (e.g. file languages where the stored
16189
- // value is a content-addressed hash that must be fetched from the language
16190
- // runtime). The Rust endpoint returns raw target URIs; we resolve them here.
16191
- const propsMeta = getPropertiesMetadata(this);
16192
- const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
16193
- opts.resolveLanguage !== 'literal');
16194
- if (resolveProps.length > 0) {
16195
- await Promise.all(instances.map(async (inst) => {
16196
- for (const [propName, opts] of resolveProps) {
16197
- const val = inst[propName];
16198
- if (typeof val !== 'string' || !val || val.startsWith('literal:'))
16199
- continue;
16200
- try {
16201
- const expression = await perspective.getExpression(val);
16202
- if (expression) {
16203
- let resolved;
16204
- try {
16205
- resolved = JSON.parse(expression.data);
16206
- }
16207
- catch {
16208
- resolved = expression.data;
16209
- }
16210
- const transform = opts.transform;
16211
- inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
16212
- }
16213
- }
16214
- catch (_) { /* resolution failed — keep raw value */ }
16215
- }
16216
- }));
16217
- }
16218
- // Take snapshots for dirty tracking
16219
- const snapshotRelations = queryInput.include;
16204
+ // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
16205
+ const snapshotRelations = query.include
16206
+ ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
16207
+ : undefined;
16220
16208
  for (const inst of instances) {
16221
- inst.takeSnapshot(snapshotRelations);
16209
+ inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
16222
16210
  }
16223
16211
  return {
16224
16212
  results: instances,
@@ -16230,15 +16218,14 @@ class Ad4mModel {
16230
16218
  *
16231
16219
  * @param perspective - The perspective to search in
16232
16220
  * @param query - Optional query parameters to filter results
16233
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
16221
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16222
+ * All queries now use the Rust SPARQL pipeline.
16234
16223
  * @returns Array of matching models
16235
16224
  *
16236
16225
  * @example
16237
16226
  * ```typescript
16238
- * // Get all recipes (uses SPARQL by default)
16239
16227
  * const allRecipes = await Recipe.findAll(perspective);
16240
16228
  *
16241
- * // Get recipes with specific criteria (uses SPARQL)
16242
16229
  * const recipes = await Recipe.findAll(perspective, {
16243
16230
  * where: {
16244
16231
  * name: "Pasta",
@@ -16247,16 +16234,14 @@ class Ad4mModel {
16247
16234
  * order: { createdAt: "DESC" },
16248
16235
  * limit: 10
16249
16236
  * });
16250
- *
16251
- * // Explicitly use Prolog (legacy, for backward compatibility)
16252
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
16253
16237
  * ```
16254
16238
  */
16255
- static async findAll(perspective, query = {}, _engine) {
16256
- if (query.properties && query.properties.length === 0) {
16239
+ static async findAll(perspective, query) {
16240
+ const q = (query ?? {});
16241
+ if (q.properties && q.properties.length === 0) {
16257
16242
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16258
16243
  }
16259
- const { results } = await this.executeModelQuery(perspective, query);
16244
+ const { results } = await this.executeModelQuery(perspective, q);
16260
16245
  return results;
16261
16246
  }
16262
16247
  /**
@@ -16266,7 +16251,7 @@ class Ad4mModel {
16266
16251
  *
16267
16252
  * @param perspective - The perspective to search in
16268
16253
  * @param query - Optional query parameters to filter results
16269
- * @param useSPARQL - Whether to use SPARQL (default: true) or Prolog (legacy)
16254
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16270
16255
  * @returns The first matching instance, or `null`
16271
16256
  *
16272
16257
  * @example
@@ -16279,8 +16264,8 @@ class Ad4mModel {
16279
16264
  * }
16280
16265
  * ```
16281
16266
  */
16282
- static async findOne(perspective, query = {}, _engine) {
16283
- const limitedQuery = { ...query, limit: 1 };
16267
+ static async findOne(perspective, query) {
16268
+ const limitedQuery = { ...(query ?? {}), limit: 1 };
16284
16269
  const results = await this.findAll(perspective, limitedQuery);
16285
16270
  return results[0] ?? null;
16286
16271
  }
@@ -16289,7 +16274,7 @@ class Ad4mModel {
16289
16274
  *
16290
16275
  * @param perspective - The perspective to search in
16291
16276
  * @param query - Optional query parameters to filter results
16292
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
16277
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16293
16278
  * @returns Object containing results array and total count
16294
16279
  *
16295
16280
  * @example
@@ -16299,13 +16284,11 @@ class Ad4mModel {
16299
16284
  * limit: 10
16300
16285
  * });
16301
16286
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16302
- *
16303
- * // Use Prolog explicitly (legacy)
16304
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
16305
16287
  * ```
16306
16288
  */
16307
- static async findAllAndCount(perspective, query = {}, _engine) {
16308
- return await this.executeModelQuery(perspective, query);
16289
+ static async findAllAndCount(perspective, query) {
16290
+ const out = await this.executeModelQuery(perspective, (query ?? {}));
16291
+ return out;
16309
16292
  }
16310
16293
  /**
16311
16294
  * Helper function for pagination with explicit page size and number.
@@ -16324,10 +16307,10 @@ class Ad4mModel {
16324
16307
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16325
16308
  * ```
16326
16309
  */
16327
- static async paginate(perspective, pageSize, pageNumber, query, _engine) {
16328
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16310
+ static async paginate(perspective, pageSize, pageNumber, query) {
16311
+ const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16329
16312
  const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
16330
- return { results, totalCount, pageSize, pageNumber };
16313
+ return { results: results, totalCount, pageSize, pageNumber };
16331
16314
  }
16332
16315
  /**
16333
16316
  * Generates a SPARQL COUNT query for the model.
@@ -16354,8 +16337,8 @@ class Ad4mModel {
16354
16337
  * });
16355
16338
  * ```
16356
16339
  */
16357
- static async count(perspective, query = {}) {
16358
- const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
16340
+ static async count(perspective, query) {
16341
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
16359
16342
  return totalCount;
16360
16343
  }
16361
16344
  async setProperty(key, value, batchId) {
@@ -16666,27 +16649,10 @@ class Ad4mModel {
16666
16649
  if (instances.length === 0)
16667
16650
  return;
16668
16651
  const metadata = this.getModelMetadata();
16669
- // Pre-compute conformance getters so the shape sent to Rust includes them
16670
- const allRelMeta = getRelationsMetadata(this);
16671
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16672
- const rel = relMeta;
16673
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16674
- continue;
16675
- const meta = allRelMeta[relName];
16676
- if (!meta?.target)
16677
- continue;
16678
- try {
16679
- const TargetClass = meta.target();
16680
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16681
- if (filter)
16682
- rel.getter = filter.getter;
16683
- }
16684
- catch (_) { /* target class may not be available */ }
16685
- }
16686
- const shapeJson = JSON.stringify(metadata);
16687
16652
  const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
16688
- // Single RPC call evaluates all getters in-process on the executor
16689
- const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
16653
+ // The executor reads getter SPARQL from the perspective's SHACL triples
16654
+ // (written by `addSdna`), so no shape JSON is shipped with the call.
16655
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
16690
16656
  // Determine which property names were evaluated for snapshot sync
16691
16657
  const evaluatedPropertyNames = [];
16692
16658
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
@@ -16977,6 +16943,22 @@ class Ad4mModel {
16977
16943
  static async register(perspective) {
16978
16944
  await perspective.ensureSDNASubjectClass(this);
16979
16945
  }
16946
+ /**
16947
+ * Batch-registers multiple model classes on a perspective in a single RPC call.
16948
+ * This is significantly faster than calling `register()` on each model individually
16949
+ * because it eliminates N-1 round-trips and mutex acquisitions.
16950
+ *
16951
+ * @param perspective - The perspective to register the models on
16952
+ * @param models - Array of Ad4mModel subclasses to register
16953
+ *
16954
+ * @example
16955
+ * ```typescript
16956
+ * await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);
16957
+ * ```
16958
+ */
16959
+ static async registerAll(perspective, models) {
16960
+ await perspective.ensureSubjectClasses(models);
16961
+ }
16980
16962
  /**
16981
16963
  * Executes a set of model operations inside a single batch (transaction).
16982
16964
  *
@@ -17034,7 +17016,7 @@ class Ad4mModel {
17034
17016
  * ```
17035
17017
  */
17036
17018
  static query(perspective, query) {
17037
- return new ModelQueryBuilder(perspective, this, query);
17019
+ return new ModelQueryBuilder(perspective, this, (query ?? {}));
17038
17020
  }
17039
17021
  /**
17040
17022
  * Creates an Ad4mModel class from a JSON Schema definition.
@@ -17221,7 +17203,7 @@ var _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_a
17221
17203
  * for the respective functionality.
17222
17204
  */
17223
17205
  class Ad4mClient {
17224
- constructor(baseUrl, token, subscribe = true) {
17206
+ constructor(baseUrl, token, subscribe = true, options) {
17225
17207
  _Ad4mClient_baseUrl.set(this, void 0);
17226
17208
  _Ad4mClient_token.set(this, void 0);
17227
17209
  _Ad4mClient_apiClient.set(this, void 0);
@@ -17234,7 +17216,7 @@ class Ad4mClient {
17234
17216
  _Ad4mClient_aiClient.set(this, void 0);
17235
17217
  __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
17236
17218
  __classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
17237
- __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token), "f");
17219
+ __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
17238
17220
  __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17239
17221
  __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17240
17222
  __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
@@ -17443,6 +17425,71 @@ class PerspectiveHandle {
17443
17425
  }
17444
17426
  }
17445
17427
 
17428
+ /**
17429
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
17430
+ *
17431
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
17432
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
17433
+ * RDF store the bindings are still in encoded form; consumers must decode
17434
+ * before use. The helpers here centralise that decode step so each call site
17435
+ * can pick the variant matching its declared binding type.
17436
+ *
17437
+ * @example
17438
+ * ```ts
17439
+ * interface MessageBinding {
17440
+ * id: string;
17441
+ * timestamp: string; // raw literal — decode with parseLitNumber
17442
+ * body?: string; // raw literal — decode with parseLit
17443
+ * }
17444
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
17445
+ * const ts = parseLitNumber(rows[0].timestamp); // number
17446
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
17447
+ * ```
17448
+ */
17449
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
17450
+ function parseSparqlCount(result) {
17451
+ if (!result || result.length === 0)
17452
+ return 0;
17453
+ const raw = result[0].count;
17454
+ const n = parseInt(raw, 10);
17455
+ return Number.isNaN(n) ? 0 : n;
17456
+ }
17457
+ /**
17458
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
17459
+ *
17460
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
17461
+ * input. Falls through to the raw value if decoding fails (defensive — the
17462
+ * binding may already be a plain string for unwrapped properties).
17463
+ */
17464
+ function parseLit(val) {
17465
+ if (val === undefined || val === null || val === '')
17466
+ return '';
17467
+ try {
17468
+ const result = Literal.fromUrl(val).get();
17469
+ if (result && typeof result === 'object') {
17470
+ return result.data ?? JSON.stringify(result);
17471
+ }
17472
+ return String(result);
17473
+ }
17474
+ catch {
17475
+ return val;
17476
+ }
17477
+ }
17478
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
17479
+ function parseLitNumber(val) {
17480
+ if (val === undefined || val === null || val === '')
17481
+ return 0;
17482
+ const decoded = parseLit(val);
17483
+ const n = Number(decoded);
17484
+ return Number.isNaN(n) ? 0 : n;
17485
+ }
17486
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
17487
+ function parseLitBoolean(val) {
17488
+ if (val === undefined || val === null || val === '')
17489
+ return false;
17490
+ return parseLit(val) === 'true';
17491
+ }
17492
+
17446
17493
  /**
17447
17494
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
17448
17495
  *
@@ -17542,10 +17589,11 @@ class WakerSubscriptionManager {
17542
17589
  const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
17543
17590
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
17544
17591
  const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
17545
- if (Array.isArray(parentResult)) {
17546
- for (const link of parentResult) {
17547
- if (link && link.source) {
17548
- parents.push(link.source);
17592
+ const bindings = parentResult?.results?.bindings;
17593
+ if (Array.isArray(bindings)) {
17594
+ for (const binding of bindings) {
17595
+ if (binding?.source?.value) {
17596
+ parents.push(binding.source.value);
17549
17597
  }
17550
17598
  }
17551
17599
  }
@@ -17728,6 +17776,195 @@ function isIncludeProjection(val) {
17728
17776
  return typeof val === 'object' && val !== null && 'from' in val;
17729
17777
  }
17730
17778
 
17779
+ /**
17780
+ * Shared query compilation utilities.
17781
+ *
17782
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
17783
+ * the compile-time SHACL generator (`decorators.ts`).
17784
+ *
17785
+ * All output uses native SPARQL syntax.
17786
+ */
17787
+ /**
17788
+ * Format a JavaScript value for embedding in a query expression.
17789
+ *
17790
+ * - Strings are single-quoted with backslash / quote / newline escaping
17791
+ * - Numbers and booleans are passed through as-is
17792
+ * - Arrays are recursed
17793
+ */
17794
+ function formatQueryValue(value) {
17795
+ if (typeof value === 'string') {
17796
+ // Escape backslashes first, then single quotes and other special characters
17797
+ const escaped = value
17798
+ .replace(/\\/g, '\\\\') // Backslash -> \\
17799
+ .replace(/'/g, "\\'") // Single quote -> \'
17800
+ .replace(/"/g, '\\"') // Double quote -> \"
17801
+ .replace(/\n/g, '\\n') // Newline -> \n
17802
+ .replace(/\r/g, '\\r') // Carriage return -> \r
17803
+ .replace(/\t/g, '\\t'); // Tab -> \t
17804
+ return `'${escaped}'`;
17805
+ }
17806
+ else if (typeof value === 'number' || typeof value === 'boolean') {
17807
+ return String(value);
17808
+ }
17809
+ else if (Array.isArray(value)) {
17810
+ return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
17811
+ }
17812
+ else {
17813
+ return String(value);
17814
+ }
17815
+ }
17816
+ /**
17817
+ * Compile a single Where condition for a property into a SPARQL triple pattern
17818
+ * that can be embedded in a getter's WHERE clause.
17819
+ *
17820
+ * The generated pattern operates on `?target` — e.g.:
17821
+ * `?target <pred> <value> .`
17822
+ * `FILTER EXISTS { ?target <pred> ?_v0 }`
17823
+ *
17824
+ * @param predicate - The predicate URI for the property
17825
+ * @param condition - The Where condition value
17826
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
17827
+ * @returns A single SPARQL condition string
17828
+ */
17829
+ function buildWhereCondition(predicate, condition, opts) {
17830
+ const escapedPredicate = escapeQueryString(predicate);
17831
+ // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
17832
+ // For language-resolved properties, we match against the plain URI
17833
+ // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
17834
+ // For language-resolved properties, values are plain URIs
17835
+ const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
17836
+ const varSuffix = opts?.varIndex ?? 0;
17837
+ function formatValue(v) {
17838
+ if (typeof v === 'string') {
17839
+ return isLiteral
17840
+ ? `<literal:string:${escapeQueryString(v)}>`
17841
+ : `<${escapeQueryString(v)}>`;
17842
+ }
17843
+ // Numbers/booleans — also stored as literal:string: in AD4M
17844
+ return `<literal:string:${v}>`;
17845
+ }
17846
+ /**
17847
+ * For literal properties, generate a FILTER-based match that handles both
17848
+ * the raw value and the literal-encoded value. This mirrors the Rust
17849
+ * `build_projection_where_patterns` approach which uses:
17850
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
17851
+ * This is more robust than exact IRI matching because it handles edge cases
17852
+ * where the stored format might vary.
17853
+ */
17854
+ function formatLiteralFilter(varName, v) {
17855
+ const raw = escapeQueryString(String(v));
17856
+ const encoded = encodeURIComponent(String(v))
17857
+ .replace(/!/g, '%21')
17858
+ .replace(/'/g, '%27')
17859
+ .replace(/\(/g, '%28')
17860
+ .replace(/\)/g, '%29')
17861
+ .replace(/\*/g, '%2A');
17862
+ if (typeof v === 'string') {
17863
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
17864
+ }
17865
+ else if (typeof v === 'number') {
17866
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
17867
+ }
17868
+ else if (typeof v === 'boolean') {
17869
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
17870
+ }
17871
+ return `FILTER(STR(${varName}) = "${raw}")`;
17872
+ }
17873
+ if (Array.isArray(condition)) {
17874
+ // Array values → FILTER IN
17875
+ if (isLiteral) {
17876
+ const varName = `?_wc${varSuffix}`;
17877
+ const inValues = condition.flatMap(v => {
17878
+ const raw = escapeQueryString(String(v));
17879
+ const encoded = encodeURIComponent(String(v))
17880
+ .replace(/!/g, '%21').replace(/'/g, '%27')
17881
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
17882
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
17883
+ }).join(', ');
17884
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
17885
+ }
17886
+ const formattedValues = condition.map(formatValue).join(', ');
17887
+ return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
17888
+ }
17889
+ else if (typeof condition === 'object' && condition !== null) {
17890
+ // Operator object
17891
+ const ops = condition;
17892
+ const parts = [];
17893
+ if (ops.not !== undefined) {
17894
+ if (Array.isArray(ops.not)) {
17895
+ const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
17896
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17897
+ // so O(N²) behavior is bounded by the number of values for this property.
17898
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
17899
+ }
17900
+ else {
17901
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17902
+ // so O(N²) behavior is bounded by the number of values for this property.
17903
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
17904
+ }
17905
+ }
17906
+ // Comparison operators — ensure property exists
17907
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
17908
+ ops.lt !== undefined || ops.lte !== undefined ||
17909
+ ops.between !== undefined || ops.contains !== undefined;
17910
+ if (hasComparisonOps) {
17911
+ parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
17912
+ }
17913
+ return parts.join(' ');
17914
+ }
17915
+ else {
17916
+ // Simple equality
17917
+ if (isLiteral) {
17918
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
17919
+ // to handle both raw values and literal-encoded IRIs robustly.
17920
+ const varName = `?_wc${varSuffix}`;
17921
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
17922
+ }
17923
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
17924
+ }
17925
+ }
17926
+ /**
17927
+ * Compile a full `Where` clause to an array of SPARQL condition strings.
17928
+ *
17929
+ * When `metadata` is provided, property names are resolved to predicates
17930
+ * using the model's property metadata. When `metadata` is `null`, property
17931
+ * names are treated as raw predicate URIs.
17932
+ *
17933
+ * Only handles **regular properties** — special fields (`id`, `author`,
17934
+ * `timestamp`) and relation fields are skipped (they are only relevant at
17935
+ * runtime query time, not for compile-time getter generation).
17936
+ */
17937
+ function compileWhereClause(where, metadata) {
17938
+ const conditions = [];
17939
+ for (const [propertyName, condition] of Object.entries(where)) {
17940
+ // Skip special fields that don't apply at compile time
17941
+ if (['id', 'author', 'timestamp'].includes(propertyName))
17942
+ continue;
17943
+ let predicate;
17944
+ let resolveLanguage;
17945
+ if (metadata) {
17946
+ const propMeta = metadata.properties[propertyName];
17947
+ if (propMeta) {
17948
+ predicate = propMeta.predicate;
17949
+ resolveLanguage = propMeta.resolveLanguage;
17950
+ }
17951
+ else {
17952
+ // Property not found in metadata — treat name as raw predicate URI
17953
+ predicate = propertyName;
17954
+ }
17955
+ }
17956
+ else {
17957
+ // No metadata — treat name as raw predicate URI
17958
+ predicate = propertyName;
17959
+ }
17960
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
17961
+ if (cond) {
17962
+ conditions.push(cond);
17963
+ }
17964
+ }
17965
+ return conditions;
17966
+ }
17967
+
17731
17968
  class Neighbourhood {
17732
17969
  constructor(linkLanguage, meta) {
17733
17970
  this.linkLanguage = linkLanguage;
@@ -17760,6 +17997,112 @@ class ModelInput {
17760
17997
  class VoiceActivityParamsInput {
17761
17998
  }
17762
17999
 
18000
+ /**
18001
+ * Builder functions for SHACL-AF Node Expressions.
18002
+ *
18003
+ * These functions construct JSON-serializable expression trees for property transforms.
18004
+ * All builders return frozen objects to prevent accidental mutation.
18005
+ */
18006
+ /**
18007
+ * Identity expression: pass the focus node through unchanged.
18008
+ */
18009
+ function focus() {
18010
+ return Object.freeze({ type: 'focus' });
18011
+ }
18012
+ /**
18013
+ * Literal constant expression.
18014
+ */
18015
+ function literal(value) {
18016
+ return Object.freeze({ type: 'literal', value });
18017
+ }
18018
+ /**
18019
+ * Path expression: navigate to a property on the resolved object.
18020
+ * The predicate can be a full IRI (e.g., "file_storage://data_base64")
18021
+ * or a simple property name. The Rust evaluator will strip the namespace.
18022
+ */
18023
+ function path(predicate) {
18024
+ return Object.freeze({ type: 'path', predicate });
18025
+ }
18026
+ /**
18027
+ * Existence check: returns true if the inner expression is non-null and non-empty.
18028
+ */
18029
+ function exists(expr) {
18030
+ return Object.freeze({ type: 'exists', expr });
18031
+ }
18032
+ /**
18033
+ * Conditional expression with optional else branch.
18034
+ * Returns a chainable builder that supports `.then()` and `.else()`.
18035
+ */
18036
+ function ifExpr(cond) {
18037
+ return {
18038
+ then: (thenExpr) => ({
18039
+ else: (elseExpr) => {
18040
+ return Object.freeze({
18041
+ type: 'if',
18042
+ cond,
18043
+ then: thenExpr,
18044
+ ...(elseExpr !== undefined && { else: elseExpr }),
18045
+ });
18046
+ },
18047
+ // Allow chaining without explicit else()
18048
+ toExpression: () => Object.freeze({
18049
+ type: 'if',
18050
+ cond,
18051
+ then: thenExpr,
18052
+ }),
18053
+ }),
18054
+ };
18055
+ }
18056
+ /**
18057
+ * String concatenation: joins evaluated arguments as strings.
18058
+ * Null/undefined arguments are skipped.
18059
+ */
18060
+ function concat(...args) {
18061
+ return Object.freeze({ type: 'concat', args });
18062
+ }
18063
+ /**
18064
+ * Coalesce: returns the first non-null evaluated argument.
18065
+ */
18066
+ function coalesce(...args) {
18067
+ return Object.freeze({ type: 'coalesce', args });
18068
+ }
18069
+ /**
18070
+ * Function call: invoke a named transform function by IRI.
18071
+ * Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
18072
+ */
18073
+ function fn(iri, args = []) {
18074
+ return Object.freeze({ type: 'function', iri, args });
18075
+ }
18076
+
18077
+ /**
18078
+ * SHACL-AF Transform DSL — public API
18079
+ *
18080
+ * Re-exports builder functions and provides common built-in transforms.
18081
+ */
18082
+ /**
18083
+ * Built-in transform: FileData → data: URI
18084
+ *
18085
+ * Converts a file stored via FILE_STORAGE_LANGUAGE into a data: URL.
18086
+ * If the object has a `data_base64` field, returns:
18087
+ * `data:{file_type};base64,{data_base64}`
18088
+ * Otherwise passes through the input unchanged.
18089
+ *
18090
+ * This is the Rust equivalent of the JS `defaultFileDecode` function.
18091
+ *
18092
+ * Usage:
18093
+ * ```typescript
18094
+ * @Property({
18095
+ * through: 'we://image',
18096
+ * resolveLanguage: FILE_STORAGE_LANGUAGE,
18097
+ * transform: fileToDataUri,
18098
+ * })
18099
+ * avatar?: string;
18100
+ * ```
18101
+ */
18102
+ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
18103
+ .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
18104
+ .else(focus());
18105
+
17763
18106
  exports.AIClient = AIClient;
17764
18107
  exports.AIModel = Model;
17765
18108
  exports.AIModelLoadingStatus = AIModelLoadingStatus;
@@ -17869,17 +18212,22 @@ exports.buildModelFromJSONSchema = buildModelFromJSONSchema;
17869
18212
  exports.buildPaginationSubquery = buildPaginationSubquery;
17870
18213
  exports.buildSDNA = buildSDNA;
17871
18214
  exports.buildSHACL = buildSHACL;
17872
- exports.buildSPARQLOrderLimitOffset = buildSPARQLOrderLimitOffset;
17873
18215
  exports.buildSPARQLQuery = buildSPARQLQuery;
17874
18216
  exports.buildWhereCondition = buildWhereCondition;
17875
18217
  exports.capSentence = capSentence;
17876
18218
  exports.clearQueryCache = clearQueryCache;
18219
+ exports.coalesce = coalesce;
17877
18220
  exports.compileWhereClause = compileWhereClause;
18221
+ exports.concat = concat;
17878
18222
  exports.createPersistentCache = createPersistentCache;
17879
18223
  exports.determineNamespace = determineNamespace;
17880
18224
  exports.determinePredicate = determinePredicate;
17881
18225
  exports.escapeQueryString = escapeQueryString;
18226
+ exports.exists = exists;
17882
18227
  exports.exprRef2String = exprRef2String;
18228
+ exports.fileToDataUri = fileToDataUri;
18229
+ exports.fn = fn;
18230
+ exports.focus = focus;
17883
18231
  exports.formatList = formatList;
17884
18232
  exports.formatQueryValue = formatQueryValue;
17885
18233
  exports.formatSPARQLValue = formatSPARQLValue;
@@ -17890,19 +18238,27 @@ exports.getPropertiesMetadata = getPropertiesMetadata;
17890
18238
  exports.getPropertyOption = getPropertyOption;
17891
18239
  exports.getRelationsMetadata = getRelationsMetadata;
17892
18240
  exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
18241
+ exports.ifExpr = ifExpr;
17893
18242
  exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
17894
18243
  exports.isArrayType = isArrayType;
17895
18244
  exports.isExpression = isExpression;
17896
18245
  exports.isIncludeProjection = isIncludeProjection;
17897
18246
  exports.isLink = isLink;
18247
+ exports.isNodeExpression = isNodeExpression;
17898
18248
  exports.isNumericType = isNumericType;
17899
18249
  exports.isObjectType = isObjectType;
17900
18250
  exports.isSchemaType = isSchemaType;
17901
18251
  exports.linkEqual = linkEqual;
18252
+ exports.literal = literal;
17902
18253
  exports.normalizeNamespaceString = normalizeNamespaceString;
17903
18254
  exports.normalizeSchemaType = normalizeSchemaType;
17904
18255
  exports.normalizeValue = normalizeValue;
17905
18256
  exports.parseExprUrl = parseExprUrl;
18257
+ exports.parseLit = parseLit;
18258
+ exports.parseLitBoolean = parseLitBoolean;
18259
+ exports.parseLitNumber = parseLitNumber;
18260
+ exports.parseSparqlCount = parseSparqlCount;
18261
+ exports.path = path;
17906
18262
  exports.queryCacheSize = queryCacheSize;
17907
18263
  exports.resolveParentPredicate = resolveParentPredicate;
17908
18264
  exports.setCachedResult = setCachedResult;