@coasys/ad4m 0.13.0-test-3 → 0.13.0-test-5

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 (337) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +6717 -15519
  4. package/lib/index.js +4811 -13662
  5. package/lib/src/Ad4mClient.d.ts +7 -3
  6. package/lib/src/Ad4mClient.js +39 -13
  7. package/lib/src/agent/Agent.js +26 -272
  8. package/lib/src/agent/AgentClient.d.ts +10 -21
  9. package/lib/src/agent/AgentClient.js +75 -427
  10. package/lib/src/agent/AgentStatus.js +2 -37
  11. package/lib/src/ai/AIClient.d.ts +12 -4
  12. package/lib/src/ai/AIClient.js +81 -285
  13. package/lib/src/ai/AITypes.d.ts +55 -0
  14. package/lib/src/ai/AITypes.js +18 -0
  15. package/lib/src/ai/Tasks.js +10 -133
  16. package/lib/src/apiClient.d.ts +52 -0
  17. package/lib/src/apiClient.js +231 -0
  18. package/lib/src/expression/Expression.d.ts +1 -1
  19. package/lib/src/expression/Expression.js +13 -122
  20. package/lib/src/expression/ExpressionClient.d.ts +3 -3
  21. package/lib/src/expression/ExpressionClient.js +13 -76
  22. package/lib/src/expression/ExpressionRef.js +2 -25
  23. package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
  24. package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
  25. package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
  26. package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
  27. package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
  28. package/lib/src/generated/api/AddLinkRequest.js +1 -0
  29. package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
  30. package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
  31. package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
  32. package/lib/src/generated/api/AddSdnaRequest.js +2 -0
  33. package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
  34. package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
  35. package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
  36. package/lib/src/generated/api/AuthInfoInput.js +1 -0
  37. package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
  38. package/lib/src/generated/api/CapabilityInput.js +1 -0
  39. package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
  40. package/lib/src/generated/api/CommitBatchRequest.js +2 -0
  41. package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
  42. package/lib/src/generated/api/ComputeLogEntry.js +2 -0
  43. package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
  44. package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
  45. package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
  46. package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
  47. package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
  48. package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
  49. package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
  50. package/lib/src/generated/api/EmbedRequest.js +2 -0
  51. package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
  52. package/lib/src/generated/api/EntanglementProofInput.js +2 -0
  53. package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
  54. package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
  55. package/lib/src/generated/api/ExportRequest.d.ts +5 -0
  56. package/lib/src/generated/api/ExportRequest.js +2 -0
  57. package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
  58. package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
  59. package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
  60. package/lib/src/generated/api/ExpressionProof.js +2 -0
  61. package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
  62. package/lib/src/generated/api/ExpressionProofInput.js +2 -0
  63. package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
  64. package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
  65. package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
  66. package/lib/src/generated/api/FriendsListRequest.js +2 -0
  67. package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
  68. package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
  69. package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
  70. package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
  71. package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
  72. package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
  73. package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
  74. package/lib/src/generated/api/ImportAgentRequest.js +2 -0
  75. package/lib/src/generated/api/ImportRequest.d.ts +4 -0
  76. package/lib/src/generated/api/ImportRequest.js +2 -0
  77. package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
  78. package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
  79. package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
  80. package/lib/src/generated/api/LanguageMetaInput.js +2 -0
  81. package/lib/src/generated/api/Link.d.ts +5 -0
  82. package/lib/src/generated/api/Link.js +2 -0
  83. package/lib/src/generated/api/LinkExpression.d.ts +10 -0
  84. package/lib/src/generated/api/LinkExpression.js +1 -0
  85. package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
  86. package/lib/src/generated/api/LinkExpressionInput.js +1 -0
  87. package/lib/src/generated/api/LinkInput.d.ts +5 -0
  88. package/lib/src/generated/api/LinkInput.js +2 -0
  89. package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
  90. package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
  91. package/lib/src/generated/api/LinkMutations.d.ts +6 -0
  92. package/lib/src/generated/api/LinkMutations.js +1 -0
  93. package/lib/src/generated/api/LinkStatus.d.ts +1 -0
  94. package/lib/src/generated/api/LinkStatus.js +2 -0
  95. package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
  96. package/lib/src/generated/api/LockAgentRequest.js +2 -0
  97. package/lib/src/generated/api/ModelType.d.ts +1 -0
  98. package/lib/src/generated/api/ModelType.js +2 -0
  99. package/lib/src/generated/api/NotificationInput.d.ts +10 -0
  100. package/lib/src/generated/api/NotificationInput.js +2 -0
  101. package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
  102. package/lib/src/generated/api/OpenLinkRequest.js +2 -0
  103. package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
  104. package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
  105. package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
  106. package/lib/src/generated/api/PerspectiveInput.js +1 -0
  107. package/lib/src/generated/api/PromptRequest.d.ts +4 -0
  108. package/lib/src/generated/api/PromptRequest.js +2 -0
  109. package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
  110. package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
  111. package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
  112. package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
  113. package/lib/src/generated/api/QueryRequest.d.ts +7 -0
  114. package/lib/src/generated/api/QueryRequest.js +2 -0
  115. package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
  116. package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
  117. package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
  118. package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
  119. package/lib/src/generated/api/ResourceInput.d.ts +4 -0
  120. package/lib/src/generated/api/ResourceInput.js +2 -0
  121. package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
  122. package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
  123. package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
  124. package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
  125. package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
  126. package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
  127. package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
  128. package/lib/src/generated/api/SetStatusRequest.js +2 -0
  129. package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
  130. package/lib/src/generated/api/SignMessageRequest.js +2 -0
  131. package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
  132. package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
  133. package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
  134. package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
  135. package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
  136. package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
  137. package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
  138. package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
  139. package/lib/src/generated/api/UserStatistics.d.ts +9 -0
  140. package/lib/src/generated/api/UserStatistics.js +2 -0
  141. package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
  142. package/lib/src/generated/api/VerificationRequestResult.js +2 -0
  143. package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
  144. package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
  145. package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
  146. package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
  147. package/lib/src/generated/api/index.d.ts +42 -0
  148. package/lib/src/generated/api/index.js +7 -0
  149. package/lib/src/index.d.ts +6 -1
  150. package/lib/src/index.js +6 -1
  151. package/lib/src/jestSetup.d.ts +0 -1
  152. package/lib/src/jestSetup.js +1 -1
  153. package/lib/src/language/Icon.js +2 -21
  154. package/lib/src/language/Language.d.ts +1 -1
  155. package/lib/src/language/Language.js +10 -76
  156. package/lib/src/language/LanguageClient.d.ts +2 -2
  157. package/lib/src/language/LanguageClient.js +15 -105
  158. package/lib/src/language/LanguageHandle.js +2 -41
  159. package/lib/src/language/LanguageMeta.js +4 -75
  160. package/lib/src/language/LanguageRef.js +2 -25
  161. package/lib/src/links/Links.js +14 -111
  162. package/lib/src/model/Ad4mModel.d.ts +76 -44
  163. package/lib/src/model/Ad4mModel.js +635 -479
  164. package/lib/src/model/Ad4mModel.test.js +371 -815
  165. package/lib/src/model/ModelQueryBuilder.d.ts +15 -27
  166. package/lib/src/model/ModelQueryBuilder.js +163 -224
  167. package/lib/src/model/decorators.d.ts +22 -0
  168. package/lib/src/model/decorators.js +7 -0
  169. package/lib/src/model/hydration.d.ts +3 -93
  170. package/lib/src/model/hydration.js +3 -970
  171. package/lib/src/model/index.d.ts +0 -4
  172. package/lib/src/model/index.js +0 -4
  173. package/lib/src/model/model-manifest.d.ts +41 -0
  174. package/lib/src/model/model-manifest.js +11 -0
  175. package/lib/src/model/query-sparql.d.ts +4 -67
  176. package/lib/src/model/query-sparql.js +26 -322
  177. package/lib/src/model/query-sparql.test.js +35 -218
  178. package/lib/src/model/query-utils.d.ts +1 -0
  179. package/lib/src/model/query-utils.js +46 -1
  180. package/lib/src/model/shacl-gen.js +4 -0
  181. package/lib/src/model/types.d.ts +51 -43
  182. package/lib/src/model/types.js +4 -1
  183. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  184. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  185. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  186. package/lib/src/perspectives/LinkQuery.js +2 -42
  187. package/lib/src/perspectives/Perspective.d.ts +1 -1
  188. package/lib/src/perspectives/Perspective.js +10 -52
  189. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -17
  190. package/lib/src/perspectives/PerspectiveClient.js +179 -429
  191. package/lib/src/perspectives/PerspectiveClient.test.js +55 -0
  192. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  193. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  194. package/lib/src/perspectives/PerspectiveProxy.d.ts +106 -71
  195. package/lib/src/perspectives/PerspectiveProxy.js +289 -310
  196. package/lib/src/runtime/RuntimeClient.d.ts +6 -6
  197. package/lib/src/runtime/RuntimeClient.js +93 -467
  198. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  199. package/lib/src/runtime/RuntimeTypes.js +45 -0
  200. package/lib/src/shacl/SHACLShape.d.ts +7 -0
  201. package/lib/src/shacl/SHACLShape.js +19 -0
  202. package/lib/src/shacl/SHACLShape.test.js +82 -0
  203. package/lib/src/typeDefs.js +3 -628
  204. package/package.json +6 -18
  205. package/rollup.config.js +0 -7
  206. package/src/Ad4mClient.test.ts +1179 -1340
  207. package/src/Ad4mClient.ts +40 -15
  208. package/src/agent/Agent.ts +0 -99
  209. package/src/agent/AgentClient.ts +112 -526
  210. package/src/agent/AgentStatus.ts +0 -12
  211. package/src/ai/AIClient.ts +96 -296
  212. package/src/ai/AITypes.ts +66 -0
  213. package/src/ai/Tasks.ts +0 -52
  214. package/src/apiClient.ts +283 -0
  215. package/src/expression/Expression.ts +3 -43
  216. package/src/expression/ExpressionClient.ts +14 -77
  217. package/src/expression/ExpressionRef.ts +0 -6
  218. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  219. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  220. package/src/generated/api/AddLinkRequest.ts +4 -0
  221. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  222. package/src/generated/api/AddSdnaRequest.ts +3 -0
  223. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  224. package/src/generated/api/AuthInfoInput.ts +4 -0
  225. package/src/generated/api/CapabilityInput.ts +4 -0
  226. package/src/generated/api/CommitBatchRequest.ts +3 -0
  227. package/src/generated/api/ComputeLogEntry.ts +3 -0
  228. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  229. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  230. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  231. package/src/generated/api/EmbedRequest.ts +3 -0
  232. package/src/generated/api/EntanglementProofInput.ts +3 -0
  233. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  234. package/src/generated/api/ExportRequest.ts +3 -0
  235. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  236. package/src/generated/api/ExpressionProof.ts +3 -0
  237. package/src/generated/api/ExpressionProofInput.ts +3 -0
  238. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  239. package/src/generated/api/FriendsListRequest.ts +3 -0
  240. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  241. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  242. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  243. package/src/generated/api/ImportAgentRequest.ts +3 -0
  244. package/src/generated/api/ImportRequest.ts +3 -0
  245. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  246. package/src/generated/api/LanguageMetaInput.ts +3 -0
  247. package/src/generated/api/Link.ts +3 -0
  248. package/src/generated/api/LinkExpression.ts +6 -0
  249. package/src/generated/api/LinkExpressionInput.ts +6 -0
  250. package/src/generated/api/LinkInput.ts +3 -0
  251. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  252. package/src/generated/api/LinkMutations.ts +5 -0
  253. package/src/generated/api/LinkStatus.ts +3 -0
  254. package/src/generated/api/LockAgentRequest.ts +3 -0
  255. package/src/generated/api/ModelType.ts +3 -0
  256. package/src/generated/api/NotificationInput.ts +3 -0
  257. package/src/generated/api/OpenLinkRequest.ts +3 -0
  258. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  259. package/src/generated/api/PerspectiveInput.ts +4 -0
  260. package/src/generated/api/PromptRequest.ts +3 -0
  261. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  262. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  263. package/src/generated/api/QueryRequest.ts +6 -0
  264. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  265. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  266. package/src/generated/api/ResourceInput.ts +3 -0
  267. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  268. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  269. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  270. package/src/generated/api/SetStatusRequest.ts +3 -0
  271. package/src/generated/api/SignMessageRequest.ts +3 -0
  272. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  273. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  274. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  275. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  276. package/src/generated/api/UserStatistics.ts +3 -0
  277. package/src/generated/api/VerificationRequestResult.ts +3 -0
  278. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  279. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  280. package/src/generated/api/index.ts +49 -0
  281. package/src/index.ts +6 -1
  282. package/src/jestSetup.ts +1 -1
  283. package/src/language/Icon.ts +0 -4
  284. package/src/language/Language.ts +2 -23
  285. package/src/language/LanguageClient.ts +21 -132
  286. package/src/language/LanguageHandle.ts +0 -14
  287. package/src/language/LanguageMeta.ts +0 -29
  288. package/src/language/LanguageRef.ts +0 -7
  289. package/src/links/Links.ts +0 -37
  290. package/src/model/Ad4mModel.test.ts +766 -1173
  291. package/src/model/Ad4mModel.ts +664 -529
  292. package/src/model/ModelQueryBuilder.ts +203 -251
  293. package/src/model/decorators.ts +29 -0
  294. package/src/model/hydration.ts +3 -1037
  295. package/src/model/index.ts +0 -4
  296. package/src/model/query-sparql.test.ts +34 -242
  297. package/src/model/query-sparql.ts +27 -337
  298. package/src/model/query-utils.ts +47 -2
  299. package/src/model/shacl-gen.ts +5 -0
  300. package/src/model/types.ts +55 -44
  301. package/src/neighbourhood/Neighbourhood.ts +0 -9
  302. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  303. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  304. package/src/perspectives/LinkQuery.ts +0 -15
  305. package/src/perspectives/Perspective.ts +1 -12
  306. package/src/perspectives/PerspectiveClient.test.ts +206 -148
  307. package/src/perspectives/PerspectiveClient.ts +247 -442
  308. package/src/perspectives/PerspectiveDiff.ts +0 -8
  309. package/src/perspectives/PerspectiveHandle.ts +1 -12
  310. package/src/perspectives/PerspectiveProxy.test.ts +41 -0
  311. package/src/perspectives/PerspectiveProxy.ts +331 -348
  312. package/src/runtime/RuntimeClient.ts +112 -474
  313. package/src/runtime/RuntimeTypes.ts +144 -0
  314. package/src/shacl/SHACLShape.test.ts +94 -0
  315. package/src/shacl/SHACLShape.ts +27 -0
  316. package/src/typeDefs.ts +3 -5
  317. package/tsconfig.json +3 -7
  318. package/shims/reflect-metadata.ts +0 -0
  319. package/shims/type-graphql.ts +0 -75
  320. package/src/PubSub.ts +0 -17
  321. package/src/agent/AgentResolver.ts +0 -263
  322. package/src/ai/AIResolver.ts +0 -372
  323. package/src/buildSchema.ts +0 -43
  324. package/src/expression/ExpressionResolver.ts +0 -64
  325. package/src/language/LanguageResolver.ts +0 -98
  326. package/src/model/Subject.ts +0 -159
  327. package/src/model/hydration-batch.ts +0 -205
  328. package/src/model/hydration-batching.test.ts +0 -563
  329. package/src/model/prolog-facts.ts +0 -145
  330. package/src/model/query-prolog.ts +0 -148
  331. package/src/model/query-sparql-batch.ts +0 -301
  332. package/src/model/subscription-delta.test.ts +0 -207
  333. package/src/model/subscription-pool.ts +0 -211
  334. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  335. package/src/perspectives/PerspectiveResolver.ts +0 -364
  336. package/src/runtime/RuntimeResolver.ts +0 -749
  337. package/src/unwrapApolloResult.ts +0 -16
@@ -3,30 +3,179 @@ import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
5
5
  import { makeRandomId } from "./util";
6
- import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
6
+ import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
7
7
  import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
8
- import { formatQueryValue } from "./query-utils";
8
+ import { formatQueryValue, compileWhereClause } from "./query-utils";
9
9
  import { resolveParentPredicate } from "./query-common";
10
- import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
11
10
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
11
+ import type { SHACLShape } from "../shacl/SHACLShape";
12
12
  import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
13
13
 
14
- import { buildSPARQLQuery, buildSPARQLGetDataQuery, groupSPARQLResults, buildSPARQLCountQuery, hasJsOnlyWhereFilters, parseSparqlCount } from "./query-sparql";
15
- import { buildBatchSPARQLQuery } from "./query-sparql-batch";
16
- import { hydrateBatchResult } from "./hydration-batch";
14
+ import { buildSPARQLQuery } from "./query-sparql";
17
15
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
18
16
  import {
19
- normalizeValue, matchesCondition, hydrateFromLinks,
20
- assignValuesToInstance as _assignValuesToInstance,
21
- evaluateCustomGettersForInstance,
22
- hydrateRelations,
17
+ normalizeValue,
23
18
  } from "./hydration";
24
19
  import type {
25
20
  ParentScope, IncludeMap, Query,
26
21
  GetOptions, AllInstancesResult, ResultsWithTotalCount,
27
- PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata, ValueTuple,
22
+ PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
23
+ IncludeProjection,
28
24
  } from "./types";
29
25
 
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Helpers for Rust-side include resolution
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /**
32
+ * Recursively enrich relation metadata in the shape with target class shapes
33
+ * so the Rust endpoint can resolve includes in-process (no extra GraphQL
34
+ * round-trips per relation).
35
+ */
36
+ function enrichShapeForIncludes(
37
+ metadata: ModelMetadata,
38
+ include: IncludeMap,
39
+ allRelMeta: Record<string, RelationMetadataEntry>,
40
+ ): void {
41
+ for (const [relName, includeVal] of Object.entries(include)) {
42
+ if (!includeVal) continue;
43
+ const meta = allRelMeta[relName];
44
+ if (!meta?.target) continue;
45
+
46
+ const TargetClass = meta.target() as typeof Ad4mModel;
47
+ // Deep-copy so we don't mutate the cached metadata
48
+ const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
49
+
50
+ // Ensure the relation is in metadata.relations (fallback for edge cases)
51
+ if (!metadata.relations[relName]) {
52
+ metadata.relations[relName] = {
53
+ name: relName,
54
+ predicate: meta.predicate,
55
+ direction:
56
+ meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
57
+ ? 'reverse'
58
+ : 'forward',
59
+ };
60
+ }
61
+ const rel = metadata.relations[relName] as any;
62
+ rel.kind = meta.kind;
63
+ rel.maxCount = meta.maxCount;
64
+ rel.targetShape = targetMeta;
65
+ rel.targetClassName = targetMeta.className;
66
+
67
+ // Recurse for nested includes
68
+ const nested =
69
+ typeof includeVal === 'object' && includeVal !== null
70
+ ? (includeVal as any).include
71
+ : undefined;
72
+ if (nested) {
73
+ const targetRelMeta = getRelationsMetadata(TargetClass as any);
74
+ enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
75
+ }
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Construct a model class instance from a plain JSON object returned by the
81
+ * Rust endpoint. Recursively converts included relation values (which come
82
+ * back as plain JSON objects) into proper model class instances.
83
+ */
84
+ function jsonToModelInstance<T extends Ad4mModel>(
85
+ ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
86
+ perspective: PerspectiveProxy,
87
+ json: any,
88
+ include?: IncludeMap,
89
+ properties?: string[],
90
+ ): T {
91
+ const instance = new ModelClass(perspective, json.id || json.baseExpression) as any;
92
+
93
+ // When a properties projection is active, remove own properties set by the
94
+ // constructor that are not in the projected JSON. This ensures assertions
95
+ // like `expect(r).to.not.have.own.property("body")` pass.
96
+ if (properties) {
97
+ const jsonKeys = new Set(Object.keys(json));
98
+ for (const key of Object.getOwnPropertyNames(instance)) {
99
+ // Keep internal fields (backing store for getters), id, baseExpression, perspective
100
+ if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_')) continue;
101
+ if (!jsonKeys.has(key)) {
102
+ delete instance[key];
103
+ }
104
+ }
105
+ }
106
+
107
+ for (const [key, value] of Object.entries(json)) {
108
+ if (key === 'baseExpression' || key === 'id') continue;
109
+
110
+ // Skip getter-only properties anywhere in the prototype chain
111
+ let isReadonly = false;
112
+ let proto = Object.getPrototypeOf(instance);
113
+ while (proto) {
114
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
115
+ if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
116
+ proto = Object.getPrototypeOf(proto);
117
+ }
118
+ if (isReadonly) continue;
119
+
120
+ // Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
121
+ if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
122
+ instance[key] = new Date(value).getTime();
123
+ continue;
124
+ }
125
+
126
+ instance[key] = value;
127
+ }
128
+
129
+ // Apply property transform functions from decorators (only for literal-resolved
130
+ // or no-resolveLanguage properties; non-literal properties are resolved + transformed
131
+ // asynchronously in executeModelQuery).
132
+ try {
133
+ const propsMeta = getPropertiesMetadata(ModelClass as any);
134
+ for (const [propName, opts] of Object.entries(propsMeta)) {
135
+ const o = opts as any;
136
+ if (typeof o.transform !== 'function' || !(propName in json)) continue;
137
+ // Skip non-literal resolveLanguage props — they need async expression resolution first
138
+ if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
139
+ instance[propName] = o.transform(instance[propName]);
140
+ }
141
+ } catch (_) { /* no metadata available */ }
142
+
143
+ // Recursively convert included relation values to class instances
144
+ if (include) {
145
+ const relMeta = getRelationsMetadata(ModelClass as any);
146
+ for (const [relName, includeVal] of Object.entries(include)) {
147
+ if (!includeVal) continue;
148
+ const meta = relMeta[relName];
149
+ if (!meta?.target) continue;
150
+ const TargetClass = meta.target() as any;
151
+ const nestedInclude =
152
+ typeof includeVal === 'object' && includeVal !== null
153
+ ? (includeVal as any).include
154
+ : undefined;
155
+ const nestedProperties =
156
+ typeof includeVal === 'object' && includeVal !== null
157
+ ? (includeVal as any).properties
158
+ : undefined;
159
+
160
+ const raw = instance[relName];
161
+ if (Array.isArray(raw)) {
162
+ instance[relName] = raw.map((item: any) => {
163
+ if (typeof item === 'object' && item !== null && item.id) {
164
+ return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
165
+ }
166
+ return item;
167
+ });
168
+ } else if (typeof raw === 'object' && raw !== null && raw.id) {
169
+ instance[relName] = jsonToModelInstance(
170
+ TargetClass, perspective, raw, nestedInclude, nestedProperties,
171
+ );
172
+ }
173
+ }
174
+ }
175
+
176
+ return instance;
177
+ }
178
+
30
179
  /**
31
180
  * Base class for defining data models in AD4M.
32
181
  *
@@ -131,6 +280,14 @@ export class Ad4mModel {
131
280
  createdAt: any;
132
281
  updatedAt: any;
133
282
 
283
+ /**
284
+ * Backwards compatibility alias for createdAt.
285
+ * @deprecated Use createdAt instead. This will be removed in a future version.
286
+ */
287
+ get timestamp(): any {
288
+ return (this as any).createdAt;
289
+ }
290
+
134
291
  private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
135
292
 
136
293
  /**
@@ -177,14 +334,6 @@ export class Ad4mModel {
177
334
  return classCache[perspectiveID];
178
335
  }
179
336
 
180
- /**
181
- * Backwards compatibility alias for createdAt.
182
- * @deprecated Use createdAt instead. This will be removed in a future version.
183
- */
184
- get timestamp(): any {
185
- return (this as any).createdAt;
186
- }
187
-
188
337
  /**
189
338
  * Extracts metadata from decorators for query building.
190
339
  *
@@ -261,9 +410,7 @@ export class Ad4mModel {
261
410
  // Extract relations (relations) from WeakMap registry
262
411
  const relationsMetadata: Record<string, RelationMetadata> = {};
263
412
  const allRelationsMeta = getRelationsMetadata(this as any);
264
- const prototypeRelations = Object.fromEntries(
265
- Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
266
- );
413
+ const prototypeRelations = allRelationsMeta;
267
414
 
268
415
  for (const [relationName, opts] of Object.entries(prototypeRelations)) {
269
416
  const options = opts as RelationMetadataEntry;
@@ -273,6 +420,8 @@ export class Ad4mModel {
273
420
  ...(options.local !== undefined && { local: options.local }),
274
421
  ...(options.getter !== undefined && { getter: options.getter }),
275
422
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
423
+ ...(options.kind !== undefined && { kind: options.kind }),
424
+ ...(options.maxCount !== undefined && { maxCount: options.maxCount }),
276
425
  ...(options.target !== undefined && { target: options.target }),
277
426
  ...(options.filter !== undefined && { filter: options.filter }),
278
427
  ...(options.where !== undefined && { where: options.where }),
@@ -359,13 +508,6 @@ export class Ad4mModel {
359
508
  return this._baseExpression;
360
509
  }
361
510
 
362
- /**
363
- * @deprecated Use `.id` instead. Will be removed in a future version.
364
- */
365
- get baseExpression(): string {
366
- return this._baseExpression;
367
- }
368
-
369
511
  /**
370
512
  * Protected getter for the perspective.
371
513
  * Allows subclasses to access the perspective while keeping it private from external code.
@@ -462,14 +604,6 @@ export class Ad4mModel {
462
604
  }];
463
605
  }
464
606
 
465
- /**
466
- * Assigns decoded Prolog property values to an instance.
467
- * Delegates to the standalone function in hydration.ts.
468
- */
469
- public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
470
- return _assignValuesToInstance(perspective, instance, values);
471
- }
472
-
473
607
  // ──────────────────────────────────────────────────────────
474
608
  // Snapshot / dirty tracking
475
609
  // ──────────────────────────────────────────────────────────
@@ -603,89 +737,51 @@ export class Ad4mModel {
603
737
  }
604
738
 
605
739
  private async getData(opts?: GetOptions) {
606
- // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
607
- // Use SPARQL for data queries
740
+ // Route through the Rust model query endpoint — same pipeline as executeModelQuery
741
+ // but for a single instance by ID.
608
742
  try {
609
743
  const ctor = this.constructor as typeof Ad4mModel;
610
- const metadata = ctor.getModelMetadata();
611
-
612
- // Query for all links from this specific node (base expression)
613
- const linksQuery = buildSPARQLGetDataQuery(this._baseExpression);
614
- const links = await this._perspective.querySparql(linksQuery);
744
+ const query: Query = {
745
+ where: { id: this._baseExpression },
746
+ limit: 1,
747
+ deepQuery: true, // Single-instance get() always evaluates property getters
748
+ };
749
+ if (opts?.properties) query.properties = opts.properties;
750
+ if (opts?.include) query.include = opts.include;
615
751
 
616
- if (links && links.length > 0) {
617
- // Core hydration: properties (latest-wins), relations, timestamps/author
618
- const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
619
- await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
620
- }
752
+ const { results } = await (ctor as any).executeModelQuery(
753
+ this._perspective, query, null
754
+ );
621
755
 
622
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
623
- const allRelsMeta = getRelationsMetadata(ctor as any);
624
- const requestedProps = opts?.properties && opts.properties.length > 0 ? new Set(opts.properties) : null;
625
- for (const [relName, relMeta] of Object.entries(allRelsMeta)) {
626
- if (relMeta.kind !== 'belongsToOne' && relMeta.kind !== 'belongsToMany') continue;
627
- if (requestedProps && !requestedProps.has(relName)) continue;
628
- const reverseLinks = await this._perspective.get(
629
- new LinkQuery({ predicate: relMeta.predicate, target: this._baseExpression })
630
- );
631
- const sourceIds = reverseLinks
632
- .filter((l) => l.data.target === this._baseExpression)
633
- .map((l) => l.data.source);
634
- if (relMeta.kind === 'belongsToOne') {
635
- (this as any)[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
636
- } else {
637
- (this as any)[relName] = sourceIds;
756
+ if (results.length > 0) {
757
+ const hydrated = results[0];
758
+ // Copy all hydrated values from the Rust-side result onto this instance
759
+ for (const [key, value] of Object.entries(hydrated as any)) {
760
+ if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot') continue;
761
+ if (key.startsWith('_')) continue;
762
+ // Check for readonly getters
763
+ let isReadonly = false;
764
+ let proto = Object.getPrototypeOf(this);
765
+ while (proto) {
766
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
767
+ if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
768
+ proto = Object.getPrototypeOf(proto);
769
+ }
770
+ if (isReadonly) continue;
771
+ (this as any)[key] = value;
638
772
  }
639
773
  }
640
774
 
641
- // Evaluate SPARQL getters
642
- const getterOpts = opts?.properties || opts?.include
643
- ? { requestedProperties: opts?.properties, include: opts?.include }
644
- : undefined;
645
- await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
646
-
647
- // Eager-load relations if requested
648
- if (opts?.include) {
649
- await hydrateRelations(ctor, [this], this._perspective, opts.include);
650
- }
775
+ // Property getters and relation conformance getters are now evaluated
776
+ // Rust-side via evaluate_getters() in model_query.rs.
651
777
  } catch (e) {
652
- console.error(`SPARQL getData also failed for ${this._baseExpression}:`, e);
778
+ console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
653
779
  }
654
780
 
655
- this.takeSnapshot();
781
+ this.takeSnapshot(opts?.include);
656
782
  return this;
657
783
  }
658
784
 
659
- public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
660
- const { properties, where, order, offset, limit, count } = query;
661
- const className = modelClassName || (await this.getClassName(perspective));
662
-
663
- // Resolve parent predicate from model metadata if needed
664
- const resolvedParentPredicate = query.parent
665
- ? resolveParentPredicate(query.parent, this)
666
- : undefined;
667
-
668
- const instanceQueries = [
669
- buildAuthorAndTimestampQuery(),
670
- buildParentQuery(query.parent, resolvedParentPredicate),
671
- buildPropertiesQuery(properties),
672
- buildWhereQuery(where),
673
- ];
674
-
675
- const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
676
-
677
- const fullQuery = `
678
- findall([Base, Properties, Collections, Timestamp, Author], (
679
- subject_class("${className}", SubjectClass),
680
- instance(SubjectClass, Base),
681
- ${instanceQueries.filter((q) => q).join(", ")}
682
- ), UnsortedInstances),
683
- ${resultSetQueries.filter((q) => q).join(", ")}
684
- `;
685
-
686
- return fullQuery;
687
- }
688
-
689
785
  /**
690
786
  * Generates a SPARQL query from a Query object.
691
787
  *
@@ -728,341 +824,329 @@ export class Ad4mModel {
728
824
  return buildSPARQLQuery(metadata, allRelMeta, query, this);
729
825
  }
730
826
 
731
- public static async instancesFromPrologResult<T extends Ad4mModel>(
732
- this: typeof Ad4mModel & (new (...args: any[]) => T),
733
- perspective: PerspectiveProxy,
734
- query: Query,
735
- result: AllInstancesResult
736
- ): Promise<ResultsWithTotalCount<T>> {
737
- if (!result?.[0]?.AllInstances) return { results: [], totalCount: 0 };
738
- // Map results to instances
739
- const requestedProperties = query?.properties || [];
740
- const allInstances = await Promise.all(
741
- result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
827
+ /**
828
+ * Build the JSON parameters needed for a model query/subscription endpoint.
829
+ * Returns the className, queryJson, and shapeJson that the Rust executor expects.
830
+ * @internal
831
+ */
832
+ static prepareModelQueryParams(
833
+ query: Query = {},
834
+ classNameOverride?: string | null,
835
+ ): { className: string; queryJson: string; shapeJson: string } {
836
+ const metadata = this.getModelMetadata();
837
+ const className = classNameOverride || metadata.className;
838
+
839
+ const queryInput: any = {};
840
+ if (query.parent) {
841
+ const parentPredicate = resolveParentPredicate(query.parent, this);
842
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
843
+ }
844
+ if (query.properties) queryInput.properties = query.properties;
845
+ if (query.include) queryInput.include = query.include;
846
+ if (query.where) queryInput.where = query.where;
847
+ if (query.order) {
848
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
849
+ }
850
+ if (query.offset !== undefined) queryInput.offset = query.offset;
851
+ if (query.limit !== undefined) queryInput.limit = query.limit;
852
+ if (query.count !== undefined) queryInput.count = query.count;
853
+ queryInput.deepQuery = query.deepQuery ?? true;
854
+
855
+ if (query.include) {
856
+ const allRelMeta = getRelationsMetadata(this as any);
857
+ enrichShapeForIncludes(metadata, query.include, allRelMeta);
858
+ }
859
+
860
+ // Pre-compute conformance getters (with where-clause support)
861
+ {
862
+ const allRelMeta = getRelationsMetadata(this as any);
863
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
864
+ const rel = relMeta as any;
865
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
866
+ const meta = allRelMeta[relName];
867
+ if (!meta?.target) continue;
742
868
  try {
743
- const instance = new this(perspective, Base) as any;
744
- // Remove unrequested attributes from instance
745
- if (requestedProperties.length) {
746
- Object.keys(instance).forEach((key) => {
747
- if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression') delete instance[key];
748
- });
869
+ const TargetClass = meta.target();
870
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
871
+
872
+ // Compile where clauses to SPARQL when all target properties use
873
+ // literal encoding (literal:string:X etc.) which is SPARQL-matchable.
874
+ // Properties with a non-literal resolveLanguage store expression hashes
875
+ // that can't be matched by value in SPARQL.
876
+ let whereConditions: string[] = [];
877
+ if (rel.where) {
878
+ try {
879
+ const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
880
+ let allSparqlFilterable = true;
881
+ if (targetMetadata) {
882
+ for (const propName of Object.keys(rel.where)) {
883
+ if (['id', 'author', 'timestamp'].includes(propName)) continue;
884
+ const propMeta = targetMetadata.properties[propName];
885
+ if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
886
+ allSparqlFilterable = false;
887
+ break;
888
+ }
889
+ }
890
+ }
891
+ if (allSparqlFilterable) {
892
+ whereConditions = compileWhereClause(rel.where, targetMetadata);
893
+ }
894
+ } catch (_) {}
749
895
  }
750
- // Collect values to assign to instance
751
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
752
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
753
-
754
- return instance;
755
- } catch (error) {
756
- console.error(`Failed to process instance ${Base}:`, error);
757
- // Return null for failed instances - we'll filter these out below
758
- return null;
759
- }
760
- })
761
- );
762
- const instances = allInstances.filter((instance) => instance !== null) as T[];
763
896
 
764
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
765
- if (query.include && instances.length > 0) {
766
- await hydrateRelations(this, instances, perspective, query.include);
897
+ if (filter) {
898
+ let getter = filter.getter;
899
+ if (whereConditions.length > 0) {
900
+ getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
901
+ }
902
+ rel.getter = getter;
903
+ } else if (whereConditions.length > 0) {
904
+ const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
905
+ rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
906
+ }
907
+ } catch (_) {}
908
+ }
767
909
  }
768
910
 
769
- // Take snapshots for dirty tracking after ALL hydration is complete
770
- // (including eager-loaded relations).
771
- // When `include` is specified, only snapshot those relations.
772
- // Otherwise snapshot ALL fields (properties + relations) since
773
- // hydrateFromLinks populates relations with stable raw IDs.
774
- const snapshotRelations = query.include;
775
- for (const inst of instances) {
776
- (inst as Ad4mModel).takeSnapshot(snapshotRelations);
777
- }
911
+ return {
912
+ className,
913
+ queryJson: JSON.stringify(queryInput),
914
+ shapeJson: JSON.stringify(metadata),
915
+ };
916
+ }
778
917
 
779
- return { results: instances, totalCount: result[0].TotalCount };
918
+ /**
919
+ * Parse raw model query/subscription result JSON into typed model instances.
920
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
921
+ * @internal
922
+ */
923
+ static parseModelResult<T extends Ad4mModel>(
924
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
925
+ perspective: PerspectiveProxy,
926
+ raw: any,
927
+ include?: IncludeMap,
928
+ properties?: string[],
929
+ ): T[] {
930
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
931
+ const arr = data.instances || data;
932
+ if (!Array.isArray(arr)) return [];
933
+ return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
780
934
  }
781
935
 
936
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
937
+
782
938
  /**
783
- * Converts SPARQL query results to Ad4mModel instances.
939
+ * Execute a model query via the executor-side endpoint.
784
940
  *
785
- * @param perspective - The perspective context
786
- * @param query - The query parameters used
787
- * @param result - Array of result objects from SPARQL
788
- * @returns Promise resolving to results with total count
941
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
942
+ * with a single RPC to the executor that handles everything in Rust.
789
943
  *
790
944
  * @internal
791
945
  */
792
- public static async instancesFromQueryResult<T extends Ad4mModel>(
793
- this: typeof Ad4mModel & (new (...args: any[]) => T),
946
+ private static async executeModelQuery<T extends Ad4mModel>(
947
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
794
948
  perspective: PerspectiveProxy,
795
- query: Query,
796
- result: any[],
797
- computeTotalCount: boolean = false
949
+ query: Query = {},
950
+ classNameOverride?: string | null,
798
951
  ): Promise<ResultsWithTotalCount<T>> {
799
- if (!result || result.length === 0) return { results: [], totalCount: 0 };
800
-
801
952
  const metadata = this.getModelMetadata();
802
- const requestedProperties = query?.properties || [];
803
-
804
- // The query used GROUP BY with graph traversal, so each row has:
805
- // - source: the node ID (e.g., "node:abc123")
806
- // - source_uri: the actual URI (the base expression)
807
- // - links: array of link objects with {predicate, target, author, timestamp}
808
-
809
- const instances: T[] = [];
810
- for (const row of result) {
811
- let base;
812
- try {
813
- // Use source_uri as the base (the actual URI), not the node ID
814
- base = row.source_uri;
953
+ const className = classNameOverride || metadata.className;
815
954
 
816
- // Skip rows without a source_uri field
817
- if (!base) {
818
- continue;
819
- }
820
-
821
- const links = row.links || [];
822
-
823
- const instance = new this(perspective, base) as any;
824
-
825
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset).
826
- // Also hydrate any properties referenced in `where` so the JS post-filter can match them,
827
- // even if they're not in the user's `properties` projection.
828
- let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
829
- if (hydrationProps && query.where) {
830
- for (const key of Object.keys(query.where)) {
831
- if (!hydrationProps.includes(key)) {
832
- hydrationProps.push(key);
833
- }
834
- }
955
+ // Expand includeAll: true to a full IncludeMap covering every forward relation.
956
+ // Done before queryInput is built so all downstream uses of query.include see the expansion.
957
+ if (query.includeAll) {
958
+ const allRelMeta = getRelationsMetadata(this as any);
959
+ const expanded: IncludeMap = {};
960
+ for (const [relName, relMeta] of Object.entries(allRelMeta)) {
961
+ if ((relMeta as any).direction !== 'reverse') {
962
+ expanded[relName] = true;
835
963
  }
836
- await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
837
-
838
- // NOTE: Property deletion for sparse fieldsets is deferred until AFTER
839
- // where-filtering so that where conditions can reference any property,
840
- // even ones not in the `properties` projection.
841
-
842
- instances.push(instance);
843
- } catch (error) {
844
- console.error(`Failed to process SPARQL instance ${base}:`, error);
845
964
  }
965
+ // Explicit include entries take precedence over the expansion
966
+ query = { ...query, include: { ...expanded, ...query.include } };
846
967
  }
847
968
 
848
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
849
- // These relations point FROM other nodes TO this instance, so they cannot be resolved
850
- // from the node's own outgoing links fetched above. We do a reverse-link lookup here
851
- // so that these fields are populated as IDs even without an explicit include.
852
- const allRelsMeta = getRelationsMetadata(this as any);
853
- const reverseRelEntries = Object.entries(allRelsMeta).filter(
854
- ([relName, meta]) =>
855
- (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
856
- (requestedProperties.length === 0 || requestedProperties.includes(relName))
857
- );
858
- if (reverseRelEntries.length > 0 && instances.length > 0) {
859
- await Promise.all(
860
- instances.map(async (inst) => {
861
- for (const [relName, relMeta] of reverseRelEntries) {
862
- const reverseLinks = await perspective.get(
863
- new LinkQuery({ predicate: relMeta.predicate, target: inst.id })
864
- );
865
- const sourceIds = reverseLinks
866
- .filter((l) => l.data.target === inst.id)
867
- .map((l) => l.data.source);
868
- if (relMeta.kind === 'belongsToOne') {
869
- (inst as any)[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
870
- } else {
871
- (inst as any)[relName] = sourceIds;
872
- }
873
- }
874
- })
875
- );
969
+ // Build the query input that the Rust endpoint expects.
970
+ // Convert the TS Query type to the executor's ModelQueryInput format.
971
+ const queryInput: any = {};
972
+ if (query.parent) {
973
+ const parentPredicate = resolveParentPredicate(query.parent, this);
974
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
876
975
  }
877
-
878
- // Evaluate custom getters for all instances.
879
- // Relation getters (type-conformance filtering) always run — they ensure
880
- // correctness of @HasMany/@HasOne targets. Property getters only run when
881
- // deepQuery is true or when where conditions reference getter-backed properties.
882
- const whereGetterProperties = query.where
883
- ? Object.keys(query.where).filter((propName) => (metadata.properties[propName] as any)?.getter)
884
- : [];
885
- const shouldEvaluatePropertyGetters = query.deepQuery === true || whereGetterProperties.length > 0;
886
- {
887
- const skipPropertyGetters = !shouldEvaluatePropertyGetters;
888
- const getterRequestedProperties = shouldEvaluatePropertyGetters
889
- ? (requestedProperties.length > 0
890
- ? Array.from(new Set([...requestedProperties, ...whereGetterProperties]))
891
- : query.deepQuery === true
892
- ? [] // deepQuery: evaluate all getters
893
- : whereGetterProperties) // only evaluate where-referenced getters
894
- : [];
895
- const getterOpts = {
896
- ...(getterRequestedProperties.length > 0 && { requestedProperties: getterRequestedProperties }),
897
- ...(query.include && { include: query.include }),
898
- skipPropertyGetters,
899
- };
900
- for (const instance of instances) {
901
- await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
976
+ if (query.properties) queryInput.properties = query.properties;
977
+ if (query.include) {
978
+ // Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
979
+ // All other keys (boolean | RelationSubQuery) → queryInput.include
980
+ const normalIncludes: IncludeMap = {};
981
+ const projections: Record<string, IncludeProjection> = {};
982
+ for (const [key, val] of Object.entries(query.include)) {
983
+ if (key.startsWith('$')) {
984
+ projections[key] = val as IncludeProjection;
985
+ } else {
986
+ normalIncludes[key] = val;
987
+ }
902
988
  }
903
- }
904
-
905
- // Filter by where conditions that couldn't be filtered in SPARQL
906
- // This includes:
907
- // - author/timestamp (computed from grouped links)
908
- // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
909
- // because <ad4m://fn/parse_literal>() returns strings, making numeric/date
910
- // comparisons unreliable. Equality, IN, and NOT are pushed to SPARQL.
911
- // - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
912
- // which require reverse-link resolution before filtering
913
- let filteredInstances = instances;
914
- if (query.where) {
915
- filteredInstances = instances.filter(instance => {
916
- for (const [propertyName, condition] of Object.entries(query.where!)) {
917
- // Skip 'base'/'id' as it's filtered in SPARQL
918
- if (propertyName === 'base' || propertyName === 'id') continue;
919
-
920
- // For author and timestamp, always filter in JS
921
- if (propertyName === 'author' || propertyName === 'timestamp') {
922
- if (!matchesCondition(instance[propertyName], condition)) {
923
- return false;
924
- }
925
- continue;
926
- }
927
-
928
- // Check if this is a relation field (not in properties metadata)
929
- const isPropField = propertyName in metadata.properties;
930
-
931
- if (!isPropField) {
932
- // Relation-based where — filter in JS against the populated field
933
- if (!matchesCondition(instance[propertyName], condition)) {
934
- return false;
935
- }
936
- continue;
937
- }
938
-
939
- // Filter ALL property conditions in JS (safety net).
940
- // Equality/IN/NOT are also filtered in SPARQL via <ad4m://fn/parse_literal>()
941
- // but JS re-validates after hydration resolves values.
942
- if (!matchesCondition(instance[propertyName], condition)) {
943
- return false;
989
+ if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
990
+ if (Object.keys(projections).length > 0) {
991
+ // Enrich projections with target shapes so Rust can apply where clause filtering
992
+ const allRelMeta = getRelationsMetadata(this as any);
993
+ for (const [, proj] of Object.entries(projections)) {
994
+ const relMeta = allRelMeta[proj.from];
995
+ if (!proj.targetShape && relMeta?.target) {
996
+ try {
997
+ const TargetClass = relMeta.target();
998
+ const targetMeta = (TargetClass as any).getModelMetadata?.();
999
+ if (targetMeta) {
1000
+ proj.targetShape = targetMeta;
1001
+ }
1002
+ } catch (_) { /* target class may not be available */ }
944
1003
  }
945
1004
  }
946
- return true;
947
- });
1005
+ queryInput.projections = projections;
1006
+ }
1007
+ }
1008
+ if (query.where) queryInput.where = query.where;
1009
+ if (query.order) {
1010
+ // Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
1011
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
1012
+ }
1013
+ if (query.offset !== undefined) queryInput.offset = query.offset;
1014
+ if (query.limit !== undefined) queryInput.limit = query.limit;
1015
+ if (query.count !== undefined) queryInput.count = query.count;
1016
+ queryInput.deepQuery = query.deepQuery ?? true;
1017
+
1018
+ // Enrich relation metadata with target class shapes for Rust-side
1019
+ // include resolution. This eliminates per-relation GraphQL round-trips
1020
+ // by letting the Rust endpoint resolve includes in-process.
1021
+ if (queryInput.include) {
1022
+ const allRelMeta = getRelationsMetadata(this as any);
1023
+ enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
948
1024
  }
949
1025
 
950
- // Apply ordering in JavaScript
951
- // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
952
- // This ensures consistent pagination behavior
953
- const effectiveOrder = query.order ||
954
- (query.limit !== undefined || query.offset !== undefined ? { createdAt: 'ASC' as 'ASC' } : null);
955
-
956
- if (effectiveOrder) {
957
- const orderEntries = Object.entries(effectiveOrder);
958
-
959
- filteredInstances.sort((a: any, b: any) => {
960
- for (const [orderPropName, orderDirection] of orderEntries) {
961
- let aVal = a[orderPropName];
962
- let bVal = b[orderPropName];
1026
+ // ── Pre-compute conformance getters for Rust-side evaluation ──────
1027
+ // For each relation with a target class and filter !== false, compute
1028
+ // the conformance getter SPARQL so Rust can evaluate it in-process
1029
+ // (eliminating N × querySparql round-trips per instance).
1030
+ // When a relation has a `where` clause, compile the where conditions
1031
+ // into the getter SPARQL so Rust applies them during evaluation.
1032
+ {
1033
+ const allRelMeta = getRelationsMetadata(this as any);
1034
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1035
+ const rel = relMeta as any;
1036
+ if (rel.getter) continue; // explicit getter already set
1037
+ if (rel.direction === 'reverse') continue; // reverse relations use reverse link lookup
1038
+ if (rel.filter === false) continue; // opt-out of conformance filtering
963
1039
 
964
- // Handle undefined values - push them to the end
965
- if (aVal === undefined && bVal === undefined) continue;
966
- if (aVal === undefined) return orderDirection === 'ASC' ? 1 : -1;
967
- if (bVal === undefined) return orderDirection === 'ASC' ? -1 : 1;
1040
+ const meta = allRelMeta[relName];
1041
+ if (!meta?.target) continue;
968
1042
 
969
- // Compare values
970
- let comparison = 0;
971
- if (typeof aVal === 'number' && typeof bVal === 'number') {
972
- comparison = aVal - bVal;
973
- } else if (typeof aVal === 'string' && typeof bVal === 'string') {
974
- comparison = aVal.localeCompare(bVal);
975
- } else {
976
- comparison = String(aVal).localeCompare(String(bVal));
1043
+ try {
1044
+ const TargetClass = meta.target();
1045
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
1046
+
1047
+ // Compile where clauses to SPARQL when all target properties use
1048
+ // literal encoding (literal:string:X etc.) which is SPARQL-matchable.
1049
+ // Properties with a non-literal resolveLanguage store expression hashes
1050
+ // that can't be matched by value in SPARQL.
1051
+ let whereConditions: string[] = [];
1052
+ if (rel.where) {
1053
+ try {
1054
+ const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
1055
+ let allSparqlFilterable = true;
1056
+ if (targetMetadata) {
1057
+ for (const propName of Object.keys(rel.where)) {
1058
+ if (['id', 'author', 'timestamp'].includes(propName)) continue;
1059
+ const propMeta = targetMetadata.properties[propName];
1060
+ if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
1061
+ allSparqlFilterable = false;
1062
+ break;
1063
+ }
1064
+ }
1065
+ }
1066
+ if (allSparqlFilterable) {
1067
+ whereConditions = compileWhereClause(rel.where, targetMetadata);
1068
+ }
1069
+ } catch (_) { /* target metadata unavailable */ }
977
1070
  }
978
1071
 
979
- if (comparison !== 0) {
980
- return orderDirection === 'DESC' ? -comparison : comparison;
1072
+ if (filter) {
1073
+ let getter = filter.getter;
1074
+ if (whereConditions.length > 0) {
1075
+ // Append where conditions before the closing }
1076
+ getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
1077
+ }
1078
+ rel.getter = getter;
1079
+ } else if (whereConditions.length > 0) {
1080
+ // No conformance filter but where clause exists — build getter from where alone
1081
+ const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
1082
+ rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
981
1083
  }
982
- // comparison === 0: continue to next sort field
1084
+ } catch (e) {
1085
+ // Target class may not be available; skip silently
983
1086
  }
984
- return 0;
985
- });
1087
+ }
986
1088
  }
987
1089
 
988
- // Determine if SPARQL already applied LIMIT/OFFSET (i.e., the pagination
989
- // subquery was used). When it was, skip JS-level slicing — instances are
990
- // already the correct page.
991
- const allRelsMeta2 = getRelationsMetadata(this as any);
992
- const sparqlPaginated = !hasJsOnlyWhereFilters(metadata, allRelsMeta2, query.where)
993
- && (query.limit !== undefined || query.offset !== undefined)
994
- && query.order !== undefined && Object.keys(query.order).length > 0;
995
-
996
- // Calculate totalCount BEFORE applying limit/offset.
997
- // When SPARQL already paginated, filteredInstances.length is the page size,
998
- // not the total — use a separate COUNT query for the real total.
999
- // Only run the COUNT query when the caller actually needs it (computeTotalCount=true).
1000
- let totalCount: number;
1001
- if (sparqlPaginated && computeTotalCount) {
1002
- try {
1003
- const countSparql = buildSPARQLCountQuery(metadata, allRelsMeta2, query, this);
1004
- const countResult = await perspective.querySparql(countSparql);
1005
- totalCount = parseSparqlCount(countResult) ?? filteredInstances.length;
1006
- } catch {
1007
- // Fallback: if count query fails, use what we have
1008
- totalCount = filteredInstances.length;
1009
- }
1010
- } else {
1011
- totalCount = filteredInstances.length;
1012
- }
1013
-
1014
- // Apply offset and limit in JavaScript only when SPARQL didn't already paginate.
1015
- // Subscription queries use unpaginated SPARQL, so JS must apply pagination.
1016
- // Direct queries use SPARQL-level pagination, so JS slicing would double-apply.
1017
- let paginatedInstances = filteredInstances;
1018
- if (!sparqlPaginated && (query.offset !== undefined || query.limit !== undefined)) {
1019
- const start = query.offset || 0;
1020
- const end = query.limit ? start + query.limit : undefined;
1021
- paginatedInstances = filteredInstances.slice(start, end);
1022
- }
1023
-
1024
- // Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
1025
- // This must happen AFTER where-filtering so conditions can reference any property.
1026
- if (requestedProperties.length > 0) {
1027
- const requested = new Set(requestedProperties);
1028
- for (const inst of paginatedInstances) {
1029
- for (const propName of Object.keys(metadata.properties)) {
1030
- if (!requested.has(propName)) {
1031
- delete (inst as any)[propName];
1032
- }
1033
- }
1034
- for (const relName of Object.keys(metadata.relations)) {
1035
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
1036
- delete (inst as any)[relName];
1037
- }
1038
- }
1039
- for (const metaField of ['author', 'createdAt', 'updatedAt'] as const) {
1040
- if (!requested.has(metaField)) {
1041
- delete (inst as any)[metaField];
1042
- }
1043
- }
1090
+ // Send shape metadata to the executor so it knows the model structure.
1091
+ // This is more reliable than reading SHACL from the store because
1092
+ // the TS decorators are the definitive source of truth.
1093
+ const shapeJson = JSON.stringify(metadata);
1094
+ const queryJson = JSON.stringify(queryInput);
1095
+
1096
+ // TEMP DEBUG: Log getters with where-clause filters to diagnose CI failure
1097
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1098
+ const rel = relMeta as any;
1099
+ if (rel.where) {
1100
+ console.log(`[MODEL_QUERY_DEBUG] relation="${relName}" getter=${rel.getter ?? 'NONE'} where=${JSON.stringify(rel.where)}`);
1044
1101
  }
1045
1102
  }
1046
1103
 
1047
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
1048
- if (query.include && paginatedInstances.length > 0) {
1049
- await hydrateRelations(this, paginatedInstances, perspective, query.include);
1104
+ const result = await perspective.modelQuery(className, queryJson, shapeJson);
1105
+
1106
+ // Convert JSON instances to model class instances, recursively constructing
1107
+ // class instances for any included relations resolved by Rust.
1108
+ const instances: T[] = result.instances.map((json: any) => {
1109
+ return jsonToModelInstance(this, perspective, json, query.include, query.properties);
1110
+ });
1111
+
1112
+ // Resolve non-literal expressions (e.g. file languages where the stored
1113
+ // value is a content-addressed hash that must be fetched from the language
1114
+ // runtime). The Rust endpoint returns raw target URIs; we resolve them here.
1115
+ const propsMeta = getPropertiesMetadata(this as any);
1116
+ const resolveProps = Object.entries(propsMeta).filter(
1117
+ ([, opts]: [string, any]) =>
1118
+ opts.resolveLanguage != null &&
1119
+ opts.resolveLanguage !== 'literal',
1120
+ );
1121
+ if (resolveProps.length > 0) {
1122
+ await Promise.all(
1123
+ instances.map(async (inst: any) => {
1124
+ for (const [propName, opts] of resolveProps) {
1125
+ const val = inst[propName];
1126
+ if (typeof val !== 'string' || !val || val.startsWith('literal:')) continue;
1127
+ try {
1128
+ const expression = await perspective.getExpression(val);
1129
+ if (expression) {
1130
+ let resolved: any;
1131
+ try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
1132
+ const transform = (opts as any).transform;
1133
+ inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
1134
+ }
1135
+ } catch (_) { /* resolution failed — keep raw value */ }
1136
+ }
1137
+ }),
1138
+ );
1050
1139
  }
1051
1140
 
1052
- // Take snapshots for dirty tracking after ALL hydration is complete
1053
- // (including eager-loaded relations).
1054
- // When `include` is specified, only snapshot those relations.
1055
- // Otherwise snapshot ALL fields (properties + relations) since
1056
- // hydrateFromLinks populates relations with stable raw IDs —
1057
- // this ensures push-to-array + save() correctly detects dirty relations.
1058
- const snapshotRelations = query.include;
1059
- for (const inst of paginatedInstances) {
1141
+ // Take snapshots for dirty tracking
1142
+ const snapshotRelations = queryInput.include;
1143
+ for (const inst of instances) {
1060
1144
  (inst as Ad4mModel).takeSnapshot(snapshotRelations);
1061
1145
  }
1062
1146
 
1063
1147
  return {
1064
- results: paginatedInstances,
1065
- totalCount
1148
+ results: instances,
1149
+ totalCount: result.totalCount,
1066
1150
  };
1067
1151
  }
1068
1152
 
@@ -1097,33 +1181,14 @@ export class Ad4mModel {
1097
1181
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1098
1182
  perspective: PerspectiveProxy,
1099
1183
  query: Query = {},
1100
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1184
+ _engine?: 'sparql' | 'prolog' | boolean
1101
1185
  ): Promise<T[]> {
1102
1186
  if (query.properties && query.properties.length === 0) {
1103
1187
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
1104
1188
  }
1105
1189
 
1106
- // Backward compatibility: boolean maps to sparql (true) or prolog (false)
1107
- const resolvedEngine = typeof engine === 'boolean'
1108
- ? (engine ? 'sparql' : 'prolog')
1109
- : engine;
1110
-
1111
- if (resolvedEngine === 'sparql') {
1112
- // Always use the regular SPARQL path + JS-level hydrateRelations for includes.
1113
- // The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
1114
- // non-conforming node filtering, and parse_literal compatibility.
1115
- // hydrateRelations handles all of these correctly via per-relation findAll calls.
1116
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1117
- const rawResult = await perspective.querySparql(sparqlQuery);
1118
- const grouped = groupSPARQLResults(rawResult);
1119
- const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
1120
- return results;
1121
- } else {
1122
- const prologQuery = await this.queryToProlog(perspective, query);
1123
- const result = await perspective.infer(prologQuery);
1124
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
1125
- return results;
1126
- }
1190
+ const { results } = await this.executeModelQuery(perspective, query);
1191
+ return results;
1127
1192
  }
1128
1193
 
1129
1194
  /**
@@ -1150,10 +1215,10 @@ export class Ad4mModel {
1150
1215
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1151
1216
  perspective: PerspectiveProxy,
1152
1217
  query: Query = {},
1153
- engine: 'sparql' | 'prolog' | boolean = 'sparql',
1218
+ _engine?: 'sparql' | 'prolog' | boolean,
1154
1219
  ): Promise<T | null> {
1155
1220
  const limitedQuery = { ...query, limit: 1 };
1156
- const results = await this.findAll(perspective, limitedQuery, engine);
1221
+ const results = await this.findAll(perspective, limitedQuery);
1157
1222
  return results[0] ?? null;
1158
1223
  }
1159
1224
 
@@ -1181,22 +1246,9 @@ export class Ad4mModel {
1181
1246
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1182
1247
  perspective: PerspectiveProxy,
1183
1248
  query: Query = {},
1184
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1249
+ _engine?: 'sparql' | 'prolog' | boolean
1185
1250
  ): Promise<ResultsWithTotalCount<T>> {
1186
- const resolvedEngine = typeof engine === 'boolean'
1187
- ? (engine ? 'sparql' : 'prolog')
1188
- : engine;
1189
-
1190
- if (resolvedEngine === 'sparql') {
1191
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1192
- const rawResult = await perspective.querySparql(sparqlQuery);
1193
- const grouped = groupSPARQLResults(rawResult);
1194
- return await this.instancesFromQueryResult(perspective, query, grouped, true);
1195
- } else {
1196
- const prologQuery = await this.queryToProlog(perspective, query);
1197
- const result = await perspective.infer(prologQuery);
1198
- return await this.instancesFromPrologResult(perspective, query, result);
1199
- }
1251
+ return await this.executeModelQuery(perspective, query);
1200
1252
  }
1201
1253
 
1202
1254
  /**
@@ -1206,7 +1258,6 @@ export class Ad4mModel {
1206
1258
  * @param pageSize - Number of items per page
1207
1259
  * @param pageNumber - Which page to retrieve (1-based)
1208
1260
  * @param query - Optional additional query parameters
1209
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1210
1261
  * @returns Paginated results with metadata
1211
1262
  *
1212
1263
  * @example
@@ -1215,9 +1266,6 @@ export class Ad4mModel {
1215
1266
  * where: { category: "Main Course" }
1216
1267
  * });
1217
1268
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
1218
- *
1219
- * // Use Prolog explicitly (legacy)
1220
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
1221
1269
  * ```
1222
1270
  */
1223
1271
  static async paginate<T extends Ad4mModel>(
@@ -1226,46 +1274,11 @@ export class Ad4mModel {
1226
1274
  pageSize: number,
1227
1275
  pageNumber: number,
1228
1276
  query?: Query,
1229
- engine: 'sparql' | 'prolog' | boolean = 'sparql'
1277
+ _engine?: 'sparql' | 'prolog' | boolean
1230
1278
  ): Promise<PaginationResult<T>> {
1231
1279
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1232
- const resolvedEngine = typeof engine === 'boolean'
1233
- ? (engine ? 'sparql' : 'prolog')
1234
- : engine;
1235
-
1236
- if (resolvedEngine === 'sparql') {
1237
- const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
1238
- const rawResult = await perspective.querySparql(sparqlQuery);
1239
- const grouped = groupSPARQLResults(rawResult);
1240
- const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped, true);
1241
- return { results, totalCount, pageSize, pageNumber };
1242
- } else {
1243
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
1244
- const result = await perspective.infer(prologQuery);
1245
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
1246
- return { results, totalCount, pageSize, pageNumber };
1247
- }
1248
- }
1249
-
1250
- static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
1251
- const { where } = query;
1252
- const className = modelClassName || (await this.getClassName(perspective));
1253
- const resolvedParentPredicate = query.parent
1254
- ? resolveParentPredicate(query.parent, this)
1255
- : undefined;
1256
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
1257
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
1258
-
1259
- const fullQuery = `
1260
- findall([Base, Properties, Collections, Timestamp, Author], (
1261
- subject_class("${className}", SubjectClass),
1262
- instance(SubjectClass, Base),
1263
- ${instanceQueries.filter((q) => q).join(", ")}
1264
- ), UnsortedInstances),
1265
- ${resultSetQueries.filter((q) => q).join(", ")}
1266
- `;
1267
-
1268
- return fullQuery;
1280
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1281
+ return { results, totalCount, pageSize, pageNumber };
1269
1282
  }
1270
1283
 
1271
1284
  /**
@@ -1277,18 +1290,13 @@ export class Ad4mModel {
1277
1290
  *
1278
1291
  * @private
1279
1292
  */
1280
- public static async countQueryToSPARQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
1281
- const metadata = this.getModelMetadata();
1282
- const allRelMeta = getRelationsMetadata(this as any);
1283
- return buildSPARQLCountQuery(metadata, allRelMeta, query, this);
1284
- }
1293
+ // countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
1285
1294
 
1286
1295
  /**
1287
1296
  * Gets a count of all matching instances.
1288
1297
  *
1289
1298
  * @param perspective - The perspective to search in
1290
1299
  * @param query - Optional query parameters to filter results
1291
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1292
1300
  * @returns Total count of matching entities
1293
1301
  *
1294
1302
  * @example
@@ -1297,36 +1305,11 @@ export class Ad4mModel {
1297
1305
  * const activeRecipes = await Recipe.count(perspective, {
1298
1306
  * where: { status: "active" }
1299
1307
  * });
1300
- *
1301
- * // Use Prolog explicitly (legacy)
1302
- * const countProlog = await Recipe.count(perspective, {}, false);
1303
1308
  * ```
1304
1309
  */
1305
- static async count(perspective: PerspectiveProxy, query: Query = {}, engine: 'sparql' | 'prolog' | boolean = 'sparql') {
1306
- const resolvedEngine = typeof engine === 'boolean'
1307
- ? (engine ? 'sparql' : 'prolog')
1308
- : engine;
1309
-
1310
- if (resolvedEngine === 'sparql') {
1311
- // When query has JS-only where filters (gt, between, author, timestamp, etc.),
1312
- // we must fall back to full hydration + JS filtering to get accurate count.
1313
- const metadata = this.getModelMetadata();
1314
- const allRelMeta = getRelationsMetadata(this as any);
1315
- if (hasJsOnlyWhereFilters(metadata, allRelMeta, query.where)) {
1316
- // Fall back to full query + JS filter path for accurate count
1317
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1318
- const rawResult = await perspective.querySparql(sparqlQuery);
1319
- const grouped = groupSPARQLResults(rawResult);
1320
- const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped, true); return totalCount;
1321
- }
1322
- // No JS-only filters — use efficient COUNT query
1323
- const countSparql = await this.countQueryToSPARQL(perspective, query);
1324
- const countResult = await perspective.querySparql(countSparql);
1325
- return parseSparqlCount(countResult) ?? 0;
1326
- } else {
1327
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
1328
- return result?.[0]?.TotalCount || 0;
1329
- }
1310
+ static async count(perspective: PerspectiveProxy, query: Query = {}): Promise<number> {
1311
+ const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
1312
+ return totalCount;
1330
1313
  }
1331
1314
 
1332
1315
  private async setProperty(key: string, value: any, batchId?: string) {
@@ -1661,10 +1644,10 @@ export class Ad4mModel {
1661
1644
  /**
1662
1645
  * Evaluate SPARQL getters for a batch of instances on demand.
1663
1646
  *
1664
- * Use after a shallow collection query (the default) to resolve
1665
- * getter-backed properties for visible items only. This avoids the
1666
- * O(N × getters) cost of evaluating every getter on every instance in
1667
- * a large collection query.
1647
+ * Since deepQuery defaults to true, property getters are evaluated
1648
+ * automatically during collection queries. Use this method when
1649
+ * deepQuery was explicitly set to false and you want to lazily
1650
+ * resolve getter-backed properties for a subset of instances.
1668
1651
  *
1669
1652
  * @param instances - Array of model instances to evaluate getters on
1670
1653
  * @param perspective - The perspective to query against
@@ -1673,8 +1656,8 @@ export class Ad4mModel {
1673
1656
  *
1674
1657
  * @example
1675
1658
  * ```typescript
1676
- * const messages = await Message.findAll(perspective, { parent: channel, limit: 30 });
1677
- * // messages[i].replyingTo is undefined (getter skipped by default)
1659
+ * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
1660
+ * // messages[i].replyingTo is undefined (getter skipped)
1678
1661
  *
1679
1662
  * // Evaluate getters for the visible subset
1680
1663
  * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
@@ -1688,11 +1671,33 @@ export class Ad4mModel {
1688
1671
  ): Promise<void> {
1689
1672
  if (instances.length === 0) return;
1690
1673
  const metadata = this.getModelMetadata();
1691
- const opts = propertyNames && propertyNames.length > 0
1692
- ? { requestedProperties: propertyNames }
1693
- : undefined;
1694
1674
 
1695
- // Determine which property names will actually be evaluated
1675
+ // Pre-compute conformance getters so the shape sent to Rust includes them
1676
+ const allRelMeta = getRelationsMetadata(this as any);
1677
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1678
+ const rel = relMeta as any;
1679
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
1680
+ const meta = allRelMeta[relName];
1681
+ if (!meta?.target) continue;
1682
+ try {
1683
+ const TargetClass = meta.target();
1684
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
1685
+ if (filter) rel.getter = filter.getter;
1686
+ } catch (_) { /* target class may not be available */ }
1687
+ }
1688
+
1689
+ const shapeJson = JSON.stringify(metadata);
1690
+ const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
1691
+
1692
+ // Single RPC call evaluates all getters in-process on the executor
1693
+ const result = await perspective.evaluateGetters(
1694
+ metadata.className,
1695
+ instanceIds,
1696
+ shapeJson,
1697
+ propertyNames,
1698
+ );
1699
+
1700
+ // Determine which property names were evaluated for snapshot sync
1696
1701
  const evaluatedPropertyNames: string[] = [];
1697
1702
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1698
1703
  if ((propMeta as any).getter) {
@@ -1701,14 +1706,25 @@ export class Ad4mModel {
1701
1706
  }
1702
1707
  }
1703
1708
  }
1709
+ // Also include relation getters
1710
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1711
+ if ((relMeta as any).getter) {
1712
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
1713
+ evaluatedPropertyNames.push(relName);
1714
+ }
1715
+ }
1716
+ }
1704
1717
 
1718
+ // Apply results to instances and sync snapshots
1705
1719
  for (const instance of instances) {
1706
- await evaluateCustomGettersForInstance(instance, perspective, metadata, opts);
1707
- // Sync snapshot so isDirty() doesn't flag getter-only changes.
1708
- // evaluateGetters() mutates instances in place, but their snapshots
1709
- // were already taken during hydration. Without this sync, the computed
1710
- // getter values would make isDirty() return true and save() would try
1711
- // to write read-only computed properties.
1720
+ const id = (instance as any).id || (instance as any)._baseExpression;
1721
+ const props = result[id];
1722
+ if (props) {
1723
+ for (const [key, value] of Object.entries(props)) {
1724
+ (instance as any)[key] = value;
1725
+ }
1726
+ }
1727
+ // Sync snapshot so isDirty() doesn't flag getter-only changes
1712
1728
  const modelInstance = instance as Ad4mModel;
1713
1729
  if (modelInstance._snapshot) {
1714
1730
  for (const propName of evaluatedPropertyNames) {
@@ -2132,5 +2148,124 @@ export class Ad4mModel {
2132
2148
  ): typeof Ad4mModel {
2133
2149
  return buildModelFromJSONSchema(this, schema, options);
2134
2150
  }
2151
+
2152
+ /**
2153
+ * Creates a fully functional Ad4mModel subclass from a SHACL shape.
2154
+ *
2155
+ * Unlike `fromJSONSchema()`, no predicate inference is required —
2156
+ * `SHACLShape` already contains the exact predicate URI in `path` for
2157
+ * every property. The method reads each property's `path`, `maxCount`,
2158
+ * `writable`, and `resolveLanguage` directly and writes them to the
2159
+ * WeakMap metadata registries.
2160
+ *
2161
+ * Properties with `hasValue` (flag / type-discrimination markers) are
2162
+ * registered as hidden flag entries so that the SPARQL query builder emits
2163
+ * the fixed triple `?source <predicate> <value>` needed for type discrimination.
2164
+ * Properties without a `name` field are skipped.
2165
+ *
2166
+ * **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
2167
+ * was persisted on property shapes) carry the flag value only in
2168
+ * `shape.constructor_actions` as the `target` of an `addLink` action.
2169
+ * This method recovers those values so that old perspectives are queried
2170
+ * with the correct type-discriminator triple.
2171
+ *
2172
+ * @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
2173
+ * @param name - Class name to assign (e.g. "Channel")
2174
+ * @returns Generated Ad4mModel subclass, ready for querying
2175
+ */
2176
+ /**
2177
+ * Synthesise an `Ad4mModel` subclass from a SHACL shape.
2178
+ *
2179
+ * @param shape - The SHACL shape to synthesise from.
2180
+ * @param name - The model name (e.g. "Channel").
2181
+ * @param classResolver - Optional thunk factory. When provided, any collection
2182
+ * property that carries a `sh:class` URI will have its `target` wired up lazily:
2183
+ * `target: () => classResolver(localName)`. Because `target` is only called at
2184
+ * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
2185
+ * resolver just needs to return the correct class by the time a query runs —
2186
+ * making it safe to pass a closure over a registry object that is still being
2187
+ * populated (e.g. the `result` record inside `getModelClasses`).
2188
+ */
2189
+ static fromSHACL(
2190
+ shape: SHACLShape,
2191
+ name: string,
2192
+ classResolver?: (localName: string) => typeof Ad4mModel | undefined,
2193
+ ): typeof Ad4mModel {
2194
+ const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
2195
+ (DynamicModelClass as any).className = name;
2196
+ (DynamicModelClass.prototype as any).className = name;
2197
+
2198
+ // Build a backward-compat fallback map: predicate → fixed-IRI-value from
2199
+ // constructor actions. Old SHACL stores (created before sh:hasValue was
2200
+ // persisted on the property shape) don't carry sh:hasValue on properties,
2201
+ // but the shape-level constructor_actions always contain an addLink action
2202
+ // with the fixed flag value as the target.
2203
+ const flagValueFromConstructor = new Map<string, string>();
2204
+ for (const action of shape.constructor_actions ?? []) {
2205
+ if (
2206
+ action.action === 'addLink' &&
2207
+ typeof action.predicate === 'string' &&
2208
+ typeof action.target === 'string' &&
2209
+ action.target !== 'value' &&
2210
+ !action.target.startsWith('literal:')
2211
+ ) {
2212
+ flagValueFromConstructor.set(action.predicate, action.target);
2213
+ }
2214
+ }
2215
+
2216
+ for (const prop of shape.properties) {
2217
+ const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
2218
+
2219
+ if (resolvedHasValue !== undefined) {
2220
+ const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
2221
+ setPropertyRegistryEntry(DynamicModelClass, flagKey, {
2222
+ through: prop.path,
2223
+ required: true,
2224
+ initial: resolvedHasValue,
2225
+ flag: true,
2226
+ writable: false,
2227
+ readOnly: true,
2228
+ });
2229
+ continue;
2230
+ }
2231
+
2232
+ // Skip properties without a declared name
2233
+ if (!prop.name) continue;
2234
+
2235
+ const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
2236
+
2237
+ if (isCollection) {
2238
+ // Derive a lazy `target` thunk when a sh:class URI is present and a
2239
+ // classResolver was supplied. The thunk is evaluated at query time so
2240
+ // it is safe even if the target class hasn't been registered yet.
2241
+ let targetThunk: (() => typeof Ad4mModel) | undefined;
2242
+ if (prop.class && classResolver) {
2243
+ const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
2244
+ const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
2245
+ targetThunk = () => classResolver(localName) as typeof Ad4mModel;
2246
+ }
2247
+
2248
+ setRelationRegistryEntry(DynamicModelClass, prop.name, {
2249
+ predicate: prop.path,
2250
+ kind: 'hasMany',
2251
+ ...(targetThunk !== undefined && { target: targetThunk }),
2252
+ ...(prop.local !== undefined && { local: prop.local }),
2253
+ ...(prop.getter !== undefined && { getter: prop.getter }),
2254
+ });
2255
+ } else {
2256
+ setPropertyRegistryEntry(DynamicModelClass, prop.name, {
2257
+ through: prop.path,
2258
+ writable: prop.writable ?? true,
2259
+ ...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
2260
+ ...(prop.local !== undefined && { local: prop.local }),
2261
+ });
2262
+ }
2263
+ }
2264
+
2265
+ const ModelDecorator = Model({ name });
2266
+ ModelDecorator(DynamicModelClass);
2267
+
2268
+ return DynamicModelClass as typeof Ad4mModel;
2269
+ }
2135
2270
  }
2136
2271