@coasys/ad4m 0.12.0 → 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 +7444 -13939
  4. package/lib/index.js +5322 -11888
  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 -373
  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 +34 -6
  226. package/lib/src/runtime/RuntimeClient.js +131 -362
  227. package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
  228. package/lib/src/runtime/RuntimeResolver.js +197 -4
  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 +27 -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 -602
  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 -465
  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 +166 -369
  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 -617
  387. package/src/unwrapApolloResult.ts +0 -16
  388. package/tsconfig-browser.json +0 -82
@@ -2,14 +2,191 @@ import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { makeRandomId } from "./util";
5
- import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
6
- import { formatSurrealValue } from "./surreal-utils";
5
+ import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
7
6
  import { resolveParentPredicate } from "./query-common";
8
- import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
9
7
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
10
- import { buildSurrealQLQuery } from "./query-surreal";
8
+ import { buildSPARQLQuery } from "./query-sparql";
11
9
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
12
- import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInstance as _assignValuesToInstance, evaluateCustomGettersForInstance, hydrateRelations, } from "./hydration";
10
+ import { normalizeValue, } from "./hydration";
11
+ // ---------------------------------------------------------------------------
12
+ // Default decoder for file-storage (non-literal resolveLanguage) properties
13
+ // ---------------------------------------------------------------------------
14
+ /**
15
+ * When the Rust executor resolves a non-literal expression it may return a
16
+ * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
17
+ * raw URI string. If the model class has no custom `transform` registered
18
+ * (e.g. it was synthesised from a SHACL shape at runtime) we still want to
19
+ * decode the content rather than passing raw `FileData` to callers.
20
+ *
21
+ * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
22
+ * - `application/json` (default when `file_type` is absent) → JSON.parse
23
+ * - anything else → raw decoded string
24
+ *
25
+ * If `resolved` is not a `FileData` object the value is returned unchanged so
26
+ * that callers can use this as a safe unconditional fallback.
27
+ */
28
+ function defaultFileDecode(resolved) {
29
+ if (resolved !== null &&
30
+ typeof resolved === 'object' &&
31
+ 'data_base64' in resolved) {
32
+ const fd = resolved;
33
+ let raw;
34
+ try {
35
+ raw = atob(fd.data_base64);
36
+ }
37
+ catch {
38
+ return resolved; // malformed base64 — keep as-is
39
+ }
40
+ const isJson = !fd.file_type || fd.file_type === 'application/json';
41
+ if (isJson) {
42
+ try {
43
+ return JSON.parse(raw);
44
+ }
45
+ catch {
46
+ return raw;
47
+ }
48
+ }
49
+ return raw;
50
+ }
51
+ return resolved;
52
+ }
53
+ // ---------------------------------------------------------------------------
54
+ // Helpers for Rust-side include resolution
55
+ // ---------------------------------------------------------------------------
56
+ /**
57
+ * Recursively enrich relation metadata in the shape with target class shapes
58
+ * so the Rust endpoint can resolve includes in-process (no extra GraphQL
59
+ * round-trips per relation).
60
+ */
61
+ function enrichShapeForIncludes(metadata, include, allRelMeta) {
62
+ for (const [relName, includeVal] of Object.entries(include)) {
63
+ if (!includeVal)
64
+ continue;
65
+ const meta = allRelMeta[relName];
66
+ if (!meta?.target)
67
+ continue;
68
+ const TargetClass = meta.target();
69
+ // Deep-copy so we don't mutate the cached metadata
70
+ const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
71
+ // Ensure the relation is in metadata.relations (fallback for edge cases)
72
+ if (!metadata.relations[relName]) {
73
+ metadata.relations[relName] = {
74
+ name: relName,
75
+ predicate: meta.predicate,
76
+ direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
77
+ ? 'reverse'
78
+ : 'forward',
79
+ };
80
+ }
81
+ const rel = metadata.relations[relName];
82
+ rel.kind = meta.kind;
83
+ rel.maxCount = meta.maxCount;
84
+ rel.targetShape = targetMeta;
85
+ rel.targetClassName = targetMeta.className;
86
+ // Recurse for nested includes
87
+ const nested = typeof includeVal === 'object' && includeVal !== null
88
+ ? includeVal.include
89
+ : undefined;
90
+ if (nested) {
91
+ const targetRelMeta = getRelationsMetadata(TargetClass);
92
+ enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
93
+ }
94
+ }
95
+ }
96
+ /**
97
+ * Construct a model class instance from a plain JSON object returned by the
98
+ * Rust endpoint. Recursively converts included relation values (which come
99
+ * back as plain JSON objects) into proper model class instances.
100
+ */
101
+ function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
102
+ const instance = new ModelClass(perspective, json.id || json.baseExpression);
103
+ // When a properties projection is active, remove own properties set by the
104
+ // constructor that are not in the projected JSON. This ensures assertions
105
+ // like `expect(r).to.not.have.own.property("body")` pass.
106
+ if (properties) {
107
+ const jsonKeys = new Set(Object.keys(json));
108
+ for (const key of Object.getOwnPropertyNames(instance)) {
109
+ // Keep internal fields (backing store for getters), id, baseExpression, perspective
110
+ if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_'))
111
+ continue;
112
+ if (!jsonKeys.has(key)) {
113
+ delete instance[key];
114
+ }
115
+ }
116
+ }
117
+ for (const [key, value] of Object.entries(json)) {
118
+ if (key === 'baseExpression' || key === 'id')
119
+ continue;
120
+ // Skip getter-only properties anywhere in the prototype chain
121
+ let isReadonly = false;
122
+ let proto = Object.getPrototypeOf(instance);
123
+ while (proto) {
124
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
125
+ if (desc) {
126
+ isReadonly = !!(desc.get && !desc.set);
127
+ break;
128
+ }
129
+ proto = Object.getPrototypeOf(proto);
130
+ }
131
+ if (isReadonly)
132
+ continue;
133
+ // Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
134
+ if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
135
+ instance[key] = new Date(value).getTime();
136
+ continue;
137
+ }
138
+ instance[key] = value;
139
+ }
140
+ // Apply property transform functions from decorators (only for literal-resolved
141
+ // or no-resolveLanguage properties; non-literal properties are resolved + transformed
142
+ // asynchronously in executeModelQuery).
143
+ try {
144
+ const propsMeta = getPropertiesMetadata(ModelClass);
145
+ for (const [propName, opts] of Object.entries(propsMeta)) {
146
+ const o = opts;
147
+ if (typeof o.transform !== 'function' || !(propName in json))
148
+ continue;
149
+ // Skip non-literal resolveLanguage props — they need async expression resolution first
150
+ if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
151
+ continue;
152
+ instance[propName] = o.transform(instance[propName]);
153
+ }
154
+ }
155
+ catch (e) {
156
+ console.debug('jsonToModelInstance: transform metadata unavailable:', e);
157
+ }
158
+ // Recursively convert included relation values to class instances
159
+ if (include) {
160
+ const relMeta = getRelationsMetadata(ModelClass);
161
+ for (const [relName, includeVal] of Object.entries(include)) {
162
+ if (!includeVal)
163
+ continue;
164
+ const meta = relMeta[relName];
165
+ if (!meta?.target)
166
+ continue;
167
+ const TargetClass = meta.target();
168
+ const nestedInclude = typeof includeVal === 'object' && includeVal !== null
169
+ ? includeVal.include
170
+ : undefined;
171
+ const nestedProperties = typeof includeVal === 'object' && includeVal !== null
172
+ ? includeVal.properties
173
+ : undefined;
174
+ const raw = instance[relName];
175
+ if (Array.isArray(raw)) {
176
+ instance[relName] = raw.map((item) => {
177
+ if (typeof item === 'object' && item !== null && item.id) {
178
+ return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
179
+ }
180
+ return item;
181
+ });
182
+ }
183
+ else if (typeof raw === 'object' && raw !== null && raw.id) {
184
+ instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
185
+ }
186
+ }
187
+ }
188
+ return instance;
189
+ }
13
190
  /**
14
191
  * Base class for defining data models in AD4M.
15
192
  *
@@ -107,6 +284,13 @@ import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInsta
107
284
  * ```
108
285
  */
109
286
  export class Ad4mModel {
287
+ /**
288
+ * Backwards compatibility alias for createdAt.
289
+ * @deprecated Use createdAt instead. This will be removed in a future version.
290
+ */
291
+ get timestamp() {
292
+ return this.createdAt;
293
+ }
110
294
  /**
111
295
  * Generates the SDNA (Subject DNA) Prolog rules for this model class.
112
296
  * Injected at class-definition time by the `@Model` decorator.
@@ -144,13 +328,6 @@ export class Ad4mModel {
144
328
  }
145
329
  return classCache[perspectiveID];
146
330
  }
147
- /**
148
- * Backwards compatibility alias for createdAt.
149
- * @deprecated Use createdAt instead. This will be removed in a future version.
150
- */
151
- get timestamp() {
152
- return this.createdAt;
153
- }
154
331
  /**
155
332
  * Extracts metadata from decorators for query building.
156
333
  *
@@ -222,7 +399,7 @@ export class Ad4mModel {
222
399
  // Extract relations (relations) from WeakMap registry
223
400
  const relationsMetadata = {};
224
401
  const allRelationsMeta = getRelationsMetadata(this);
225
- const prototypeRelations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
402
+ const prototypeRelations = allRelationsMeta;
226
403
  for (const [relationName, opts] of Object.entries(prototypeRelations)) {
227
404
  const options = opts;
228
405
  relationsMetadata[relationName] = {
@@ -231,6 +408,8 @@ export class Ad4mModel {
231
408
  ...(options.local !== undefined && { local: options.local }),
232
409
  ...(options.getter !== undefined && { getter: options.getter }),
233
410
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
411
+ ...(options.kind !== undefined && { kind: options.kind }),
412
+ ...(options.maxCount !== undefined && { maxCount: options.maxCount }),
234
413
  ...(options.target !== undefined && { target: options.target }),
235
414
  ...(options.filter !== undefined && { filter: options.filter }),
236
415
  ...(options.where !== undefined && { where: options.where }),
@@ -291,7 +470,7 @@ export class Ad4mModel {
291
470
  * const recipe = new Recipe(perspective);
292
471
  *
293
472
  * // Create with specific base expression
294
- * const recipe = new Recipe(perspective, "literal://...");
473
+ * const recipe = new Recipe(perspective, "literal:...");
295
474
  * ```
296
475
  */
297
476
  constructor(perspective, baseExpression) {
@@ -305,12 +484,6 @@ export class Ad4mModel {
305
484
  get id() {
306
485
  return this._baseExpression;
307
486
  }
308
- /**
309
- * @deprecated Use `.id` instead. Will be removed in a future version.
310
- */
311
- get baseExpression() {
312
- return this._baseExpression;
313
- }
314
487
  /**
315
488
  * Protected getter for the perspective.
316
489
  * Allows subclasses to access the perspective while keeping it private from external code.
@@ -391,13 +564,6 @@ export class Ad4mModel {
391
564
  ...(metadata.local && { local: true })
392
565
  }];
393
566
  }
394
- /**
395
- * Assigns decoded Prolog property values to an instance.
396
- * Delegates to the standalone function in hydration.ts.
397
- */
398
- static async assignValuesToInstance(perspective, instance, values) {
399
- return _assignValuesToInstance(perspective, instance, values);
400
- }
401
567
  // ──────────────────────────────────────────────────────────
402
568
  // Snapshot / dirty tracking
403
569
  // ──────────────────────────────────────────────────────────
@@ -412,6 +578,7 @@ export class Ad4mModel {
412
578
  * • `null` / empty object — skip ALL relations (used by bare
413
579
  * subscriptions that don't eagerly load relations).
414
580
  */
581
+ /** @internal */
415
582
  takeSnapshot(includedRelations) {
416
583
  const ctor = this.constructor;
417
584
  const metadata = ctor.getModelMetadata();
@@ -517,92 +684,61 @@ export class Ad4mModel {
517
684
  return changed;
518
685
  }
519
686
  async getData(opts) {
520
- // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
521
- // Use SurrealDB for data queries
687
+ // Route through the Rust model query endpoint — same pipeline as executeModelQuery
688
+ // but for a single instance by ID.
522
689
  try {
523
690
  const ctor = this.constructor;
524
- const metadata = ctor.getModelMetadata();
525
- // Query for all links from this specific node (base expression)
526
- const safeBaseExpression = formatSurrealValue(this._baseExpression);
527
- const linksQuery = `
528
- SELECT id, predicate, out.uri AS target, author, timestamp
529
- FROM link
530
- WHERE in.uri = ${safeBaseExpression}
531
- ORDER BY timestamp ASC
532
- `;
533
- const links = await this._perspective.querySurrealDB(linksQuery);
534
- if (links && links.length > 0) {
535
- // Core hydration: properties (latest-wins), relations, timestamps/author
536
- const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
537
- await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
538
- }
539
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
540
- const allRelsMeta = getRelationsMetadata(ctor);
541
- const requestedProps = opts?.properties && opts.properties.length > 0 ? new Set(opts.properties) : null;
542
- for (const [relName, relMeta] of Object.entries(allRelsMeta)) {
543
- if (relMeta.kind !== 'belongsToOne' && relMeta.kind !== 'belongsToMany')
544
- continue;
545
- if (requestedProps && !requestedProps.has(relName))
546
- continue;
547
- const reverseLinks = await this._perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: this._baseExpression }));
548
- const sourceIds = reverseLinks
549
- .filter((l) => l.data.target === this._baseExpression)
550
- .map((l) => l.data.source);
551
- if (relMeta.kind === 'belongsToOne') {
552
- this[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
553
- }
554
- else {
555
- this[relName] = sourceIds;
691
+ const query = {
692
+ where: { id: this._baseExpression },
693
+ limit: 1,
694
+ deepQuery: true, // Single-instance get() always evaluates property getters
695
+ };
696
+ if (opts?.properties)
697
+ query.properties = opts.properties;
698
+ if (opts?.include)
699
+ query.include = opts.include;
700
+ const { results } = await ctor.executeModelQuery(this._perspective, query, null);
701
+ if (results.length > 0) {
702
+ const hydrated = results[0];
703
+ // Copy all hydrated values from the Rust-side result onto this instance
704
+ for (const [key, value] of Object.entries(hydrated)) {
705
+ if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot')
706
+ continue;
707
+ if (key.startsWith('_'))
708
+ continue;
709
+ // Check for readonly getters
710
+ let isReadonly = false;
711
+ let proto = Object.getPrototypeOf(this);
712
+ while (proto) {
713
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
714
+ if (desc) {
715
+ isReadonly = !!(desc.get && !desc.set);
716
+ break;
717
+ }
718
+ proto = Object.getPrototypeOf(proto);
719
+ }
720
+ if (isReadonly)
721
+ continue;
722
+ this[key] = value;
556
723
  }
557
724
  }
558
- // Evaluate SurrealQL getters
559
- const getterOpts = opts?.properties || opts?.include
560
- ? { requestedProperties: opts?.properties, include: opts?.include }
561
- : undefined;
562
- await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
563
- // Eager-load relations if requested
564
- if (opts?.include) {
565
- await hydrateRelations(ctor, [this], this._perspective, opts.include);
566
- }
725
+ // Property getters and relation conformance getters are now evaluated
726
+ // Rust-side via evaluate_getters() in model_query.rs.
567
727
  }
568
728
  catch (e) {
569
- console.error(`SurrealDB getData also failed for ${this._baseExpression}:`, e);
729
+ console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
570
730
  }
571
- this.takeSnapshot();
731
+ this.takeSnapshot(opts?.include);
572
732
  return this;
573
733
  }
574
- static async queryToProlog(perspective, query, modelClassName) {
575
- const { properties, where, order, offset, limit, count } = query;
576
- const className = modelClassName || (await this.getClassName(perspective));
577
- // Resolve parent predicate from model metadata if needed
578
- const resolvedParentPredicate = query.parent
579
- ? resolveParentPredicate(query.parent, this)
580
- : undefined;
581
- const instanceQueries = [
582
- buildAuthorAndTimestampQuery(),
583
- buildParentQuery(query.parent, resolvedParentPredicate),
584
- buildPropertiesQuery(properties),
585
- buildWhereQuery(where),
586
- ];
587
- const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
588
- const fullQuery = `
589
- findall([Base, Properties, Collections, Timestamp, Author], (
590
- subject_class("${className}", SubjectClass),
591
- instance(SubjectClass, Base),
592
- ${instanceQueries.filter((q) => q).join(", ")}
593
- ), UnsortedInstances),
594
- ${resultSetQueries.filter((q) => q).join(", ")}
595
- `;
596
- return fullQuery;
597
- }
598
734
  /**
599
- * Generates a SurrealQL query from a Query object.
735
+ * Generates a SPARQL query from a Query object.
600
736
  *
601
737
  * @description
602
- * This method translates high-level query parameters into a SurrealQL query string
603
- * that can be executed against the SurrealDB backend. Unlike Prolog queries which
604
- * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
605
- * stored in SurrealDB.
738
+ * This method translates high-level query parameters into a SPARQL query string
739
+ * that can be executed against the SPARQL backend. Unlike Prolog queries which
740
+ * operate on SDNA-aware predicates, SPARQL queries operate directly on raw links
741
+ * stored in SPARQL.
606
742
  *
607
743
  * The generated query uses a CTE (Common Table Expression) pattern:
608
744
  * 1. First, identify candidate base expressions by filtering links based on where conditions
@@ -610,7 +746,7 @@ export class Ad4mModel {
610
746
  * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
611
747
  *
612
748
  * Key architectural notes:
613
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
749
+ * - SPARQL stores only raw links (source, predicate, target, author, timestamp)
614
750
  * - No SDNA knowledge at the database level
615
751
  * - Properties are resolved via subqueries that look for links with specific predicates
616
752
  * - Relations are similar but return multiple values instead of one
@@ -618,11 +754,11 @@ export class Ad4mModel {
618
754
  *
619
755
  * @param perspective - The perspective to query (used for metadata extraction)
620
756
  * @param query - Query parameters (where, order, limit, offset, properties, relations)
621
- * @returns Complete SurrealQL query string ready for execution
757
+ * @returns Complete SPARQL query string ready for execution
622
758
  *
623
759
  * @example
624
760
  * ```typescript
625
- * const query = Recipe.queryToSurrealQL(perspective, {
761
+ * const query = Recipe.queryToSPARQL(perspective, {
626
762
  * where: { name: "Pasta", rating: { gt: 4 } },
627
763
  * order: { timestamp: "DESC" },
628
764
  * limit: 10
@@ -631,243 +767,243 @@ export class Ad4mModel {
631
767
  * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
632
768
  * ```
633
769
  */
634
- static async queryToSurrealQL(perspective, query) {
770
+ static async queryToSPARQL(perspective, query) {
635
771
  const metadata = this.getModelMetadata();
636
772
  const allRelMeta = getRelationsMetadata(this);
637
- return buildSurrealQLQuery(metadata, allRelMeta, query, this);
638
- }
639
- static async instancesFromPrologResult(perspective, query, result) {
640
- if (!result?.[0]?.AllInstances)
641
- return { results: [], totalCount: 0 };
642
- // Map results to instances
643
- const requestedProperties = query?.properties || [];
644
- const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
645
- try {
646
- const instance = new this(perspective, Base);
647
- // Remove unrequested attributes from instance
648
- if (requestedProperties.length) {
649
- Object.keys(instance).forEach((key) => {
650
- if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
651
- delete instance[key];
652
- });
653
- }
654
- // Collect values to assign to instance
655
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
656
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
657
- return instance;
658
- }
659
- catch (error) {
660
- console.error(`Failed to process instance ${Base}:`, error);
661
- // Return null for failed instances - we'll filter these out below
662
- return null;
663
- }
664
- }));
665
- const instances = allInstances.filter((instance) => instance !== null);
666
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
667
- if (query.include && instances.length > 0) {
668
- await hydrateRelations(this, instances, perspective, query.include);
669
- }
670
- // Take snapshots for dirty tracking after ALL hydration is complete
671
- // (including eager-loaded relations).
672
- // When `include` is specified, only snapshot those relations.
673
- // Otherwise snapshot ALL fields (properties + relations) since
674
- // hydrateFromLinks populates relations with stable raw IDs.
675
- const snapshotRelations = query.include;
676
- for (const inst of instances) {
677
- inst.takeSnapshot(snapshotRelations);
678
- }
679
- return { results: instances, totalCount: result[0].TotalCount };
773
+ return buildSPARQLQuery(metadata, allRelMeta, query, this);
680
774
  }
681
775
  /**
682
- * Converts SurrealDB query results to Ad4mModel instances.
683
- *
684
- * @param perspective - The perspective context
685
- * @param query - The query parameters used
686
- * @param result - Array of result objects from SurrealDB
687
- * @returns Promise resolving to results with total count
688
- *
776
+ * Build the JSON parameters needed for a model query/subscription endpoint.
777
+ * Returns the className, queryJson, and shapeJson that the Rust executor expects.
689
778
  * @internal
690
779
  */
691
- static async instancesFromSurrealResult(perspective, query, result) {
692
- if (!result || result.length === 0)
693
- return { results: [], totalCount: 0 };
780
+ static prepareModelQueryParams(query = {}, classNameOverride) {
694
781
  const metadata = this.getModelMetadata();
695
- const requestedProperties = query?.properties || [];
696
- // The query used GROUP BY with graph traversal, so each row has:
697
- // - source: the node ID (e.g., "node:abc123")
698
- // - source_uri: the actual URI (the base expression)
699
- // - links: array of link objects with {predicate, target, author, timestamp}
700
- const instances = [];
701
- for (const row of result) {
702
- let base;
703
- try {
704
- // Use source_uri as the base (the actual URI), not the node ID
705
- base = row.source_uri;
706
- // Skip rows without a source_uri field
707
- if (!base) {
708
- continue;
782
+ const className = classNameOverride || metadata.className;
783
+ // Expand includeAll: true to a full IncludeMap covering every forward relation.
784
+ if (query.includeAll) {
785
+ const allRelMeta = getRelationsMetadata(this);
786
+ const expanded = {};
787
+ for (const [relName, relMeta] of Object.entries(allRelMeta)) {
788
+ if (relMeta.direction !== 'reverse') {
789
+ expanded[relName] = true;
709
790
  }
710
- const links = row.links || [];
711
- const instance = new this(perspective, base);
712
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
713
- await hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
714
- // When specific properties are requested, delete unrequested properties
715
- // so they return undefined instead of their constructor defaults (e.g. 0, [])
716
- if (requestedProperties.length > 0) {
717
- const requested = new Set(requestedProperties);
718
- for (const propName of Object.keys(metadata.properties)) {
719
- if (!requested.has(propName)) {
720
- delete instance[propName];
721
- }
722
- }
723
- for (const relName of Object.keys(metadata.relations)) {
724
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
725
- delete instance[relName];
791
+ }
792
+ query = { ...query, include: { ...expanded, ...query.include } };
793
+ }
794
+ const queryInput = {};
795
+ if (query.parent) {
796
+ const parentPredicate = resolveParentPredicate(query.parent, this);
797
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
798
+ }
799
+ if (query.properties)
800
+ queryInput.properties = query.properties;
801
+ if (query.include) {
802
+ // Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
803
+ // All other keys (boolean | RelationSubQuery) → queryInput.include
804
+ const normalIncludes = {};
805
+ const projections = {};
806
+ for (const [key, val] of Object.entries(query.include)) {
807
+ if (key.startsWith('$')) {
808
+ projections[key] = val;
809
+ }
810
+ else {
811
+ normalIncludes[key] = val;
812
+ }
813
+ }
814
+ if (Object.keys(normalIncludes).length > 0)
815
+ queryInput.include = normalIncludes;
816
+ if (Object.keys(projections).length > 0) {
817
+ // Enrich projections with target shapes so Rust can apply where clause filtering
818
+ const allRelMeta = getRelationsMetadata(this);
819
+ for (const [, proj] of Object.entries(projections)) {
820
+ const relMeta = allRelMeta[proj.from];
821
+ if (!proj.targetShape && relMeta?.target) {
822
+ try {
823
+ const TargetClass = relMeta.target();
824
+ const targetMeta = TargetClass.getModelMetadata?.();
825
+ if (targetMeta) {
826
+ proj.targetShape = targetMeta;
827
+ }
726
828
  }
727
- }
728
- // Also strip metadata fields unless explicitly requested
729
- for (const metaField of ['author', 'createdAt', 'updatedAt']) {
730
- if (!requested.has(metaField)) {
731
- delete instance[metaField];
829
+ catch (e) {
830
+ console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e);
732
831
  }
733
832
  }
734
833
  }
735
- instances.push(instance);
834
+ queryInput.projections = projections;
736
835
  }
737
- catch (error) {
738
- console.error(`Failed to process SurrealDB instance ${base}:`, error);
739
- }
740
- }
741
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
742
- // These relations point FROM other nodes TO this instance, so they cannot be resolved
743
- // from the node's own outgoing links fetched above. We do a reverse-link lookup here
744
- // so that these fields are populated as IDs even without an explicit include.
745
- const allRelsMeta = getRelationsMetadata(this);
746
- const reverseRelEntries = Object.entries(allRelsMeta).filter(([relName, meta]) => (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
747
- (requestedProperties.length === 0 || requestedProperties.includes(relName)));
748
- if (reverseRelEntries.length > 0 && instances.length > 0) {
749
- await Promise.all(instances.map(async (inst) => {
750
- for (const [relName, relMeta] of reverseRelEntries) {
751
- const reverseLinks = await perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: inst.id }));
752
- const sourceIds = reverseLinks
753
- .filter((l) => l.data.target === inst.id)
754
- .map((l) => l.data.source);
755
- if (relMeta.kind === 'belongsToOne') {
756
- inst[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
757
- }
758
- else {
759
- inst[relName] = sourceIds;
760
- }
761
- }
762
- }));
763
836
  }
764
- // Evaluate custom getters for all instances (single pass)
765
- const getterOpts = requestedProperties.length > 0 || query.include
766
- ? { requestedProperties, include: query.include }
767
- : undefined;
768
- for (const instance of instances) {
769
- await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
770
- }
771
- // Filter by where conditions that couldn't be filtered in SQL
772
- // This includes:
773
- // - author/timestamp (computed from grouped links)
774
- // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
775
- // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
776
- let filteredInstances = instances;
777
- if (query.where) {
778
- filteredInstances = instances.filter(instance => {
779
- for (const [propertyName, condition] of Object.entries(query.where)) {
780
- // Skip 'base' as it's filtered in SQL
781
- if (propertyName === 'base')
782
- continue;
783
- // For author and timestamp, always filter in JS
784
- if (propertyName === 'author' || propertyName === 'timestamp') {
785
- if (!matchesCondition(instance[propertyName], condition)) {
786
- return false;
787
- }
788
- continue;
837
+ if (query.where)
838
+ queryInput.where = query.where;
839
+ if (query.order) {
840
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
841
+ }
842
+ if (query.offset !== undefined)
843
+ queryInput.offset = query.offset;
844
+ if (query.limit !== undefined)
845
+ queryInput.limit = query.limit;
846
+ if (query.count !== undefined)
847
+ queryInput.count = query.count;
848
+ queryInput.deepQuery = query.deepQuery ?? true;
849
+ if (queryInput.include) {
850
+ const allRelMeta = getRelationsMetadata(this);
851
+ enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
852
+ }
853
+ // Pre-compute conformance getters for Rust-side evaluation.
854
+ // Where clauses are NOT compiled into getter SPARQL because stored
855
+ // property values are signed expression envelopes (literal:json:...),
856
+ // not simple literal:string:X values. Instead, where clauses are
857
+ // attached as metadata for Rust-side post-evaluation filtering.
858
+ {
859
+ const allRelMeta = getRelationsMetadata(this);
860
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
861
+ const rel = relMeta;
862
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
863
+ continue;
864
+ const meta = allRelMeta[relName];
865
+ if (!meta?.target)
866
+ continue;
867
+ try {
868
+ const TargetClass = meta.target();
869
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
870
+ if (filter) {
871
+ rel.getter = filter.getter;
789
872
  }
790
- // For regular properties, only filter comparison operators in JS
791
- // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
792
- if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
793
- const ops = condition;
794
- // Check if any comparison operators are present
795
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
796
- ops.lt !== undefined || ops.lte !== undefined ||
797
- ops.between !== undefined || ops.contains !== undefined;
798
- if (hasComparisonOps) {
799
- if (!matchesCondition(instance[propertyName], condition)) {
800
- return false;
873
+ // Attach where-clause metadata for Rust-side post-getter filtering
874
+ if (rel.where) {
875
+ try {
876
+ const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
877
+ if (targetMetadata) {
878
+ const predicates = {};
879
+ for (const propName of Object.keys(rel.where)) {
880
+ if (['id', 'author', 'timestamp'].includes(propName))
881
+ continue;
882
+ const propMeta = targetMetadata.properties[propName];
883
+ if (propMeta?.predicate) {
884
+ predicates[propName] = propMeta.predicate;
885
+ }
886
+ }
887
+ if (Object.keys(predicates).length > 0) {
888
+ rel.whereFilter = rel.where;
889
+ rel.wherePredicates = predicates;
890
+ }
801
891
  }
802
892
  }
893
+ catch (e) {
894
+ console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e);
895
+ }
803
896
  }
804
897
  }
805
- return true;
806
- });
898
+ catch (e) {
899
+ console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e);
900
+ }
901
+ }
807
902
  }
808
- // Apply ordering in JavaScript
809
- // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
810
- // This ensures consistent pagination behavior
811
- const effectiveOrder = query.order ||
812
- (query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' } : null);
813
- if (effectiveOrder) {
814
- const orderEntries = Object.entries(effectiveOrder);
815
- filteredInstances.sort((a, b) => {
816
- for (const [orderPropName, orderDirection] of orderEntries) {
817
- let aVal = a[orderPropName];
818
- let bVal = b[orderPropName];
819
- // Handle undefined values - push them to the end
820
- if (aVal === undefined && bVal === undefined)
821
- continue;
822
- if (aVal === undefined)
823
- return orderDirection === 'ASC' ? 1 : -1;
824
- if (bVal === undefined)
825
- return orderDirection === 'ASC' ? -1 : 1;
826
- // Compare values
827
- let comparison = 0;
828
- if (typeof aVal === 'number' && typeof bVal === 'number') {
829
- comparison = aVal - bVal;
830
- }
831
- else if (typeof aVal === 'string' && typeof bVal === 'string') {
832
- comparison = aVal.localeCompare(bVal);
833
- }
834
- else {
835
- comparison = String(aVal).localeCompare(String(bVal));
903
+ return {
904
+ className,
905
+ queryJson: JSON.stringify(queryInput),
906
+ shapeJson: JSON.stringify(metadata),
907
+ metadata,
908
+ };
909
+ }
910
+ /**
911
+ * Parse raw model query/subscription result JSON into typed model instances.
912
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
913
+ * @internal
914
+ */
915
+ static parseModelResult(perspective, raw, include, properties) {
916
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
917
+ const arr = data.instances || data;
918
+ if (!Array.isArray(arr))
919
+ return [];
920
+ return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
921
+ }
922
+ /**
923
+ * Resolve non-literal (file-language) properties on an array of already-constructed
924
+ * model instances. Handles two cases:
925
+ *
926
+ * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
927
+ * 2. The Rust executor already resolved the expression and returned a `FileData` object
928
+ * (happens when the perspective backend eagerly fetches file content) → apply transform
929
+ * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
930
+ * synthesised model classes).
931
+ *
932
+ * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
933
+ * duplicating logic or introducing a circular dependency.
934
+ * @internal
935
+ */
936
+ static async resolveNonLiteralProps(perspective, instances) {
937
+ const propsMeta = getPropertiesMetadata(this);
938
+ const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
939
+ opts.resolveLanguage !== 'literal');
940
+ if (resolveProps.length === 0)
941
+ return;
942
+ await Promise.all(instances.map(async (inst) => {
943
+ for (const [propName, opts] of resolveProps) {
944
+ const val = inst[propName];
945
+ const transform = opts.transform;
946
+ const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
947
+ if (typeof val === 'string' && val && !val.startsWith('literal:')) {
948
+ // Case 1: raw URI — fetch from language runtime
949
+ try {
950
+ const expression = await perspective.getExpression(val);
951
+ if (expression) {
952
+ let resolved;
953
+ try {
954
+ resolved = JSON.parse(expression.data);
955
+ }
956
+ catch {
957
+ resolved = expression.data;
958
+ }
959
+ inst[propName] = applyTransform(resolved);
960
+ }
836
961
  }
837
- if (comparison !== 0) {
838
- return orderDirection === 'DESC' ? -comparison : comparison;
962
+ catch (e) {
963
+ console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);
839
964
  }
840
- // comparison === 0: continue to next sort field
841
965
  }
842
- return 0;
843
- });
844
- }
845
- // Calculate totalCount BEFORE applying limit/offset
846
- const totalCount = filteredInstances.length;
847
- // Apply offset and limit in JavaScript
848
- let paginatedInstances = filteredInstances;
849
- if (query.offset !== undefined || query.limit !== undefined) {
850
- const start = query.offset || 0;
851
- const end = query.limit ? start + query.limit : undefined;
852
- paginatedInstances = filteredInstances.slice(start, end);
853
- }
854
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
855
- if (query.include && paginatedInstances.length > 0) {
856
- await hydrateRelations(this, paginatedInstances, perspective, query.include);
857
- }
858
- // Take snapshots for dirty tracking after ALL hydration is complete
859
- // (including eager-loaded relations).
860
- // When `include` is specified, only snapshot those relations.
861
- // Otherwise snapshot ALL fields (properties + relations) since
862
- // hydrateFromLinks populates relations with stable raw IDs —
863
- // this ensures push-to-array + save() correctly detects dirty relations.
864
- const snapshotRelations = query.include;
865
- for (const inst of paginatedInstances) {
866
- inst.takeSnapshot(snapshotRelations);
966
+ else if (val !== null && val !== undefined && typeof val === 'object') {
967
+ // Case 2: already resolved by Rust — apply transform / default decode
968
+ inst[propName] = applyTransform(val);
969
+ }
970
+ }
971
+ }));
972
+ }
973
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
974
+ /**
975
+ * Execute a model query via the executor-side endpoint.
976
+ *
977
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
978
+ * with a single RPC to the executor that handles everything in Rust.
979
+ *
980
+ * @internal
981
+ */
982
+ static async executeModelQuery(perspective, query = {}, classNameOverride) {
983
+ // Delegate all query input building, shape enrichment, and getter
984
+ // pre-computation to the shared prepareModelQueryParams helper.
985
+ const { className, queryJson, shapeJson } = this.prepareModelQueryParams(query, classNameOverride);
986
+ const result = await perspective.modelQuery(className, queryJson, shapeJson);
987
+ // Convert JSON instances to model class instances, recursively constructing
988
+ // class instances for any included relations resolved by Rust.
989
+ const instances = result.instances.map((json) => {
990
+ return jsonToModelInstance(this, perspective, json, query.include, query.properties);
991
+ });
992
+ // Resolve non-literal expressions (e.g. file languages where the stored
993
+ // value is a content-addressed hash that must be fetched from the language
994
+ // runtime). The Rust endpoint may return either a raw target URI (string)
995
+ // or an already-resolved FileData object — both cases are handled here.
996
+ await this.resolveNonLiteralProps(perspective, instances);
997
+ // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
998
+ const snapshotRelations = query.include
999
+ ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
1000
+ : undefined;
1001
+ for (const inst of instances) {
1002
+ inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
867
1003
  }
868
1004
  return {
869
- results: paginatedInstances,
870
- totalCount
1005
+ results: instances,
1006
+ totalCount: result.totalCount,
871
1007
  };
872
1008
  }
873
1009
  /**
@@ -875,15 +1011,14 @@ export class Ad4mModel {
875
1011
  *
876
1012
  * @param perspective - The perspective to search in
877
1013
  * @param query - Optional query parameters to filter results
878
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1014
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
1015
+ * All queries now use the Rust SPARQL pipeline.
879
1016
  * @returns Array of matching models
880
1017
  *
881
1018
  * @example
882
1019
  * ```typescript
883
- * // Get all recipes (uses SurrealDB by default)
884
1020
  * const allRecipes = await Recipe.findAll(perspective);
885
1021
  *
886
- * // Get recipes with specific criteria (uses SurrealDB)
887
1022
  * const recipes = await Recipe.findAll(perspective, {
888
1023
  * where: {
889
1024
  * name: "Pasta",
@@ -892,27 +1027,16 @@ export class Ad4mModel {
892
1027
  * order: { createdAt: "DESC" },
893
1028
  * limit: 10
894
1029
  * });
895
- *
896
- * // Explicitly use Prolog (legacy, for backward compatibility)
897
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
898
1030
  * ```
899
1031
  */
900
- static async findAll(perspective, query = {}, useSurrealDB = true) {
1032
+ static async findAll(perspective, query = {},
1033
+ /** @deprecated Ignored — Prolog engine has been removed. */
1034
+ _engine) {
901
1035
  if (query.properties && query.properties.length === 0) {
902
1036
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
903
1037
  }
904
- if (useSurrealDB) {
905
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
906
- const result = await perspective.querySurrealDB(surrealQuery);
907
- const { results } = await this.instancesFromSurrealResult(perspective, query, result);
908
- return results;
909
- }
910
- else {
911
- const prologQuery = await this.queryToProlog(perspective, query);
912
- const result = await perspective.infer(prologQuery);
913
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
914
- return results;
915
- }
1038
+ const { results } = await this.executeModelQuery(perspective, query);
1039
+ return results;
916
1040
  }
917
1041
  /**
918
1042
  * Finds the first instance matching the query, or `null` if none exists.
@@ -921,7 +1045,7 @@ export class Ad4mModel {
921
1045
  *
922
1046
  * @param perspective - The perspective to search in
923
1047
  * @param query - Optional query parameters to filter results
924
- * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
1048
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
925
1049
  * @returns The first matching instance, or `null`
926
1050
  *
927
1051
  * @example
@@ -934,9 +1058,11 @@ export class Ad4mModel {
934
1058
  * }
935
1059
  * ```
936
1060
  */
937
- static async findOne(perspective, query = {}, useSurrealDB = true) {
1061
+ static async findOne(perspective, query = {},
1062
+ /** @deprecated Ignored — Prolog engine has been removed. */
1063
+ _engine) {
938
1064
  const limitedQuery = { ...query, limit: 1 };
939
- const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
1065
+ const results = await this.findAll(perspective, limitedQuery);
940
1066
  return results[0] ?? null;
941
1067
  }
942
1068
  /**
@@ -944,7 +1070,7 @@ export class Ad4mModel {
944
1070
  *
945
1071
  * @param perspective - The perspective to search in
946
1072
  * @param query - Optional query parameters to filter results
947
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1073
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
948
1074
  * @returns Object containing results array and total count
949
1075
  *
950
1076
  * @example
@@ -954,22 +1080,12 @@ export class Ad4mModel {
954
1080
  * limit: 10
955
1081
  * });
956
1082
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
957
- *
958
- * // Use Prolog explicitly (legacy)
959
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
960
1083
  * ```
961
1084
  */
962
- static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
963
- if (useSurrealDB) {
964
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
965
- const result = await perspective.querySurrealDB(surrealQuery);
966
- return await this.instancesFromSurrealResult(perspective, query, result);
967
- }
968
- else {
969
- const prologQuery = await this.queryToProlog(perspective, query);
970
- const result = await perspective.infer(prologQuery);
971
- return await this.instancesFromPrologResult(perspective, query, result);
972
- }
1085
+ static async findAllAndCount(perspective, query = {},
1086
+ /** @deprecated Ignored — Prolog engine has been removed. */
1087
+ _engine) {
1088
+ return await this.executeModelQuery(perspective, query);
973
1089
  }
974
1090
  /**
975
1091
  * Helper function for pagination with explicit page size and number.
@@ -978,7 +1094,6 @@ export class Ad4mModel {
978
1094
  * @param pageSize - Number of items per page
979
1095
  * @param pageNumber - Which page to retrieve (1-based)
980
1096
  * @param query - Optional additional query parameters
981
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
982
1097
  * @returns Paginated results with metadata
983
1098
  *
984
1099
  * @example
@@ -987,67 +1102,30 @@ export class Ad4mModel {
987
1102
  * where: { category: "Main Course" }
988
1103
  * });
989
1104
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
990
- *
991
- * // Use Prolog explicitly (legacy)
992
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
993
1105
  * ```
994
1106
  */
995
- static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
1107
+ static async paginate(perspective, pageSize, pageNumber, query,
1108
+ /** @deprecated Ignored — Prolog engine has been removed. */
1109
+ _engine) {
996
1110
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
997
- if (useSurrealDB) {
998
- const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
999
- const result = await perspective.querySurrealDB(surrealQuery);
1000
- const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
1001
- return { results, totalCount, pageSize, pageNumber };
1002
- }
1003
- else {
1004
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
1005
- const result = await perspective.infer(prologQuery);
1006
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
1007
- return { results, totalCount, pageSize, pageNumber };
1008
- }
1009
- }
1010
- static async countQueryToProlog(perspective, query = {}, modelClassName) {
1011
- const { where } = query;
1012
- const className = modelClassName || (await this.getClassName(perspective));
1013
- const resolvedParentPredicate = query.parent
1014
- ? resolveParentPredicate(query.parent, this)
1015
- : undefined;
1016
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
1017
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
1018
- const fullQuery = `
1019
- findall([Base, Properties, Collections, Timestamp, Author], (
1020
- subject_class("${className}", SubjectClass),
1021
- instance(SubjectClass, Base),
1022
- ${instanceQueries.filter((q) => q).join(", ")}
1023
- ), UnsortedInstances),
1024
- ${resultSetQueries.filter((q) => q).join(", ")}
1025
- `;
1026
- return fullQuery;
1111
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1112
+ return { results, totalCount, pageSize, pageNumber };
1027
1113
  }
1028
1114
  /**
1029
- * Generates a SurrealQL COUNT query for the model.
1115
+ * Generates a SPARQL COUNT query for the model.
1030
1116
  *
1031
1117
  * @param perspective - The perspective context
1032
1118
  * @param query - Query parameters to filter the count
1033
- * @returns SurrealQL COUNT query string
1119
+ * @returns SPARQL COUNT query string
1034
1120
  *
1035
1121
  * @private
1036
1122
  */
1037
- static async countQueryToSurrealQL(perspective, query) {
1038
- // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
1039
- // We'll count the number of rows returned (one row per source)
1040
- const countQuery = { ...query };
1041
- delete countQuery.limit;
1042
- delete countQuery.offset;
1043
- return await this.queryToSurrealQL(perspective, countQuery);
1044
- }
1123
+ // countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
1045
1124
  /**
1046
1125
  * Gets a count of all matching instances.
1047
1126
  *
1048
1127
  * @param perspective - The perspective to search in
1049
1128
  * @param query - Optional query parameters to filter results
1050
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1051
1129
  * @returns Total count of matching entities
1052
1130
  *
1053
1131
  * @example
@@ -1056,25 +1134,11 @@ export class Ad4mModel {
1056
1134
  * const activeRecipes = await Recipe.count(perspective, {
1057
1135
  * where: { status: "active" }
1058
1136
  * });
1059
- *
1060
- * // Use Prolog explicitly (legacy)
1061
- * const countProlog = await Recipe.count(perspective, {}, false);
1062
1137
  * ```
1063
1138
  */
1064
- static async count(perspective, query = {}, useSurrealDB = true) {
1065
- if (useSurrealDB) {
1066
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
1067
- const result = await perspective.querySurrealDB(surrealQuery);
1068
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
1069
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
1070
- // This ensures count() returns the same number as findAll().length
1071
- const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
1072
- return totalCount;
1073
- }
1074
- else {
1075
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
1076
- return result?.[0]?.TotalCount || 0;
1077
- }
1139
+ static async count(perspective, query = {}) {
1140
+ const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
1141
+ return totalCount;
1078
1142
  }
1079
1143
  async setProperty(key, value, batchId) {
1080
1144
  const metadata = this.getPropertyMetadata(key);
@@ -1086,7 +1150,7 @@ export class Ad4mModel {
1086
1150
  const actions = this.generatePropertySetterAction(key, metadata);
1087
1151
  // Get resolve language from metadata (replaces Prolog query)
1088
1152
  let resolveLanguage = metadata.resolveLanguage;
1089
- // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
1153
+ // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
1090
1154
  if (value === undefined || value === null || value === "") {
1091
1155
  return;
1092
1156
  }
@@ -1357,6 +1421,92 @@ export class Ad4mModel {
1357
1421
  }
1358
1422
  }
1359
1423
  }
1424
+ /**
1425
+ * Evaluate SPARQL getters for a batch of instances on demand.
1426
+ *
1427
+ * Since deepQuery defaults to true, property getters are evaluated
1428
+ * automatically during collection queries. Use this method when
1429
+ * deepQuery was explicitly set to false and you want to lazily
1430
+ * resolve getter-backed properties for a subset of instances.
1431
+ *
1432
+ * @param instances - Array of model instances to evaluate getters on
1433
+ * @param perspective - The perspective to query against
1434
+ * @param propertyNames - Optional list of getter-backed property names to evaluate.
1435
+ * If omitted, all getters are evaluated.
1436
+ *
1437
+ * @example
1438
+ * ```typescript
1439
+ * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
1440
+ * // messages[i].replyingTo is undefined (getter skipped)
1441
+ *
1442
+ * // Evaluate getters for the visible subset
1443
+ * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
1444
+ * // messages[0..9].replyingTo is now populated
1445
+ * ```
1446
+ */
1447
+ static async evaluateGetters(instances, perspective, propertyNames) {
1448
+ if (instances.length === 0)
1449
+ return;
1450
+ const metadata = this.getModelMetadata();
1451
+ // Pre-compute conformance getters so the shape sent to Rust includes them
1452
+ const allRelMeta = getRelationsMetadata(this);
1453
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1454
+ const rel = relMeta;
1455
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
1456
+ continue;
1457
+ const meta = allRelMeta[relName];
1458
+ if (!meta?.target)
1459
+ continue;
1460
+ try {
1461
+ const TargetClass = meta.target();
1462
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
1463
+ if (filter)
1464
+ rel.getter = filter.getter;
1465
+ }
1466
+ catch (e) {
1467
+ console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e);
1468
+ }
1469
+ }
1470
+ const shapeJson = JSON.stringify(metadata);
1471
+ const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
1472
+ // Single RPC call evaluates all getters in-process on the executor
1473
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
1474
+ // Determine which property names were evaluated for snapshot sync
1475
+ const evaluatedPropertyNames = [];
1476
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1477
+ if (propMeta.getter) {
1478
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {
1479
+ evaluatedPropertyNames.push(propName);
1480
+ }
1481
+ }
1482
+ }
1483
+ // Also include relation getters
1484
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1485
+ if (relMeta.getter) {
1486
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
1487
+ evaluatedPropertyNames.push(relName);
1488
+ }
1489
+ }
1490
+ }
1491
+ // Apply results to instances and sync snapshots
1492
+ for (const instance of instances) {
1493
+ const id = instance.id || instance._baseExpression;
1494
+ const props = result[id];
1495
+ if (props) {
1496
+ for (const [key, value] of Object.entries(props)) {
1497
+ instance[key] = value;
1498
+ }
1499
+ }
1500
+ // Sync snapshot so isDirty() doesn't flag getter-only changes
1501
+ const modelInstance = instance;
1502
+ if (modelInstance._snapshot) {
1503
+ for (const propName of evaluatedPropertyNames) {
1504
+ const val = instance[propName];
1505
+ modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
1506
+ }
1507
+ }
1508
+ }
1509
+ }
1360
1510
  /**
1361
1511
  * Gets the model instance with all properties and relations populated.
1362
1512
  *
@@ -1611,6 +1761,22 @@ export class Ad4mModel {
1611
1761
  static async register(perspective) {
1612
1762
  await perspective.ensureSDNASubjectClass(this);
1613
1763
  }
1764
+ /**
1765
+ * Batch-registers multiple model classes on a perspective in a single RPC call.
1766
+ * This is significantly faster than calling `register()` on each model individually
1767
+ * because it eliminates N-1 round-trips and mutex acquisitions.
1768
+ *
1769
+ * @param perspective - The perspective to register the models on
1770
+ * @param models - Array of Ad4mModel subclasses to register
1771
+ *
1772
+ * @example
1773
+ * ```typescript
1774
+ * await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);
1775
+ * ```
1776
+ */
1777
+ static async registerAll(perspective, models) {
1778
+ await perspective.ensureSubjectClasses(models);
1779
+ }
1614
1780
  /**
1615
1781
  * Executes a set of model operations inside a single batch (transaction).
1616
1782
  *
@@ -1724,5 +1890,111 @@ export class Ad4mModel {
1724
1890
  static fromJSONSchema(schema, options) {
1725
1891
  return buildModelFromJSONSchema(this, schema, options);
1726
1892
  }
1893
+ /**
1894
+ * Creates a fully functional Ad4mModel subclass from a SHACL shape.
1895
+ *
1896
+ * Unlike `fromJSONSchema()`, no predicate inference is required —
1897
+ * `SHACLShape` already contains the exact predicate URI in `path` for
1898
+ * every property. The method reads each property's `path`, `maxCount`,
1899
+ * `writable`, and `resolveLanguage` directly and writes them to the
1900
+ * WeakMap metadata registries.
1901
+ *
1902
+ * Properties with `hasValue` (flag / type-discrimination markers) are
1903
+ * registered as hidden flag entries so that the SPARQL query builder emits
1904
+ * the fixed triple `?source <predicate> <value>` needed for type discrimination.
1905
+ * Properties without a `name` field are skipped.
1906
+ *
1907
+ * **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
1908
+ * was persisted on property shapes) carry the flag value only in
1909
+ * `shape.constructor_actions` as the `target` of an `addLink` action.
1910
+ * This method recovers those values so that old perspectives are queried
1911
+ * with the correct type-discriminator triple.
1912
+ *
1913
+ * @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
1914
+ * @param name - Class name to assign (e.g. "Channel")
1915
+ * @returns Generated Ad4mModel subclass, ready for querying
1916
+ */
1917
+ /**
1918
+ * Synthesise an `Ad4mModel` subclass from a SHACL shape.
1919
+ *
1920
+ * @param shape - The SHACL shape to synthesise from.
1921
+ * @param name - The model name (e.g. "Channel").
1922
+ * @param classResolver - Optional thunk factory. When provided, any collection
1923
+ * property that carries a `sh:class` URI will have its `target` wired up lazily:
1924
+ * `target: () => classResolver(localName)`. Because `target` is only called at
1925
+ * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
1926
+ * resolver just needs to return the correct class by the time a query runs —
1927
+ * making it safe to pass a closure over a registry object that is still being
1928
+ * populated (e.g. the `result` record inside `getModelClasses`).
1929
+ */
1930
+ static fromSHACL(shape, name, classResolver) {
1931
+ const DynamicModelClass = class extends this {
1932
+ };
1933
+ DynamicModelClass.className = name;
1934
+ DynamicModelClass.prototype.className = name;
1935
+ // Build a backward-compat fallback map: predicate → fixed-IRI-value from
1936
+ // constructor actions. Old SHACL stores (created before sh:hasValue was
1937
+ // persisted on the property shape) don't carry sh:hasValue on properties,
1938
+ // but the shape-level constructor_actions always contain an addLink action
1939
+ // with the fixed flag value as the target.
1940
+ const flagValueFromConstructor = new Map();
1941
+ for (const action of shape.constructor_actions ?? []) {
1942
+ if (action.action === 'addLink' &&
1943
+ typeof action.predicate === 'string' &&
1944
+ typeof action.target === 'string' &&
1945
+ action.target !== 'value' &&
1946
+ !action.target.startsWith('literal:')) {
1947
+ flagValueFromConstructor.set(action.predicate, action.target);
1948
+ }
1949
+ }
1950
+ for (const prop of shape.properties) {
1951
+ const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
1952
+ if (resolvedHasValue !== undefined) {
1953
+ const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
1954
+ setPropertyRegistryEntry(DynamicModelClass, flagKey, {
1955
+ through: prop.path,
1956
+ required: true,
1957
+ initial: resolvedHasValue,
1958
+ flag: true,
1959
+ writable: false,
1960
+ readOnly: true,
1961
+ });
1962
+ continue;
1963
+ }
1964
+ // Skip properties without a declared name
1965
+ if (!prop.name)
1966
+ continue;
1967
+ const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
1968
+ if (isCollection) {
1969
+ // Derive a lazy `target` thunk when a sh:class URI is present and a
1970
+ // classResolver was supplied. The thunk is evaluated at query time so
1971
+ // it is safe even if the target class hasn't been registered yet.
1972
+ let targetThunk;
1973
+ if (prop.class && classResolver) {
1974
+ const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
1975
+ const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
1976
+ targetThunk = () => classResolver(localName);
1977
+ }
1978
+ setRelationRegistryEntry(DynamicModelClass, prop.name, {
1979
+ predicate: prop.path,
1980
+ kind: 'hasMany',
1981
+ ...(targetThunk !== undefined && { target: targetThunk }),
1982
+ ...(prop.local !== undefined && { local: prop.local }),
1983
+ ...(prop.getter !== undefined && { getter: prop.getter }),
1984
+ });
1985
+ }
1986
+ else {
1987
+ setPropertyRegistryEntry(DynamicModelClass, prop.name, {
1988
+ through: prop.path,
1989
+ writable: prop.writable ?? true,
1990
+ ...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
1991
+ ...(prop.local !== undefined && { local: prop.local }),
1992
+ });
1993
+ }
1994
+ }
1995
+ const ModelDecorator = Model({ name });
1996
+ ModelDecorator(DynamicModelClass);
1997
+ return DynamicModelClass;
1998
+ }
1727
1999
  }
1728
2000
  Ad4mModel.classNamesByClass = new WeakMap();