@coasys/ad4m 0.12.1-dev → 0.13.0-postmessage-ws-proxy.0

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 (388) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +5097 -11841
  4. package/lib/index.js +5289 -12104
  5. package/lib/src/Ad4mClient.d.ts +9 -3
  6. package/lib/src/Ad4mClient.js +40 -13
  7. package/lib/src/Literal.js +6 -5
  8. package/lib/src/agent/Agent.js +26 -272
  9. package/lib/src/agent/AgentClient.d.ts +33 -21
  10. package/lib/src/agent/AgentClient.js +180 -374
  11. package/lib/src/agent/AgentStatus.js +2 -37
  12. package/lib/src/ai/AIClient.d.ts +12 -4
  13. package/lib/src/ai/AIClient.js +81 -285
  14. package/lib/src/ai/AITypes.d.ts +55 -0
  15. package/lib/src/ai/AITypes.js +18 -0
  16. package/lib/src/ai/Tasks.js +10 -133
  17. package/lib/src/apiClient.d.ts +53 -0
  18. package/lib/src/apiClient.js +234 -0
  19. package/lib/src/cache/PersistentCache.d.ts +40 -0
  20. package/lib/src/cache/PersistentCache.js +139 -0
  21. package/lib/src/expression/Expression.d.ts +1 -1
  22. package/lib/src/expression/Expression.js +13 -122
  23. package/lib/src/expression/ExpressionClient.d.ts +11 -3
  24. package/lib/src/expression/ExpressionClient.js +120 -75
  25. package/lib/src/expression/ExpressionRef.js +4 -27
  26. package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
  27. package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
  28. package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
  29. package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
  30. package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
  31. package/lib/src/generated/api/AddLinkRequest.js +1 -0
  32. package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
  33. package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
  34. package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
  35. package/lib/src/generated/api/AddSdnaRequest.js +2 -0
  36. package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
  37. package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
  38. package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
  39. package/lib/src/generated/api/AuthInfoInput.js +1 -0
  40. package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
  41. package/lib/src/generated/api/CapabilityInput.js +1 -0
  42. package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
  43. package/lib/src/generated/api/CommitBatchRequest.js +2 -0
  44. package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
  45. package/lib/src/generated/api/ComputeLogEntry.js +2 -0
  46. package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
  47. package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
  48. package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
  49. package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
  50. package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
  51. package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
  52. package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
  53. package/lib/src/generated/api/EmbedRequest.js +2 -0
  54. package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
  55. package/lib/src/generated/api/EntanglementProofInput.js +2 -0
  56. package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
  57. package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
  58. package/lib/src/generated/api/ExportRequest.d.ts +5 -0
  59. package/lib/src/generated/api/ExportRequest.js +2 -0
  60. package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
  61. package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
  62. package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
  63. package/lib/src/generated/api/ExpressionProof.js +2 -0
  64. package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
  65. package/lib/src/generated/api/ExpressionProofInput.js +2 -0
  66. package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
  67. package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
  68. package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
  69. package/lib/src/generated/api/FriendsListRequest.js +2 -0
  70. package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
  71. package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
  72. package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
  73. package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
  74. package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
  75. package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
  76. package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
  77. package/lib/src/generated/api/ImportAgentRequest.js +2 -0
  78. package/lib/src/generated/api/ImportRequest.d.ts +4 -0
  79. package/lib/src/generated/api/ImportRequest.js +2 -0
  80. package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
  81. package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
  82. package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
  83. package/lib/src/generated/api/LanguageMetaInput.js +2 -0
  84. package/lib/src/generated/api/Link.d.ts +5 -0
  85. package/lib/src/generated/api/Link.js +2 -0
  86. package/lib/src/generated/api/LinkExpression.d.ts +10 -0
  87. package/lib/src/generated/api/LinkExpression.js +1 -0
  88. package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
  89. package/lib/src/generated/api/LinkExpressionInput.js +1 -0
  90. package/lib/src/generated/api/LinkInput.d.ts +5 -0
  91. package/lib/src/generated/api/LinkInput.js +2 -0
  92. package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
  93. package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
  94. package/lib/src/generated/api/LinkMutations.d.ts +6 -0
  95. package/lib/src/generated/api/LinkMutations.js +1 -0
  96. package/lib/src/generated/api/LinkStatus.d.ts +1 -0
  97. package/lib/src/generated/api/LinkStatus.js +2 -0
  98. package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
  99. package/lib/src/generated/api/LockAgentRequest.js +2 -0
  100. package/lib/src/generated/api/ModelType.d.ts +1 -0
  101. package/lib/src/generated/api/ModelType.js +2 -0
  102. package/lib/src/generated/api/NotificationInput.d.ts +10 -0
  103. package/lib/src/generated/api/NotificationInput.js +2 -0
  104. package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
  105. package/lib/src/generated/api/OpenLinkRequest.js +2 -0
  106. package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
  107. package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
  108. package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
  109. package/lib/src/generated/api/PerspectiveInput.js +1 -0
  110. package/lib/src/generated/api/PromptRequest.d.ts +4 -0
  111. package/lib/src/generated/api/PromptRequest.js +2 -0
  112. package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
  113. package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
  114. package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
  115. package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
  116. package/lib/src/generated/api/QueryRequest.d.ts +7 -0
  117. package/lib/src/generated/api/QueryRequest.js +2 -0
  118. package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
  119. package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
  120. package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
  121. package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
  122. package/lib/src/generated/api/ResourceInput.d.ts +4 -0
  123. package/lib/src/generated/api/ResourceInput.js +2 -0
  124. package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
  125. package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
  126. package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
  127. package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
  128. package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
  129. package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
  130. package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
  131. package/lib/src/generated/api/SetStatusRequest.js +2 -0
  132. package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
  133. package/lib/src/generated/api/SignMessageRequest.js +2 -0
  134. package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
  135. package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
  136. package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
  137. package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
  138. package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
  139. package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
  140. package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
  141. package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
  142. package/lib/src/generated/api/UserStatistics.d.ts +9 -0
  143. package/lib/src/generated/api/UserStatistics.js +2 -0
  144. package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
  145. package/lib/src/generated/api/VerificationRequestResult.js +2 -0
  146. package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
  147. package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
  148. package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
  149. package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
  150. package/lib/src/generated/api/index.d.ts +42 -0
  151. package/lib/src/generated/api/index.js +7 -0
  152. package/lib/src/index.d.ts +7 -2
  153. package/lib/src/index.js +7 -2
  154. package/lib/src/jestSetup.d.ts +0 -1
  155. package/lib/src/jestSetup.js +1 -1
  156. package/lib/src/language/Icon.js +2 -21
  157. package/lib/src/language/Language.d.ts +26 -176
  158. package/lib/src/language/Language.js +32 -72
  159. package/lib/src/language/LanguageClient.d.ts +2 -2
  160. package/lib/src/language/LanguageClient.js +15 -105
  161. package/lib/src/language/LanguageHandle.js +2 -41
  162. package/lib/src/language/LanguageMeta.js +4 -75
  163. package/lib/src/language/LanguageRef.js +2 -25
  164. package/lib/src/links/Links.js +14 -111
  165. package/lib/src/model/Ad4mModel.d.ts +150 -62
  166. package/lib/src/model/Ad4mModel.js +689 -417
  167. package/lib/src/model/Ad4mModel.test.js +1434 -688
  168. package/lib/src/model/ModelQueryBuilder.d.ts +59 -38
  169. package/lib/src/model/ModelQueryBuilder.js +317 -153
  170. package/lib/src/model/Subject.js +6 -6
  171. package/lib/src/model/decorators.d.ts +36 -8
  172. package/lib/src/model/decorators.js +41 -14
  173. package/lib/src/model/hydration-batch.d.ts +34 -0
  174. package/lib/src/model/hydration-batch.js +147 -0
  175. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  176. package/lib/src/model/hydration-batching.test.js +456 -0
  177. package/lib/src/model/hydration.d.ts +3 -92
  178. package/lib/src/model/hydration.js +3 -691
  179. package/lib/src/model/index.d.ts +3 -4
  180. package/lib/src/model/index.js +3 -4
  181. package/lib/src/model/json-schema.js +2 -2
  182. package/lib/src/model/model-manifest.d.ts +41 -0
  183. package/lib/src/model/model-manifest.js +11 -0
  184. package/lib/src/model/query-cache.d.ts +30 -0
  185. package/lib/src/model/query-cache.js +66 -0
  186. package/lib/src/model/query-cache.test.d.ts +1 -0
  187. package/lib/src/model/query-cache.test.js +43 -0
  188. package/lib/src/model/query-common.d.ts +1 -1
  189. package/lib/src/model/query-common.js +1 -1
  190. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  191. package/lib/src/model/query-sparql-batch.js +260 -0
  192. package/lib/src/model/query-sparql.d.ts +51 -0
  193. package/lib/src/model/query-sparql.js +466 -0
  194. package/lib/src/model/query-sparql.test.d.ts +1 -0
  195. package/lib/src/model/query-sparql.test.js +312 -0
  196. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +13 -9
  197. package/lib/src/model/query-utils.js +189 -0
  198. package/lib/src/model/relation-filtering.test.js +15 -15
  199. package/lib/src/model/sdna.js +1 -1
  200. package/lib/src/model/shacl-gen.js +46 -18
  201. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  202. package/lib/src/model/subscription-delta.test.js +180 -0
  203. package/lib/src/model/subscription-pool.d.ts +39 -0
  204. package/lib/src/model/subscription-pool.js +165 -0
  205. package/lib/src/model/types.d.ts +60 -5
  206. package/lib/src/model/types.js +5 -2
  207. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  208. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  209. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  210. package/lib/src/perspectives/LinkQuery.js +2 -42
  211. package/lib/src/perspectives/Perspective.d.ts +1 -1
  212. package/lib/src/perspectives/Perspective.js +10 -52
  213. package/lib/src/perspectives/PerspectiveClient.d.ts +22 -32
  214. package/lib/src/perspectives/PerspectiveClient.js +189 -454
  215. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  216. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  217. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  218. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  219. package/lib/src/perspectives/PerspectiveProxy.d.ts +156 -78
  220. package/lib/src/perspectives/PerspectiveProxy.js +474 -389
  221. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  222. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  223. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  224. package/lib/src/perspectives/WakerSubscriptionManager.js +12 -12
  225. package/lib/src/runtime/RuntimeClient.d.ts +8 -6
  226. package/lib/src/runtime/RuntimeClient.js +97 -454
  227. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  228. package/lib/src/runtime/RuntimeResolver.js +84 -0
  229. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  230. package/lib/src/runtime/RuntimeTypes.js +45 -0
  231. package/lib/src/schema.gql +14 -1
  232. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  233. package/lib/src/shacl/SHACLFlow.js +9 -9
  234. package/lib/src/shacl/SHACLShape.d.ts +8 -1
  235. package/lib/src/shacl/SHACLShape.js +57 -38
  236. package/lib/src/shacl/SHACLShape.test.js +82 -0
  237. package/lib/src/typeDefs.js +3 -615
  238. package/lib/src/utils.d.ts +6 -6
  239. package/lib/src/utils.js +6 -6
  240. package/package.json +6 -18
  241. package/rollup.config.js +0 -7
  242. package/src/Ad4mClient.test.ts +1192 -1288
  243. package/src/Ad4mClient.ts +46 -15
  244. package/src/Literal.test.ts +10 -5
  245. package/src/Literal.ts +6 -5
  246. package/src/agent/Agent.ts +0 -99
  247. package/src/agent/AgentClient.ts +238 -467
  248. package/src/agent/AgentStatus.ts +0 -12
  249. package/src/ai/AIClient.ts +96 -296
  250. package/src/ai/AITypes.ts +66 -0
  251. package/src/ai/Tasks.ts +0 -52
  252. package/src/apiClient.ts +287 -0
  253. package/src/cache/PersistentCache.ts +145 -0
  254. package/src/cache/cache.test.ts +713 -0
  255. package/src/expression/Expression.ts +3 -43
  256. package/src/expression/ExpressionClient.ts +148 -77
  257. package/src/expression/ExpressionRef.ts +2 -8
  258. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  259. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  260. package/src/generated/api/AddLinkRequest.ts +4 -0
  261. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  262. package/src/generated/api/AddSdnaRequest.ts +3 -0
  263. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  264. package/src/generated/api/AuthInfoInput.ts +4 -0
  265. package/src/generated/api/CapabilityInput.ts +4 -0
  266. package/src/generated/api/CommitBatchRequest.ts +3 -0
  267. package/src/generated/api/ComputeLogEntry.ts +3 -0
  268. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  269. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  270. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  271. package/src/generated/api/EmbedRequest.ts +3 -0
  272. package/src/generated/api/EntanglementProofInput.ts +3 -0
  273. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  274. package/src/generated/api/ExportRequest.ts +3 -0
  275. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  276. package/src/generated/api/ExpressionProof.ts +3 -0
  277. package/src/generated/api/ExpressionProofInput.ts +3 -0
  278. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  279. package/src/generated/api/FriendsListRequest.ts +3 -0
  280. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  281. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  282. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  283. package/src/generated/api/ImportAgentRequest.ts +3 -0
  284. package/src/generated/api/ImportRequest.ts +3 -0
  285. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  286. package/src/generated/api/LanguageMetaInput.ts +3 -0
  287. package/src/generated/api/Link.ts +3 -0
  288. package/src/generated/api/LinkExpression.ts +6 -0
  289. package/src/generated/api/LinkExpressionInput.ts +6 -0
  290. package/src/generated/api/LinkInput.ts +3 -0
  291. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  292. package/src/generated/api/LinkMutations.ts +5 -0
  293. package/src/generated/api/LinkStatus.ts +3 -0
  294. package/src/generated/api/LockAgentRequest.ts +3 -0
  295. package/src/generated/api/ModelType.ts +3 -0
  296. package/src/generated/api/NotificationInput.ts +3 -0
  297. package/src/generated/api/OpenLinkRequest.ts +3 -0
  298. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  299. package/src/generated/api/PerspectiveInput.ts +4 -0
  300. package/src/generated/api/PromptRequest.ts +3 -0
  301. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  302. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  303. package/src/generated/api/QueryRequest.ts +6 -0
  304. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  305. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  306. package/src/generated/api/ResourceInput.ts +3 -0
  307. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  308. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  309. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  310. package/src/generated/api/SetStatusRequest.ts +3 -0
  311. package/src/generated/api/SignMessageRequest.ts +3 -0
  312. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  313. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  314. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  315. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  316. package/src/generated/api/UserStatistics.ts +3 -0
  317. package/src/generated/api/VerificationRequestResult.ts +3 -0
  318. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  319. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  320. package/src/generated/api/index.ts +49 -0
  321. package/src/index.ts +7 -2
  322. package/src/jestSetup.ts +1 -1
  323. package/src/language/Icon.ts +0 -4
  324. package/src/language/Language.ts +51 -248
  325. package/src/language/LanguageClient.ts +21 -132
  326. package/src/language/LanguageHandle.ts +0 -14
  327. package/src/language/LanguageMeta.ts +0 -29
  328. package/src/language/LanguageRef.ts +0 -7
  329. package/src/links/Links.ts +0 -37
  330. package/src/model/Ad4mModel.test.ts +1690 -777
  331. package/src/model/Ad4mModel.ts +749 -477
  332. package/src/model/ModelQueryBuilder.ts +356 -171
  333. package/src/model/decorators.ts +71 -22
  334. package/src/model/hydration.ts +3 -772
  335. package/src/model/index.ts +3 -4
  336. package/src/model/json-schema.ts +2 -2
  337. package/src/model/query-cache.test.ts +54 -0
  338. package/src/model/query-cache.ts +79 -0
  339. package/src/model/query-common.ts +1 -1
  340. package/src/model/query-sparql.test.ts +376 -0
  341. package/src/model/query-sparql.ts +504 -0
  342. package/src/model/query-utils.ts +209 -0
  343. package/src/model/relation-filtering.test.ts +15 -15
  344. package/src/model/sdna.ts +1 -1
  345. package/src/model/shacl-gen.ts +47 -17
  346. package/src/model/types.ts +65 -5
  347. package/src/neighbourhood/Neighbourhood.ts +0 -9
  348. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  349. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  350. package/src/perspectives/LinkQuery.ts +0 -15
  351. package/src/perspectives/Perspective.ts +1 -12
  352. package/src/perspectives/PerspectiveClient.test.ts +262 -0
  353. package/src/perspectives/PerspectiveClient.ts +254 -468
  354. package/src/perspectives/PerspectiveDiff.ts +0 -8
  355. package/src/perspectives/PerspectiveHandle.ts +1 -12
  356. package/src/perspectives/PerspectiveProxy.test.ts +125 -0
  357. package/src/perspectives/PerspectiveProxy.ts +522 -434
  358. package/src/perspectives/WakerSubscriptionManager.ts +13 -13
  359. package/src/runtime/RuntimeClient.ts +118 -461
  360. package/src/runtime/RuntimeTypes.ts +144 -0
  361. package/src/shacl/SHACLFlow.ts +9 -9
  362. package/src/shacl/SHACLShape.test.ts +94 -0
  363. package/src/shacl/SHACLShape.ts +66 -39
  364. package/src/typeDefs.ts +3 -5
  365. package/src/utils.ts +6 -6
  366. package/tsconfig.json +3 -7
  367. package/lib/src/model/query-surreal.d.ts +0 -44
  368. package/lib/src/model/query-surreal.js +0 -249
  369. package/lib/src/model/surreal-utils.js +0 -128
  370. package/shims/reflect-metadata.ts +0 -0
  371. package/shims/type-graphql.ts +0 -75
  372. package/src/PubSub.ts +0 -17
  373. package/src/agent/AgentResolver.ts +0 -263
  374. package/src/ai/AIResolver.ts +0 -372
  375. package/src/buildSchema.ts +0 -43
  376. package/src/expression/ExpressionResolver.ts +0 -64
  377. package/src/language/LanguageContext.ts +0 -37
  378. package/src/language/LanguageResolver.ts +0 -98
  379. package/src/model/Subject.ts +0 -159
  380. package/src/model/prolog-facts.ts +0 -145
  381. package/src/model/query-prolog.ts +0 -148
  382. package/src/model/query-surreal.ts +0 -280
  383. package/src/model/surreal-utils.ts +0 -147
  384. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  385. package/src/perspectives/PerspectiveResolver.ts +0 -372
  386. package/src/runtime/RuntimeResolver.ts +0 -691
  387. package/src/unwrapApolloResult.ts +0 -16
  388. package/tsconfig-browser.json +0 -82
@@ -4,22 +4,33 @@ import { LinkQuery } from "./LinkQuery";
4
4
  import { PerspectiveHandle, PerspectiveState } from './PerspectiveHandle'
5
5
  import { Perspective } from "./Perspective";
6
6
  import { Literal } from "../Literal";
7
- import { Subject } from "../model/Subject";
8
7
  import { ExpressionRendered } from "../expression/Expression";
9
8
  import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
10
9
  import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
11
10
  import { AIClient } from "../ai/AIClient";
12
- import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
13
- import { gql } from "@apollo/client/core";
11
+
14
12
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
13
+ import { getCachedResult, setCachedResult, invalidatePerspectiveCache } from "../model/query-cache";
15
14
  import { AllInstancesResult } from "../model/types";
16
- import { escapeSurrealString } from "../utils";
15
+
17
16
  import { SHACLShape } from "../shacl/SHACLShape";
18
17
  import { SHACLFlow, LinkPattern } from "../shacl/SHACLFlow";
19
18
 
20
19
  type QueryCallback = (result: AllInstancesResult) => void;
21
20
 
22
- // Generic subscription interface that matches Apollo's Subscription
21
+ /** Extract namespace prefix from a URI (everything up to and including the last / or #) */
22
+ function extractNamespaceFromUri(uri: string): string {
23
+ const hashIdx = uri.lastIndexOf('#');
24
+ if (hashIdx >= 0) return uri.substring(0, hashIdx + 1);
25
+ const slashIdx = uri.lastIndexOf('/');
26
+ if (slashIdx >= 0) return uri.substring(0, slashIdx + 1);
27
+ const colonIdx = uri.lastIndexOf(':');
28
+ if (colonIdx >= 0) return uri.substring(0, colonIdx + 1);
29
+ return uri;
30
+ }
31
+
32
+
33
+ // Generic unsubscribe interface for event subscriptions
23
34
  interface Unsubscribable {
24
35
  unsubscribe(): void;
25
36
  }
@@ -29,7 +40,7 @@ interface Unsubscribable {
29
40
  * This class handles:
30
41
  * - Keeping the subscription alive by sending periodic keepalive signals
31
42
  * - Managing callbacks for result updates
32
- * - Subscribing to query updates via GraphQL subscriptions
43
+ * - Subscribing to query updates via WebSocket subscriptions
33
44
  * - Maintaining the latest query result
34
45
  * - Ensuring subscription is fully initialized before allowing access
35
46
  * - Cleaning up resources when disposed
@@ -71,7 +82,6 @@ export class QuerySubscriptionProxy {
71
82
  #initReject?: (reason?: any) => void;
72
83
  #initTimeoutId?: NodeJS.Timeout;
73
84
  #query: string;
74
- isSurrealDB: boolean = false;
75
85
 
76
86
  /** Creates a new query subscription
77
87
  * @param uuid - The UUID of the perspective
@@ -114,29 +124,35 @@ export class QuerySubscriptionProxy {
114
124
  try {
115
125
  // Initialize the query subscription
116
126
  let initialResult;
117
- if (this.isSurrealDB) {
118
- initialResult = await this.#client.perspectiveSubscribeSurrealQuery(this.#uuid, this.#query);
119
- } else {
120
- initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
121
- }
127
+ initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
122
128
  this.#subscriptionId = initialResult.subscriptionId;
123
129
 
124
- // Process the initial result immediately for fast UX
125
- if (initialResult.result) {
130
+ // Process the initial result immediately for fast UX.
131
+ // The subscribeQuery() RPC call already returns the initial result,
132
+ // so treat that as successful initialization instead of waiting for a
133
+ // follow-up WebSocket update that may never arrive until the query changes.
134
+ if (initialResult.result !== undefined) {
126
135
  this.#latestResult = initialResult.result;
127
136
  this.#notifyCallbacks(initialResult.result);
137
+
138
+ if (this.#initResolve) {
139
+ this.#initResolve(true);
140
+ this.#initResolve = undefined;
141
+ this.#initReject = undefined;
142
+ }
128
143
  } else {
129
144
  console.warn('⚠️ No initial result returned from subscribeQuery!');
130
- }
131
145
 
132
- // Set up timeout for retry
133
- this.#initTimeoutId = setTimeout(() => {
134
- console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
135
- // Recursively retry subscription, catching any errors
136
- this.subscribe().catch(error => {
137
- console.error('Error during subscription retry after timeout:', error);
138
- });
139
- }, 30000);
146
+ // Only keep the initialization timeout when the backend did not
147
+ // provide an initial result up front.
148
+ this.#initTimeoutId = setTimeout(() => {
149
+ console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
150
+ // Recursively retry subscription, catching any errors
151
+ this.subscribe().catch(error => {
152
+ console.error('Error during subscription retry after timeout:', error);
153
+ });
154
+ }, 30000);
155
+ }
140
156
 
141
157
  // Subscribe to query updates
142
158
  this.#unsubscribe = this.#client.subscribeToQueryUpdates(
@@ -155,9 +171,6 @@ export class QuerySubscriptionProxy {
155
171
  this.#initReject = undefined;
156
172
  }
157
173
 
158
- // Skip duplicate init messages
159
- if (updateResult.isInit && this.#latestResult) return;
160
-
161
174
  this.#latestResult = updateResult;
162
175
  this.#notifyCallbacks(updateResult);
163
176
  }
@@ -180,11 +193,7 @@ export class QuerySubscriptionProxy {
180
193
  if (this.#disposed) return;
181
194
 
182
195
  try {
183
- if (this.isSurrealDB) {
184
- await this.#client.perspectiveKeepAliveSurrealQuery(this.#uuid, this.#subscriptionId);
185
- } else {
186
- await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
187
- }
196
+ await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
188
197
  } catch (e) {
189
198
  console.error('Error in keepalive:', e);
190
199
  // try to reinitialize the subscription
@@ -287,7 +296,7 @@ export class QuerySubscriptionProxy {
287
296
  *
288
297
  * This method:
289
298
  * 1. Stops the keepalive timer
290
- * 2. Unsubscribes from GraphQL subscription updates
299
+ * 2. Unsubscribes from subscription updates
291
300
  * 3. Clears all registered callbacks
292
301
  * 4. Cleans up any pending initialization timeout
293
302
  *
@@ -308,13 +317,8 @@ export class QuerySubscriptionProxy {
308
317
 
309
318
  // Tell the backend to dispose of the subscription
310
319
  if (this.#subscriptionId) {
311
- if (this.isSurrealDB) {
312
- this.#client.perspectiveDisposeSurrealQuerySubscription(this.#uuid, this.#subscriptionId)
313
- .catch(e => console.error('Error disposing surreal query subscription:', e));
314
- } else {
315
- this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
316
- .catch(e => console.error('Error disposing query subscription:', e));
317
- }
320
+ this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
321
+ .catch(e => console.error('Error disposing query subscription:', e));
318
322
  }
319
323
  }
320
324
  }
@@ -387,10 +391,15 @@ export class PerspectiveProxy {
387
391
 
388
392
  #handle: PerspectiveHandle
389
393
  #client: PerspectiveClient
394
+
395
+ /** @internal Exposed for ModelQueryBuilder subscription management */
396
+ get client(): PerspectiveClient { return this.#client; }
397
+
390
398
  #perspectiveLinkAddedCallbacks: LinkCallback[]
391
399
  #perspectiveLinkRemovedCallbacks: LinkCallback[]
392
400
  #perspectiveLinkUpdatedCallbacks: LinkCallback[]
393
401
  #perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]
402
+ #ensuredSubjectClasses = new Set<string>()
394
403
 
395
404
  /**
396
405
  * Creates a new PerspectiveProxy instance.
@@ -415,6 +424,24 @@ export class PerspectiveProxy {
415
424
  this.#client.addPerspectiveSyncStateChangeListener(this.#handle.uuid, this.#perspectiveSyncStateChangeCallbacks)
416
425
  }
417
426
 
427
+ /** Update the proxy's internal handle and public fields in-place.
428
+ * Keeps the same object reference so all holders see the update. */
429
+ updateHandle(handle: PerspectiveHandle): void {
430
+ if (handle.uuid !== this.#handle.uuid) {
431
+ throw new Error(
432
+ `PerspectiveProxy.updateHandle: UUID mismatch — proxy is bound to "${this.#handle.uuid}" but received handle with UUID "${handle.uuid}". ` +
433
+ `This would silently diverge from listeners registered under the original UUID.`
434
+ );
435
+ }
436
+ this.#handle = handle;
437
+ this.uuid = handle.uuid;
438
+ this.name = handle.name;
439
+ this.owners = handle.owners;
440
+ this.sharedUrl = handle.sharedUrl;
441
+ this.neighbourhood = handle.neighbourhood;
442
+ this.state = handle.state;
443
+ }
444
+
418
445
  /**
419
446
  * Escapes special regex characters in a string to prevent ReDoS attacks
420
447
  * and regex injection when building dynamic regular expressions.
@@ -489,7 +516,9 @@ export class PerspectiveProxy {
489
516
  * @param batchId - Optional batch ID to group this operation with others
490
517
  */
491
518
  async executeAction(actions, expression, parameters: Parameter[], batchId?: string) {
492
- return await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
519
+ const result = await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
520
+ invalidatePerspectiveCache(this.#handle.uuid);
521
+ return result
493
522
  }
494
523
 
495
524
  /**
@@ -545,34 +574,80 @@ export class PerspectiveProxy {
545
574
  }
546
575
 
547
576
  /**
548
- * Executes a SurrealQL query against the perspective's link cache.
549
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
577
+ * Executes a SPARQL query against the perspective's link cache.
578
+ * This allows powerful SQL-like queries on the link data stored in SPARQL.
550
579
  *
551
580
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
552
581
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
553
582
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
554
583
  *
555
- * @param query - SurrealQL query string (read-only operations only)
584
+ * @param query - SPARQL query string (read-only operations only)
556
585
  * @returns Query results as parsed JSON
557
586
  *
558
- * @example
559
- * ```typescript
560
- * // Get all links
561
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
562
- *
563
- * // Filter links by predicate
564
- * const follows = await perspective.querySurrealDB(
565
- * "SELECT * FROM link WHERE predicate = 'follows'"
566
- * );
567
- *
568
- * // Complex aggregation query
569
- * const stats = await perspective.querySurrealDB(
570
- * "SELECT predicate, count() as total FROM link GROUP BY predicate"
571
- * );
572
- * ```
587
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
588
+ *
589
+ * @param query - SPARQL query string
590
+ * @returns Query results as parsed JSON
591
+ */
592
+ async querySparql(query: string): Promise<any> {
593
+ const cached = getCachedResult(this.#handle.uuid, query);
594
+ if (cached !== undefined) return cached;
595
+ const result = await this.#client.querySparql(this.#handle.uuid, query);
596
+ setCachedResult(this.#handle.uuid, query, result);
597
+ return result;
598
+ }
599
+
600
+ /**
601
+ * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
602
+ *
603
+ * @param className - The model class name (e.g. "Recipe")
604
+ * @param queryJson - Structured query as JSON string
605
+ * @param shapeJson - Optional shape metadata JSON from the model class
606
+ * @returns Object with `instances` array and `totalCount`
573
607
  */
574
- async querySurrealDB(query: string): Promise<any> {
575
- return await this.#client.querySurrealDB(this.#handle.uuid, query)
608
+ async modelQuery(className: string, queryJson: string, shapeJson?: string): Promise<{ instances: any[], totalCount: number }> {
609
+ return await this.#client.modelQuery(this.#handle.uuid, className, queryJson, shapeJson);
610
+ }
611
+
612
+ /**
613
+ * Evaluate property getters for a batch of instances in a single RPC call.
614
+ * Returns a map of `{ instanceId: { prop: value, ... } }`.
615
+ *
616
+ * Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading
617
+ * getter-backed properties on visible items (e.g. `replyingTo` on messages).
618
+ *
619
+ * @param className - The model class name (e.g. "Message")
620
+ * @param instanceIds - Array of instance base expression URIs
621
+ * @param shapeJson - Shape metadata JSON from the model class
622
+ * @param propertyNames - Optional subset of property names to evaluate
623
+ * @returns Map of instance ID → evaluated property values
624
+ */
625
+ async evaluateGetters(
626
+ className: string,
627
+ instanceIds: string[],
628
+ shapeJson: string,
629
+ propertyNames?: string[],
630
+ ): Promise<Record<string, Record<string, any>>> {
631
+ return await this.#client.evaluateGetters(
632
+ this.#handle.uuid, className, instanceIds, shapeJson, propertyNames,
633
+ );
634
+ }
635
+
636
+ /**
637
+ * Subscribe to model query changes. Builds trigger SPARQL from the model shape
638
+ * internally in Rust, registers a subscription, runs the initial query, and
639
+ * pushes updated results when relevant links change.
640
+ *
641
+ * The subscription reuses the same GraphQL subscription channel as subscribeQuery().
642
+ * Use keepAliveQuery() / disposeQuerySubscription() with the returned subscriptionId.
643
+ *
644
+ * @param className - The model class name
645
+ * @param queryJson - JSON-serialized query parameters (same as modelQuery)
646
+ * @param shapeJson - Optional shape metadata JSON from the model class
647
+ * @returns Object with `subscriptionId` and initial `result`
648
+ */
649
+ async modelSubscribe(className: string, queryJson: string, shapeJson?: string): Promise<{ subscriptionId: string, result: any }> {
650
+ return await this.#client.modelSubscribe(this.#handle.uuid, className, queryJson, shapeJson);
576
651
  }
577
652
 
578
653
  /**
@@ -601,7 +676,9 @@ export class PerspectiveProxy {
601
676
  * ```
602
677
  */
603
678
  async add(link: Link, status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression> {
604
- return await this.#client.addLink(this.#handle.uuid, link, status, batchId)
679
+ const result = await this.#client.addLink(this.#handle.uuid, link, status, batchId)
680
+ invalidatePerspectiveCache(this.#handle.uuid);
681
+ return result;
605
682
  }
606
683
 
607
684
  /**
@@ -614,7 +691,9 @@ export class PerspectiveProxy {
614
691
  * @returns Array of created LinkExpressions
615
692
  */
616
693
  async addLinks(links: Link[], status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression[]> {
617
- return await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
694
+ const result = await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
695
+ invalidatePerspectiveCache(this.#handle.uuid);
696
+ return result;
618
697
  }
619
698
 
620
699
  /**
@@ -625,7 +704,9 @@ export class PerspectiveProxy {
625
704
  * @returns Array of removed LinkExpressions
626
705
  */
627
706
  async removeLinks(links: LinkExpressionInput[], batchId?: string): Promise<LinkExpression[]> {
628
- return await this.#client.removeLinks(this.#handle.uuid, links, batchId)
707
+ const result = await this.#client.removeLinks(this.#handle.uuid, links, batchId)
708
+ invalidatePerspectiveCache(this.#handle.uuid);
709
+ return result;
629
710
  }
630
711
 
631
712
  /**
@@ -637,7 +718,9 @@ export class PerspectiveProxy {
637
718
  * @returns Object containing results of the mutations
638
719
  */
639
720
  async linkMutations(mutations: LinkMutations, status: LinkStatus = 'shared'): Promise<LinkExpressionMutations> {
640
- return await this.#client.linkMutations(this.#handle.uuid, mutations, status)
721
+ const result = await this.#client.linkMutations(this.#handle.uuid, mutations, status)
722
+ invalidatePerspectiveCache(this.#handle.uuid);
723
+ return result;
641
724
  }
642
725
 
643
726
  /**
@@ -660,7 +743,9 @@ export class PerspectiveProxy {
660
743
  * @param batchId - Optional batch ID to group this operation with others
661
744
  */
662
745
  async update(oldLink: LinkExpressionInput, newLink: Link, batchId?: string): Promise<LinkExpression> {
663
- return await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
746
+ const result = await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
747
+ invalidatePerspectiveCache(this.#handle.uuid);
748
+ return result;
664
749
  }
665
750
 
666
751
  /**
@@ -670,7 +755,9 @@ export class PerspectiveProxy {
670
755
  * @param batchId - Optional batch ID to group this operation with others
671
756
  */
672
757
  async remove(link: LinkExpressionInput, batchId?: string): Promise<boolean> {
673
- return await this.#client.removeLink(this.#handle.uuid, link, batchId)
758
+ const result = await this.#client.removeLink(this.#handle.uuid, link, batchId)
759
+ invalidatePerspectiveCache(this.#handle.uuid);
760
+ return result;
674
761
  }
675
762
 
676
763
  /** Creates a new batch for grouping operations */
@@ -680,9 +767,9 @@ export class PerspectiveProxy {
680
767
 
681
768
  /** Commits a batch of operations */
682
769
  async commitBatch(batchId: string): Promise<LinkExpressionMutations> {
683
- return await this.#client.commitBatch(this.#handle.uuid, batchId)
684
-
685
-
770
+ const result = await this.#client.commitBatch(this.#handle.uuid, batchId)
771
+ invalidatePerspectiveCache(this.#handle.uuid);
772
+ return result;
686
773
  }
687
774
  /**
688
775
  * Retrieves and renders an Expression referenced in this perspective.
@@ -759,23 +846,31 @@ export class PerspectiveProxy {
759
846
  async removeListener(type: PerspectiveListenerTypes, cb: LinkCallback) {
760
847
  if (type === 'link-added') {
761
848
  const index = this.#perspectiveLinkAddedCallbacks.indexOf(cb);
762
-
763
- this.#perspectiveLinkAddedCallbacks.splice(index, 1);
849
+ if (index >= 0) this.#perspectiveLinkAddedCallbacks.splice(index, 1);
764
850
  } else if (type === 'link-removed') {
765
851
  const index = this.#perspectiveLinkRemovedCallbacks.indexOf(cb);
766
-
767
- this.#perspectiveLinkRemovedCallbacks.splice(index, 1);
852
+ if (index >= 0) this.#perspectiveLinkRemovedCallbacks.splice(index, 1);
768
853
  } else if (type === 'link-updated') {
769
854
  const index = this.#perspectiveLinkUpdatedCallbacks.indexOf(cb);
770
-
771
- this.#perspectiveLinkUpdatedCallbacks.splice(index, 1);
855
+ if (index >= 0) this.#perspectiveLinkUpdatedCallbacks.splice(index, 1);
772
856
  }
773
857
  }
774
858
 
859
+ /** Clean up all subscriptions registered by this proxy.
860
+ * Call this when the proxy is no longer needed to prevent subscription leaks.
861
+ * After calling dispose(), the proxy should not be used. */
862
+ dispose(): void {
863
+ this.#client.removeAllListeners(this.#handle.uuid)
864
+ this.#perspectiveLinkAddedCallbacks.length = 0
865
+ this.#perspectiveLinkRemovedCallbacks.length = 0
866
+ this.#perspectiveLinkUpdatedCallbacks.length = 0
867
+ this.#perspectiveSyncStateChangeCallbacks.length = 0
868
+ }
869
+
775
870
  /**
776
871
  * Creates a snapshot of the current perspective state.
777
872
  * Useful for backup or sharing.
778
- *
873
+ *
779
874
  * @returns Perspective object containing all links
780
875
  */
781
876
  async snapshot(): Promise<Perspective> {
@@ -1055,7 +1150,7 @@ export class PerspectiveProxy {
1055
1150
  * Adds Social DNA code to the perspective.
1056
1151
  *
1057
1152
  * **Recommended:** Use {@link addShacl} instead, which accepts the `SHACLShape` type directly.
1058
- * This method is primarily for the GraphQL layer and legacy Prolog code.
1153
+ * This method is primarily for the RPC API layer and legacy Prolog code.
1059
1154
  *
1060
1155
  * @param name - Unique name for this SDNA definition
1061
1156
  * @param sdnaCode - Prolog SDNA code (legacy, can be empty string if shaclJson provided)
@@ -1075,6 +1170,51 @@ export class PerspectiveProxy {
1075
1170
  return this.#client.addSdna(this.#handle.uuid, name, sdnaCode, sdnaType, shaclJson)
1076
1171
  }
1077
1172
 
1173
+ /**
1174
+ * Batch variant of addSdna — registers multiple SDNA entries in a single RPC call.
1175
+ * Acquires the Rust-side mutex once for the entire batch.
1176
+ */
1177
+ async addSdnaAll(entries: { name: string; sdnaCode?: string; sdnaType: "subject_class" | "flow" | "custom"; shaclJson?: string }[]): Promise<boolean[]> {
1178
+ return this.#client.addSdnaBatch(this.#handle.uuid, entries)
1179
+ }
1180
+
1181
+ /**
1182
+ * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.
1183
+ * Skips classes already registered on this perspective instance.
1184
+ */
1185
+ async ensureSubjectClasses(jsClasses: any[]): Promise<void> {
1186
+ const entries: { name: string; sdnaCode?: string; sdnaType: "subject_class" | "flow" | "custom"; shaclJson?: string }[] = [];
1187
+ for (const jsClass of jsClasses) {
1188
+ const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
1189
+ if (this.#ensuredSubjectClasses.has(className)) continue;
1190
+
1191
+ if (!jsClass.generateSHACL) {
1192
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
1193
+ }
1194
+
1195
+ const { shape } = jsClass.generateSHACL();
1196
+ entries.push({
1197
+ name: className,
1198
+ sdnaType: 'subject_class',
1199
+ shaclJson: JSON.stringify(shape.toJSON()),
1200
+ });
1201
+ }
1202
+ if (entries.length === 0) return;
1203
+
1204
+ await this.addSdnaAll(entries);
1205
+ for (const entry of entries) {
1206
+ this.#ensuredSubjectClasses.add(entry.name);
1207
+ }
1208
+ }
1209
+
1210
+ /**
1211
+ * Adds a subject class to the perspective.
1212
+ * Alias for addSdna() with sdnaType='subject_class'.
1213
+ */
1214
+ async addSubjectClass(name: string, shaclJson: string) {
1215
+ return this.addSdna(name, '', 'subject_class', shaclJson);
1216
+ }
1217
+
1078
1218
  /**
1079
1219
  * **Recommended way to add SDNA schemas.**
1080
1220
  *
@@ -1107,7 +1247,7 @@ export class PerspectiveProxy {
1107
1247
  const shapeLinks = shape.toLinks();
1108
1248
 
1109
1249
  // Create name -> shape mapping links
1110
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1250
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1111
1251
  const allLinks: Link[] = [
1112
1252
  ...shapeLinks.map(l => new Link({
1113
1253
  source: l.source,
@@ -1135,7 +1275,7 @@ export class PerspectiveProxy {
1135
1275
  */
1136
1276
  async getShacl(name: string): Promise<SHACLShape | null> {
1137
1277
  // Find the shape URI from the name mapping
1138
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1278
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1139
1279
  const shapeUriLinks = await this.get(new LinkQuery({
1140
1280
  source: nameMapping.toUrl(),
1141
1281
  predicate: "ad4m://shacl_shape_uri"
@@ -1146,7 +1286,6 @@ export class PerspectiveProxy {
1146
1286
  }
1147
1287
 
1148
1288
  const shapeUri = shapeUriLinks[0].data.target;
1149
- const escapedShapeUri = escapeSurrealString(shapeUri);
1150
1289
 
1151
1290
  // First get property shape URIs so we can query everything in one go
1152
1291
  const propertyLinks = await this.get(new LinkQuery({
@@ -1154,18 +1293,21 @@ export class PerspectiveProxy {
1154
1293
  predicate: "sh://property"
1155
1294
  }));
1156
1295
 
1157
- // Build a single surreal query that fetches all relevant links
1296
+ // Fetch all links from the shape and its property shapes
1158
1297
  const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
1159
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
1160
-
1161
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
1162
- const result = await this.querySurrealDB(query);
1298
+ const allLinks: Array<{source: string, predicate: string, target: string}> = [];
1299
+ for (const uri of sourceUris) {
1300
+ const links = await this.get(new LinkQuery({ source: uri }));
1301
+ for (const l of links) {
1302
+ allLinks.push({
1303
+ source: l.data.source,
1304
+ predicate: l.data.predicate,
1305
+ target: l.data.target
1306
+ });
1307
+ }
1308
+ }
1163
1309
 
1164
- const shapeLinks = (result || []).map((r: any) => ({
1165
- source: r.source,
1166
- predicate: r.predicate,
1167
- target: r.target
1168
- }));
1310
+ const shapeLinks = allLinks;
1169
1311
 
1170
1312
  return SHACLShape.fromLinks(shapeLinks, shapeUri);
1171
1313
  }
@@ -1279,22 +1421,22 @@ export class PerspectiveProxy {
1279
1421
  }
1280
1422
 
1281
1423
  const flowUri = flowUriLinks[0].data.target;
1282
- const escapedFlowUri = escapeSurrealString(flowUri);
1283
-
1284
1424
  // Compute alternate prefix for state/transition URIs
1285
1425
  const alternatePrefix = flowUri.endsWith('Flow')
1286
1426
  ? flowUri.slice(0, -4) + '.'
1287
1427
  : flowUri + '.';
1288
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
1289
1428
 
1290
- // Single surreal query to get all flow-related links
1291
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri = '${escapedFlowUri}' OR string::starts_with(in.uri, '${escapedAltPrefix}')`;
1292
- const result = await this.querySurrealDB(query);
1429
+ // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
1430
+ const sparqlQuery = `SELECT ?s ?p ?o WHERE {
1431
+ ?s ?p ?o .
1432
+ FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
1433
+ }`;
1434
+ const sparqlResult = await this.querySparql(sparqlQuery);
1293
1435
 
1294
- const flowLinks = (result || []).map((r: any) => ({
1295
- source: r.source,
1296
- predicate: r.predicate,
1297
- target: r.target
1436
+ const flowLinks = (sparqlResult || []).map((r: any) => ({
1437
+ source: r.s,
1438
+ predicate: r.p,
1439
+ target: r.o
1298
1440
  }));
1299
1441
 
1300
1442
  return SHACLFlow.fromLinks(flowLinks, flowUri);
@@ -1306,7 +1448,7 @@ export class PerspectiveProxy {
1306
1448
  */
1307
1449
  async subjectClasses(): Promise<string[]> {
1308
1450
  try {
1309
- // Query SHACL class links directly — no need for a separate GraphQL endpoint
1451
+ // Query SHACL class links directly — no need for a separate RPC endpoint
1310
1452
  const classLinks = await this.get(new LinkQuery({
1311
1453
  predicate: "rdf://type",
1312
1454
  target: "ad4m://SubjectClass"
@@ -1398,7 +1540,9 @@ export class PerspectiveProxy {
1398
1540
  return exprAddr as B extends undefined ? T : string;
1399
1541
  }
1400
1542
 
1401
- return this.getSubjectProxy(exprAddr, subjectClass) as Promise<B extends undefined ? T : string>;
1543
+ // Return the expression address directly — callers should use Ad4mModel or
1544
+ // getSubjectData() to interact with the created instance.
1545
+ return exprAddr as unknown as B extends undefined ? T : string;
1402
1546
  }
1403
1547
 
1404
1548
  async getSubjectData<T>(subjectClass: T, exprAddr: string): Promise<T> {
@@ -1427,8 +1571,8 @@ export class PerspectiveProxy {
1427
1571
 
1428
1572
  for (const link of links) {
1429
1573
  if (shapePattern.test(link.data.source)) {
1430
- // Parse actions from literal://string:{json}
1431
- const prefix = "literal://string:";
1574
+ // Parse actions from literal:string:{json}
1575
+ const prefix = "literal:string:";
1432
1576
  if (link.data.target.startsWith(prefix)) {
1433
1577
  const jsonStr = link.data.target.slice(prefix.length);
1434
1578
  // Decode URL-encoded JSON if needed, with fallback for raw % characters
@@ -1480,7 +1624,7 @@ export class PerspectiveProxy {
1480
1624
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
1481
1625
 
1482
1626
  // Get metadata from SHACL links
1483
- const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1627
+ const metadata = await this.getSubjectClassMetadata(className);
1484
1628
  if (!metadata) {
1485
1629
  console.warn(`isSubjectInstance: No SHACL metadata found for class ${className}`);
1486
1630
  return false;
@@ -1488,70 +1632,26 @@ export class PerspectiveProxy {
1488
1632
 
1489
1633
  // If no required triples, any expression with links is an instance
1490
1634
  if (metadata.requiredTriples.length === 0) {
1491
- const escapedExpression = escapeSurrealString(expression);
1492
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
1493
- const result = await this.querySurrealDB(checkQuery);
1494
- const count = result[0]?.count ?? 0;
1495
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1496
- return countValue > 0;
1635
+ const links = await this.get(new LinkQuery({ source: expression }));
1636
+ return links.length > 0;
1497
1637
  }
1498
1638
 
1499
- // Check if the expression has all required triples (predicate + optional exact target)
1500
- for (const triple of metadata.requiredTriples) {
1501
- const escapedExpression = escapeSurrealString(expression);
1502
- const escapedPredicate = escapeSurrealString(triple.predicate);
1503
- let checkQuery: string;
1504
- if (triple.target) {
1505
- // Flag: must match both predicate AND exact target value
1506
- const escapedTarget = escapeSurrealString(triple.target);
1507
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1508
- } else {
1509
- // Property: just check predicate exists
1510
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
1511
- }
1512
- const result = await this.querySurrealDB(checkQuery);
1513
-
1514
- if (!result || result.length === 0) {
1515
- return false;
1516
- }
1517
-
1518
- const count = result[0]?.count ?? 0;
1519
- // Handle potential object response like {Int: 0}
1520
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1639
+ // Build a single SPARQL ASK query with all required triple patterns
1640
+ const patterns = metadata.requiredTriples.map((t, i) => {
1641
+ const target = t.target ? `<${t.target}>` : `?t${i}`;
1642
+ return `<${expression}> <${t.predicate}> ${target} .`;
1643
+ }).join('\n ');
1521
1644
 
1522
- if (countValue === 0) {
1523
- return false;
1524
- }
1525
- }
1526
-
1527
- return true;
1645
+ const result = await this.querySparql(`ASK WHERE {\n ${patterns}\n}`);
1646
+ return result === true;
1528
1647
  }
1529
1648
 
1530
1649
 
1531
- /** For an existing subject instance (existing in the perspective's links)
1532
- * this function returns a proxy object that can be used to access the subject's
1533
- * properties and methods.
1534
- *
1535
- * @param base URI of the subject's root expression
1536
- * @param subjectClass Either a string with the name of the subject class, or an object
1537
- * with the properties of the subject class. In the latter case, the first subject class
1538
- * that matches the given properties will be used.
1539
- */
1540
- async getSubjectProxy<T>(base: string, subjectClass: T): Promise<T> {
1541
- if(!await this.isSubjectInstance(base, subjectClass)) {
1542
- throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`
1543
- }
1544
- let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
1545
- let subject = new Subject(this, base, className)
1546
- await subject.init()
1547
- return subject as unknown as T
1548
- }
1549
-
1550
1650
  /**
1551
1651
  * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
1552
1652
  * Retrieves the SHACL shape and extracts metadata for instance queries.
1553
1653
  */
1554
- async getSubjectClassMetadataFromSDNA(className: string): Promise<{
1654
+ async getSubjectClassMetadata(className: string): Promise<{
1555
1655
  requiredPredicates: string[],
1556
1656
  requiredTriples: Array<{predicate: string, target?: string}>,
1557
1657
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
@@ -1611,232 +1711,38 @@ export class PerspectiveProxy {
1611
1711
  return null;
1612
1712
  }
1613
1713
  }
1714
+
1614
1715
  /**
1615
- * Generates a SurrealDB query to find instances based on class metadata.
1716
+ * Generates a SPARQL query to find instances based on class metadata.
1616
1717
  */
1617
- private generateSurrealInstanceQuery(metadata: {
1718
+ /**
1719
+ * Finds all instances matching subject class metadata by querying links.
1720
+ * Returns base URIs of matching instances.
1721
+ */
1722
+ private async findInstancesByMetadata(metadata: {
1618
1723
  requiredPredicates: string[],
1619
1724
  requiredTriples: Array<{predicate: string, target?: string}>,
1620
1725
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1621
1726
  relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1622
- }): string {
1727
+ }): Promise<Array<{base: string}>> {
1623
1728
  if (metadata.requiredTriples.length === 0) {
1624
- // No required triples - any node with links is an instance
1625
- return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
1729
+ // No required triples - return all unique sources that have any link
1730
+ const allLinks = await this.get(new LinkQuery({}));
1731
+ const sources = new Set(allLinks.map(l => l.data.source));
1732
+ return Array.from(sources).map(s => ({ base: s }));
1626
1733
  }
1627
1734
 
1628
- // Generate WHERE conditions for each required triple (predicate + optional exact target)
1629
- const whereConditions = metadata.requiredTriples.map(triple => {
1630
- const escapedPredicate = escapeSurrealString(triple.predicate);
1631
- if (triple.target) {
1632
- // Flag: must match both predicate AND exact target value
1633
- const escapedTarget = escapeSurrealString(triple.target);
1634
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
1635
- } else {
1636
- // Property: just check predicate exists
1637
- return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
1638
- }
1639
- }).join(' AND ');
1735
+ // Build a single SPARQL SELECT with all required triple patterns joined
1736
+ const patterns = metadata.requiredTriples.map((t, i) => {
1737
+ const target = t.target ? `<${t.target}>` : `?t${i}`;
1738
+ return `?base <${t.predicate}> ${target} .`;
1739
+ }).join('\n ');
1640
1740
 
1641
- return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
1642
- }
1643
-
1644
- /**
1645
- * Gets a property value using SurrealDB when Prolog fails.
1646
- * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1647
- */
1648
- async getPropertyValueViaSurreal(baseExpression: string, className: string, propertyName: string): Promise<any> {
1649
- const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1650
- if (!metadata) {
1651
- return undefined;
1652
- }
1653
-
1654
- const propMeta = metadata.properties.get(propertyName);
1655
- if (!propMeta) {
1656
- return undefined;
1657
- }
1658
-
1659
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1660
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1661
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
1662
- const result = await this.querySurrealDB(query);
1663
-
1664
- if (!result || result.length === 0) {
1665
- return undefined;
1666
- }
1667
-
1668
- const value = result[0].value;
1669
-
1670
- // Handle expression resolution if needed
1671
- if (propMeta.resolveLanguage && value) {
1672
- try {
1673
- const expression = await this.getExpression(value);
1674
- try {
1675
- return JSON.parse(expression.data);
1676
- } catch (e) {
1677
- return expression.data;
1678
- }
1679
- } catch (err) {
1680
- return value;
1681
- }
1682
- }
1683
-
1684
- return value;
1685
- }
1686
-
1687
- /**
1688
- * Gets relation values using SurrealDB when Prolog fails.
1689
- * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1690
- * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
1691
- */
1692
- async getRelationValuesViaSurreal(baseExpression: string, className: string, relationName: string): Promise<any[]> {
1693
- const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1694
- if (!metadata) {
1695
- return [];
1696
- }
1697
-
1698
- const relMeta = metadata.relations.get(relationName);
1699
- if (!relMeta) {
1700
- return [];
1701
- }
1702
-
1703
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1704
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1705
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
1706
- const result = await this.querySurrealDB(query);
1707
-
1708
- if (!result || result.length === 0) {
1709
- return [];
1710
- }
1711
-
1712
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1713
-
1714
- // Apply condition filtering if present
1715
- if (relMeta.condition && values.length > 0) {
1716
- try {
1717
- const filteredValues: string[] = [];
1718
-
1719
- for (const value of values) {
1720
- let condition = relMeta.condition
1721
- .replace(/\$perspective/g, `'${this.uuid}'`)
1722
- .replace(/\$base/g, `'${baseExpression}'`)
1723
- .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
1724
-
1725
- // If condition starts with WHERE, wrap in array length check
1726
- if (condition.trim().startsWith('WHERE')) {
1727
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
1728
- }
1729
-
1730
- const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
1731
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
1732
- if (isTrue) {
1733
- filteredValues.push(value);
1734
- }
1735
- }
1736
-
1737
- values = filteredValues;
1738
- } catch (error) {
1739
- console.warn(`Failed to apply condition filter for ${relationName}:`, error);
1740
- }
1741
- }
1742
-
1743
- // Apply instance filter if present - batch-check all values at once
1744
- if (relMeta.instanceFilter) {
1745
- try {
1746
- const filterMetadata = await this.getSubjectClassMetadataFromSDNA(relMeta.instanceFilter);
1747
- if (!filterMetadata) {
1748
- // Fallback to sequential checks if metadata isn't available
1749
- return this.filterInstancesSequential(values, relMeta.instanceFilter);
1750
- }
1751
-
1752
- return await this.batchCheckSubjectInstances(values, filterMetadata);
1753
- } catch (err) {
1754
- // Fallback to sequential checks on error
1755
- return this.filterInstancesSequential(values, relMeta.instanceFilter);
1756
- }
1757
- }
1758
-
1759
- return values;
1760
- }
1761
-
1762
- /**
1763
- * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
1764
- * This avoids N+1 query problems by checking all values at once.
1765
- */
1766
- async batchCheckSubjectInstances(
1767
- expressions: string[],
1768
- metadata: {
1769
- requiredPredicates: string[],
1770
- requiredTriples: Array<{predicate: string, target?: string}>,
1771
- properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1772
- relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1773
- }
1774
- ): Promise<string[]> {
1775
- if (expressions.length === 0) {
1776
- return [];
1777
- }
1778
-
1779
- // If no required triples, check which expressions have any links
1780
- if (metadata.requiredTriples.length === 0) {
1781
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1782
- const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
1783
- const result = await this.querySurrealDB(checkQuery);
1784
- return result.map(r => r.uri);
1785
- }
1786
-
1787
- // For each required triple, build a query that finds matching expressions
1788
- const validExpressionSets: Set<string>[] = [];
1789
-
1790
- for (const triple of metadata.requiredTriples) {
1791
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1792
- const escapedPredicate = escapeSurrealString(triple.predicate);
1793
-
1794
- let checkQuery: string;
1795
- if (triple.target) {
1796
- // Flag: must match both predicate AND exact target value
1797
- const escapedTarget = escapeSurrealString(triple.target);
1798
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1799
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1800
- } else {
1801
- // Property: just check predicate exists
1802
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1803
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
1804
- }
1805
-
1806
- const result = await this.querySurrealDB(checkQuery);
1807
- validExpressionSets.push(new Set(result.map(r => r.uri)));
1808
- }
1809
-
1810
- // Find intersection: expressions that passed ALL required triple checks
1811
- if (validExpressionSets.length === 0) {
1812
- return expressions;
1813
- }
1814
-
1815
- const firstSet = validExpressionSets[0];
1816
- const validExpressions = expressions.filter(expr => {
1817
- return validExpressionSets.every(set => set.has(expr));
1818
- });
1819
-
1820
- return validExpressions;
1821
- }
1822
-
1823
- /**
1824
- * Fallback sequential instance checking when batch checking isn't available.
1825
- */
1826
- private async filterInstancesSequential(values: string[], instanceFilter: string): Promise<string[]> {
1827
- const filteredValues = [];
1828
- for (const value of values) {
1829
- try {
1830
- const isInstance = await this.isSubjectInstance(value, instanceFilter);
1831
- if (isInstance) {
1832
- filteredValues.push(value);
1833
- }
1834
- } catch (err) {
1835
- // Skip values that fail instance check
1836
- continue;
1837
- }
1838
- }
1839
- return filteredValues;
1741
+ const results = await this.querySparql(
1742
+ `SELECT DISTINCT ?base WHERE {\n ${patterns}\n}`
1743
+ );
1744
+ if (!Array.isArray(results)) return [];
1745
+ return results.map((row: any) => ({ base: row.base }));
1840
1746
  }
1841
1747
 
1842
1748
  /** Returns all subject instances of the given subject class as proxy objects.
@@ -1860,13 +1766,13 @@ export class PerspectiveProxy {
1860
1766
  let instances = []
1861
1767
  for(let className of classes) {
1862
1768
  //console.log(`getAllSubjectInstances: Processing class ${className}`);
1863
- // Query SDNA for metadata, then query SurrealDB for instances
1864
- const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1769
+ // Query SDNA for metadata, then query SPARQL for instances
1770
+ const metadata = await this.getSubjectClassMetadata(className);
1865
1771
  //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
1866
1772
  if (metadata) {
1867
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1868
- const results = await this.querySurrealDB(surrealQuery);
1869
- // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
1773
+ const results = await this.findInstancesByMetadata(metadata);
1774
+
1775
+ // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);
1870
1776
 
1871
1777
  for (const result of results || []) {
1872
1778
  //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
@@ -1879,9 +1785,9 @@ export class PerspectiveProxy {
1879
1785
  // Load the instance data from links
1880
1786
  await instance.get();
1881
1787
  } else {
1882
- // Legacy: Create a Subject proxy
1883
- instance = new Subject(this, result.base, className);
1884
- await instance.init();
1788
+ // Return plain data for string-based lookups
1789
+ const data = await this.getSubjectData(className, result.base);
1790
+ instance = { id: result.base, ...data };
1885
1791
  }
1886
1792
  instances.push(instance as unknown as T);
1887
1793
  //console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);
@@ -1897,41 +1803,6 @@ export class PerspectiveProxy {
1897
1803
  return instances
1898
1804
  }
1899
1805
 
1900
- /** Returns all subject proxies of the given subject class as proxy objects.
1901
- * @param subjectClass Either a string with the name of the subject class, or an object
1902
- * with the properties of the subject class. In the latter case, all subject classes
1903
- * that match the given properties will be used.
1904
- */
1905
- async getAllSubjectProxies<T>(subjectClass: T): Promise<T[]> {
1906
- let classes = []
1907
- if(typeof subjectClass === "string") {
1908
- classes = [subjectClass]
1909
- } else {
1910
- classes = await this.subjectClassesByTemplate(subjectClass as object)
1911
- }
1912
-
1913
- let instances = []
1914
- for(let className of classes) {
1915
- // Query SDNA for metadata, then query SurrealDB for instances
1916
- const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1917
- if (metadata) {
1918
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1919
- const results = await this.querySurrealDB(surrealQuery);
1920
-
1921
- for (const result of results || []) {
1922
- try {
1923
- let subject = new Subject(this, result.base, className);
1924
- await subject.init();
1925
- instances.push(subject as unknown as T);
1926
- } catch (e) {
1927
- // Skip subjects that fail to initialize
1928
- }
1929
- }
1930
- }
1931
- }
1932
- return instances
1933
- }
1934
-
1935
1806
 
1936
1807
  /**
1937
1808
  * Find a subject class by matching an object's properties/relations against SHACL shapes.
@@ -1967,16 +1838,17 @@ export class PerspectiveProxy {
1967
1838
  return null;
1968
1839
  }
1969
1840
 
1970
- // Single SurrealDB query to find all classes and their properties/relations
1971
- const query = `SELECT
1972
- in.uri AS shape_source,
1973
- predicate,
1974
- out.uri AS target
1975
- FROM link
1976
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
1977
-
1978
- const results = await this.querySurrealDB(query);
1979
- if (!results || results.length === 0) return null;
1841
+ // Single SPARQL query to get all class shapes with their properties and collections
1842
+ const results = await this.querySparql(`
1843
+ SELECT ?shape ?predicate ?target WHERE {
1844
+ { ?shape <rdf://type> <ad4m://SubjectClass> . BIND(<rdf://type> AS ?predicate) BIND(<ad4m://SubjectClass> AS ?target) }
1845
+ UNION
1846
+ { ?shape <sh://property> ?target . BIND(<sh://property> AS ?predicate) }
1847
+ UNION
1848
+ { ?shape <sh://collection> ?target . BIND(<sh://collection> AS ?predicate) }
1849
+ }
1850
+ `);
1851
+ if (!Array.isArray(results) || results.length === 0) return null;
1980
1852
 
1981
1853
  // Build a map of className -> { properties, relations }
1982
1854
  const classShapes: Map<string, { shapeUri: string, properties: string[], relations: string[] }> = new Map();
@@ -1984,7 +1856,7 @@ export class PerspectiveProxy {
1984
1856
  // First pass: find all subject classes
1985
1857
  for (const r of results) {
1986
1858
  if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {
1987
- const source = r.shape_source;
1859
+ const source = r.shape;
1988
1860
  const sepIdx = source.indexOf('://');
1989
1861
  if (sepIdx < 0) continue;
1990
1862
  const className = source.substring(sepIdx + 3).split('/').pop();
@@ -1998,7 +1870,7 @@ export class PerspectiveProxy {
1998
1870
  if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {
1999
1871
  // Match shape source to class (e.g., "recipe://RecipeShape" -> "Recipe")
2000
1872
  for (const [className, shape] of classShapes) {
2001
- if (r.shape_source.endsWith(`${className}Shape`)) {
1873
+ if (r.shape.endsWith(`${className}Shape`)) {
2002
1874
  const dotIdx = r.target.lastIndexOf('.');
2003
1875
  if (dotIdx < 0) continue;
2004
1876
  const name = r.target.substring(dotIdx + 1);
@@ -2076,9 +1948,17 @@ export class PerspectiveProxy {
2076
1948
  * static generateSDNA() function and adds it to the perspective's SDNA.
2077
1949
  */
2078
1950
  async ensureSDNASubjectClass(jsClass: any): Promise<void> {
1951
+ return this.ensureSubjectClass(jsClass);
1952
+ }
1953
+
1954
+ /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
1955
+ async ensureSubjectClass(jsClass: any): Promise<void> {
2079
1956
  // Get the class name from the JS class
2080
1957
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
2081
1958
 
1959
+ // Skip if already registered for this perspective instance
1960
+ if (this.#ensuredSubjectClasses.has(className)) return;
1961
+
2082
1962
  // Note: Duplicate checking is handled on the Rust side in add_sdna
2083
1963
 
2084
1964
  // Generate SHACL SDNA (Prolog-free)
@@ -2095,6 +1975,214 @@ export class PerspectiveProxy {
2095
1975
  // Pass SHACL JSON to backend (Prolog-free)
2096
1976
  // Backend stores SHACL links directly
2097
1977
  await this.addSdna(className, '', 'subject_class', shaclJson);
1978
+
1979
+ // Mark as registered for this perspective instance
1980
+ this.#ensuredSubjectClasses.add(className);
1981
+ }
1982
+
1983
+ /** Clear the per-instance ensured subject class cache.
1984
+ * Call this after wiping a perspective's links so that
1985
+ * subsequent register() calls re-add SHACL definitions. */
1986
+ clearEnsuredSubjectClasses(): void {
1987
+ this.#ensuredSubjectClasses.clear();
1988
+ }
1989
+
1990
+ /**
1991
+ * Returns a list of all class names that have been registered as SHACL
1992
+ * subject classes in this perspective (via `ensureSDNASubjectClass` or `addSdna`).
1993
+ *
1994
+ * @returns Array of class name strings (e.g. `["Channel", "Message", "Task"]`)
1995
+ */
1996
+ async listRegisteredClasses(): Promise<string[]> {
1997
+ const results = await this.querySparql(
1998
+ `SELECT DISTINCT ?class WHERE { ?class <rdf://type> <ad4m://SubjectClass> . }`
1999
+ );
2000
+ if (!Array.isArray(results)) return [];
2001
+ return results.map((row: any) => {
2002
+ const uri: string = row.class || '';
2003
+ // Extract class name from URI like "recipe://Recipe" or "flux://Channel"
2004
+ const hashIdx = uri.lastIndexOf('#');
2005
+ if (hashIdx >= 0) return uri.substring(hashIdx + 1);
2006
+ const slashIdx = uri.lastIndexOf('/');
2007
+ if (slashIdx >= 0) return uri.substring(slashIdx + 1);
2008
+ return uri;
2009
+ }).filter(Boolean);
2010
+ }
2011
+
2012
+ /**
2013
+ * Returns the SHACL shape metadata for a registered class, including
2014
+ * property names, predicates, datatypes, and cardinality constraints.
2015
+ *
2016
+ * @param className - The name of the registered class
2017
+ * @returns Shape metadata or `null` if the class is not registered
2018
+ */
2019
+ async getClassShape(className: string): Promise<{
2020
+ className: string;
2021
+ shapeUri: string;
2022
+ properties: Array<{
2023
+ name: string;
2024
+ predicate: string;
2025
+ datatype?: string;
2026
+ required: boolean;
2027
+ collection: boolean;
2028
+ writable: boolean;
2029
+ options?: Array<{ value: string; label?: string }>;
2030
+ }>;
2031
+ } | null> {
2032
+ // Find the shape URI for this class
2033
+ const safeName = className.replace(/['"\\]/g, '');
2034
+ const shapeResults = await this.querySparql(
2035
+ `SELECT ?shapeUri ?targetClass WHERE {
2036
+ ?targetClass <rdf://type> <ad4m://SubjectClass> .
2037
+ ?targetClass <ad4m://shape> ?shapeUri .
2038
+ FILTER(STRENDS(STR(?targetClass), "/${safeName}") || STRENDS(STR(?targetClass), "#${safeName}"))
2039
+ } LIMIT 1`
2040
+ );
2041
+ if (!Array.isArray(shapeResults) || shapeResults.length === 0) return null;
2042
+
2043
+ const shapeUri = shapeResults[0].shapeUri;
2044
+ const classUri = shapeResults[0].targetClass;
2045
+
2046
+ // Query all properties for this shape, including sh:in
2047
+ const propResults = await this.querySparql(
2048
+ `SELECT ?propShape ?path ?datatype ?minCount ?maxCount ?writable ?propType ?shIn WHERE {
2049
+ <${shapeUri}> <sh://property> ?propShape .
2050
+ ?propShape <sh://path> ?path .
2051
+ ?propShape <rdf://type> ?propType .
2052
+ OPTIONAL { ?propShape <sh://datatype> ?datatype }
2053
+ OPTIONAL { ?propShape <sh://minCount> ?minCount }
2054
+ OPTIONAL { ?propShape <sh://maxCount> ?maxCount }
2055
+ OPTIONAL { ?propShape <ad4m://writable> ?writable }
2056
+ OPTIONAL { ?propShape <sh://in> ?shIn }
2057
+ }`
2058
+ );
2059
+
2060
+ const properties = (Array.isArray(propResults) ? propResults : []).map((row: any) => {
2061
+ // Extract property name from shape URI like "recipe://Recipe.name"
2062
+ const propUri: string = row.propShape || '';
2063
+ const dotIdx = propUri.lastIndexOf('.');
2064
+ const name = dotIdx >= 0 ? propUri.substring(dotIdx + 1) : propUri;
2065
+
2066
+ const minCount = parseInt(row.minCount || '0', 10);
2067
+ const isCollection = row.propType === 'ad4m://CollectionShape';
2068
+ const writable = row.writable === 'true' || row.writable === 'literal:true';
2069
+
2070
+ // Parse sh:in values if present
2071
+ let options: Array<{ value: string; label?: string }> | undefined;
2072
+ if (row.shIn) {
2073
+ try {
2074
+ let raw = row.shIn;
2075
+ // Strip literal: prefix if present, and URI-decode for robustness
2076
+ if (raw.startsWith('literal:string:')) {
2077
+ raw = decodeURIComponent(raw.substring('literal:string:'.length));
2078
+ }
2079
+ options = JSON.parse(raw);
2080
+ } catch { /* ignore parse errors */ }
2081
+ }
2082
+
2083
+ return {
2084
+ name,
2085
+ predicate: row.path || '',
2086
+ datatype: row.datatype || undefined,
2087
+ required: minCount > 0,
2088
+ collection: isCollection,
2089
+ writable,
2090
+ ...(options && options.length > 0 ? { options } : {}),
2091
+ };
2092
+ });
2093
+
2094
+ return { className: safeName, shapeUri, properties };
2095
+ }
2096
+
2097
+ /**
2098
+ * Detects which registered subject classes a given instance conforms to,
2099
+ * based on its stored triples matching the class shapes' required properties.
2100
+ *
2101
+ * @param baseExpression - The instance's base expression / subject URI
2102
+ * @returns Array of class names the instance matches
2103
+ */
2104
+ async getInstanceClasses(baseExpression: string): Promise<string[]> {
2105
+ const safeId = baseExpression.replace(/['"\\]/g, '');
2106
+ // Get all registered classes and their required conformance properties
2107
+ const results = await this.querySparql(
2108
+ `SELECT DISTINCT ?class WHERE {
2109
+ ?class <rdf://type> <ad4m://SubjectClass> .
2110
+ ?class <ad4m://shape> ?shape .
2111
+ ?shape <sh://property> ?propShape .
2112
+ ?propShape <sh://minCount> ?mc .
2113
+ FILTER(?mc >= 1)
2114
+ ?propShape <sh://path> ?path .
2115
+ <${safeId}> ?path ?_val .
2116
+ }`
2117
+ );
2118
+ if (!Array.isArray(results)) return [];
2119
+ return results.map((row: any) => {
2120
+ const uri: string = row.class || '';
2121
+ const hashIdx = uri.lastIndexOf('#');
2122
+ if (hashIdx >= 0) return uri.substring(hashIdx + 1);
2123
+ const slashIdx = uri.lastIndexOf('/');
2124
+ if (slashIdx >= 0) return uri.substring(slashIdx + 1);
2125
+ return uri;
2126
+ }).filter(Boolean);
2127
+ }
2128
+
2129
+ /**
2130
+ * Returns all named options (sh:in values) for a registered class, grouped by property.
2131
+ *
2132
+ * @param className - The name of the registered class
2133
+ * @returns Record mapping property name → array of { value, label } options
2134
+ */
2135
+ async getNamedOptions(className: string): Promise<Record<string, Array<{ value: string; label?: string }>>> {
2136
+ const shape = await this.getClassShape(className);
2137
+ if (!shape) return {};
2138
+ const result: Record<string, Array<{ value: string; label?: string }>> = {};
2139
+ for (const prop of shape.properties) {
2140
+ if (prop.options && prop.options.length > 0) {
2141
+ result[prop.name] = prop.options;
2142
+ }
2143
+ }
2144
+ return result;
2145
+ }
2146
+
2147
+ /**
2148
+ * Adds a named option (sh:in value) to a property of a registered class.
2149
+ * This appends to the existing sh:in list stored on the property shape.
2150
+ *
2151
+ * @param className - The registered class name
2152
+ * @param propertyName - The property to add the option to
2153
+ * @param value - The RDF value for the option
2154
+ * @param label - Optional human-readable label
2155
+ */
2156
+ async addNamedOption(className: string, propertyName: string, value: string, label?: string): Promise<void> {
2157
+ const shape = await this.getClassShape(className);
2158
+ if (!shape) throw new Error(`Class "${className}" not found`);
2159
+
2160
+ const prop = shape.properties.find(p => p.name === propertyName);
2161
+ if (!prop) throw new Error(`Property "${propertyName}" not found on class "${className}"`);
2162
+
2163
+ // Build the property shape URI
2164
+ const ns = extractNamespaceFromUri(shape.shapeUri);
2165
+ const propShapeId = `${ns}${className}.${propertyName}`;
2166
+
2167
+ // Get existing options
2168
+ const existing = prop.options || [];
2169
+ // Don't add duplicates
2170
+ if (existing.some(o => o.value === value)) return;
2171
+
2172
+ const updated = [...existing, { value, ...(label ? { label } : {}) }];
2173
+
2174
+ // Remove old sh:in link if exists by querying for it
2175
+ const oldLinks = await this.get(new LinkQuery({ source: propShapeId, predicate: "sh://in" }));
2176
+ for (const oldLink of oldLinks) {
2177
+ await this.remove(oldLink);
2178
+ }
2179
+
2180
+ // Add new sh:in link
2181
+ await this.add(new Link({
2182
+ source: propShapeId,
2183
+ predicate: "sh://in",
2184
+ target: `literal:string:${JSON.stringify(updated)}`
2185
+ }));
2098
2186
  }
2099
2187
 
2100
2188
  getNeighbourhoodProxy(): NeighbourhoodProxy {
@@ -2175,7 +2263,7 @@ export class PerspectiveProxy {
2175
2263
  }
2176
2264
 
2177
2265
  /**
2178
- * Creates a subscription for a SurrealQL query that updates in real-time.
2266
+ * Creates a subscription for a SPARQL query that updates in real-time.
2179
2267
  *
2180
2268
  * This method:
2181
2269
  * 1. Creates the subscription on the Rust side
@@ -2190,16 +2278,16 @@ export class PerspectiveProxy {
2190
2278
  * when dispose() is called. Make sure to call dispose() when you're done to
2191
2279
  * prevent memory leaks and ensure proper cleanup of resources.
2192
2280
  *
2193
- * @param query - SurrealQL query string
2281
+ /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
2282
+ * @param query - Query string
2194
2283
  * @returns Initialized QuerySubscriptionProxy instance
2195
2284
  */
2196
- async subscribeSurrealDB(query: string): Promise<QuerySubscriptionProxy> {
2285
+ async subscribeQuery(query: string): Promise<QuerySubscriptionProxy> {
2197
2286
  const subscriptionProxy = new QuerySubscriptionProxy(
2198
2287
  this.uuid,
2199
2288
  query,
2200
2289
  this.#client
2201
2290
  );
2202
- subscriptionProxy.isSurrealDB = true;
2203
2291
 
2204
2292
  // Start the subscription on the Rust side first to get the real subscription ID
2205
2293
  await subscriptionProxy.subscribe();