@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
@@ -1,5 +1,6 @@
1
1
  import { Ad4mModel } from "./Ad4mModel";
2
- import { Model, Property, Optional, ReadOnly, HasMany, Flag } from "./decorators";
2
+ import { isIncludeProjection } from "./types";
3
+ import { Model, Property, Optional, ReadOnly, HasMany, HasOne, Flag } from "./decorators";
3
4
 
4
5
  describe("Ad4mModel.getModelMetadata()", () => {
5
6
  it("should extract basic model metadata with className", () => {
@@ -617,7 +618,7 @@ describe("Ad4mModel.queryToSPARQL()", () => {
617
618
  expect(norm).toContain("SELECT DISTINCT ?source");
618
619
  });
619
620
  });
620
- describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
621
+ describe("Ad4mModel query methods (modelQuery integration)", () => {
621
622
  // Test Recipe model
622
623
  @Model({ name: "Recipe" })
623
624
  class Recipe extends Ad4mModel {
@@ -631,9 +632,10 @@ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
631
632
  ingredients: string[] = [];
632
633
  }
633
634
 
634
- // Mock perspective with both querySparql and infer methods
635
+ // Mock perspective with querySparql, modelQuery, and infer methods
635
636
  const mockPerspective = {
636
637
  querySparql: jest.fn(),
638
+ modelQuery: jest.fn(),
637
639
  infer: jest.fn(),
638
640
  uuid: 'test-perspective-uuid',
639
641
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -643,201 +645,65 @@ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
643
645
  jest.clearAllMocks();
644
646
  });
645
647
 
646
- it("should convert empty query results correctly", async () => {
647
- const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, []);
648
-
649
- expect(result.results).toEqual([]);
650
- expect(result.totalCount).toBe(0);
651
- });
652
-
653
- it("should convert query results to model instances", async () => {
654
- const queryResults = [
655
- {
656
- source: "node:abc123",
657
- source_uri: "literal:recipe1",
658
- links: [
659
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
660
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
661
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
662
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
663
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
664
- ]
665
- },
666
- {
667
- source: "node:def456",
668
- source_uri: "literal:recipe2",
669
- links: [
670
- { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
671
- { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
672
- { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
673
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
674
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
675
- ]
676
- }
677
- ];
678
-
679
- const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
680
-
681
- expect(result.results).toHaveLength(2);
682
- expect(result.totalCount).toBe(2);
683
-
684
- const recipe1 = result.results[0];
685
- expect(recipe1).toBeInstanceOf(Recipe);
686
- expect(recipe1.name).toBe("Pasta");
687
- expect(recipe1.rating).toBe(5);
688
- expect(recipe1.ingredients).toEqual(["pasta", "tomato", "cheese"]);
689
-
690
- const recipe2 = result.results[1];
691
- expect(recipe2).toBeInstanceOf(Recipe);
692
- expect(recipe2.name).toBe("Pizza");
693
- expect(recipe2.rating).toBe(4);
694
- });
695
-
696
- it("should filter properties when query specifies properties", async () => {
697
- const queryResults = [
698
- {
699
- source: "node:abc123",
700
- source_uri: "literal:recipe1",
701
- links: [
702
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
703
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
704
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
705
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
706
- ]
707
- }
708
- ];
709
-
710
- const result = await Recipe.instancesFromQueryResult(
711
- mockPerspective,
712
- { properties: ["name"] },
713
- queryResults
714
- );
715
-
716
- expect(result.results).toHaveLength(1);
717
- const recipe = result.results[0];
718
- expect(recipe.name).toBe("Pasta");
719
- // rating and ingredients should be removed since only "name" was requested
720
- expect(recipe.rating).toBeUndefined();
721
- expect(recipe.ingredients).toBeUndefined();
722
- // author, createdAt, updatedAt are also stripped unless explicitly requested
723
- expect(recipe.author).toBeUndefined();
724
- expect(recipe.timestamp).toBeUndefined();
725
- });
726
-
727
- it("should filter properties when query specifies properties", async () => {
728
- const queryResults = [
729
- {
730
- source: "node:abc123",
731
- source_uri: "literal:recipe1",
732
- links: [
733
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
734
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
735
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
736
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
737
- ]
738
- }
739
- ];
740
-
741
- const result = await Recipe.instancesFromQueryResult(
742
- mockPerspective,
743
- { properties: ["name"] },
744
- queryResults
745
- );
746
-
747
- expect(result.results).toHaveLength(1);
748
- const recipe = result.results[0];
749
- expect(recipe.name).toBe("Pasta");
750
- // rating and ingredients should be removed since only "name" was requested
751
- expect(recipe.rating).toBeUndefined();
752
- });
753
-
754
- it("should handle results missing base field", async () => {
755
- const queryResults = [
756
- {
757
- links: [
758
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
759
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
760
- ]
761
- // Missing source field
762
- } as any
763
- ];
764
-
765
- const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
766
-
767
- // Should filter out the invalid result (or handle gracefully)
768
- expect(result.results).toHaveLength(0);
769
- expect(result.totalCount).toBe(0);
770
- });
771
-
772
648
  it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
773
- // Raw SPARQL rows (flat) — groupSPARQLResults will group them
774
- const queryResults = [
775
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
776
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
777
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
778
- ];
779
-
780
- mockPerspective.querySparql.mockResolvedValue(queryResults);
649
+ // modelQuery returns already-hydrated instances from the Rust executor
650
+ mockPerspective.modelQuery.mockResolvedValue({
651
+ instances: [
652
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
653
+ ],
654
+ totalCount: 1
655
+ });
781
656
 
782
657
  const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
783
658
 
784
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
659
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
785
660
  expect(mockPerspective.infer).not.toHaveBeenCalled();
786
661
  expect(results).toHaveLength(1);
787
662
  expect(results[0].name).toBe("Pasta");
788
663
  });
789
664
 
790
- it("should use Prolog when engine is prolog in findAll()", async () => {
791
- const prologResults = [{
792
- AllInstances: [
793
- ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
665
+ it("should route through modelQuery when engine is 'prolog' in findAll() (prolog is now no-op)", async () => {
666
+ mockPerspective.modelQuery.mockResolvedValue({
667
+ instances: [
668
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
794
669
  ],
795
- TotalCount: 1
796
- }];
797
-
798
- mockPerspective.infer.mockResolvedValue(prologResults);
670
+ totalCount: 1
671
+ });
799
672
 
800
673
  const results = await Recipe.findAll(mockPerspective, {}, false);
801
674
 
802
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
803
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
675
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
676
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
804
677
  expect(results).toHaveLength(1);
805
678
  });
806
679
 
807
680
  it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
808
- const queryResults = [
809
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
810
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
811
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
812
- ];
813
-
814
- mockPerspective.querySparql.mockResolvedValue(queryResults);
681
+ mockPerspective.modelQuery.mockResolvedValue({
682
+ instances: [
683
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
684
+ ],
685
+ totalCount: 1
686
+ });
815
687
 
816
- const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {}, 'sparql');
688
+ const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
817
689
 
818
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
690
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
819
691
  expect(mockPerspective.infer).not.toHaveBeenCalled();
820
692
  expect(results).toHaveLength(1);
821
693
  expect(totalCount).toBe(1);
822
694
  });
823
695
 
824
696
  it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
825
- const queryResults = [
826
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
827
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
828
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
829
- ];
830
-
831
- // First call returns data, second call returns count (for SPARQL-paginated totalCount)
832
- mockPerspective.querySparql
833
- .mockResolvedValueOnce(queryResults)
834
- .mockResolvedValueOnce([{ count: 1 }]);
697
+ mockPerspective.modelQuery.mockResolvedValue({
698
+ instances: [
699
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
700
+ ],
701
+ totalCount: 1
702
+ });
835
703
 
836
- // Include order to trigger SPARQL-level pagination (data + count queries)
837
- const page = await Recipe.paginate(mockPerspective, 10, 1, { order: { name: 'ASC' as const } }, 'sparql');
704
+ const page = await Recipe.paginate(mockPerspective, 10, 1, {});
838
705
 
839
- // paginate now issues 2 SPARQL queries: data + count
840
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(2);
706
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
841
707
  expect(mockPerspective.infer).not.toHaveBeenCalled();
842
708
  expect(page.results).toHaveLength(1);
843
709
  expect(page.pageSize).toBe(10);
@@ -845,103 +711,100 @@ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
845
711
  expect(page.totalCount).toBe(1);
846
712
  });
847
713
 
848
- it("should use SPARQL when engine is 'sparql' in count()", async () => {
849
- // count() now uses an efficient COUNT query that returns [{ count: N }]
850
- mockPerspective.querySparql.mockResolvedValue([{ count: 5 }]);
714
+ it("should use SPARQL in count()", async () => {
715
+ mockPerspective.modelQuery.mockResolvedValue({
716
+ instances: [],
717
+ totalCount: 5
718
+ });
851
719
 
852
- const count = await Recipe.count(mockPerspective, {}, 'sparql');
720
+ const count = await Recipe.count(mockPerspective, {});
853
721
 
854
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
722
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
855
723
  expect(mockPerspective.infer).not.toHaveBeenCalled();
856
724
  expect(count).toBe(5);
857
725
  });
858
726
 
859
- it("should use Prolog when engine is prolog in count()", async () => {
860
- const prologResults = [{ TotalCount: 10 }];
861
- mockPerspective.infer.mockResolvedValue(prologResults);
727
+ it("should return count from modelQuery", async () => {
728
+ mockPerspective.modelQuery.mockResolvedValue({
729
+ instances: [],
730
+ totalCount: 10
731
+ });
862
732
 
863
- const count = await Recipe.count(mockPerspective, {}, false);
733
+ const count = await Recipe.count(mockPerspective, {});
864
734
 
865
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
735
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
866
736
  expect(mockPerspective.querySparql).not.toHaveBeenCalled();
867
737
  expect(count).toBe(10);
868
738
  });
869
739
 
870
740
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
871
- const queryResults = [
872
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
873
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
874
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
875
- ];
876
-
877
- mockPerspective.querySparql.mockResolvedValue(queryResults);
741
+ mockPerspective.modelQuery.mockResolvedValue({
742
+ instances: [
743
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
744
+ ],
745
+ totalCount: 1
746
+ });
878
747
 
879
748
  const results = await Recipe.query(mockPerspective)
880
749
  .where({ name: "Pasta" })
881
750
  .engine('sparql')
882
751
  .get();
883
752
 
884
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
753
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
885
754
  expect(mockPerspective.infer).not.toHaveBeenCalled();
886
755
  expect(results).toHaveLength(1);
887
756
  expect(results[0].name).toBe("Pasta");
888
757
  });
889
758
 
890
- it("should use Prolog when.engine('prolog') in ModelQueryBuilder.get()", async () => {
891
- const prologResults = [{
892
- AllInstances: [
893
- ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
759
+ it("should use modelQuery when .engine('prolog') is called (engine is now a no-op)", async () => {
760
+ mockPerspective.modelQuery.mockResolvedValue({
761
+ instances: [
762
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
894
763
  ],
895
- TotalCount: 1
896
- }];
897
-
898
- mockPerspective.infer.mockResolvedValue(prologResults);
764
+ totalCount: 1
765
+ });
899
766
 
900
767
  const results = await Recipe.query(mockPerspective)
901
768
  .where({ name: "Pasta" })
902
769
  .engine('prolog')
903
770
  .get();
904
771
 
905
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
906
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
772
+ // engine('prolog') is now a no-op — everything goes through modelQuery
773
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
774
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
907
775
  expect(results).toHaveLength(1);
908
776
  });
909
777
 
910
778
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
911
- // count() counts the number of rows returned by the query (one row per source)
912
- const queryResults = [
913
- ...Array.from({ length: 3 }, (_, i) => [
914
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
915
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
916
- ]).flat()
917
- ];
918
- mockPerspective.querySparql.mockResolvedValue(queryResults);
779
+ mockPerspective.modelQuery.mockResolvedValue({
780
+ instances: [],
781
+ totalCount: 3
782
+ });
919
783
 
920
784
  const count = await Recipe.query(mockPerspective)
921
785
  .where({ rating: { gt: 4 } })
922
786
  .engine('sparql')
923
787
  .count();
924
788
 
925
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
789
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
926
790
  expect(mockPerspective.infer).not.toHaveBeenCalled();
927
791
  expect(count).toBe(3);
928
792
  });
929
793
 
930
794
  it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
931
- const queryResults = [
932
- { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
933
- { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
934
- { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
935
- ];
936
-
937
- mockPerspective.querySparql.mockResolvedValue(queryResults);
795
+ mockPerspective.modelQuery.mockResolvedValue({
796
+ instances: [
797
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
798
+ ],
799
+ totalCount: 1
800
+ });
938
801
 
939
802
  const page = await Recipe.query(mockPerspective)
940
803
  .where({ rating: { gt: 3 } })
941
804
  .engine('sparql')
942
805
  .paginate(10, 1);
943
806
 
944
- expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
807
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
945
808
  expect(mockPerspective.infer).not.toHaveBeenCalled();
946
809
  expect(page.results).toHaveLength(1);
947
810
  expect(page.pageSize).toBe(10);
@@ -966,6 +829,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
966
829
  // Mock perspective
967
830
  const mockPerspective = {
968
831
  querySparql: jest.fn(),
832
+ modelQuery: jest.fn(),
969
833
  infer: jest.fn(),
970
834
  uuid: 'test-perspective-uuid',
971
835
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -975,132 +839,80 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
975
839
  jest.clearAllMocks();
976
840
  });
977
841
 
978
- it("should apply JS-level filtering for gt operator on properties in SPARQL count()", async () => {
979
- // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
980
- const queryResults = [
981
- ...Array.from({ length: 5 }, (_, i) => [
982
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
983
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
984
- ]).flat()
985
- ];
986
-
987
- mockPerspective.querySparql.mockResolvedValue(queryResults);
842
+ it("should apply filtering for gt operator on properties in SPARQL count()", async () => {
843
+ // With the new modelQuery endpoint, filtering happens server-side in Rust
844
+ mockPerspective.modelQuery.mockResolvedValue({
845
+ instances: [],
846
+ totalCount: 2
847
+ });
988
848
 
989
849
  // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
990
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
991
-
992
- // Verify count matches the number of instances that would be returned by findAll
993
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
850
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
994
851
 
995
852
  expect(count).toBe(2);
996
- expect(count).toBe(findAllResults.length);
853
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
997
854
  });
998
855
 
999
- it("should apply JS-level filtering for between operator on properties in SPARQL count()", async () => {
1000
- // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
1001
- const queryResults = [
1002
- ...Array.from({ length: 5 }, (_, i) => [
1003
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1004
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1005
- ]).flat()
1006
- ];
1007
-
1008
- mockPerspective.querySparql.mockResolvedValue(queryResults);
856
+ it("should apply filtering for between operator on properties in SPARQL count()", async () => {
857
+ mockPerspective.modelQuery.mockResolvedValue({
858
+ instances: [],
859
+ totalCount: 3
860
+ });
1009
861
 
1010
862
  // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1011
- const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
1012
-
1013
- // Verify count matches the number of instances that would be returned by findAll
1014
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
863
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1015
864
 
1016
865
  expect(count).toBe(3);
1017
- expect(count).toBe(findAllResults.length);
866
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1018
867
  });
1019
868
 
1020
- it("should apply JS-level filtering for timestamp gt operator in SPARQL count()", async () => {
1021
- // Mock query results: 5 recipes with different timestamps
1022
- const queryResults = [
1023
- ...Array.from({ length: 5 }, (_, i) => [
1024
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1025
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1026
- ]).flat()
1027
- ];
1028
-
1029
- mockPerspective.querySparql.mockResolvedValue(queryResults);
869
+ it("should apply filtering for timestamp gt operator in SPARQL count()", async () => {
870
+ mockPerspective.modelQuery.mockResolvedValue({
871
+ instances: [],
872
+ totalCount: 2
873
+ });
1030
874
 
1031
- // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1032
875
  const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1033
- const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
1034
-
1035
- // Verify count matches the number of instances that would be returned by findAll
1036
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
876
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1037
877
 
1038
878
  expect(count).toBe(2);
1039
- expect(count).toBe(findAllResults.length);
879
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1040
880
  });
1041
881
 
1042
- it("should apply JS-level filtering for timestamp between operator in SPARQL count()", async () => {
1043
- // Mock query results: 5 recipes with different timestamps
1044
- const queryResults = [
1045
- ...Array.from({ length: 5 }, (_, i) => [
1046
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1047
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1048
- ]).flat()
1049
- ];
1050
-
1051
- mockPerspective.querySparql.mockResolvedValue(queryResults);
882
+ it("should apply filtering for timestamp between operator in SPARQL count()", async () => {
883
+ mockPerspective.modelQuery.mockResolvedValue({
884
+ instances: [],
885
+ totalCount: 3
886
+ });
1052
887
 
1053
- // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1054
888
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1055
889
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1056
890
  const count = await Recipe.count(mockPerspective, {
1057
891
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1058
- }, 'sparql');
1059
-
1060
- // Verify count matches the number of instances that would be returned by findAll
1061
- const findAllResults = await Recipe.findAll(mockPerspective, {
1062
- where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1063
- }, 'sparql');
892
+ });
1064
893
 
1065
894
  expect(count).toBe(3);
1066
- expect(count).toBe(findAllResults.length);
1067
- });
1068
-
1069
- it("should apply JS-level filtering for author filtering in SPARQL count()", async () => {
1070
- // Mock query results: 3 recipes by Alice and 2 by Bob
1071
- const queryResults = [
1072
- ...Array.from({ length: 3 }, (_, i) => [
1073
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1074
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1075
- ]).flat(),
1076
- ...Array.from({ length: 2 }, (_, i) => [
1077
- { source: `literal:recipe${i+4}`, predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1078
- { source: `literal:recipe${i+4}`, predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1079
- ]).flat()
1080
- ];
1081
-
1082
- mockPerspective.querySparql.mockResolvedValue(queryResults);
895
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
896
+ });
897
+
898
+ it("should apply filtering for author filtering in SPARQL count()", async () => {
899
+ mockPerspective.modelQuery.mockResolvedValue({
900
+ instances: [],
901
+ totalCount: 3
902
+ });
1083
903
 
1084
904
  // Count recipes by Alice (should match 3 recipes)
1085
- const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
1086
-
1087
- // Verify count matches the number of instances that would be returned by findAll
1088
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
905
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1089
906
 
1090
907
  expect(count).toBe(3);
1091
- expect(count).toBe(findAllResults.length);
908
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1092
909
  });
1093
910
 
1094
- it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1095
- // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
1096
- const queryResults = [
1097
- ...Array.from({ length: 5 }, (_, i) => [
1098
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1099
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1100
- ]).flat()
1101
- ];
1102
-
1103
- mockPerspective.querySparql.mockResolvedValue(queryResults);
911
+ it("should apply filtering in ModelQueryBuilder.count() with gt operator", async () => {
912
+ mockPerspective.modelQuery.mockResolvedValue({
913
+ instances: [],
914
+ totalCount: 2
915
+ });
1104
916
 
1105
917
  // Count recipes with rating > 3 using ModelQueryBuilder
1106
918
  const count = await Recipe.query(mockPerspective)
@@ -1108,26 +920,15 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1108
920
  .engine('sparql')
1109
921
  .count();
1110
922
 
1111
- // Verify count matches the number of instances that would be returned by get()
1112
- const getResults = await Recipe.query(mockPerspective)
1113
- .where({ rating: { gt: 3 } })
1114
- .engine('sparql')
1115
- .get();
1116
-
1117
923
  expect(count).toBe(2);
1118
- expect(count).toBe(getResults.length);
924
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1119
925
  });
1120
926
 
1121
- it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1122
- // Mock query results: 5 recipes with different timestamps
1123
- const queryResults = [
1124
- ...Array.from({ length: 5 }, (_, i) => [
1125
- { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1126
- { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1127
- ]).flat()
1128
- ];
1129
-
1130
- mockPerspective.querySparql.mockResolvedValue(queryResults);
927
+ it("should apply filtering in ModelQueryBuilder.count() with timestamp between", async () => {
928
+ mockPerspective.modelQuery.mockResolvedValue({
929
+ instances: [],
930
+ totalCount: 3
931
+ });
1131
932
 
1132
933
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1133
934
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
@@ -1138,114 +939,13 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1138
939
  .engine('sparql')
1139
940
  .count();
1140
941
 
1141
- // Verify count matches the number of instances that would be returned by get()
1142
- const getResults = await Recipe.query(mockPerspective)
1143
- .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1144
- .engine('sparql')
1145
- .get();
1146
-
1147
942
  expect(count).toBe(3);
1148
- expect(count).toBe(getResults.length);
1149
- });
1150
-
1151
- it("should handle count() with Prolog for gt operator (legacy)", async () => {
1152
- const prologResults = [{ TotalCount: 2 }];
1153
- mockPerspective.infer.mockResolvedValue(prologResults);
1154
-
1155
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1156
-
1157
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1158
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1159
- expect(count).toBe(2);
943
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1160
944
  });
1161
945
 
1162
- it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1163
- const prologResults = [{ TotalCount: 3 }];
1164
- mockPerspective.infer.mockResolvedValue(prologResults);
1165
-
1166
- const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1167
- const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1168
-
1169
- const count = await Recipe.count(
1170
- mockPerspective,
1171
- { where: { timestamp: { between: [startTimestamp, endTimestamp] } } },
1172
- false
1173
- );
1174
-
1175
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1176
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1177
- expect(count).toBe(3);
1178
- });
1179
946
  });
1180
947
 
1181
948
 
1182
- // ──────────────────────────────────────────────────────────
1183
- // Batch SPARQL query builder tests
1184
- // ──────────────────────────────────────────────────────────
1185
-
1186
- import { buildBatchSPARQLQuery } from "./query-sparql-batch";
1187
-
1188
- describe("buildBatchSPARQLQuery", () => {
1189
- @Model({ name: "Author" })
1190
- class Author extends Ad4mModel {
1191
- @Property({ through: "author://name", required: true })
1192
- name!: string;
1193
- }
1194
-
1195
- @Model({ name: "Book" })
1196
- class Book extends Ad4mModel {
1197
- @Property({ through: "book://title", required: true })
1198
- title!: string;
1199
-
1200
- @HasMany(() => Author, { through: "book://author" })
1201
- authors!: Author[];
1202
- }
1203
-
1204
- it("should generate UNION branches for depth 0 and depth 1 includes", () => {
1205
- const metadata = Book.getModelMetadata();
1206
- const query = { include: { authors: true } };
1207
- const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1208
-
1209
- expect(sparql).toContain("?depth");
1210
- expect(sparql).toContain("?parentBase");
1211
- expect(sparql).toContain("?relationName");
1212
- expect(sparql).toContain("UNION");
1213
- expect(sparql).toContain("BIND(\"0\" AS ?depth)");
1214
- expect(sparql).toContain("BIND(\"1\" AS ?depth)");
1215
- expect(sparql).toContain("book://author");
1216
- });
1217
-
1218
- it("should include parent filter when query.parent is specified", () => {
1219
- const metadata = Book.getModelMetadata();
1220
- const query = {
1221
- parent: { id: "flux://library1", predicate: "library://books" },
1222
- include: { authors: true },
1223
- };
1224
- const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1225
-
1226
- expect(sparql).toContain("flux://library1");
1227
- expect(sparql).toContain("library://books");
1228
- });
1229
-
1230
- it("should include where filter for simple equality", () => {
1231
- const metadata = Book.getModelMetadata();
1232
- const query = {
1233
- where: { title: "My Book" },
1234
- include: { authors: true },
1235
- };
1236
- const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1237
-
1238
- // For literal-stored properties, SPARQL only has a JOIN (no FILTER value) — filtering in JS
1239
- expect(sparql).toContain("book://title");
1240
- expect(sparql).toContain("root_wTarget_eq_title");
1241
- });
1242
-
1243
- it("should throw when include is empty", () => {
1244
- const metadata = Book.getModelMetadata();
1245
- expect(() => buildBatchSPARQLQuery(metadata, {}, Book)).toThrow("requires query.include");
1246
- });
1247
- });
1248
-
1249
949
  describe("SPARQL comparison filters", () => {
1250
950
  @Model({ name: "Item" })
1251
951
  class Item extends Ad4mModel {
@@ -1282,7 +982,8 @@ describe("SPARQL comparison filters", () => {
1282
982
  // SPARQL Direct Triple Pattern & IRI Tests
1283
983
  // ──────────────────────────────────────────────────────────
1284
984
 
1285
- import { buildSPARQLQuery, groupSPARQLResults, formatSPARQLValue, buildSPARQLGetDataQuery } from "./query-sparql";
985
+ import { buildSPARQLQuery, formatSPARQLValue } from "./query-sparql";
986
+ import { SHACLShape } from "../shacl/SHACLShape";
1286
987
 
1287
988
  describe("SPARQL direct triple pattern generation", () => {
1288
989
  @Model({ name: "Channel" })
@@ -1322,17 +1023,14 @@ describe("SPARQL direct triple pattern generation", () => {
1322
1023
  expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
1323
1024
  });
1324
1025
 
1325
- it("uses GRAPH ?linkGraph pattern for author/timestamp", async () => {
1326
- const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1327
- expect(query).toContain("GRAPH ?linkGraph { ?source ?predicate ?target . }");
1328
- expect(query).toContain("?linkGraph <ad4m://ontology/author> ?author");
1329
- expect(query).toContain("?linkGraph <ad4m://ontology/timestamp> ?timestamp");
1330
- });
1331
-
1332
- it("does NOT contain RDF-star BIND(<< >> AS ?ann) pattern", async () => {
1026
+ it("uses RDF 1.2 reifier pattern for author/timestamp", async () => {
1333
1027
  const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1334
- expect(query).not.toContain("BIND(<<");
1335
- expect(query).not.toContain("?ann ");
1028
+ expect(query).toContain("<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>");
1029
+ expect(query).toContain("?source ?predicate ?target .");
1030
+ expect(query).toContain("?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>>");
1031
+ expect(query).toContain("?_reifier <ad4m://ontology/author> ?author");
1032
+ expect(query).toContain("?_reifier <ad4m://ontology/timestamp> ?timestamp");
1033
+ expect(query).not.toContain("GRAPH");
1336
1034
  });
1337
1035
 
1338
1036
  it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
@@ -1341,60 +1039,7 @@ describe("SPARQL direct triple pattern generation", () => {
1341
1039
  });
1342
1040
  });
1343
1041
 
1344
- describe("SPARQL IRI formatting", () => {
1345
- it("wraps AD4M URIs in angle brackets", () => {
1346
- const query = buildSPARQLGetDataQuery("ad4m://test123");
1347
- expect(query).toContain("<ad4m://test123>");
1348
- });
1349
-
1350
- it("wraps literal: URIs in angle brackets", () => {
1351
- const query = buildSPARQLGetDataQuery("literal:string:foo");
1352
- expect(query).toContain("<literal:string:foo>");
1353
- });
1354
-
1355
- it("wraps flux:// URIs in angle brackets", () => {
1356
- const query = buildSPARQLGetDataQuery("flux://has_channel");
1357
- expect(query).toContain("<flux://has_channel>");
1358
- });
1359
-
1360
- it("wraps did:key URIs in angle brackets", () => {
1361
- const query = buildSPARQLGetDataQuery("did:key:z6MkhaXg");
1362
- expect(query).toContain("<did:key:z6MkhaXg>");
1363
- });
1364
- });
1365
-
1366
- describe("groupSPARQLResults", () => {
1367
- it("groups flat rows by source URI", () => {
1368
- const rows = [
1369
- { source: "ad4m://a", predicate: "p1", target: "t1", author: "auth1", timestamp: "ts1" },
1370
- { source: "ad4m://a", predicate: "p2", target: "t2", author: "auth1", timestamp: "ts1" },
1371
- { source: "ad4m://b", predicate: "p1", target: "t3", author: "auth2", timestamp: "ts2" },
1372
- ];
1373
- const grouped = groupSPARQLResults(rows);
1374
- expect(grouped).toHaveLength(2);
1375
-
1376
- const aGroup = grouped.find(g => g.source_uri === "ad4m://a");
1377
- expect(aGroup).toBeDefined();
1378
- expect(aGroup!.links).toHaveLength(2);
1379
-
1380
- const bGroup = grouped.find(g => g.source_uri === "ad4m://b");
1381
- expect(bGroup).toBeDefined();
1382
- expect(bGroup!.links).toHaveLength(1);
1383
- });
1384
-
1385
- it("returns empty array for empty input", () => {
1386
- expect(groupSPARQLResults([])).toEqual([]);
1387
- });
1388
1042
 
1389
- it("preserves metadata in grouped links", () => {
1390
- const rows = [
1391
- { source: "x", predicate: "p", target: "t", author: "did:key:z6Mk", timestamp: "2024-01-01T00:00:00Z" },
1392
- ];
1393
- const grouped = groupSPARQLResults(rows);
1394
- expect(grouped[0].links[0].author).toBe("did:key:z6Mk");
1395
- expect(grouped[0].links[0].timestamp).toBe("2024-01-01T00:00:00Z");
1396
- });
1397
- });
1398
1043
 
1399
1044
  describe("formatSPARQLValue", () => {
1400
1045
  it("wraps strings in double quotes", () => {
@@ -1414,7 +1059,6 @@ describe("formatSPARQLValue", () => {
1414
1059
  // Comprehensive SPARQL migration unit tests
1415
1060
  // ──────────────────────────────────────────────────────────
1416
1061
 
1417
- import { matchesCondition, hydrateFromLinks } from "./hydration";
1418
1062
  import { Literal } from "../Literal";
1419
1063
 
1420
1064
  // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
@@ -1424,301 +1068,6 @@ function literalUrl(value: any): string {
1424
1068
  return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
1425
1069
  }
1426
1070
 
1427
- describe("matchesCondition()", () => {
1428
- // Simple equality
1429
- it("simple string equality — match", () => {
1430
- expect(matchesCondition("hello", "hello")).toBe(true);
1431
- });
1432
- it("simple string equality — mismatch", () => {
1433
- expect(matchesCondition("hello", "world")).toBe(false);
1434
- });
1435
- it("simple boolean equality — true", () => {
1436
- expect(matchesCondition(true, true)).toBe(true);
1437
- });
1438
- it("simple boolean equality — false", () => {
1439
- expect(matchesCondition(false, false)).toBe(true);
1440
- });
1441
- it("boolean mismatch", () => {
1442
- expect(matchesCondition(true, false)).toBe(false);
1443
- });
1444
- it("simple number equality", () => {
1445
- expect(matchesCondition(42, 42)).toBe(true);
1446
- });
1447
- it("number mismatch", () => {
1448
- expect(matchesCondition(42, 99)).toBe(false);
1449
- });
1450
-
1451
- // Array IN clause
1452
- it("array IN clause — value present", () => {
1453
- expect(matchesCondition("a", ["a", "b", "c"])).toBe(true);
1454
- });
1455
- it("array IN clause — value absent", () => {
1456
- expect(matchesCondition("d", ["a", "b", "c"])).toBe(false);
1457
- });
1458
-
1459
- // NOT operator
1460
- it("not operator with string", () => {
1461
- expect(matchesCondition("bob", { not: "alice" })).toBe(true);
1462
- expect(matchesCondition("alice", { not: "alice" })).toBe(false);
1463
- });
1464
- it("not operator with array (NOT IN)", () => {
1465
- expect(matchesCondition("a", { not: ["b", "c"] })).toBe(true);
1466
- expect(matchesCondition("b", { not: ["b", "c"] })).toBe(false);
1467
- });
1468
-
1469
- // Comparison operators
1470
- it("gt", () => {
1471
- expect(matchesCondition(10, { gt: 5 })).toBe(true);
1472
- expect(matchesCondition(5, { gt: 5 })).toBe(false);
1473
- });
1474
- it("gte", () => {
1475
- expect(matchesCondition(5, { gte: 5 })).toBe(true);
1476
- expect(matchesCondition(4, { gte: 5 })).toBe(false);
1477
- });
1478
- it("lt", () => {
1479
- expect(matchesCondition(3, { lt: 5 })).toBe(true);
1480
- expect(matchesCondition(5, { lt: 5 })).toBe(false);
1481
- });
1482
- it("lte", () => {
1483
- expect(matchesCondition(5, { lte: 5 })).toBe(true);
1484
- expect(matchesCondition(6, { lte: 5 })).toBe(false);
1485
- });
1486
- it("combined gt + lt (range)", () => {
1487
- expect(matchesCondition(5, { gt: 3, lt: 7 })).toBe(true);
1488
- expect(matchesCondition(3, { gt: 3, lt: 7 })).toBe(false);
1489
- expect(matchesCondition(7, { gt: 3, lt: 7 })).toBe(false);
1490
- });
1491
-
1492
- // Between
1493
- it("between — inclusive range", () => {
1494
- expect(matchesCondition(5, { between: [3, 7] })).toBe(true);
1495
- expect(matchesCondition(3, { between: [3, 7] })).toBe(true);
1496
- expect(matchesCondition(7, { between: [3, 7] })).toBe(true);
1497
- expect(matchesCondition(2, { between: [3, 7] })).toBe(false);
1498
- expect(matchesCondition(8, { between: [3, 7] })).toBe(false);
1499
- });
1500
-
1501
- // Contains
1502
- it("contains with string", () => {
1503
- expect(matchesCondition("hello world", { contains: "world" })).toBe(true);
1504
- expect(matchesCondition("hello world", { contains: "xyz" })).toBe(false);
1505
- });
1506
- it("contains with array", () => {
1507
- expect(matchesCondition(["a", "b", "c"], { contains: "b" })).toBe(true);
1508
- expect(matchesCondition(["a", "b", "c"], { contains: "d" })).toBe(false);
1509
- });
1510
-
1511
- // Edge cases
1512
- it("returns false for undefined value with equality check", () => {
1513
- expect(matchesCondition(undefined, "hello")).toBe(false);
1514
- });
1515
- it("returns false for empty string when condition is non-empty", () => {
1516
- expect(matchesCondition("", "Recipe 2")).toBe(false);
1517
- });
1518
- it("returns true for undefined with not operator", () => {
1519
- expect(matchesCondition(undefined, { not: "hello" })).toBe(true);
1520
- });
1521
- });
1522
-
1523
- describe("hydrateFromLinks()", () => {
1524
- // Create a mock perspective that won't be called for literal properties
1525
- const mockPerspective = {} as any;
1526
-
1527
- @Model({ name: "HydrationTest" })
1528
- class HydrationTest extends Ad4mModel {
1529
- @Property({ through: "test://name", resolveLanguage: "literal" })
1530
- name: string = "";
1531
-
1532
- @Property({ through: "test://score", resolveLanguage: "literal" })
1533
- score: number = 0;
1534
-
1535
- @Property({ through: "test://active", resolveLanguage: "literal" })
1536
- active: boolean = false;
1537
- }
1538
-
1539
- const metadata = HydrationTest.getModelMetadata();
1540
-
1541
- it("hydrates all properties when requestedProperties is undefined", async () => {
1542
- const instance = new HydrationTest(mockPerspective) as any;
1543
- const links = [
1544
- { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1545
- { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1546
- { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1547
- ];
1548
- await hydrateFromLinks(instance, links, metadata, mockPerspective, undefined);
1549
- expect(instance.name).toBe("Alice");
1550
- expect(instance.score).toBe(42);
1551
- expect(instance.active).toBe(true);
1552
- });
1553
-
1554
- it("hydrates only requested properties when requestedProperties is provided", async () => {
1555
- const instance = new HydrationTest(mockPerspective) as any;
1556
- const links = [
1557
- { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1558
- { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1559
- { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1560
- ];
1561
- await hydrateFromLinks(instance, links, metadata, mockPerspective, ["name"]);
1562
- expect(instance.name).toBe("Alice");
1563
- // score and active should remain at defaults since not requested
1564
- expect(instance.score).toBe(0);
1565
- expect(instance.active).toBe(false);
1566
- });
1567
-
1568
- it("hydrates where-clause + projection properties when both are in requestedProperties", async () => {
1569
- const instance = new HydrationTest(mockPerspective) as any;
1570
- const links = [
1571
- { predicate: "test://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1572
- { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1573
- ];
1574
- // Simulate merged hydration props: projection ["active"] + where clause props ["name"]
1575
- await hydrateFromLinks(instance, links, metadata, mockPerspective, ["active", "name"]);
1576
- expect(instance.name).toBe("Recipe 2");
1577
- expect(instance.active).toBe(true);
1578
- });
1579
-
1580
- it("sets author and timestamps from links", async () => {
1581
- const instance = new HydrationTest(mockPerspective) as any;
1582
- const links = [
1583
- { predicate: "test://name", target: literalUrl("Bob"), author: "did:author1", timestamp: "1000" },
1584
- { predicate: "test://score", target: literalUrl(10), author: "did:author2", timestamp: "2000" },
1585
- ];
1586
- await hydrateFromLinks(instance, links, metadata, mockPerspective);
1587
- expect(instance.author).toBe("did:author1");
1588
- expect(instance.createdAt).toBe(1000);
1589
- expect(instance.updatedAt).toBe(2000);
1590
- });
1591
-
1592
- it("handles empty links array", async () => {
1593
- const instance = new HydrationTest(mockPerspective) as any;
1594
- await hydrateFromLinks(instance, [], metadata, mockPerspective);
1595
- expect(instance.name).toBe("");
1596
- expect(instance.score).toBe(0);
1597
- });
1598
- });
1599
-
1600
- describe("instancesFromQueryResult — where + properties interaction", () => {
1601
- const mockPerspective = {
1602
- get: jest.fn().mockResolvedValue([]),
1603
- querySparql: jest.fn().mockResolvedValue([]),
1604
- getExpression: jest.fn().mockResolvedValue(null),
1605
- } as any;
1606
-
1607
- @Model({ name: "Recipe" })
1608
- class Recipe extends Ad4mModel {
1609
- @Property({ through: "recipe://name", resolveLanguage: "literal", required: true })
1610
- name: string = "";
1611
-
1612
- @Property({ through: "recipe://booleanTest", resolveLanguage: "literal" })
1613
- booleanTest: boolean = false;
1614
-
1615
- @Property({ through: "recipe://score", resolveLanguage: "literal" })
1616
- score: number = 0;
1617
- }
1618
-
1619
- it("should filter by where clause property even when not in properties projection", async () => {
1620
- // Simulate SPARQL result with two recipes
1621
- const grouped = [
1622
- {
1623
- source_uri: "expr:recipe1",
1624
- links: [
1625
- { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1626
- { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1627
- ],
1628
- },
1629
- {
1630
- source_uri: "expr:recipe2",
1631
- links: [
1632
- { predicate: "recipe://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1633
- { predicate: "recipe://booleanTest", target: literalUrl(false), author: "did:test", timestamp: "1000" },
1634
- ],
1635
- },
1636
- ];
1637
-
1638
- const query = { where: { name: "Recipe 2" }, properties: ["booleanTest"] };
1639
- const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1640
-
1641
- expect(results.length).toBe(1);
1642
- expect((results[0] as any).booleanTest).toBe(false);
1643
- // name should be deleted after filtering since it wasn't in properties projection
1644
- expect((results[0] as any).name).toBeUndefined();
1645
- });
1646
-
1647
- it("should delete unrequested properties AFTER where-filtering", async () => {
1648
- const grouped = [
1649
- {
1650
- source_uri: "expr:recipe1",
1651
- links: [
1652
- { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1653
- { predicate: "recipe://score", target: literalUrl(99), author: "did:test", timestamp: "1000" },
1654
- ],
1655
- },
1656
- ];
1657
-
1658
- const query = { where: { name: "Recipe 1" }, properties: ["score"] };
1659
- const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1660
-
1661
- expect(results.length).toBe(1);
1662
- expect((results[0] as any).score).toBe(99);
1663
- // name was used for filtering but should be deleted from final result
1664
- expect((results[0] as any).name).toBeUndefined();
1665
- });
1666
-
1667
- it("should return all properties when no projection is specified", async () => {
1668
- const grouped = [
1669
- {
1670
- source_uri: "expr:recipe1",
1671
- links: [
1672
- { predicate: "recipe://name", target: literalUrl("Test"), author: "did:test", timestamp: "1000" },
1673
- { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1674
- { predicate: "recipe://score", target: literalUrl(50), author: "did:test", timestamp: "1000" },
1675
- ],
1676
- },
1677
- ];
1678
-
1679
- const query = { where: { name: "Test" } };
1680
- const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1681
-
1682
- expect(results.length).toBe(1);
1683
- expect((results[0] as any).name).toBe("Test");
1684
- expect((results[0] as any).booleanTest).toBe(true);
1685
- expect((results[0] as any).score).toBe(50);
1686
- });
1687
- });
1688
-
1689
- describe("groupSPARQLResults()", () => {
1690
- it("groups rows by source", () => {
1691
- const rows = [
1692
- { source: "a", predicate: "p1", target: "t1", author: "auth", timestamp: "ts1" },
1693
- { source: "a", predicate: "p2", target: "t2", author: "auth", timestamp: "ts2" },
1694
- { source: "b", predicate: "p1", target: "t3", author: "auth", timestamp: "ts3" },
1695
- ];
1696
- const grouped = groupSPARQLResults(rows);
1697
- expect(grouped.length).toBe(2);
1698
- const groupA = grouped.find(g => g.source_uri === "a")!;
1699
- const groupB = grouped.find(g => g.source_uri === "b")!;
1700
- expect(groupA.links.length).toBe(2);
1701
- expect(groupB.links.length).toBe(1);
1702
- });
1703
-
1704
- it("handles empty input", () => {
1705
- expect(groupSPARQLResults([])).toEqual([]);
1706
- });
1707
-
1708
- it("preserves link metadata", () => {
1709
- const rows = [
1710
- { source: "x", predicate: "pred", target: "tgt", author: "did:auth", timestamp: "2024-01-01" },
1711
- ];
1712
- const grouped = groupSPARQLResults(rows);
1713
- expect(grouped[0].links[0]).toEqual({
1714
- predicate: "pred",
1715
- target: "tgt",
1716
- author: "did:auth",
1717
- timestamp: "2024-01-01",
1718
- });
1719
- });
1720
- });
1721
-
1722
1071
  describe("buildSPARQLQuery edge cases", () => {
1723
1072
  @Model({ name: "FlagModel" })
1724
1073
  class FlagModel extends Ad4mModel {
@@ -1772,93 +1121,18 @@ describe("buildSPARQLQuery edge cases", () => {
1772
1121
  });
1773
1122
  });
1774
1123
 
1775
- describe("sparse fieldset property deletion timing", () => {
1776
- const mockPerspective = {
1777
- get: jest.fn().mockResolvedValue([]),
1778
- querySparql: jest.fn().mockResolvedValue([]),
1779
- getExpression: jest.fn().mockResolvedValue(null),
1780
- } as any;
1781
-
1782
- @Model({ name: "TimingTest" })
1783
- class TimingTest extends Ad4mModel {
1784
- @Property({ through: "timing://a", resolveLanguage: "literal" })
1785
- a: string = "";
1786
-
1787
- @Property({ through: "timing://b", resolveLanguage: "literal" })
1788
- b: string = "";
1789
-
1790
- @Property({ through: "timing://c", resolveLanguage: "literal" })
1791
- c: string = "";
1792
- }
1793
-
1794
- it("where-clause properties are available during filtering but deleted after", async () => {
1795
- const grouped = [
1796
- {
1797
- source_uri: "expr:1",
1798
- links: [
1799
- { predicate: "timing://a", target: literalUrl("match"), author: "did:test", timestamp: "1000" },
1800
- { predicate: "timing://b", target: literalUrl("keep"), author: "did:test", timestamp: "1000" },
1801
- { predicate: "timing://c", target: literalUrl("ignore"), author: "did:test", timestamp: "1000" },
1802
- ],
1803
- },
1804
- {
1805
- source_uri: "expr:2",
1806
- links: [
1807
- { predicate: "timing://a", target: literalUrl("no-match"), author: "did:test", timestamp: "1000" },
1808
- { predicate: "timing://b", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1809
- { predicate: "timing://c", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1810
- ],
1811
- },
1812
- ];
1813
-
1814
- // properties projection asks for "b" only, where clause filters on "a"
1815
- const query = { where: { a: "match" }, properties: ["b"] };
1816
- const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1817
-
1818
- // Only the matching instance should survive
1819
- expect(results.length).toBe(1);
1820
- // "b" was requested — should be present
1821
- expect((results[0] as any).b).toBe("keep");
1822
- // "a" was used for filtering but not in projection — should be deleted
1823
- expect((results[0] as any).a).toBeUndefined();
1824
- // "c" was not requested — should be deleted
1825
- expect((results[0] as any).c).toBeUndefined();
1826
- });
1827
-
1828
- it("properties not in projection are undefined after instancesFromQueryResult", async () => {
1829
- const grouped = [
1830
- {
1831
- source_uri: "expr:1",
1832
- links: [
1833
- { predicate: "timing://a", target: literalUrl("val-a"), author: "did:test", timestamp: "1000" },
1834
- { predicate: "timing://b", target: literalUrl("val-b"), author: "did:test", timestamp: "1000" },
1835
- { predicate: "timing://c", target: literalUrl("val-c"), author: "did:test", timestamp: "1000" },
1836
- ],
1837
- },
1838
- ];
1839
-
1840
- const query = { properties: ["a"] };
1841
- const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1842
-
1843
- expect(results.length).toBe(1);
1844
- expect((results[0] as any).a).toBe("val-a");
1845
- expect((results[0] as any).b).toBeUndefined();
1846
- expect((results[0] as any).c).toBeUndefined();
1847
- });
1848
- });
1849
-
1850
- // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1851
- describe("Batch hydration for reverse relations", () => {
1852
- it("batch hydration should correctly group targets by parent instance ID", () => {
1853
- // Test the grouping logic used in batch SPARQL hydration
1854
- const sparqlResults = [
1855
- { target: "inst:1", source: "child:a" },
1856
- { target: "inst:1", source: "child:b" },
1857
- { target: "inst:2", source: "child:c" },
1858
- { target: "inst:3", source: "child:d" },
1859
- { target: "inst:3", source: "child:e" },
1860
- { target: "inst:3", source: "child:f" },
1861
- ];
1124
+ // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1125
+ describe("Batch hydration for reverse relations", () => {
1126
+ it("batch hydration should correctly group targets by parent instance ID", () => {
1127
+ // Test the grouping logic used in batch SPARQL hydration
1128
+ const sparqlResults = [
1129
+ { target: "inst:1", source: "child:a" },
1130
+ { target: "inst:1", source: "child:b" },
1131
+ { target: "inst:2", source: "child:c" },
1132
+ { target: "inst:3", source: "child:d" },
1133
+ { target: "inst:3", source: "child:e" },
1134
+ { target: "inst:3", source: "child:f" },
1135
+ ];
1862
1136
 
1863
1137
  const reverseLinksMap = new Map<string, string[]>();
1864
1138
  for (const row of sparqlResults) {
@@ -2029,240 +1303,247 @@ describe("Lightweight fingerprint optimization", () => {
2029
1303
  });
2030
1304
  });
2031
1305
 
2032
- // ── Native SPARQL getter evaluation ──────────────────────────────────────────
2033
- describe("Native SPARQL getter evaluation", () => {
2034
- const { evaluateCustomGettersForInstance } = require("./hydration");
2035
1306
 
2036
- const mockPerspective = {
2037
- getLinks: jest.fn().mockResolvedValue([]),
2038
- querySparql: jest.fn(),
2039
- get: jest.fn().mockResolvedValue([]),
2040
- };
2041
1307
 
2042
- beforeEach(() => {
2043
- jest.clearAllMocks();
2044
- });
1308
+ // ── Subscribe callback timing ──────────────────────────────────────────
1309
+ describe("ModelQueryBuilder subscribe callback timing", () => {
1310
+ it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
1311
+ // This test verifies that subscribe() uses the Rust model subscription endpoint
1312
+ // and properly handles the subscription lifecycle.
1313
+
1314
+ const mockSubscriptionId = "test-sub-123";
1315
+ let updateCallback: ((result: any) => void) | null = null;
2045
1316
 
2046
- it("should execute SELECT getter directly via querySparql", async () => {
2047
- const metadata = {
2048
- properties: {
2049
- replyingTo: {
2050
- predicate: "flux://has_reply",
2051
- getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
2052
- type: "string",
2053
- }
2054
- },
2055
- relations: {},
1317
+ const mockClient = {
1318
+ modelSubscribe: jest.fn().mockResolvedValue({
1319
+ subscriptionId: mockSubscriptionId,
1320
+ result: { instances: [], totalCount: 0 },
1321
+ }),
1322
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1323
+ updateCallback = cb;
1324
+ return () => {}; // unsubscribe function
1325
+ }),
1326
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1327
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
2056
1328
  };
2057
1329
 
2058
- mockPerspective.querySparql.mockResolvedValue([
2059
- { target: { value: "literal:string:msg123" } }
2060
- ]);
1330
+ const mockPerspective = {
1331
+ uuid: "test-uuid",
1332
+ client: mockClient,
1333
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1334
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1335
+ }),
1336
+ getLinks: jest.fn().mockResolvedValue([]),
1337
+ modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
1338
+ } as any;
2061
1339
 
2062
- const instance = { id: "test://msg1", replyingTo: undefined };
2063
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1340
+ const { Ad4mModel, Model, Property, Flag } = require("./index");
2064
1341
 
2065
- expect(mockPerspective.querySparql).toHaveBeenCalledWith(
2066
- expect.stringContaining("SELECT ?target WHERE")
2067
- );
2068
- expect(instance.replyingTo).toBe("literal:string:msg123");
2069
- });
1342
+ @Model({ name: "TimingTest" })
1343
+ class TimingTest extends Ad4mModel {
1344
+ @Flag({ through: "test://type", value: "test://timing" })
1345
+ type: string = "test://timing";
1346
+ @Property({ through: "test://name" })
1347
+ name: string = "";
1348
+ }
2070
1349
 
2071
- it("should execute ASK getter and return boolean", async () => {
2072
- const metadata = {
2073
- properties: {
2074
- isPopular: {
2075
- predicate: "flux://is_popular",
2076
- getter: 'ASK WHERE { SELECT (COUNT(DISTINCT ?reactor) AS ?count) WHERE { ?reactor <flux://reaction> ?source . } HAVING(?count > 5) }',
2077
- type: "boolean",
2078
- readOnly: true,
2079
- }
2080
- },
2081
- relations: {},
2082
- };
1350
+ let callbackInvokedBeforeResolve = false;
1351
+ let promiseResolved = false;
1352
+
1353
+ const query = TimingTest.query(mockPerspective);
1354
+ const promise = query.subscribe((results: any[]) => {
1355
+ if (!promiseResolved) {
1356
+ callbackInvokedBeforeResolve = true;
1357
+ }
1358
+ });
2083
1359
 
2084
- mockPerspective.querySparql.mockResolvedValue(true);
1360
+ // At this point the Promise hasn't resolved yet
1361
+ // The callback should NOT have fired synchronously
1362
+ expect(callbackInvokedBeforeResolve).toBe(false);
2085
1363
 
2086
- const instance = { id: "test://msg1", isPopular: false };
2087
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1364
+ const initialResults = await promise;
1365
+ promiseResolved = true;
2088
1366
 
2089
- expect(mockPerspective.querySparql).toHaveBeenCalledWith(
2090
- expect.stringContaining("ASK WHERE")
2091
- );
2092
- expect(instance.isPopular).toBe(true);
1367
+ expect(initialResults).toEqual([]);
1368
+ expect(mockPerspective.modelSubscribe).toHaveBeenCalled();
2093
1369
  });
1370
+ });
2094
1371
 
2095
- it("should replace ?source with instance ID in SPARQL getter", async () => {
2096
- const metadata = {
2097
- properties: {
2098
- author: {
2099
- predicate: "test://author",
2100
- getter: 'SELECT ?target WHERE { ?source <test://author> ?target . }',
2101
- type: "string",
2102
- }
2103
- },
2104
- relations: {},
1372
+ describe("ModelQueryBuilder paginateSubscribe", () => {
1373
+ it("paginateSubscribe should use a single query with count: true", async () => {
1374
+ const mockSubscriptionId = "paginate-sub-123";
1375
+
1376
+ const mockClient = {
1377
+ modelSubscribe: jest.fn().mockResolvedValue({
1378
+ subscriptionId: mockSubscriptionId,
1379
+ result: { instances: [], totalCount: 0 },
1380
+ }),
1381
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, _cb: any) => {
1382
+ return () => {};
1383
+ }),
1384
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1385
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
2105
1386
  };
2106
1387
 
2107
- mockPerspective.querySparql.mockResolvedValue([
2108
- { target: { value: "did:key:abc123" } }
2109
- ]);
1388
+ const mockPerspective = {
1389
+ uuid: "test-uuid",
1390
+ client: mockClient,
1391
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1392
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1393
+ }),
1394
+ modelQuery: jest.fn().mockResolvedValue({ instances: [{ id: "item1", type: "test://paginate" }], totalCount: 42 }),
1395
+ } as any;
2110
1396
 
2111
- const instance = { id: "test://post1", author: undefined };
2112
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1397
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
2113
1398
 
2114
- expect(mockPerspective.querySparql).toHaveBeenCalledWith(
2115
- expect.stringContaining("<test://post1>")
2116
- );
2117
- expect(mockPerspective.querySparql).not.toHaveBeenCalledWith(
2118
- expect.stringContaining("?source")
2119
- );
2120
- });
1399
+ @Model({ name: "PaginateTest" })
1400
+ class PaginateTest extends Ad4mModel {
1401
+ @Flag({ through: "test://type", value: "test://paginate" })
1402
+ type: string = "test://paginate";
1403
+ @Property({ through: "test://name" })
1404
+ name: string = "";
1405
+ }
2121
1406
 
2122
- it("should handle empty SPARQL results gracefully", async () => {
2123
- const metadata = {
2124
- properties: {
2125
- replyingTo: {
2126
- predicate: "flux://has_reply",
2127
- getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
2128
- type: "string",
2129
- }
2130
- },
2131
- relations: {},
2132
- };
1407
+ const builder = PaginateTest.query(mockPerspective);
1408
+ const result = await builder.paginateSubscribe(10, 1, () => {});
2133
1409
 
2134
- mockPerspective.querySparql.mockResolvedValue([]);
1410
+ // Should return paginated result structure
1411
+ expect(result).toHaveProperty("results");
1412
+ expect(result).toHaveProperty("totalCount");
1413
+ expect(result).toHaveProperty("pageSize", 10);
1414
+ expect(result).toHaveProperty("pageNumber", 1);
2135
1415
 
2136
- const instance = { id: "test://msg1", replyingTo: "original" };
2137
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1416
+ // modelQuery should be called exactly once (not twice — no separate count query)
1417
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
2138
1418
 
2139
- // Should not overwrite with undefined
2140
- expect(instance.replyingTo).toBe("original");
1419
+ // The query should have count: true
1420
+ const callArgs = mockPerspective.modelQuery.mock.calls[0];
1421
+ const queryJson = JSON.parse(callArgs[1]);
1422
+ expect(queryJson.count).toBe(true);
1423
+ expect(queryJson.limit).toBe(10);
1424
+ expect(queryJson.offset).toBe(0);
2141
1425
  });
2142
1426
 
2143
- it("should handle SPARQL getter errors without crashing", async () => {
2144
- const metadata = {
2145
- properties: {
2146
- broken: {
2147
- predicate: "test://broken",
2148
- getter: 'SELECT ?target WHERE { INVALID SPARQL }',
2149
- type: "string",
2150
- }
2151
- },
2152
- relations: {},
2153
- };
1427
+ it("paginateSubscribe should skip isInit messages from subscription", async () => {
1428
+ const mockSubscriptionId = "paginate-init-sub";
1429
+ let capturedCallback: ((result: any) => void) | null = null;
2154
1430
 
2155
- mockPerspective.querySparql.mockRejectedValue(new Error("SPARQL parse error"));
1431
+ const mockClient = {
1432
+ modelSubscribe: jest.fn().mockResolvedValue({
1433
+ subscriptionId: mockSubscriptionId,
1434
+ result: { instances: [], totalCount: 0 },
1435
+ }),
1436
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1437
+ capturedCallback = cb;
1438
+ return () => {};
1439
+ }),
1440
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1441
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1442
+ };
2156
1443
 
2157
- const instance = { id: "test://msg1", broken: undefined };
2158
- const consoleSpy = jest.spyOn(console, "warn").mockImplementation();
2159
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2160
- consoleSpy.mockRestore();
1444
+ let modelQueryCallCount = 0;
1445
+ const mockPerspective = {
1446
+ uuid: "test-uuid",
1447
+ client: mockClient,
1448
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1449
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1450
+ }),
1451
+ modelQuery: jest.fn().mockImplementation(async () => {
1452
+ modelQueryCallCount++;
1453
+ return { instances: [], totalCount: 0 };
1454
+ }),
1455
+ } as any;
2161
1456
 
2162
- // Should not throw, should warn
2163
- expect(instance.broken).toBeUndefined();
2164
- });
1457
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
2165
1458
 
2166
- it("should execute SPARQL getter for relations", async () => {
2167
- const metadata = {
2168
- properties: {},
2169
- relations: {
2170
- tags: {
2171
- predicate: "test://has_tag",
2172
- getter: 'SELECT ?target WHERE { ?source <test://has_tag> ?target . }',
2173
- direction: "forward",
2174
- }
2175
- },
2176
- };
1459
+ @Model({ name: "InitGuardTest" })
1460
+ class InitGuardTest extends Ad4mModel {
1461
+ @Flag({ through: "test://type", value: "test://init" })
1462
+ type: string = "test://init";
1463
+ @Property({ through: "test://name" })
1464
+ name: string = "";
1465
+ }
2177
1466
 
2178
- mockPerspective.querySparql.mockResolvedValue([
2179
- { target: { value: "tag:a" } },
2180
- { target: { value: "tag:b" } },
2181
- ]);
1467
+ const userCallback = jest.fn();
1468
+ const builder = InitGuardTest.query(mockPerspective);
1469
+ await builder.paginateSubscribe(10, 1, userCallback);
2182
1470
 
2183
- const instance = { id: "test://post1", tags: [] };
2184
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1471
+ // Reset the count after initial fetch
1472
+ const initialCallCount = modelQueryCallCount;
2185
1473
 
2186
- expect(instance.tags).toEqual(["tag:a", "tag:b"]);
2187
- });
1474
+ // Simulate an isInit message from subscription
1475
+ expect(capturedCallback).not.toBeNull();
1476
+ capturedCallback!({ isInit: true });
2188
1477
 
2189
- it("should warn for legacy SurrealDB-style getter syntax instead of converting", async () => {
2190
- const metadata = {
2191
- properties: {
2192
- legacy: {
2193
- predicate: "test://legacy",
2194
- getter: "(<-link[WHERE predicate = 'test://legacy'].in.uri)[0]",
2195
- type: "string",
2196
- }
2197
- },
2198
- relations: {},
2199
- };
1478
+ // Wait for any async processing
1479
+ await new Promise(r => setTimeout(r, 50));
2200
1480
 
2201
- const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
1481
+ // modelQuery should NOT have been called again (isInit was filtered)
1482
+ expect(modelQueryCallCount).toBe(initialCallCount);
1483
+ // User callback should NOT have been invoked by isInit
1484
+ expect(userCallback).not.toHaveBeenCalled();
1485
+ });
2202
1486
 
2203
- const instance = { id: "test://msg1", legacy: undefined };
2204
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2205
-
2206
- // Should NOT call querySparql — legacy getters are no longer converted
2207
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
2208
- // Should warn about unsupported syntax
2209
- expect(warnSpy).toHaveBeenCalledWith(
2210
- expect.stringContaining("Unsupported legacy getter syntax")
2211
- );
2212
- // Value should remain undefined
2213
- expect(instance.legacy).toBeUndefined();
1487
+ it("paginateSubscribe should re-fetch on real subscription updates", async () => {
1488
+ const mockSubscriptionId = "paginate-update-sub";
1489
+ let capturedCallback: ((result: any) => void) | null = null;
2214
1490
 
2215
- warnSpy.mockRestore();
2216
- });
2217
- });
1491
+ const mockClient = {
1492
+ modelSubscribe: jest.fn().mockResolvedValue({
1493
+ subscriptionId: mockSubscriptionId,
1494
+ result: { instances: [], totalCount: 0 },
1495
+ }),
1496
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1497
+ capturedCallback = cb;
1498
+ return () => {};
1499
+ }),
1500
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1501
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1502
+ };
2218
1503
 
2219
- // ── Subscribe callback timing ──────────────────────────────────────────
2220
- describe("ModelQueryBuilder subscribe callback timing", () => {
2221
- it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
2222
- // This test verifies that the initial callback from subscribe() is deferred
2223
- // via queueMicrotask, preventing Preact/React hook lifecycle violations
2224
- // when subscribe() is called from useEffect.
2225
-
1504
+ let modelQueryCallCount = 0;
2226
1505
  const mockPerspective = {
2227
- getLinks: jest.fn().mockResolvedValue([]),
2228
- subscribeQuery: jest.fn().mockResolvedValue({
2229
- result: '[]',
2230
- onResult: jest.fn(),
2231
- dispose: jest.fn(),
1506
+ uuid: "test-uuid",
1507
+ client: mockClient,
1508
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1509
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1510
+ }),
1511
+ modelQuery: jest.fn().mockImplementation(async () => {
1512
+ modelQueryCallCount++;
1513
+ return { instances: [{ id: "new-item", type: "test://update" }], totalCount: 1 };
2232
1514
  }),
2233
- querySparql: jest.fn().mockResolvedValue('[]'),
2234
1515
  } as any;
2235
1516
 
2236
- const { Ad4mModel, Model, Property, Flag } = require("./index");
1517
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
2237
1518
 
2238
- @Model({ name: "TimingTest" })
2239
- class TimingTest extends Ad4mModel {
2240
- @Flag({ through: "test://type", value: "test://timing" })
2241
- type: string = "test://timing";
1519
+ @Model({ name: "UpdateTest" })
1520
+ class UpdateTest extends Ad4mModel {
1521
+ @Flag({ through: "test://type", value: "test://update" })
1522
+ type: string = "test://update";
2242
1523
  @Property({ through: "test://name" })
2243
1524
  name: string = "";
2244
1525
  }
2245
1526
 
2246
- let callbackInvokedBeforeResolve = false;
2247
- let promiseResolved = false;
1527
+ const userCallback = jest.fn();
1528
+ const builder = UpdateTest.query(mockPerspective);
1529
+ await builder.paginateSubscribe(10, 1, userCallback);
2248
1530
 
2249
- const query = TimingTest.query(mockPerspective);
2250
- const promise = query.subscribe((results: any[]) => {
2251
- if (!promiseResolved) {
2252
- callbackInvokedBeforeResolve = true;
2253
- }
2254
- });
1531
+ const initialCallCount = modelQueryCallCount;
2255
1532
 
2256
- // At this point the Promise hasn't resolved yet
2257
- // The callback should NOT have fired synchronously
2258
- expect(callbackInvokedBeforeResolve).toBe(false);
1533
+ // Simulate a real subscription update (not isInit)
1534
+ capturedCallback!({ instances: [{ id: "new-item" }], totalCount: 1 });
2259
1535
 
2260
- await promise;
2261
- promiseResolved = true;
1536
+ // Wait for async processing
1537
+ await new Promise(r => setTimeout(r, 100));
2262
1538
 
2263
- // After the microtask queue drains, the callback should fire
2264
- await new Promise(r => setTimeout(r, 10));
2265
- // The callback was deferred — it fires after the Promise resolves
1539
+ // modelQuery should have been called again for the re-fetch
1540
+ expect(modelQueryCallCount).toBeGreaterThan(initialCallCount);
1541
+ // User callback should have been invoked with paginated results
1542
+ expect(userCallback).toHaveBeenCalled();
1543
+ const callArg = userCallback.mock.calls[0][0];
1544
+ expect(callArg).toHaveProperty("totalCount");
1545
+ expect(callArg).toHaveProperty("pageSize", 10);
1546
+ expect(callArg).toHaveProperty("pageNumber", 1);
2266
1547
  });
2267
1548
  });
2268
1549
 
@@ -2271,7 +1552,6 @@ describe("ModelQueryBuilder subscribe callback timing", () => {
2271
1552
  // ============================================================================
2272
1553
 
2273
1554
  import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
2274
- import { clearSubscriptionPool, subscriptionPoolSize } from "./subscription-pool";
2275
1555
  import { getPropertiesMetadata, getRelationsMetadata, getMemoizedSHACL } from "./decorators";
2276
1556
 
2277
1557
  describe("QueryCache", () => {
@@ -2399,65 +1679,10 @@ describe("Lazy Conformance Filters", () => {
2399
1679
  });
2400
1680
 
2401
1681
  // ──────────────────────────────────────────────────────────
2402
- // instancesFromQueryResult — SPARQL vs JS pagination behaviour
2403
- // ──────────────────────────────────────────────────────────
2404
-
2405
- describe("instancesFromQueryResult — SPARQL vs JS pagination", () => {
2406
- @Model({ name: "PaginationTestChannel" })
2407
- class PaginationTestChannel extends Ad4mModel {
2408
- @Flag({ through: "flux://entry_type", value: "flux://channel" })
2409
- type: string = "";
2410
-
2411
- @Property({ through: "flux://name", resolveLanguage: "literal" })
2412
- name: string = "";
2413
- }
2414
-
2415
- const mockPerspective: any = {
2416
- uuid: "test-uuid",
2417
- querySparql: jest.fn().mockResolvedValue([]),
2418
- get: jest.fn().mockResolvedValue([]),
2419
- getExpression: jest.fn().mockResolvedValue(null),
2420
- };
2421
-
2422
- it("does NOT slice results when SPARQL pagination was applied", async () => {
2423
- const grouped = Array.from({ length: 5 }, (_, i) => ({
2424
- source_uri: `flux://ch-${i}`,
2425
- links: [
2426
- { predicate: "flux://entry_type", target: "flux://channel", author: "did:key:a", timestamp: String(1000 + i) },
2427
- { predicate: "flux://name", target: `literal:string:Channel${i}`, author: "did:key:a", timestamp: String(1000 + i) },
2428
- ],
2429
- }));
2430
-
2431
- // Include order to trigger SPARQL-level pagination (subquery with ORDER BY)
2432
- const query = { limit: 5, offset: 10, order: { name: 'ASC' as const } };
2433
- const result = await (PaginationTestChannel as any).instancesFromQueryResult(mockPerspective, query, grouped);
2434
-
2435
- // sparqlPaginated = true (limit+offset+order present, no JS-only where filters),
2436
- // so JS should NOT re-slice — all 5 items come through as-is.
2437
- expect(result.results.length).toBe(5);
2438
- expect(result.totalCount).toBe(5);
2439
- });
2440
-
2441
- it("applies JS-level slicing as fallback when JS-only filters exist", async () => {
2442
- const grouped = Array.from({ length: 10 }, (_, i) => ({
2443
- source_uri: `flux://ch-${i}`,
2444
- links: [
2445
- { predicate: "flux://entry_type", target: "flux://channel", author: "did:key:a", timestamp: String(1000 + i) },
2446
- { predicate: "flux://name", target: `literal:string:Ch${i}`, author: "did:key:a", timestamp: String(1000 + i) },
2447
- ],
2448
- }));
2449
-
2450
- const query = { limit: 3, offset: 0, where: { author: "did:key:a" } };
2451
- const result = await (PaginationTestChannel as any).instancesFromQueryResult(mockPerspective, query, grouped);
2452
- expect(result.results.length).toBe(3);
2453
- });
2454
- });
2455
-
2456
- // ──────────────────────────────────────────────────────────
2457
- // deepQuery opt-in — getter evaluation on collection queries
1682
+ // deepQuery — getter evaluation on collection queries
2458
1683
  // ──────────────────────────────────────────────────────────
2459
1684
 
2460
- describe("deepQuery opt-in — getter evaluation", () => {
1685
+ describe("deepQuery — getter evaluation", () => {
2461
1686
  @Model({ name: "DeepQueryTestMessage" })
2462
1687
  class DeepQueryTestMessage extends Ad4mModel {
2463
1688
  @Flag({ through: "flux://entry_type", value: "flux://message" })
@@ -2485,6 +1710,23 @@ describe("deepQuery opt-in — getter evaluation", () => {
2485
1710
  let sparqlCalls: string[];
2486
1711
  const mockPerspective: any = {
2487
1712
  uuid: "test-uuid",
1713
+ modelQuery: jest.fn(async (className: string, queryJson: string, shapeJson: string) => {
1714
+ // Return a basic result for the single-instance getData() path
1715
+ const query = JSON.parse(queryJson);
1716
+ const id = query?.where?.id;
1717
+ if (id) {
1718
+ return {
1719
+ instances: [{ id, body: "Hello" }],
1720
+ totalCount: 1,
1721
+ };
1722
+ }
1723
+ return { instances: [], totalCount: 0 };
1724
+ }),
1725
+ evaluateGetters: jest.fn(async (className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]) => {
1726
+ // Return empty results by default — tests can override this mock
1727
+ const result: Record<string, Record<string, any>> = {};
1728
+ return result;
1729
+ }),
2488
1730
  querySparql: jest.fn(async (q: string) => {
2489
1731
  sparqlCalls.push(q);
2490
1732
  return [];
@@ -2497,42 +1739,18 @@ describe("deepQuery opt-in — getter evaluation", () => {
2497
1739
  beforeEach(() => {
2498
1740
  sparqlCalls = [];
2499
1741
  mockPerspective.querySparql.mockClear();
1742
+ mockPerspective.evaluateGetters.mockClear();
1743
+ mockPerspective.modelQuery.mockClear();
2500
1744
  mockPerspective.get.mockClear();
2501
1745
  });
2502
1746
 
2503
- function makeMessageRows(count: number) {
2504
- return Array.from({ length: count }, (_, i) => ({
2505
- source_uri: `flux://msg-${i}`,
2506
- links: [
2507
- { predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: String(2000 + i) },
2508
- { predicate: "flux://body", target: `literal:string:Hello${i}`, author: "did:key:a", timestamp: String(2000 + i) },
2509
- ],
2510
- }));
2511
- }
2512
-
2513
- it("skips getter evaluation on collection queries by default", async () => {
2514
- const grouped = makeMessageRows(5);
2515
- const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
2516
- expect(result.results.length).toBe(5);
2517
-
2518
- const getterCalls = sparqlCalls.filter(
2519
- (q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
1747
+ function makeInstances(count: number): InstanceType<typeof DeepQueryTestMessage>[] {
1748
+ return Array.from({ length: count }, (_, i) =>
1749
+ new DeepQueryTestMessage(mockPerspective, `flux://msg-${i}`)
2520
1750
  );
2521
- expect(getterCalls.length).toBe(0);
2522
- });
2523
-
2524
- it("evaluates getter properties when deepQuery is true", async () => {
2525
- const grouped = makeMessageRows(3);
2526
- const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, { deepQuery: true }, grouped);
2527
- expect(result.results.length).toBe(3);
2528
-
2529
- const getterCalls = sparqlCalls.filter(
2530
- (q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
2531
- );
2532
- expect(getterCalls.length).toBe(6); // 3 instances × 2 getters
2533
- });
1751
+ }
2534
1752
 
2535
- it("single-instance get() still evaluates getters by default", async () => {
1753
+ it("single-instance get() delegates getter evaluation to Rust (no JS-side SPARQL)", async () => {
2536
1754
  const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
2537
1755
  mockPerspective.querySparql.mockImplementation(async (q: string) => {
2538
1756
  sparqlCalls.push(q);
@@ -2546,43 +1764,58 @@ describe("deepQuery opt-in — getter evaluation", () => {
2546
1764
  });
2547
1765
 
2548
1766
  await instance.get();
1767
+ // Getter evaluation now happens Rust-side via evaluate_getters() — no JS SPARQL calls
2549
1768
  const getterCalls = sparqlCalls.filter(
2550
1769
  (q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
2551
1770
  );
2552
- expect(getterCalls.length).toBe(2);
1771
+ expect(getterCalls.length).toBe(0);
2553
1772
  });
2554
1773
 
2555
1774
  describe("Ad4mModel.evaluateGetters()", () => {
2556
- it("resolves getters for a batch of instances", async () => {
2557
- const grouped = makeMessageRows(4);
2558
- const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
2559
- sparqlCalls = [];
1775
+ it("resolves getters for a batch of instances via single RPC", async () => {
1776
+ const instances = makeInstances(4);
1777
+
1778
+ await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
1779
+
1780
+ // Should make exactly 1 RPC call via perspective.evaluateGetters
1781
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1782
+ const [className, instanceIds, shapeJson, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1783
+ expect(className).toBe("DeepQueryTestMessage");
1784
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1785
+ expect(propertyNames).toEqual(["replyingTo"]);
1786
+ // No querySparql calls — all done in-process
1787
+ expect(sparqlCalls.length).toBe(0);
1788
+ });
2560
1789
 
2561
- await DeepQueryTestMessage.evaluateGetters(result.results.slice(0, 2), mockPerspective, ["replyingTo"]);
1790
+ it("evaluates all getters when propertyNames is omitted", async () => {
1791
+ const instances = makeInstances(2);
2562
1792
 
2563
- const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2564
- expect(replyCalls.length).toBe(2);
2565
- const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2566
- expect(popularCalls.length).toBe(0);
1793
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
1794
+
1795
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1796
+ const [className, instanceIds, shapeJson, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1797
+ expect(className).toBe("DeepQueryTestMessage");
1798
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1799
+ expect(propertyNames).toBeUndefined();
2567
1800
  });
2568
1801
 
2569
- it("evaluates all getters when propertyNames is omitted", async () => {
2570
- const grouped = makeMessageRows(2);
2571
- const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
2572
- sparqlCalls = [];
1802
+ it("applies results to instances and syncs snapshots", async () => {
1803
+ const instances = makeInstances(2);
1804
+ // Simulate Rust returning getter results
1805
+ mockPerspective.evaluateGetters.mockResolvedValueOnce({
1806
+ "flux://msg-0": { replyingTo: "flux://msg-99" },
1807
+ "flux://msg-1": { replyingTo: "flux://msg-88" },
1808
+ });
2573
1809
 
2574
- await DeepQueryTestMessage.evaluateGetters(result.results, mockPerspective);
1810
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective, ["replyingTo"]);
2575
1811
 
2576
- const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2577
- const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2578
- expect(replyCalls.length).toBe(2);
2579
- expect(popularCalls.length).toBe(2);
1812
+ expect((instances[0] as any).replyingTo).toBe("flux://msg-99");
1813
+ expect((instances[1] as any).replyingTo).toBe("flux://msg-88");
2580
1814
  });
2581
1815
 
2582
1816
  it("handles empty array gracefully", async () => {
2583
- sparqlCalls = [];
2584
1817
  await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
2585
- expect(sparqlCalls.length).toBe(0);
1818
+ expect(mockPerspective.evaluateGetters).not.toHaveBeenCalled();
2586
1819
  });
2587
1820
  });
2588
1821
 
@@ -2592,5 +1825,365 @@ describe("deepQuery opt-in — getter evaluation", () => {
2592
1825
  (builder as any).deepQuery();
2593
1826
  expect((builder as any).queryParams.deepQuery).toBe(true);
2594
1827
  });
1828
+
1829
+ it("deepQuery defaults to true when not explicitly set", async () => {
1830
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1831
+ await DeepQueryTestMessage.query(mockPerspective).get();
1832
+
1833
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1834
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1835
+ const qi = JSON.parse(queryJson);
1836
+ expect(qi.deepQuery).toBe(true);
1837
+ });
1838
+
1839
+ it("deepQuery can be explicitly set to false", async () => {
1840
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1841
+ await DeepQueryTestMessage.query(mockPerspective).deepQuery(false).get();
1842
+
1843
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1844
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1845
+ const qi = JSON.parse(queryJson);
1846
+ expect(qi.deepQuery).toBe(false);
1847
+ });
1848
+ });
1849
+ });
1850
+
1851
+ // ─── Ad4mModel.fromSHACL() ───────────────────────────────────────────────────
1852
+
1853
+ describe("Ad4mModel.fromSHACL()", () => {
1854
+ function makeShape(targetClass: string, props: Array<import("../shacl/SHACLShape").SHACLPropertyShape>) {
1855
+ const shape = new SHACLShape(targetClass);
1856
+ for (const p of props) shape.addProperty(p);
1857
+ return shape;
1858
+ }
1859
+
1860
+ it("assigns the given name as className", () => {
1861
+ const shape = makeShape("flux://Channel", []);
1862
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1863
+ expect((Cls as any).className).toBe("Channel");
1864
+ expect((new (Cls as any)({}, "flux://1")).className).toBe("Channel");
1865
+ });
1866
+
1867
+ it("registers scalar property (maxCount=1) via setPropertyRegistryEntry", () => {
1868
+ const shape = makeShape("flux://Channel", [
1869
+ { name: "title", path: "flux://has_title", maxCount: 1, writable: true },
1870
+ ]);
1871
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1872
+ const meta = Cls.getModelMetadata();
1873
+ expect(meta.properties["title"]).toBeDefined();
1874
+ expect(meta.properties["title"].predicate).toBe("flux://has_title");
1875
+ expect(meta.properties["title"].readOnly).toBe(false);
1876
+ });
1877
+
1878
+ it("registers collection property (no maxCount) as hasMany relation", () => {
1879
+ const shape = makeShape("flux://Channel", [
1880
+ { name: "messages", path: "flux://has_message" },
1881
+ ]);
1882
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1883
+ const meta = Cls.getModelMetadata();
1884
+ expect(meta.relations["messages"]).toBeDefined();
1885
+ expect(meta.relations["messages"].predicate).toBe("flux://has_message");
1886
+ expect(meta.relations["messages"].direction).toBe("forward");
1887
+ });
1888
+
1889
+ it("registers collection property (maxCount=5) as hasMany relation", () => {
1890
+ const shape = makeShape("flux://Channel", [
1891
+ { name: "participants", path: "flux://participant", maxCount: 5 },
1892
+ ]);
1893
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1894
+ const meta = Cls.getModelMetadata();
1895
+ expect(meta.relations["participants"]).toBeDefined();
1896
+ expect(meta.relations["participants"].direction).toBe("forward");
1897
+ });
1898
+
1899
+ it("propagates resolveLanguage onto scalar properties", () => {
1900
+ const shape = makeShape("flux://Post", [
1901
+ { name: "body", path: "flux://body", maxCount: 1, resolveLanguage: "literal" },
1902
+ ]);
1903
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
1904
+ const meta = Cls.getModelMetadata();
1905
+ expect(meta.properties["body"].resolveLanguage).toBe("literal");
1906
+ });
1907
+
1908
+ it("defaults writable to true when not specified", () => {
1909
+ const shape = makeShape("flux://Post", [
1910
+ { name: "body", path: "flux://body", maxCount: 1 },
1911
+ ]);
1912
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
1913
+ const meta = Cls.getModelMetadata();
1914
+ expect(meta.properties["body"].readOnly).toBe(false);
1915
+ });
1916
+
1917
+ it("respects writable:false", () => {
1918
+ const shape = makeShape("flux://Post", [
1919
+ { name: "id", path: "flux://id", maxCount: 1, writable: false },
1920
+ ]);
1921
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
1922
+ const meta = Cls.getModelMetadata();
1923
+ expect(meta.properties["id"].readOnly).toBe(true);
1924
+ });
1925
+
1926
+ it("registers flag properties (hasValue) as type-discrimination entries", () => {
1927
+ const shape = makeShape("flux://Message", [
1928
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
1929
+ { name: "body", path: "flux://body", maxCount: 1 },
1930
+ ]);
1931
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
1932
+ const meta = Cls.getModelMetadata();
1933
+ expect(meta.properties["type"]).toBeDefined();
1934
+ expect(meta.properties["type"].predicate).toBe("flux://entry_type");
1935
+ expect(meta.properties["type"].flag).toBe(true);
1936
+ expect(meta.properties["type"].required).toBe(true);
1937
+ expect(meta.properties["type"].initial).toBe("flux://message");
1938
+ expect(meta.properties["body"]).toBeDefined();
1939
+ });
1940
+
1941
+ it("flag property from fromSHACL produces SPARQL type-discriminator triple", () => {
1942
+ const shape = makeShape("flux://Message", [
1943
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
1944
+ { name: "body", path: "flux://body", maxCount: 1 },
1945
+ ]);
1946
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
1947
+ const meta = Cls.getModelMetadata();
1948
+ const allRelsMeta = {} as any;
1949
+ const sparql = buildSPARQLQuery(meta, allRelsMeta, {}, Cls);
1950
+ expect(sparql).toContain("<flux://entry_type>");
1951
+ expect(sparql).toContain("<flux://message>");
1952
+ });
1953
+
1954
+ it("recovers flag value from constructor_actions (backward-compat for old shapes)", () => {
1955
+ const shape = new SHACLShape("flux://Channel");
1956
+ // An old shape: property has NO hasValue, but constructor_actions carries it
1957
+ shape.addProperty({ name: "type", path: "flux://entry_type", maxCount: 1 });
1958
+ shape.addProperty({ name: "name", path: "flux://name", maxCount: 1 });
1959
+ shape.constructor_actions = [
1960
+ { action: "addLink", source: "this", predicate: "flux://entry_type", target: "flux://channel" },
1961
+ ];
1962
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1963
+ const meta = Cls.getModelMetadata();
1964
+ expect(meta.properties["type"]).toBeDefined();
1965
+ expect(meta.properties["type"].flag).toBe(true);
1966
+ expect(meta.properties["type"].initial).toBe("flux://channel");
1967
+ });
1968
+
1969
+ it("skips properties without a name field", () => {
1970
+ const shape = makeShape("flux://Message", [
1971
+ { path: "flux://anonymous" } as any,
1972
+ { name: "body", path: "flux://body", maxCount: 1 },
1973
+ ]);
1974
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
1975
+ const meta = Cls.getModelMetadata();
1976
+ expect(Object.keys(meta.properties)).toEqual(["body"]);
1977
+ });
1978
+
1979
+ it("propagates local flag onto relations", () => {
1980
+ const shape = makeShape("flux://Channel", [
1981
+ { name: "drafts", path: "flux://draft", local: true },
1982
+ ]);
1983
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1984
+ const meta = Cls.getModelMetadata();
1985
+ expect(meta.relations["drafts"].local).toBe(true);
1986
+ });
1987
+
1988
+ it("applies Model decorator so generateSHACL and generateSDNA are available", () => {
1989
+ const shape = makeShape("flux://Channel", [
1990
+ { name: "title", path: "flux://has_title", maxCount: 1 },
1991
+ ]);
1992
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1993
+ expect(typeof (Cls as any).generateSDNA).toBe("function");
1994
+ expect(typeof (Cls as any).generateSHACL).toBe("function");
1995
+ });
1996
+
1997
+ it("handles shapes with no properties", () => {
1998
+ const shape = makeShape("flux://Empty", []);
1999
+ const Cls = Ad4mModel.fromSHACL(shape, "Empty");
2000
+ const meta = Cls.getModelMetadata();
2001
+ expect(Object.keys(meta.properties)).toHaveLength(0);
2002
+ expect(Object.keys(meta.relations)).toHaveLength(0);
2003
+ });
2004
+ });
2005
+
2006
+ // ---------------------------------------------------------------------------
2007
+ // IncludeProjection — key splitting and query routing
2008
+ // ---------------------------------------------------------------------------
2009
+
2010
+ describe("IncludeProjection type guard and key splitting", () => {
2011
+ // Shared test models
2012
+ @Model({ name: "Signal" })
2013
+ class Signal extends Ad4mModel {
2014
+ @Property({ through: "signal://type" })
2015
+ signalTypeId: string = "";
2016
+
2017
+ @Property({ through: "signal://author" })
2018
+ author: string = "";
2019
+ }
2020
+
2021
+ @Model({ name: "Post" })
2022
+ class Post extends Ad4mModel {
2023
+ @Property({ through: "post://title" })
2024
+ title: string = "";
2025
+
2026
+ @HasMany({ through: "post://signal", target: () => Signal })
2027
+ signals: Signal[] = [];
2028
+
2029
+ @HasMany({ through: "post://comment" })
2030
+ comments: string[] = [];
2031
+ }
2032
+
2033
+ const mockPerspective = {
2034
+ querySparql: jest.fn(),
2035
+ modelQuery: jest.fn(),
2036
+ infer: jest.fn(),
2037
+ uuid: "test-perspective-uuid",
2038
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("Post"),
2039
+ } as any;
2040
+
2041
+ beforeEach(() => {
2042
+ jest.clearAllMocks();
2043
+ mockPerspective.modelQuery.mockResolvedValue({
2044
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 3 }],
2045
+ totalCount: 1,
2046
+ });
2047
+ });
2048
+
2049
+ // --- isIncludeProjection type guard ---
2050
+
2051
+ it("isIncludeProjection returns true for objects with a 'from' field", () => {
2052
+ expect(isIncludeProjection({ from: "signals", count: true })).toBe(true);
2053
+ expect(isIncludeProjection({ from: "comments", limit: 1 })).toBe(true);
2054
+ });
2055
+
2056
+ it("isIncludeProjection returns false for non-projection values", () => {
2057
+ expect(isIncludeProjection(true)).toBe(false);
2058
+ expect(isIncludeProjection(false)).toBe(false);
2059
+ expect(isIncludeProjection(null)).toBe(false);
2060
+ expect(isIncludeProjection(undefined)).toBe(false);
2061
+ expect(isIncludeProjection(42)).toBe(false);
2062
+ // RelationSubQuery (has no 'from' key)
2063
+ expect(isIncludeProjection({ limit: 5, order: { timestamp: "DESC" } })).toBe(false);
2064
+ });
2065
+
2066
+ // --- $-key splitting ---
2067
+
2068
+ it("routes $-prefixed keys to queryInput.projections, not queryInput.include", async () => {
2069
+ await Post.findAll(mockPerspective, {
2070
+ include: {
2071
+ $signalCount: { from: "signals", count: true },
2072
+ comments: true,
2073
+ },
2074
+ });
2075
+
2076
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2077
+ const qi = JSON.parse(queryJson);
2078
+
2079
+ // Normal relation goes to include
2080
+ expect(qi.include?.comments).toBe(true);
2081
+ expect(qi.include?.$signalCount).toBeUndefined();
2082
+
2083
+ // Projection goes to projections
2084
+ expect(qi.projections?.$signalCount).toMatchObject({ from: "signals", count: true });
2085
+ expect(qi.projections?.comments).toBeUndefined();
2086
+ });
2087
+
2088
+ it("routes $-prefixed IncludeProjection values to projections ($ prefix required)", async () => {
2089
+ await Post.findAll(mockPerspective, {
2090
+ include: {
2091
+ $mySignals: { from: "signals", limit: 1 },
2092
+ comments: true,
2093
+ },
2094
+ });
2095
+
2096
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2097
+ const qi = JSON.parse(queryJson);
2098
+
2099
+ expect(qi.projections?.$mySignals).toMatchObject({ from: "signals", limit: 1 });
2100
+ expect(qi.include?.comments).toBe(true);
2101
+ });
2102
+
2103
+ it("does NOT route non-$ keys to projections even if value has 'from' shape", async () => {
2104
+ // $ prefix is required — a key without it goes to include, not projections
2105
+ await Post.findAll(mockPerspective, {
2106
+ include: {
2107
+ mySignals: { from: "signals", limit: 1 } as any,
2108
+ comments: true,
2109
+ },
2110
+ });
2111
+
2112
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2113
+ const qi = JSON.parse(queryJson);
2114
+
2115
+ // Without $ prefix it stays in include (behaviour is undefined/broken but not silently rerouted)
2116
+ expect(qi.projections?.mySignals).toBeUndefined();
2117
+ expect(qi.include?.mySignals).toBeDefined();
2118
+ });
2119
+
2120
+ it("omits queryInput.include when all keys are projections", async () => {
2121
+ await Post.findAll(mockPerspective, {
2122
+ include: {
2123
+ $count: { from: "signals", count: true },
2124
+ },
2125
+ });
2126
+
2127
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2128
+ const qi = JSON.parse(queryJson);
2129
+
2130
+ expect(qi.include).toBeUndefined();
2131
+ expect(qi.projections?.$count).toMatchObject({ from: "signals", count: true });
2132
+ });
2133
+
2134
+ it("omits queryInput.projections when all keys are normal includes", async () => {
2135
+ await Post.findAll(mockPerspective, {
2136
+ include: { comments: true },
2137
+ });
2138
+
2139
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2140
+ const qi = JSON.parse(queryJson);
2141
+
2142
+ expect(qi.projections).toBeUndefined();
2143
+ expect(qi.include?.comments).toBe(true);
2144
+ });
2145
+
2146
+ it("enriches projection with targetShape when relation target is registered", async () => {
2147
+ await Post.findAll(mockPerspective, {
2148
+ include: {
2149
+ $signalCount: { from: "signals", count: true },
2150
+ },
2151
+ });
2152
+
2153
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2154
+ const qi = JSON.parse(queryJson);
2155
+
2156
+ // targetShape should have been injected from the Signal model
2157
+ // ($ prefix is required for projection enrichment to apply)
2158
+ expect(qi.projections?.$signalCount?.targetShape?.className).toBe("Signal");
2159
+ });
2160
+
2161
+ it("leaves targetShape absent when relation has no target decorator", async () => {
2162
+ await Post.findAll(mockPerspective, {
2163
+ include: {
2164
+ $commentCount: { from: "comments", count: true },
2165
+ },
2166
+ });
2167
+
2168
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2169
+ const qi = JSON.parse(queryJson);
2170
+
2171
+ // 'comments' HasMany has no target() thunk → no targetShape
2172
+ expect(qi.projections?.$commentCount?.targetShape).toBeUndefined();
2173
+ });
2174
+
2175
+ // --- result passthrough ---
2176
+
2177
+ it("returns $-keyed projection values attached by Rust on instances", async () => {
2178
+ mockPerspective.modelQuery.mockResolvedValue({
2179
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 7 }],
2180
+ totalCount: 1,
2181
+ });
2182
+
2183
+ const results = await Post.findAll(mockPerspective, {
2184
+ include: { $signalCount: { from: "signals", count: true } },
2185
+ });
2186
+
2187
+ expect((results[0] as any).$signalCount).toBe(7);
2595
2188
  });
2596
2189
  });