@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
@@ -0,0 +1,224 @@
1
+ import { PerspectiveClient } from "./PerspectiveClient";
2
+ import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle";
3
+ /**
4
+ * Focused unit tests for PerspectiveClient proxy cache behaviour.
5
+ * Uses a mock Apollo client to isolate cache logic from network.
6
+ */
7
+ // Minimal mock Apollo client that returns controllable results
8
+ function createMockApolloClient(overrides = {}) {
9
+ return {
10
+ query: overrides.query || jest.fn().mockResolvedValue({ data: {} }),
11
+ mutate: overrides.mutate || jest.fn().mockResolvedValue({ data: {} }),
12
+ subscribe: overrides.subscribe || jest.fn().mockReturnValue({
13
+ subscribe: jest.fn()
14
+ }),
15
+ };
16
+ }
17
+ function makeHandle(uuid, name, state = PerspectiveState.Private) {
18
+ const h = new PerspectiveHandle(uuid, name, state);
19
+ return h;
20
+ }
21
+ describe('PerspectiveClient proxy cache', () => {
22
+ it('byUUID returns the same proxy reference on cache hit', async () => {
23
+ const handle = makeHandle('uuid-1', 'Test');
24
+ const mockClient = createMockApolloClient({
25
+ query: jest.fn().mockResolvedValue({
26
+ data: { perspective: handle }
27
+ }),
28
+ });
29
+ const client = new PerspectiveClient(mockClient, false);
30
+ const p1 = await client.byUUID('uuid-1');
31
+ const p2 = await client.byUUID('uuid-1');
32
+ expect(p1).toBe(p2);
33
+ // Only one query should have been made (second is cache hit)
34
+ expect(mockClient.query).toHaveBeenCalledTimes(1);
35
+ });
36
+ it('byUUID returns null for non-existent perspectives', async () => {
37
+ const mockClient = createMockApolloClient({
38
+ query: jest.fn().mockResolvedValue({
39
+ data: { perspective: null }
40
+ }),
41
+ });
42
+ const client = new PerspectiveClient(mockClient, false);
43
+ const p = await client.byUUID('non-existent');
44
+ expect(p).toBeNull();
45
+ });
46
+ it('all() populates cache so subsequent byUUID is a hit', async () => {
47
+ const handles = [
48
+ makeHandle('uuid-a', 'A'),
49
+ makeHandle('uuid-b', 'B'),
50
+ ];
51
+ const queryFn = jest.fn()
52
+ .mockResolvedValueOnce({ data: { perspectives: handles } });
53
+ const mockClient = createMockApolloClient({ query: queryFn });
54
+ const client = new PerspectiveClient(mockClient, false);
55
+ const all = await client.all();
56
+ expect(all.length).toBe(2);
57
+ // byUUID should be a cache hit — no additional query
58
+ const pa = await client.byUUID('uuid-a');
59
+ expect(pa).toBe(all[0]);
60
+ expect(queryFn).toHaveBeenCalledTimes(1); // only the all() query
61
+ });
62
+ it('add() populates cache', async () => {
63
+ const handle = makeHandle('uuid-new', 'New');
64
+ const mockClient = createMockApolloClient({
65
+ mutate: jest.fn().mockResolvedValue({
66
+ data: { perspectiveAdd: handle }
67
+ }),
68
+ });
69
+ const client = new PerspectiveClient(mockClient, false);
70
+ const added = await client.add('New');
71
+ expect(added.uuid).toBe('uuid-new');
72
+ // byUUID should hit cache
73
+ const fetched = await client.byUUID('uuid-new');
74
+ expect(fetched).toBe(added);
75
+ });
76
+ it('update() evicts and recreates cached proxy', async () => {
77
+ const originalHandle = makeHandle('uuid-u', 'Original');
78
+ const updatedHandle = makeHandle('uuid-u', 'Updated');
79
+ const queryFn = jest.fn().mockResolvedValue({
80
+ data: { perspective: originalHandle }
81
+ });
82
+ const mutateFn = jest.fn().mockResolvedValue({
83
+ data: { perspectiveUpdate: updatedHandle }
84
+ });
85
+ const mockClient = createMockApolloClient({
86
+ query: queryFn,
87
+ mutate: mutateFn,
88
+ });
89
+ const client = new PerspectiveClient(mockClient, false);
90
+ const original = await client.byUUID('uuid-u');
91
+ expect(original.name).toBe('Original');
92
+ const updated = await client.update('uuid-u', 'Updated');
93
+ expect(updated).not.toBe(original); // new reference after eviction
94
+ expect(updated.name).toBe('Updated');
95
+ expect(original.name).toBe('Original'); // old reference retains stale data
96
+ });
97
+ it('remove() evicts from cache', async () => {
98
+ const handle = makeHandle('uuid-r', 'ToRemove');
99
+ const queryFn = jest.fn().mockResolvedValue({
100
+ data: { perspective: handle }
101
+ });
102
+ const mutateFn = jest.fn().mockResolvedValue({
103
+ data: { perspectiveRemove: true }
104
+ });
105
+ const mockClient = createMockApolloClient({
106
+ query: queryFn,
107
+ mutate: mutateFn,
108
+ });
109
+ const client = new PerspectiveClient(mockClient, false);
110
+ const p = await client.byUUID('uuid-r');
111
+ expect(p).toBeTruthy();
112
+ expect(queryFn).toHaveBeenCalledTimes(1);
113
+ await client.remove('uuid-r');
114
+ // byUUID should miss cache and query again
115
+ const handle2 = makeHandle('uuid-r', 'Recreated');
116
+ queryFn.mockResolvedValueOnce({ data: { perspective: handle2 } });
117
+ const p2 = await client.byUUID('uuid-r');
118
+ expect(p2).not.toBe(p);
119
+ expect(p2.name).toBe('Recreated');
120
+ expect(queryFn).toHaveBeenCalledTimes(2);
121
+ });
122
+ it('getOrCreateProxy does not re-register listeners on cache hit', async () => {
123
+ // Verify that getting the same proxy twice does not create duplicate subscriptions
124
+ const handle = makeHandle('uuid-dup', 'NoDuplicates');
125
+ const subscribeCalls = [];
126
+ const subscribeFn = jest.fn().mockImplementation((opts) => {
127
+ // Track subscription query names
128
+ const queryStr = opts.query?.loc?.source?.body || '';
129
+ subscribeCalls.push(queryStr);
130
+ return {
131
+ subscribe: jest.fn()
132
+ };
133
+ });
134
+ const queryFn = jest.fn()
135
+ .mockResolvedValueOnce({ data: { perspectives: [handle] } });
136
+ const mockClient = createMockApolloClient({
137
+ query: queryFn,
138
+ subscribe: subscribeFn,
139
+ });
140
+ const client = new PerspectiveClient(mockClient, false);
141
+ const all = await client.all();
142
+ const firstProxy = all[0];
143
+ // Record how many subscribe calls happened from PerspectiveProxy constructor
144
+ const callsAfterFirst = subscribeFn.mock.calls.length;
145
+ // Get same proxy again via all() — should be cache hit, no new constructor call
146
+ queryFn.mockResolvedValueOnce({ data: { perspectives: [handle] } });
147
+ const all2 = await client.all();
148
+ const secondProxy = all2[0];
149
+ expect(secondProxy).toBe(firstProxy);
150
+ // No additional subscribe calls should have been made
151
+ expect(subscribeFn.mock.calls.length).toBe(callsAfterFirst);
152
+ });
153
+ it('all() updates existing cached proxies with fresh data', async () => {
154
+ const handle1 = makeHandle('uuid-f', 'OldName');
155
+ const handle2 = makeHandle('uuid-f', 'FreshName');
156
+ const queryFn = jest.fn()
157
+ .mockResolvedValueOnce({ data: { perspective: handle1 } })
158
+ .mockResolvedValueOnce({ data: { perspectives: [handle2] } });
159
+ const mockClient = createMockApolloClient({ query: queryFn });
160
+ const client = new PerspectiveClient(mockClient, false);
161
+ const original = await client.byUUID('uuid-f');
162
+ expect(original.name).toBe('OldName');
163
+ const all = await client.all();
164
+ const refreshed = all.find(p => p.uuid === 'uuid-f');
165
+ expect(refreshed).toBe(original); // same reference
166
+ expect(refreshed.name).toBe('FreshName'); // updated in-place
167
+ expect(original.name).toBe('FreshName'); // original ref also updated
168
+ });
169
+ });
170
+ describe('PerspectiveProxy getClassShape sh:in URI-decoding', () => {
171
+ // This tests the sh:in parsing logic in getClassShape() which was fixed
172
+ // to URI-decode values from the Rust executor's SPARQL results
173
+ function parseShInValue(raw) {
174
+ // Reproduce the exact parsing logic from PerspectiveProxy.getClassShape()
175
+ try {
176
+ if (raw.startsWith('literal:string:')) {
177
+ raw = decodeURIComponent(raw.substring('literal:string:'.length));
178
+ }
179
+ return JSON.parse(raw);
180
+ }
181
+ catch {
182
+ return undefined;
183
+ }
184
+ }
185
+ it('parses plain JSON sh:in values', () => {
186
+ const result = parseShInValue('[{"value":"a"},{"value":"b","label":"B"}]');
187
+ expect(result).toEqual([
188
+ { value: 'a' },
189
+ { value: 'b', label: 'B' },
190
+ ]);
191
+ });
192
+ it('strips literal:string: prefix and parses', () => {
193
+ const result = parseShInValue('literal:string:[{"value":"x"},{"value":"y"}]');
194
+ expect(result).toEqual([
195
+ { value: 'x' },
196
+ { value: 'y' },
197
+ ]);
198
+ });
199
+ it('URI-decodes encoded sh:in values from Rust executor', () => {
200
+ // Rust executor may URI-encode the JSON when returning SPARQL results
201
+ const encoded = 'literal:string:' + encodeURIComponent('[{"value":"hello world"},{"value":"a&b"}]');
202
+ const result = parseShInValue(encoded);
203
+ expect(result).toEqual([
204
+ { value: 'hello world' },
205
+ { value: 'a&b' },
206
+ ]);
207
+ });
208
+ it('handles double-encoded brackets and quotes', () => {
209
+ const encoded = 'literal:string:%5B%7B%22value%22%3A%22active%22%7D%2C%7B%22value%22%3A%22inactive%22%7D%5D';
210
+ const result = parseShInValue(encoded);
211
+ expect(result).toEqual([
212
+ { value: 'active' },
213
+ { value: 'inactive' },
214
+ ]);
215
+ });
216
+ it('returns undefined for malformed JSON', () => {
217
+ const result = parseShInValue('literal:string:not-json');
218
+ expect(result).toBeUndefined();
219
+ });
220
+ it('handles already-decoded values without prefix', () => {
221
+ const result = parseShInValue('[{"value":"test"}]');
222
+ expect(result).toEqual([{ value: 'test' }]);
223
+ });
224
+ });
@@ -318,16 +318,19 @@ export declare class PerspectiveProxy {
318
318
  * @param query - SPARQL query string
319
319
  * @returns Query results as parsed JSON
320
320
  */
321
- querySparql(query: string): Promise<any>;
321
+ querySparql<T = any>(query: string): Promise<T>;
322
322
  /**
323
323
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
324
324
  *
325
+ * The executor resolves the model's shape from the perspective's SHACL
326
+ * triples (written by `addSdna`). Callers no longer ship shape
327
+ * metadata with the query; the perspective is the source of truth.
328
+ *
325
329
  * @param className - The model class name (e.g. "Recipe")
326
330
  * @param queryJson - Structured query as JSON string
327
- * @param shapeJson - Optional shape metadata JSON from the model class
328
331
  * @returns Object with `instances` array and `totalCount`
329
332
  */
330
- modelQuery(className: string, queryJson: string, shapeJson?: string): Promise<{
333
+ modelQuery(className: string, queryJson: string): Promise<{
331
334
  instances: any[];
332
335
  totalCount: number;
333
336
  }>;
@@ -340,11 +343,10 @@ export declare class PerspectiveProxy {
340
343
  *
341
344
  * @param className - The model class name (e.g. "Message")
342
345
  * @param instanceIds - Array of instance base expression URIs
343
- * @param shapeJson - Shape metadata JSON from the model class
344
346
  * @param propertyNames - Optional subset of property names to evaluate
345
347
  * @returns Map of instance ID → evaluated property values
346
348
  */
347
- evaluateGetters(className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
349
+ evaluateGetters(className: string, instanceIds: string[], propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
348
350
  /**
349
351
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
350
352
  * internally in Rust, registers a subscription, runs the initial query, and
@@ -355,10 +357,9 @@ export declare class PerspectiveProxy {
355
357
  *
356
358
  * @param className - The model class name
357
359
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
358
- * @param shapeJson - Optional shape metadata JSON from the model class
359
360
  * @returns Object with `subscriptionId` and initial `result`
360
361
  */
361
- modelSubscribe(className: string, queryJson: string, shapeJson?: string): Promise<{
362
+ modelSubscribe(className: string, queryJson: string): Promise<{
362
363
  subscriptionId: string;
363
364
  result: any;
364
365
  }>;
@@ -498,6 +499,10 @@ export declare class PerspectiveProxy {
498
499
  * @param cb - The callback function to remove
499
500
  */
500
501
  removeListener(type: PerspectiveListenerTypes, cb: LinkCallback): Promise<void>;
502
+ /** Clean up all subscriptions registered by this proxy.
503
+ * Call this when the proxy is no longer needed to prevent subscription leaks.
504
+ * After calling dispose(), the proxy should not be used. */
505
+ dispose(): void;
501
506
  /**
502
507
  * Creates a snapshot of the current perspective state.
503
508
  * Useful for backup or sharing.
@@ -588,6 +593,21 @@ export declare class PerspectiveProxy {
588
593
  * await perspective.addSdna('Recipe', prologCode, 'subject_class');
589
594
  */
590
595
  addSdna(name: string, sdnaCode: string, sdnaType: "subject_class" | "flow" | "custom", shaclJson?: string): Promise<boolean>;
596
+ /**
597
+ * Batch variant of addSdna — registers multiple SDNA entries in a single RPC call.
598
+ * Acquires the Rust-side mutex once for the entire batch.
599
+ */
600
+ addSdnaAll(entries: {
601
+ name: string;
602
+ sdnaCode?: string;
603
+ sdnaType: "subject_class" | "flow" | "custom";
604
+ shaclJson?: string;
605
+ }[]): Promise<boolean[]>;
606
+ /**
607
+ * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.
608
+ * Skips classes already registered on this perspective instance.
609
+ */
610
+ ensureSubjectClasses(jsClasses: any[]): Promise<void>;
591
611
  /**
592
612
  * Adds a subject class to the perspective.
593
613
  * Alias for addSdna() with sdnaType='subject_class'.
@@ -540,13 +540,16 @@ export class PerspectiveProxy {
540
540
  /**
541
541
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
542
542
  *
543
+ * The executor resolves the model's shape from the perspective's SHACL
544
+ * triples (written by `addSdna`). Callers no longer ship shape
545
+ * metadata with the query; the perspective is the source of truth.
546
+ *
543
547
  * @param className - The model class name (e.g. "Recipe")
544
548
  * @param queryJson - Structured query as JSON string
545
- * @param shapeJson - Optional shape metadata JSON from the model class
546
549
  * @returns Object with `instances` array and `totalCount`
547
550
  */
548
- async modelQuery(className, queryJson, shapeJson) {
549
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
551
+ async modelQuery(className, queryJson) {
552
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
550
553
  }
551
554
  /**
552
555
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -557,12 +560,11 @@ export class PerspectiveProxy {
557
560
  *
558
561
  * @param className - The model class name (e.g. "Message")
559
562
  * @param instanceIds - Array of instance base expression URIs
560
- * @param shapeJson - Shape metadata JSON from the model class
561
563
  * @param propertyNames - Optional subset of property names to evaluate
562
564
  * @returns Map of instance ID → evaluated property values
563
565
  */
564
- async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
565
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
566
+ async evaluateGetters(className, instanceIds, propertyNames) {
567
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
566
568
  }
567
569
  /**
568
570
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
@@ -574,11 +576,10 @@ export class PerspectiveProxy {
574
576
  *
575
577
  * @param className - The model class name
576
578
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
577
- * @param shapeJson - Optional shape metadata JSON from the model class
578
579
  * @returns Object with `subscriptionId` and initial `result`
579
580
  */
580
- async modelSubscribe(className, queryJson, shapeJson) {
581
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
581
+ async modelSubscribe(className, queryJson) {
582
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
582
583
  }
583
584
  /**
584
585
  * Adds a new link to the perspective.
@@ -766,17 +767,30 @@ export class PerspectiveProxy {
766
767
  async removeListener(type, cb) {
767
768
  if (type === 'link-added') {
768
769
  const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
769
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
770
+ if (index >= 0)
771
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
770
772
  }
771
773
  else if (type === 'link-removed') {
772
774
  const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
773
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
775
+ if (index >= 0)
776
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
774
777
  }
775
778
  else if (type === 'link-updated') {
776
779
  const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
777
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
780
+ if (index >= 0)
781
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
778
782
  }
779
783
  }
784
+ /** Clean up all subscriptions registered by this proxy.
785
+ * Call this when the proxy is no longer needed to prevent subscription leaks.
786
+ * After calling dispose(), the proxy should not be used. */
787
+ dispose() {
788
+ __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeAllListeners(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
789
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").length = 0;
790
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").length = 0;
791
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").length = 0;
792
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").length = 0;
793
+ }
780
794
  /**
781
795
  * Creates a snapshot of the current perspective state.
782
796
  * Useful for backup or sharing.
@@ -1066,6 +1080,40 @@ export class PerspectiveProxy {
1066
1080
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
1067
1081
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
1068
1082
  }
1083
+ /**
1084
+ * Batch variant of addSdna — registers multiple SDNA entries in a single RPC call.
1085
+ * Acquires the Rust-side mutex once for the entire batch.
1086
+ */
1087
+ async addSdnaAll(entries) {
1088
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdnaBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, entries);
1089
+ }
1090
+ /**
1091
+ * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.
1092
+ * Skips classes already registered on this perspective instance.
1093
+ */
1094
+ async ensureSubjectClasses(jsClasses) {
1095
+ const entries = [];
1096
+ for (const jsClass of jsClasses) {
1097
+ const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
1098
+ if (__classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
1099
+ continue;
1100
+ if (!jsClass.generateSHACL) {
1101
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
1102
+ }
1103
+ const { shape } = jsClass.generateSHACL();
1104
+ entries.push({
1105
+ name: className,
1106
+ sdnaType: 'subject_class',
1107
+ shaclJson: JSON.stringify(shape.toJSON()),
1108
+ });
1109
+ }
1110
+ if (entries.length === 0)
1111
+ return;
1112
+ await this.addSdnaAll(entries);
1113
+ for (const entry of entries) {
1114
+ __classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(entry.name);
1115
+ }
1116
+ }
1069
1117
  /**
1070
1118
  * Adds a subject class to the perspective.
1071
1119
  * Alias for addSdna() with sdnaType='subject_class'.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,34 @@
1
+ import { QuerySubscriptionProxy } from './PerspectiveProxy';
2
+ describe('QuerySubscriptionProxy', () => {
3
+ it('treats the initial subscribeQuery() result as a completed initialization', async () => {
4
+ const initialResult = [
5
+ {
6
+ source: 'literal:string:test-channel',
7
+ predicate: 'flux://has_channel_name',
8
+ target: 'literal:string:Runtime Fix Channel',
9
+ },
10
+ ];
11
+ const unsubscribe = jest.fn();
12
+ const mockClient = {
13
+ subscribeQuery: jest.fn().mockResolvedValue({
14
+ subscriptionId: 'sub-1',
15
+ result: initialResult,
16
+ }),
17
+ subscribeToQueryUpdates: jest.fn().mockReturnValue(unsubscribe),
18
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
19
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
20
+ };
21
+ const subscription = new QuerySubscriptionProxy('perspective-1', 'SELECT * WHERE { ?s ?p ?o }', mockClient);
22
+ await subscription.subscribe();
23
+ const initialized = await Promise.race([
24
+ subscription.initialized.then(() => 'resolved'),
25
+ new Promise((resolve) => setTimeout(() => resolve('timeout'), 25)),
26
+ ]);
27
+ expect(initialized).toBe('resolved');
28
+ expect(subscription.result).toEqual(initialResult);
29
+ expect(mockClient.subscribeQuery).toHaveBeenCalledWith('perspective-1', 'SELECT * WHERE { ?s ?p ?o }');
30
+ expect(mockClient.subscribeToQueryUpdates).toHaveBeenCalledWith('sub-1', expect.any(Function));
31
+ subscription.dispose();
32
+ expect(unsubscribe).toHaveBeenCalled();
33
+ });
34
+ });
@@ -22,7 +22,6 @@ export default class PerspectiveResolver {
22
22
  perspectivePublishSnapshot(uuid: string): String | null;
23
23
  perspectiveQueryLinks(uuid: string, query: LinkQuery): LinkExpression[];
24
24
  perspectiveQueryProlog(uuid: string, query: string): Promise<string>;
25
- perspectiveQuerySurrealDB(uuid: string, query: string): Promise<string>;
26
25
  perspectiveSubscribeQuery(uuid: string, query: string): Promise<QuerySubscription>;
27
26
  perspectiveAdd(name: string, pubSub: any): PerspectiveHandle;
28
27
  perspectiveUpdate(uuid: string, name: string, pubSub: any): PerspectiveHandle;
@@ -87,9 +87,6 @@ let PerspectiveResolver = class PerspectiveResolver {
87
87
  async perspectiveQueryProlog(uuid, query) {
88
88
  return `[{"X": 1}]`;
89
89
  }
90
- async perspectiveQuerySurrealDB(uuid, query) {
91
- return `[]`;
92
- }
93
90
  async perspectiveSubscribeQuery(uuid, query) {
94
91
  const result = `[{"X": 1}]`;
95
92
  return {
@@ -277,14 +274,6 @@ __decorate([
277
274
  __metadata("design:paramtypes", [String, String]),
278
275
  __metadata("design:returntype", Promise)
279
276
  ], PerspectiveResolver.prototype, "perspectiveQueryProlog", null);
280
- __decorate([
281
- Query(returns => String),
282
- __param(0, Arg('uuid')),
283
- __param(1, Arg('query')),
284
- __metadata("design:type", Function),
285
- __metadata("design:paramtypes", [String, String]),
286
- __metadata("design:returntype", Promise)
287
- ], PerspectiveResolver.prototype, "perspectiveQuerySurrealDB", null);
288
277
  __decorate([
289
278
  Mutation(returns => QuerySubscription),
290
279
  __param(0, Arg('uuid')),
@@ -0,0 +1,47 @@
1
+ /**
2
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
3
+ *
4
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
5
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
6
+ * RDF store the bindings are still in encoded form; consumers must decode
7
+ * before use. The helpers here centralise that decode step so each call site
8
+ * can pick the variant matching its declared binding type.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * interface MessageBinding {
13
+ * id: string;
14
+ * timestamp: string; // raw literal — decode with parseLitNumber
15
+ * body?: string; // raw literal — decode with parseLit
16
+ * }
17
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
18
+ * const ts = parseLitNumber(rows[0].timestamp); // number
19
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
20
+ * ```
21
+ */
22
+ /** Common AD4M link binding — matches the `?source/?predicate/?target/?author/?timestamp` pattern. */
23
+ export interface LinkBinding {
24
+ source: string;
25
+ predicate: string;
26
+ target: string;
27
+ author?: string;
28
+ timestamp?: string;
29
+ }
30
+ /** COUNT(?x) result binding — SPARQL returns counts as string literals. */
31
+ export interface CountBinding {
32
+ count: string;
33
+ }
34
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
35
+ export declare function parseSparqlCount(result: CountBinding[] | undefined | null): number;
36
+ /**
37
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
38
+ *
39
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
40
+ * input. Falls through to the raw value if decoding fails (defensive — the
41
+ * binding may already be a plain string for unwrapped properties).
42
+ */
43
+ export declare function parseLit(val: string | undefined | null): string;
44
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
45
+ export declare function parseLitNumber(val: string | undefined | null): number;
46
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
47
+ export declare function parseLitBoolean(val: string | undefined | null): boolean;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
3
+ *
4
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
5
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
6
+ * RDF store the bindings are still in encoded form; consumers must decode
7
+ * before use. The helpers here centralise that decode step so each call site
8
+ * can pick the variant matching its declared binding type.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * interface MessageBinding {
13
+ * id: string;
14
+ * timestamp: string; // raw literal — decode with parseLitNumber
15
+ * body?: string; // raw literal — decode with parseLit
16
+ * }
17
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
18
+ * const ts = parseLitNumber(rows[0].timestamp); // number
19
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
20
+ * ```
21
+ */
22
+ import { Literal } from "../Literal";
23
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
24
+ export function parseSparqlCount(result) {
25
+ if (!result || result.length === 0)
26
+ return 0;
27
+ const raw = result[0].count;
28
+ const n = parseInt(raw, 10);
29
+ return Number.isNaN(n) ? 0 : n;
30
+ }
31
+ /**
32
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
33
+ *
34
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
35
+ * input. Falls through to the raw value if decoding fails (defensive — the
36
+ * binding may already be a plain string for unwrapped properties).
37
+ */
38
+ export function parseLit(val) {
39
+ if (val === undefined || val === null || val === '')
40
+ return '';
41
+ try {
42
+ const result = Literal.fromUrl(val).get();
43
+ if (result && typeof result === 'object') {
44
+ return result.data ?? JSON.stringify(result);
45
+ }
46
+ return String(result);
47
+ }
48
+ catch {
49
+ return val;
50
+ }
51
+ }
52
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
53
+ export function parseLitNumber(val) {
54
+ if (val === undefined || val === null || val === '')
55
+ return 0;
56
+ const decoded = parseLit(val);
57
+ const n = Number(decoded);
58
+ return Number.isNaN(n) ? 0 : n;
59
+ }
60
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
61
+ export function parseLitBoolean(val) {
62
+ if (val === undefined || val === null || val === '')
63
+ return false;
64
+ return parseLit(val) === 'true';
65
+ }
@@ -97,10 +97,11 @@ export class WakerSubscriptionManager {
97
97
  const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
98
98
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
99
99
  const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
100
- if (Array.isArray(parentResult)) {
101
- for (const link of parentResult) {
102
- if (link && link.source) {
103
- parents.push(link.source);
100
+ const bindings = parentResult?.results?.bindings;
101
+ if (Array.isArray(bindings)) {
102
+ for (const binding of bindings) {
103
+ if (binding?.source?.value) {
104
+ parents.push(binding.source.value);
104
105
  }
105
106
  }
106
107
  }