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

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 (393) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +8677 -15318
  4. package/lib/index.js +14507 -21223
  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 +8 -2
  153. package/lib/src/index.js +8 -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 +143 -63
  166. package/lib/src/model/Ad4mModel.js +583 -425
  167. package/lib/src/model/Ad4mModel.test.js +1434 -688
  168. package/lib/src/model/ModelQueryBuilder.d.ts +61 -45
  169. package/lib/src/model/ModelQueryBuilder.js +315 -157
  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 +154 -57
  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 +195 -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 +188 -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 +157 -78
  220. package/lib/src/perspectives/PerspectiveProxy.js +475 -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/SparqlBindings.d.ts +47 -0
  224. package/lib/src/perspectives/SparqlBindings.js +65 -0
  225. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  226. package/lib/src/perspectives/WakerSubscriptionManager.js +12 -12
  227. package/lib/src/runtime/RuntimeClient.d.ts +8 -6
  228. package/lib/src/runtime/RuntimeClient.js +97 -454
  229. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  230. package/lib/src/runtime/RuntimeResolver.js +84 -0
  231. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  232. package/lib/src/runtime/RuntimeTypes.js +45 -0
  233. package/lib/src/schema.gql +14 -1
  234. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  235. package/lib/src/shacl/SHACLFlow.js +9 -9
  236. package/lib/src/shacl/SHACLShape.d.ts +26 -1
  237. package/lib/src/shacl/SHACLShape.js +140 -38
  238. package/lib/src/shacl/SHACLShape.test.js +82 -0
  239. package/lib/src/typeDefs.js +3 -615
  240. package/lib/src/utils.d.ts +6 -6
  241. package/lib/src/utils.js +6 -6
  242. package/package.json +9 -24
  243. package/rollup.config.js +0 -7
  244. package/src/Ad4mClient.test.ts +1192 -1288
  245. package/src/Ad4mClient.ts +46 -15
  246. package/src/Literal.test.ts +10 -5
  247. package/src/Literal.ts +6 -5
  248. package/src/agent/Agent.ts +0 -99
  249. package/src/agent/AgentClient.ts +238 -467
  250. package/src/agent/AgentStatus.ts +0 -12
  251. package/src/ai/AIClient.ts +96 -296
  252. package/src/ai/AITypes.ts +66 -0
  253. package/src/ai/Tasks.ts +0 -52
  254. package/src/apiClient.ts +287 -0
  255. package/src/cache/PersistentCache.ts +145 -0
  256. package/src/cache/cache.test.ts +713 -0
  257. package/src/expression/Expression.ts +3 -43
  258. package/src/expression/ExpressionClient.ts +148 -77
  259. package/src/expression/ExpressionRef.ts +2 -8
  260. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  261. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  262. package/src/generated/api/AddLinkRequest.ts +4 -0
  263. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  264. package/src/generated/api/AddSdnaRequest.ts +3 -0
  265. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  266. package/src/generated/api/AuthInfoInput.ts +4 -0
  267. package/src/generated/api/CapabilityInput.ts +4 -0
  268. package/src/generated/api/CommitBatchRequest.ts +3 -0
  269. package/src/generated/api/ComputeLogEntry.ts +3 -0
  270. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  271. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  272. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  273. package/src/generated/api/EmbedRequest.ts +3 -0
  274. package/src/generated/api/EntanglementProofInput.ts +3 -0
  275. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  276. package/src/generated/api/ExportRequest.ts +3 -0
  277. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  278. package/src/generated/api/ExpressionProof.ts +3 -0
  279. package/src/generated/api/ExpressionProofInput.ts +3 -0
  280. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  281. package/src/generated/api/FriendsListRequest.ts +3 -0
  282. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  283. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  284. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  285. package/src/generated/api/ImportAgentRequest.ts +3 -0
  286. package/src/generated/api/ImportRequest.ts +3 -0
  287. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  288. package/src/generated/api/LanguageMetaInput.ts +3 -0
  289. package/src/generated/api/Link.ts +3 -0
  290. package/src/generated/api/LinkExpression.ts +6 -0
  291. package/src/generated/api/LinkExpressionInput.ts +6 -0
  292. package/src/generated/api/LinkInput.ts +3 -0
  293. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  294. package/src/generated/api/LinkMutations.ts +5 -0
  295. package/src/generated/api/LinkStatus.ts +3 -0
  296. package/src/generated/api/LockAgentRequest.ts +3 -0
  297. package/src/generated/api/ModelType.ts +3 -0
  298. package/src/generated/api/NotificationInput.ts +3 -0
  299. package/src/generated/api/OpenLinkRequest.ts +3 -0
  300. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  301. package/src/generated/api/PerspectiveInput.ts +4 -0
  302. package/src/generated/api/PromptRequest.ts +3 -0
  303. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  304. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  305. package/src/generated/api/QueryRequest.ts +6 -0
  306. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  307. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  308. package/src/generated/api/ResourceInput.ts +3 -0
  309. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  310. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  311. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  312. package/src/generated/api/SetStatusRequest.ts +3 -0
  313. package/src/generated/api/SignMessageRequest.ts +3 -0
  314. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  315. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  316. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  317. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  318. package/src/generated/api/UserStatistics.ts +3 -0
  319. package/src/generated/api/VerificationRequestResult.ts +3 -0
  320. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  321. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  322. package/src/generated/api/index.ts +49 -0
  323. package/src/index.ts +8 -2
  324. package/src/jestSetup.ts +1 -1
  325. package/src/language/Icon.ts +0 -4
  326. package/src/language/Language.ts +51 -248
  327. package/src/language/LanguageClient.ts +21 -132
  328. package/src/language/LanguageHandle.ts +0 -14
  329. package/src/language/LanguageMeta.ts +0 -29
  330. package/src/language/LanguageRef.ts +0 -7
  331. package/src/links/Links.ts +0 -37
  332. package/src/model/Ad4mModel.test.ts +1664 -792
  333. package/src/model/Ad4mModel.ts +664 -499
  334. package/src/model/ModelQueryBuilder.ts +362 -183
  335. package/src/model/decorators.ts +71 -22
  336. package/src/model/hydration.ts +3 -772
  337. package/src/model/index.ts +3 -4
  338. package/src/model/json-schema.ts +2 -2
  339. package/src/model/query-cache.test.ts +54 -0
  340. package/src/model/query-cache.ts +79 -0
  341. package/src/model/query-common.ts +1 -1
  342. package/src/model/query-sparql.test.ts +376 -0
  343. package/src/model/query-sparql.ts +504 -0
  344. package/src/model/query-utils.ts +209 -0
  345. package/src/model/relation-filtering.test.ts +60 -53
  346. package/src/model/sdna.ts +1 -1
  347. package/src/model/shacl-gen.ts +163 -64
  348. package/src/model/shacl-roundtrip.test.ts +197 -0
  349. package/src/model/types-typed-query.test.ts +360 -0
  350. package/src/model/types.ts +256 -5
  351. package/src/neighbourhood/Neighbourhood.ts +0 -9
  352. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  353. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  354. package/src/perspectives/LinkQuery.ts +0 -15
  355. package/src/perspectives/Perspective.ts +1 -12
  356. package/src/perspectives/PerspectiveClient.test.ts +262 -0
  357. package/src/perspectives/PerspectiveClient.ts +252 -468
  358. package/src/perspectives/PerspectiveDiff.ts +0 -8
  359. package/src/perspectives/PerspectiveHandle.ts +1 -12
  360. package/src/perspectives/PerspectiveProxy.test.ts +125 -0
  361. package/src/perspectives/PerspectiveProxy.ts +522 -434
  362. package/src/perspectives/SparqlBindings.ts +79 -0
  363. package/src/perspectives/WakerSubscriptionManager.ts +13 -13
  364. package/src/runtime/RuntimeClient.ts +118 -461
  365. package/src/runtime/RuntimeTypes.ts +144 -0
  366. package/src/shacl/SHACLFlow.ts +9 -9
  367. package/src/shacl/SHACLShape.test.ts +204 -0
  368. package/src/shacl/SHACLShape.ts +191 -39
  369. package/src/typeDefs.ts +3 -5
  370. package/src/utils.ts +6 -6
  371. package/tsconfig.json +3 -7
  372. package/lib/src/model/query-surreal.d.ts +0 -44
  373. package/lib/src/model/query-surreal.js +0 -249
  374. package/lib/src/model/surreal-utils.js +0 -128
  375. package/shims/reflect-metadata.ts +0 -0
  376. package/shims/type-graphql.ts +0 -75
  377. package/src/PubSub.ts +0 -17
  378. package/src/agent/AgentResolver.ts +0 -263
  379. package/src/ai/AIResolver.ts +0 -372
  380. package/src/buildSchema.ts +0 -43
  381. package/src/expression/ExpressionResolver.ts +0 -64
  382. package/src/language/LanguageContext.ts +0 -37
  383. package/src/language/LanguageResolver.ts +0 -98
  384. package/src/model/Subject.ts +0 -159
  385. package/src/model/prolog-facts.ts +0 -145
  386. package/src/model/query-prolog.ts +0 -148
  387. package/src/model/query-surreal.ts +0 -280
  388. package/src/model/surreal-utils.ts +0 -147
  389. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  390. package/src/perspectives/PerspectiveResolver.ts +0 -372
  391. package/src/runtime/RuntimeResolver.ts +0 -691
  392. package/src/unwrapApolloResult.ts +0 -16
  393. package/tsconfig-browser.json +0 -82
@@ -2,14 +2,151 @@ 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, 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
+ * Construct a model class instance from a plain JSON object returned by the
58
+ * Rust endpoint. Recursively converts included relation values (which come
59
+ * back as plain JSON objects) into proper model class instances.
60
+ */
61
+ function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
62
+ const instance = new ModelClass(perspective, json.id || json.baseExpression);
63
+ // When a properties projection is active, remove own properties set by the
64
+ // constructor that are not in the projected JSON. This ensures assertions
65
+ // like `expect(r).to.not.have.own.property("body")` pass.
66
+ if (properties) {
67
+ const jsonKeys = new Set(Object.keys(json));
68
+ for (const key of Object.getOwnPropertyNames(instance)) {
69
+ // Keep internal fields (backing store for getters), id, baseExpression, perspective
70
+ if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_'))
71
+ continue;
72
+ if (!jsonKeys.has(key)) {
73
+ delete instance[key];
74
+ }
75
+ }
76
+ }
77
+ for (const [key, value] of Object.entries(json)) {
78
+ if (key === 'baseExpression' || key === 'id')
79
+ continue;
80
+ // Skip getter-only properties anywhere in the prototype chain
81
+ let isReadonly = false;
82
+ let proto = Object.getPrototypeOf(instance);
83
+ while (proto) {
84
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
85
+ if (desc) {
86
+ isReadonly = !!(desc.get && !desc.set);
87
+ break;
88
+ }
89
+ proto = Object.getPrototypeOf(proto);
90
+ }
91
+ if (isReadonly)
92
+ continue;
93
+ // Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
94
+ if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
95
+ instance[key] = new Date(value).getTime();
96
+ continue;
97
+ }
98
+ instance[key] = value;
99
+ }
100
+ // Apply property transform functions from decorators (only for literal-resolved
101
+ // or no-resolveLanguage properties; non-literal properties are resolved + transformed
102
+ // asynchronously in executeModelQuery).
103
+ try {
104
+ const propsMeta = getPropertiesMetadata(ModelClass);
105
+ for (const [propName, opts] of Object.entries(propsMeta)) {
106
+ const o = opts;
107
+ if (typeof o.transform !== 'function' || !(propName in json))
108
+ continue;
109
+ // Skip non-literal resolveLanguage props — they need async expression resolution first
110
+ if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
111
+ continue;
112
+ instance[propName] = o.transform(instance[propName]);
113
+ }
114
+ }
115
+ catch (e) {
116
+ console.debug('jsonToModelInstance: transform metadata unavailable:', e);
117
+ }
118
+ // Recursively convert included relation values to class instances
119
+ if (include) {
120
+ const relMeta = getRelationsMetadata(ModelClass);
121
+ for (const [relName, includeVal] of Object.entries(include)) {
122
+ if (!includeVal)
123
+ continue;
124
+ const meta = relMeta[relName];
125
+ if (!meta?.target)
126
+ continue;
127
+ const TargetClass = meta.target();
128
+ const nestedInclude = typeof includeVal === 'object' && includeVal !== null
129
+ ? includeVal.include
130
+ : undefined;
131
+ const nestedProperties = typeof includeVal === 'object' && includeVal !== null
132
+ ? includeVal.properties
133
+ : undefined;
134
+ const raw = instance[relName];
135
+ if (Array.isArray(raw)) {
136
+ instance[relName] = raw.map((item) => {
137
+ if (typeof item === 'object' && item !== null && item.id) {
138
+ return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
139
+ }
140
+ return item;
141
+ });
142
+ }
143
+ else if (typeof raw === 'object' && raw !== null && raw.id) {
144
+ instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
145
+ }
146
+ }
147
+ }
148
+ return instance;
149
+ }
13
150
  /**
14
151
  * Base class for defining data models in AD4M.
15
152
  *
@@ -107,6 +244,13 @@ import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInsta
107
244
  * ```
108
245
  */
109
246
  export class Ad4mModel {
247
+ /**
248
+ * Backwards compatibility alias for createdAt.
249
+ * @deprecated Use createdAt instead. This will be removed in a future version.
250
+ */
251
+ get timestamp() {
252
+ return this.createdAt;
253
+ }
110
254
  /**
111
255
  * Generates the SDNA (Subject DNA) Prolog rules for this model class.
112
256
  * Injected at class-definition time by the `@Model` decorator.
@@ -144,13 +288,6 @@ export class Ad4mModel {
144
288
  }
145
289
  return classCache[perspectiveID];
146
290
  }
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
291
  /**
155
292
  * Extracts metadata from decorators for query building.
156
293
  *
@@ -222,7 +359,7 @@ export class Ad4mModel {
222
359
  // Extract relations (relations) from WeakMap registry
223
360
  const relationsMetadata = {};
224
361
  const allRelationsMeta = getRelationsMetadata(this);
225
- const prototypeRelations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
362
+ const prototypeRelations = allRelationsMeta;
226
363
  for (const [relationName, opts] of Object.entries(prototypeRelations)) {
227
364
  const options = opts;
228
365
  relationsMetadata[relationName] = {
@@ -231,6 +368,8 @@ export class Ad4mModel {
231
368
  ...(options.local !== undefined && { local: options.local }),
232
369
  ...(options.getter !== undefined && { getter: options.getter }),
233
370
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
371
+ ...(options.kind !== undefined && { kind: options.kind }),
372
+ ...(options.maxCount !== undefined && { maxCount: options.maxCount }),
234
373
  ...(options.target !== undefined && { target: options.target }),
235
374
  ...(options.filter !== undefined && { filter: options.filter }),
236
375
  ...(options.where !== undefined && { where: options.where }),
@@ -291,7 +430,7 @@ export class Ad4mModel {
291
430
  * const recipe = new Recipe(perspective);
292
431
  *
293
432
  * // Create with specific base expression
294
- * const recipe = new Recipe(perspective, "literal://...");
433
+ * const recipe = new Recipe(perspective, "literal:...");
295
434
  * ```
296
435
  */
297
436
  constructor(perspective, baseExpression) {
@@ -305,12 +444,6 @@ export class Ad4mModel {
305
444
  get id() {
306
445
  return this._baseExpression;
307
446
  }
308
- /**
309
- * @deprecated Use `.id` instead. Will be removed in a future version.
310
- */
311
- get baseExpression() {
312
- return this._baseExpression;
313
- }
314
447
  /**
315
448
  * Protected getter for the perspective.
316
449
  * Allows subclasses to access the perspective while keeping it private from external code.
@@ -391,13 +524,6 @@ export class Ad4mModel {
391
524
  ...(metadata.local && { local: true })
392
525
  }];
393
526
  }
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
527
  // ──────────────────────────────────────────────────────────
402
528
  // Snapshot / dirty tracking
403
529
  // ──────────────────────────────────────────────────────────
@@ -412,6 +538,7 @@ export class Ad4mModel {
412
538
  * • `null` / empty object — skip ALL relations (used by bare
413
539
  * subscriptions that don't eagerly load relations).
414
540
  */
541
+ /** @internal */
415
542
  takeSnapshot(includedRelations) {
416
543
  const ctor = this.constructor;
417
544
  const metadata = ctor.getModelMetadata();
@@ -517,92 +644,61 @@ export class Ad4mModel {
517
644
  return changed;
518
645
  }
519
646
  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
647
+ // Route through the Rust model query endpoint — same pipeline as executeModelQuery
648
+ // but for a single instance by ID.
522
649
  try {
523
650
  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;
651
+ const query = {
652
+ where: { id: this._baseExpression },
653
+ limit: 1,
654
+ deepQuery: true, // Single-instance get() always evaluates property getters
655
+ };
656
+ if (opts?.properties)
657
+ query.properties = opts.properties;
658
+ if (opts?.include)
659
+ query.include = opts.include;
660
+ const { results } = await ctor.executeModelQuery(this._perspective, query, null);
661
+ if (results.length > 0) {
662
+ const hydrated = results[0];
663
+ // Copy all hydrated values from the Rust-side result onto this instance
664
+ for (const [key, value] of Object.entries(hydrated)) {
665
+ if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot')
666
+ continue;
667
+ if (key.startsWith('_'))
668
+ continue;
669
+ // Check for readonly getters
670
+ let isReadonly = false;
671
+ let proto = Object.getPrototypeOf(this);
672
+ while (proto) {
673
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
674
+ if (desc) {
675
+ isReadonly = !!(desc.get && !desc.set);
676
+ break;
677
+ }
678
+ proto = Object.getPrototypeOf(proto);
679
+ }
680
+ if (isReadonly)
681
+ continue;
682
+ this[key] = value;
556
683
  }
557
684
  }
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
- }
685
+ // Property getters and relation conformance getters are now evaluated
686
+ // Rust-side via evaluate_getters() in model_query.rs.
567
687
  }
568
688
  catch (e) {
569
- console.error(`SurrealDB getData also failed for ${this._baseExpression}:`, e);
689
+ console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
570
690
  }
571
- this.takeSnapshot();
691
+ this.takeSnapshot(opts?.include);
572
692
  return this;
573
693
  }
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
694
  /**
599
- * Generates a SurrealQL query from a Query object.
695
+ * Generates a SPARQL query from a Query object.
600
696
  *
601
697
  * @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.
698
+ * This method translates high-level query parameters into a SPARQL query string
699
+ * that can be executed against the SPARQL backend. Unlike Prolog queries which
700
+ * operate on SDNA-aware predicates, SPARQL queries operate directly on raw links
701
+ * stored in SPARQL.
606
702
  *
607
703
  * The generated query uses a CTE (Common Table Expression) pattern:
608
704
  * 1. First, identify candidate base expressions by filtering links based on where conditions
@@ -610,7 +706,7 @@ export class Ad4mModel {
610
706
  * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
611
707
  *
612
708
  * Key architectural notes:
613
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
709
+ * - SPARQL stores only raw links (source, predicate, target, author, timestamp)
614
710
  * - No SDNA knowledge at the database level
615
711
  * - Properties are resolved via subqueries that look for links with specific predicates
616
712
  * - Relations are similar but return multiple values instead of one
@@ -618,11 +714,11 @@ export class Ad4mModel {
618
714
  *
619
715
  * @param perspective - The perspective to query (used for metadata extraction)
620
716
  * @param query - Query parameters (where, order, limit, offset, properties, relations)
621
- * @returns Complete SurrealQL query string ready for execution
717
+ * @returns Complete SPARQL query string ready for execution
622
718
  *
623
719
  * @example
624
720
  * ```typescript
625
- * const query = Recipe.queryToSurrealQL(perspective, {
721
+ * const query = Recipe.queryToSPARQL(perspective, {
626
722
  * where: { name: "Pasta", rating: { gt: 4 } },
627
723
  * order: { timestamp: "DESC" },
628
724
  * limit: 10
@@ -631,243 +727,194 @@ export class Ad4mModel {
631
727
  * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
632
728
  * ```
633
729
  */
634
- static async queryToSurrealQL(perspective, query) {
730
+ static async queryToSPARQL(perspective, query) {
635
731
  const metadata = this.getModelMetadata();
636
732
  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 };
733
+ return buildSPARQLQuery(metadata, allRelMeta, query, this);
680
734
  }
681
735
  /**
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
- *
736
+ * Build the JSON parameters needed for a model query/subscription endpoint.
737
+ * Returns the className and queryJson that the Rust executor expects.
738
+ * Shape resolution happens server-side from the perspective's SHACL triples.
689
739
  * @internal
690
740
  */
691
- static async instancesFromSurrealResult(perspective, query, result) {
692
- if (!result || result.length === 0)
693
- return { results: [], totalCount: 0 };
741
+ static prepareModelQueryParams(query = {}, classNameOverride) {
694
742
  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;
743
+ const className = classNameOverride || metadata.className;
744
+ // Expand includeAll: true to a full IncludeMap covering every forward relation.
745
+ if (query.includeAll) {
746
+ const allRelMeta = getRelationsMetadata(this);
747
+ const expanded = {};
748
+ for (const [relName, relMeta] of Object.entries(allRelMeta)) {
749
+ if (relMeta.direction !== 'reverse') {
750
+ expanded[relName] = true;
709
751
  }
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];
752
+ }
753
+ query = { ...query, include: { ...expanded, ...query.include } };
754
+ }
755
+ const queryInput = {};
756
+ if (query.parent) {
757
+ const parentPredicate = resolveParentPredicate(query.parent, this);
758
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
759
+ }
760
+ if (query.properties)
761
+ queryInput.properties = query.properties;
762
+ if (query.include) {
763
+ // Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
764
+ // All other keys (boolean | RelationSubQuery) → queryInput.include
765
+ const normalIncludes = {};
766
+ const projections = {};
767
+ for (const [key, val] of Object.entries(query.include)) {
768
+ if (key.startsWith('$')) {
769
+ projections[key] = val;
770
+ }
771
+ else {
772
+ normalIncludes[key] = val;
773
+ }
774
+ }
775
+ if (Object.keys(normalIncludes).length > 0)
776
+ queryInput.include = normalIncludes;
777
+ if (Object.keys(projections).length > 0) {
778
+ // Tag each projection with its target class name so the executor can
779
+ // resolve the target shape through its in-memory cache when applying
780
+ // projection where-clause filters.
781
+ const allRelMeta = getRelationsMetadata(this);
782
+ for (const [, proj] of Object.entries(projections)) {
783
+ const relMeta = allRelMeta[proj.from];
784
+ if (!proj.targetClassName && relMeta?.target) {
785
+ try {
786
+ const TargetClass = relMeta.target();
787
+ const targetMeta = TargetClass.getModelMetadata?.();
788
+ if (targetMeta?.className) {
789
+ proj.targetClassName = targetMeta.className;
790
+ }
726
791
  }
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];
792
+ catch (e) {
793
+ console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e);
732
794
  }
733
795
  }
734
796
  }
735
- instances.push(instance);
736
- }
737
- catch (error) {
738
- console.error(`Failed to process SurrealDB instance ${base}:`, error);
797
+ queryInput.projections = projections;
739
798
  }
740
799
  }
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
- }
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;
789
- }
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;
800
+ if (query.where)
801
+ queryInput.where = query.where;
802
+ if (query.order) {
803
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
804
+ }
805
+ if (query.offset !== undefined)
806
+ queryInput.offset = query.offset;
807
+ if (query.limit !== undefined)
808
+ queryInput.limit = query.limit;
809
+ if (query.count !== undefined)
810
+ queryInput.count = query.count;
811
+ queryInput.deepQuery = query.deepQuery ?? true;
812
+ // Conformance getters, where filters, and target shapes for includes
813
+ // are all resolved by the executor from the perspective's SHACL triples
814
+ // — no client-side pre-computation is needed any more.
815
+ return {
816
+ className,
817
+ queryJson: JSON.stringify(queryInput),
818
+ metadata,
819
+ };
820
+ }
821
+ /**
822
+ * Parse raw model query/subscription result JSON into typed model instances.
823
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
824
+ * @internal
825
+ */
826
+ static parseModelResult(perspective, raw, include, properties) {
827
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
828
+ const arr = data.instances || data;
829
+ if (!Array.isArray(arr))
830
+ return [];
831
+ return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
832
+ }
833
+ /**
834
+ * Resolve non-literal (file-language) properties on an array of already-constructed
835
+ * model instances. Handles two cases:
836
+ *
837
+ * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
838
+ * 2. The Rust executor already resolved the expression and returned a `FileData` object
839
+ * (happens when the perspective backend eagerly fetches file content) → apply transform
840
+ * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
841
+ * synthesised model classes).
842
+ *
843
+ * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
844
+ * duplicating logic or introducing a circular dependency.
845
+ * @internal
846
+ */
847
+ static async resolveNonLiteralProps(perspective, instances) {
848
+ const propsMeta = getPropertiesMetadata(this);
849
+ const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
850
+ opts.resolveLanguage !== 'literal');
851
+ if (resolveProps.length === 0)
852
+ return;
853
+ await Promise.all(instances.map(async (inst) => {
854
+ for (const [propName, opts] of resolveProps) {
855
+ const val = inst[propName];
856
+ const transform = opts.transform;
857
+ const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
858
+ if (typeof val === 'string' && val && !val.startsWith('literal:')) {
859
+ // Case 1: raw URI — fetch from language runtime
860
+ try {
861
+ const expression = await perspective.getExpression(val);
862
+ if (expression) {
863
+ let resolved;
864
+ try {
865
+ resolved = JSON.parse(expression.data);
866
+ }
867
+ catch {
868
+ resolved = expression.data;
801
869
  }
870
+ inst[propName] = applyTransform(resolved);
802
871
  }
803
872
  }
804
- }
805
- return true;
806
- });
807
- }
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));
836
- }
837
- if (comparison !== 0) {
838
- return orderDirection === 'DESC' ? -comparison : comparison;
873
+ catch (e) {
874
+ console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);
839
875
  }
840
- // comparison === 0: continue to next sort field
841
876
  }
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);
877
+ else if (val !== null && val !== undefined && typeof val === 'object') {
878
+ // Case 2: already resolved by Rust — apply transform / default decode
879
+ inst[propName] = applyTransform(val);
880
+ }
881
+ }
882
+ }));
883
+ }
884
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
885
+ /**
886
+ * Execute a model query via the executor-side endpoint.
887
+ *
888
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
889
+ * with a single RPC to the executor that handles everything in Rust.
890
+ *
891
+ * @internal
892
+ */
893
+ static async executeModelQuery(perspective, query = {}, classNameOverride) {
894
+ // Delegate query input building to the shared prepareModelQueryParams
895
+ // helper. The executor resolves the shape from SHACL server-side.
896
+ const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
897
+ const result = await perspective.modelQuery(className, queryJson);
898
+ // Convert JSON instances to model class instances, recursively constructing
899
+ // class instances for any included relations resolved by Rust.
900
+ const instances = result.instances.map((json) => {
901
+ return jsonToModelInstance(this, perspective, json, query.include, query.properties);
902
+ });
903
+ // Resolve non-literal expressions (e.g. file languages where the stored
904
+ // value is a content-addressed hash that must be fetched from the language
905
+ // runtime). The Rust endpoint may return either a raw target URI (string)
906
+ // or an already-resolved FileData object — both cases are handled here.
907
+ await this.resolveNonLiteralProps(perspective, instances);
908
+ // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
909
+ const snapshotRelations = query.include
910
+ ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
911
+ : undefined;
912
+ for (const inst of instances) {
913
+ inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
867
914
  }
868
915
  return {
869
- results: paginatedInstances,
870
- totalCount
916
+ results: instances,
917
+ totalCount: result.totalCount,
871
918
  };
872
919
  }
873
920
  /**
@@ -875,15 +922,14 @@ export class Ad4mModel {
875
922
  *
876
923
  * @param perspective - The perspective to search in
877
924
  * @param query - Optional query parameters to filter results
878
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
925
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
926
+ * All queries now use the Rust SPARQL pipeline.
879
927
  * @returns Array of matching models
880
928
  *
881
929
  * @example
882
930
  * ```typescript
883
- * // Get all recipes (uses SurrealDB by default)
884
931
  * const allRecipes = await Recipe.findAll(perspective);
885
932
  *
886
- * // Get recipes with specific criteria (uses SurrealDB)
887
933
  * const recipes = await Recipe.findAll(perspective, {
888
934
  * where: {
889
935
  * name: "Pasta",
@@ -892,27 +938,15 @@ export class Ad4mModel {
892
938
  * order: { createdAt: "DESC" },
893
939
  * limit: 10
894
940
  * });
895
- *
896
- * // Explicitly use Prolog (legacy, for backward compatibility)
897
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
898
941
  * ```
899
942
  */
900
- static async findAll(perspective, query = {}, useSurrealDB = true) {
901
- if (query.properties && query.properties.length === 0) {
943
+ static async findAll(perspective, query) {
944
+ const q = (query ?? {});
945
+ if (q.properties && q.properties.length === 0) {
902
946
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
903
947
  }
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
- }
948
+ const { results } = await this.executeModelQuery(perspective, q);
949
+ return results;
916
950
  }
917
951
  /**
918
952
  * Finds the first instance matching the query, or `null` if none exists.
@@ -921,7 +955,7 @@ export class Ad4mModel {
921
955
  *
922
956
  * @param perspective - The perspective to search in
923
957
  * @param query - Optional query parameters to filter results
924
- * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
958
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
925
959
  * @returns The first matching instance, or `null`
926
960
  *
927
961
  * @example
@@ -934,9 +968,9 @@ export class Ad4mModel {
934
968
  * }
935
969
  * ```
936
970
  */
937
- static async findOne(perspective, query = {}, useSurrealDB = true) {
938
- const limitedQuery = { ...query, limit: 1 };
939
- const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
971
+ static async findOne(perspective, query) {
972
+ const limitedQuery = { ...(query ?? {}), limit: 1 };
973
+ const results = await this.findAll(perspective, limitedQuery);
940
974
  return results[0] ?? null;
941
975
  }
942
976
  /**
@@ -944,7 +978,7 @@ export class Ad4mModel {
944
978
  *
945
979
  * @param perspective - The perspective to search in
946
980
  * @param query - Optional query parameters to filter results
947
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
981
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
948
982
  * @returns Object containing results array and total count
949
983
  *
950
984
  * @example
@@ -954,22 +988,11 @@ export class Ad4mModel {
954
988
  * limit: 10
955
989
  * });
956
990
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
957
- *
958
- * // Use Prolog explicitly (legacy)
959
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
960
991
  * ```
961
992
  */
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
- }
993
+ static async findAllAndCount(perspective, query) {
994
+ const out = await this.executeModelQuery(perspective, (query ?? {}));
995
+ return out;
973
996
  }
974
997
  /**
975
998
  * Helper function for pagination with explicit page size and number.
@@ -978,7 +1001,6 @@ export class Ad4mModel {
978
1001
  * @param pageSize - Number of items per page
979
1002
  * @param pageNumber - Which page to retrieve (1-based)
980
1003
  * @param query - Optional additional query parameters
981
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
982
1004
  * @returns Paginated results with metadata
983
1005
  *
984
1006
  * @example
@@ -987,67 +1009,28 @@ export class Ad4mModel {
987
1009
  * where: { category: "Main Course" }
988
1010
  * });
989
1011
  * 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
1012
  * ```
994
1013
  */
995
- static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
996
- 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;
1014
+ static async paginate(perspective, pageSize, pageNumber, query) {
1015
+ const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1016
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1017
+ return { results: results, totalCount, pageSize, pageNumber };
1027
1018
  }
1028
1019
  /**
1029
- * Generates a SurrealQL COUNT query for the model.
1020
+ * Generates a SPARQL COUNT query for the model.
1030
1021
  *
1031
1022
  * @param perspective - The perspective context
1032
1023
  * @param query - Query parameters to filter the count
1033
- * @returns SurrealQL COUNT query string
1024
+ * @returns SPARQL COUNT query string
1034
1025
  *
1035
1026
  * @private
1036
1027
  */
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
- }
1028
+ // countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
1045
1029
  /**
1046
1030
  * Gets a count of all matching instances.
1047
1031
  *
1048
1032
  * @param perspective - The perspective to search in
1049
1033
  * @param query - Optional query parameters to filter results
1050
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1051
1034
  * @returns Total count of matching entities
1052
1035
  *
1053
1036
  * @example
@@ -1056,25 +1039,11 @@ export class Ad4mModel {
1056
1039
  * const activeRecipes = await Recipe.count(perspective, {
1057
1040
  * where: { status: "active" }
1058
1041
  * });
1059
- *
1060
- * // Use Prolog explicitly (legacy)
1061
- * const countProlog = await Recipe.count(perspective, {}, false);
1062
1042
  * ```
1063
1043
  */
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
- }
1044
+ static async count(perspective, query) {
1045
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
1046
+ return totalCount;
1078
1047
  }
1079
1048
  async setProperty(key, value, batchId) {
1080
1049
  const metadata = this.getPropertyMetadata(key);
@@ -1086,7 +1055,7 @@ export class Ad4mModel {
1086
1055
  const actions = this.generatePropertySetterAction(key, metadata);
1087
1056
  // Get resolve language from metadata (replaces Prolog query)
1088
1057
  let resolveLanguage = metadata.resolveLanguage;
1089
- // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
1058
+ // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
1090
1059
  if (value === undefined || value === null || value === "") {
1091
1060
  return;
1092
1061
  }
@@ -1357,6 +1326,73 @@ export class Ad4mModel {
1357
1326
  }
1358
1327
  }
1359
1328
  }
1329
+ /**
1330
+ * Evaluate SPARQL getters for a batch of instances on demand.
1331
+ *
1332
+ * Since deepQuery defaults to true, property getters are evaluated
1333
+ * automatically during collection queries. Use this method when
1334
+ * deepQuery was explicitly set to false and you want to lazily
1335
+ * resolve getter-backed properties for a subset of instances.
1336
+ *
1337
+ * @param instances - Array of model instances to evaluate getters on
1338
+ * @param perspective - The perspective to query against
1339
+ * @param propertyNames - Optional list of getter-backed property names to evaluate.
1340
+ * If omitted, all getters are evaluated.
1341
+ *
1342
+ * @example
1343
+ * ```typescript
1344
+ * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
1345
+ * // messages[i].replyingTo is undefined (getter skipped)
1346
+ *
1347
+ * // Evaluate getters for the visible subset
1348
+ * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
1349
+ * // messages[0..9].replyingTo is now populated
1350
+ * ```
1351
+ */
1352
+ static async evaluateGetters(instances, perspective, propertyNames) {
1353
+ if (instances.length === 0)
1354
+ return;
1355
+ const metadata = this.getModelMetadata();
1356
+ const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
1357
+ // The executor reads getter SPARQL from the perspective's SHACL triples
1358
+ // (written by `addSdna`), so no shape JSON is shipped with the call.
1359
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
1360
+ // Determine which property names were evaluated for snapshot sync
1361
+ const evaluatedPropertyNames = [];
1362
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1363
+ if (propMeta.getter) {
1364
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {
1365
+ evaluatedPropertyNames.push(propName);
1366
+ }
1367
+ }
1368
+ }
1369
+ // Also include relation getters
1370
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1371
+ if (relMeta.getter) {
1372
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
1373
+ evaluatedPropertyNames.push(relName);
1374
+ }
1375
+ }
1376
+ }
1377
+ // Apply results to instances and sync snapshots
1378
+ for (const instance of instances) {
1379
+ const id = instance.id || instance._baseExpression;
1380
+ const props = result[id];
1381
+ if (props) {
1382
+ for (const [key, value] of Object.entries(props)) {
1383
+ instance[key] = value;
1384
+ }
1385
+ }
1386
+ // Sync snapshot so isDirty() doesn't flag getter-only changes
1387
+ const modelInstance = instance;
1388
+ if (modelInstance._snapshot) {
1389
+ for (const propName of evaluatedPropertyNames) {
1390
+ const val = instance[propName];
1391
+ modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1360
1396
  /**
1361
1397
  * Gets the model instance with all properties and relations populated.
1362
1398
  *
@@ -1611,6 +1647,22 @@ export class Ad4mModel {
1611
1647
  static async register(perspective) {
1612
1648
  await perspective.ensureSDNASubjectClass(this);
1613
1649
  }
1650
+ /**
1651
+ * Batch-registers multiple model classes on a perspective in a single RPC call.
1652
+ * This is significantly faster than calling `register()` on each model individually
1653
+ * because it eliminates N-1 round-trips and mutex acquisitions.
1654
+ *
1655
+ * @param perspective - The perspective to register the models on
1656
+ * @param models - Array of Ad4mModel subclasses to register
1657
+ *
1658
+ * @example
1659
+ * ```typescript
1660
+ * await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);
1661
+ * ```
1662
+ */
1663
+ static async registerAll(perspective, models) {
1664
+ await perspective.ensureSubjectClasses(models);
1665
+ }
1614
1666
  /**
1615
1667
  * Executes a set of model operations inside a single batch (transaction).
1616
1668
  *
@@ -1668,7 +1720,7 @@ export class Ad4mModel {
1668
1720
  * ```
1669
1721
  */
1670
1722
  static query(perspective, query) {
1671
- return new ModelQueryBuilder(perspective, this, query);
1723
+ return new ModelQueryBuilder(perspective, this, (query ?? {}));
1672
1724
  }
1673
1725
  /**
1674
1726
  * Creates an Ad4mModel class from a JSON Schema definition.
@@ -1724,5 +1776,111 @@ export class Ad4mModel {
1724
1776
  static fromJSONSchema(schema, options) {
1725
1777
  return buildModelFromJSONSchema(this, schema, options);
1726
1778
  }
1779
+ /**
1780
+ * Creates a fully functional Ad4mModel subclass from a SHACL shape.
1781
+ *
1782
+ * Unlike `fromJSONSchema()`, no predicate inference is required —
1783
+ * `SHACLShape` already contains the exact predicate URI in `path` for
1784
+ * every property. The method reads each property's `path`, `maxCount`,
1785
+ * `writable`, and `resolveLanguage` directly and writes them to the
1786
+ * WeakMap metadata registries.
1787
+ *
1788
+ * Properties with `hasValue` (flag / type-discrimination markers) are
1789
+ * registered as hidden flag entries so that the SPARQL query builder emits
1790
+ * the fixed triple `?source <predicate> <value>` needed for type discrimination.
1791
+ * Properties without a `name` field are skipped.
1792
+ *
1793
+ * **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
1794
+ * was persisted on property shapes) carry the flag value only in
1795
+ * `shape.constructor_actions` as the `target` of an `addLink` action.
1796
+ * This method recovers those values so that old perspectives are queried
1797
+ * with the correct type-discriminator triple.
1798
+ *
1799
+ * @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
1800
+ * @param name - Class name to assign (e.g. "Channel")
1801
+ * @returns Generated Ad4mModel subclass, ready for querying
1802
+ */
1803
+ /**
1804
+ * Synthesise an `Ad4mModel` subclass from a SHACL shape.
1805
+ *
1806
+ * @param shape - The SHACL shape to synthesise from.
1807
+ * @param name - The model name (e.g. "Channel").
1808
+ * @param classResolver - Optional thunk factory. When provided, any collection
1809
+ * property that carries a `sh:class` URI will have its `target` wired up lazily:
1810
+ * `target: () => classResolver(localName)`. Because `target` is only called at
1811
+ * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
1812
+ * resolver just needs to return the correct class by the time a query runs —
1813
+ * making it safe to pass a closure over a registry object that is still being
1814
+ * populated (e.g. the `result` record inside `getModelClasses`).
1815
+ */
1816
+ static fromSHACL(shape, name, classResolver) {
1817
+ const DynamicModelClass = class extends this {
1818
+ };
1819
+ DynamicModelClass.className = name;
1820
+ DynamicModelClass.prototype.className = name;
1821
+ // Build a backward-compat fallback map: predicate → fixed-IRI-value from
1822
+ // constructor actions. Old SHACL stores (created before sh:hasValue was
1823
+ // persisted on the property shape) don't carry sh:hasValue on properties,
1824
+ // but the shape-level constructor_actions always contain an addLink action
1825
+ // with the fixed flag value as the target.
1826
+ const flagValueFromConstructor = new Map();
1827
+ for (const action of shape.constructor_actions ?? []) {
1828
+ if (action.action === 'addLink' &&
1829
+ typeof action.predicate === 'string' &&
1830
+ typeof action.target === 'string' &&
1831
+ action.target !== 'value' &&
1832
+ !action.target.startsWith('literal:')) {
1833
+ flagValueFromConstructor.set(action.predicate, action.target);
1834
+ }
1835
+ }
1836
+ for (const prop of shape.properties) {
1837
+ const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
1838
+ if (resolvedHasValue !== undefined) {
1839
+ const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
1840
+ setPropertyRegistryEntry(DynamicModelClass, flagKey, {
1841
+ through: prop.path,
1842
+ required: true,
1843
+ initial: resolvedHasValue,
1844
+ flag: true,
1845
+ writable: false,
1846
+ readOnly: true,
1847
+ });
1848
+ continue;
1849
+ }
1850
+ // Skip properties without a declared name
1851
+ if (!prop.name)
1852
+ continue;
1853
+ const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
1854
+ if (isCollection) {
1855
+ // Derive a lazy `target` thunk when a sh:class URI is present and a
1856
+ // classResolver was supplied. The thunk is evaluated at query time so
1857
+ // it is safe even if the target class hasn't been registered yet.
1858
+ let targetThunk;
1859
+ if (prop.class && classResolver) {
1860
+ const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
1861
+ const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
1862
+ targetThunk = () => classResolver(localName);
1863
+ }
1864
+ setRelationRegistryEntry(DynamicModelClass, prop.name, {
1865
+ predicate: prop.path,
1866
+ kind: 'hasMany',
1867
+ ...(targetThunk !== undefined && { target: targetThunk }),
1868
+ ...(prop.local !== undefined && { local: prop.local }),
1869
+ ...(prop.getter !== undefined && { getter: prop.getter }),
1870
+ });
1871
+ }
1872
+ else {
1873
+ setPropertyRegistryEntry(DynamicModelClass, prop.name, {
1874
+ through: prop.path,
1875
+ writable: prop.writable ?? true,
1876
+ ...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
1877
+ ...(prop.local !== undefined && { local: prop.local }),
1878
+ });
1879
+ }
1880
+ }
1881
+ const ModelDecorator = Model({ name });
1882
+ ModelDecorator(DynamicModelClass);
1883
+ return DynamicModelClass;
1884
+ }
1727
1885
  }
1728
1886
  Ad4mModel.classNamesByClass = new WeakMap();