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

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 (334) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +2406 -11070
  4. package/lib/index.js +2209 -10925
  5. package/lib/src/Ad4mClient.d.ts +7 -3
  6. package/lib/src/Ad4mClient.js +29 -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 +57 -38
  163. package/lib/src/model/Ad4mModel.js +594 -460
  164. package/lib/src/model/Ad4mModel.test.js +371 -815
  165. package/lib/src/model/ModelQueryBuilder.d.ts +9 -21
  166. package/lib/src/model/ModelQueryBuilder.js +138 -217
  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 +7 -60
  170. package/lib/src/model/hydration.js +7 -716
  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/shacl-gen.js +4 -0
  179. package/lib/src/model/types.d.ts +47 -38
  180. package/lib/src/model/types.js +4 -1
  181. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  182. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  183. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  184. package/lib/src/perspectives/LinkQuery.js +2 -42
  185. package/lib/src/perspectives/Perspective.d.ts +1 -1
  186. package/lib/src/perspectives/Perspective.js +10 -52
  187. package/lib/src/perspectives/PerspectiveClient.d.ts +12 -17
  188. package/lib/src/perspectives/PerspectiveClient.js +169 -429
  189. package/lib/src/perspectives/PerspectiveClient.test.js +55 -0
  190. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  191. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  192. package/lib/src/perspectives/PerspectiveProxy.d.ts +92 -71
  193. package/lib/src/perspectives/PerspectiveProxy.js +273 -310
  194. package/lib/src/runtime/RuntimeClient.d.ts +6 -6
  195. package/lib/src/runtime/RuntimeClient.js +93 -467
  196. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  197. package/lib/src/runtime/RuntimeTypes.js +45 -0
  198. package/lib/src/shacl/SHACLShape.d.ts +7 -0
  199. package/lib/src/shacl/SHACLShape.js +19 -0
  200. package/lib/src/shacl/SHACLShape.test.js +82 -0
  201. package/lib/src/typeDefs.js +3 -628
  202. package/package.json +9 -24
  203. package/rollup.config.js +0 -7
  204. package/src/Ad4mClient.test.ts +1179 -1340
  205. package/src/Ad4mClient.ts +30 -15
  206. package/src/agent/Agent.ts +0 -99
  207. package/src/agent/AgentClient.ts +112 -526
  208. package/src/agent/AgentStatus.ts +0 -12
  209. package/src/ai/AIClient.ts +96 -296
  210. package/src/ai/AITypes.ts +66 -0
  211. package/src/ai/Tasks.ts +0 -52
  212. package/src/apiClient.ts +283 -0
  213. package/src/expression/Expression.ts +3 -43
  214. package/src/expression/ExpressionClient.ts +14 -77
  215. package/src/expression/ExpressionRef.ts +0 -6
  216. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  217. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  218. package/src/generated/api/AddLinkRequest.ts +4 -0
  219. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  220. package/src/generated/api/AddSdnaRequest.ts +3 -0
  221. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  222. package/src/generated/api/AuthInfoInput.ts +4 -0
  223. package/src/generated/api/CapabilityInput.ts +4 -0
  224. package/src/generated/api/CommitBatchRequest.ts +3 -0
  225. package/src/generated/api/ComputeLogEntry.ts +3 -0
  226. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  227. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  228. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  229. package/src/generated/api/EmbedRequest.ts +3 -0
  230. package/src/generated/api/EntanglementProofInput.ts +3 -0
  231. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  232. package/src/generated/api/ExportRequest.ts +3 -0
  233. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  234. package/src/generated/api/ExpressionProof.ts +3 -0
  235. package/src/generated/api/ExpressionProofInput.ts +3 -0
  236. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  237. package/src/generated/api/FriendsListRequest.ts +3 -0
  238. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  239. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  240. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  241. package/src/generated/api/ImportAgentRequest.ts +3 -0
  242. package/src/generated/api/ImportRequest.ts +3 -0
  243. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  244. package/src/generated/api/LanguageMetaInput.ts +3 -0
  245. package/src/generated/api/Link.ts +3 -0
  246. package/src/generated/api/LinkExpression.ts +6 -0
  247. package/src/generated/api/LinkExpressionInput.ts +6 -0
  248. package/src/generated/api/LinkInput.ts +3 -0
  249. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  250. package/src/generated/api/LinkMutations.ts +5 -0
  251. package/src/generated/api/LinkStatus.ts +3 -0
  252. package/src/generated/api/LockAgentRequest.ts +3 -0
  253. package/src/generated/api/ModelType.ts +3 -0
  254. package/src/generated/api/NotificationInput.ts +3 -0
  255. package/src/generated/api/OpenLinkRequest.ts +3 -0
  256. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  257. package/src/generated/api/PerspectiveInput.ts +4 -0
  258. package/src/generated/api/PromptRequest.ts +3 -0
  259. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  260. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  261. package/src/generated/api/QueryRequest.ts +6 -0
  262. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  263. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  264. package/src/generated/api/ResourceInput.ts +3 -0
  265. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  266. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  267. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  268. package/src/generated/api/SetStatusRequest.ts +3 -0
  269. package/src/generated/api/SignMessageRequest.ts +3 -0
  270. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  271. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  272. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  273. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  274. package/src/generated/api/UserStatistics.ts +3 -0
  275. package/src/generated/api/VerificationRequestResult.ts +3 -0
  276. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  277. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  278. package/src/generated/api/index.ts +49 -0
  279. package/src/index.ts +6 -1
  280. package/src/jestSetup.ts +1 -1
  281. package/src/language/Icon.ts +0 -4
  282. package/src/language/Language.ts +2 -23
  283. package/src/language/LanguageClient.ts +21 -132
  284. package/src/language/LanguageHandle.ts +0 -14
  285. package/src/language/LanguageMeta.ts +0 -29
  286. package/src/language/LanguageRef.ts +0 -7
  287. package/src/links/Links.ts +0 -37
  288. package/src/model/Ad4mModel.test.ts +708 -876
  289. package/src/model/Ad4mModel.ts +613 -508
  290. package/src/model/ModelQueryBuilder.ts +178 -244
  291. package/src/model/decorators.ts +29 -0
  292. package/src/model/hydration.ts +9 -766
  293. package/src/model/index.ts +0 -4
  294. package/src/model/query-sparql.test.ts +34 -242
  295. package/src/model/query-sparql.ts +27 -337
  296. package/src/model/shacl-gen.ts +5 -0
  297. package/src/model/types.ts +51 -39
  298. package/src/neighbourhood/Neighbourhood.ts +0 -9
  299. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  300. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  301. package/src/perspectives/LinkQuery.ts +0 -15
  302. package/src/perspectives/Perspective.ts +1 -12
  303. package/src/perspectives/PerspectiveClient.test.ts +206 -148
  304. package/src/perspectives/PerspectiveClient.ts +228 -442
  305. package/src/perspectives/PerspectiveDiff.ts +0 -8
  306. package/src/perspectives/PerspectiveHandle.ts +1 -12
  307. package/src/perspectives/PerspectiveProxy.test.ts +41 -0
  308. package/src/perspectives/PerspectiveProxy.ts +307 -348
  309. package/src/runtime/RuntimeClient.ts +112 -474
  310. package/src/runtime/RuntimeTypes.ts +144 -0
  311. package/src/shacl/SHACLShape.test.ts +94 -0
  312. package/src/shacl/SHACLShape.ts +27 -0
  313. package/src/typeDefs.ts +3 -5
  314. package/tsconfig.json +3 -7
  315. package/shims/reflect-metadata.ts +0 -0
  316. package/shims/type-graphql.ts +0 -75
  317. package/src/PubSub.ts +0 -17
  318. package/src/agent/AgentResolver.ts +0 -263
  319. package/src/ai/AIResolver.ts +0 -372
  320. package/src/buildSchema.ts +0 -43
  321. package/src/expression/ExpressionResolver.ts +0 -64
  322. package/src/language/LanguageResolver.ts +0 -98
  323. package/src/model/Subject.ts +0 -159
  324. package/src/model/hydration-batch.ts +0 -205
  325. package/src/model/hydration-batching.test.ts +0 -563
  326. package/src/model/prolog-facts.ts +0 -145
  327. package/src/model/query-prolog.ts +0 -148
  328. package/src/model/query-sparql-batch.ts +0 -301
  329. package/src/model/subscription-delta.test.ts +0 -207
  330. package/src/model/subscription-pool.ts +0 -211
  331. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  332. package/src/perspectives/PerspectiveResolver.ts +0 -364
  333. package/src/runtime/RuntimeResolver.ts +0 -749
  334. 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
1042
 
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
-
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,7 @@ describe("formatSPARQLValue", () => {
1414
1059
  // Comprehensive SPARQL migration unit tests
1415
1060
  // ──────────────────────────────────────────────────────────
1416
1061
 
1417
- import { matchesCondition, hydrateFromLinks } from "./hydration";
1062
+ import { matchesCondition } from "./hydration";
1418
1063
  import { Literal } from "../Literal";
1419
1064
 
1420
1065
  // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
@@ -1520,205 +1165,6 @@ describe("matchesCondition()", () => {
1520
1165
  });
1521
1166
  });
1522
1167
 
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
1168
  describe("buildSPARQLQuery edge cases", () => {
1723
1169
  @Model({ name: "FlagModel" })
1724
1170
  class FlagModel extends Ad4mModel {
@@ -1772,81 +1218,6 @@ describe("buildSPARQLQuery edge cases", () => {
1772
1218
  });
1773
1219
  });
1774
1220
 
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
1221
  // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1851
1222
  describe("Batch hydration for reverse relations", () => {
1852
1223
  it("batch hydration should correctly group targets by parent instance ID", () => {
@@ -2219,18 +1590,33 @@ describe("Native SPARQL getter evaluation", () => {
2219
1590
  // ── Subscribe callback timing ──────────────────────────────────────────
2220
1591
  describe("ModelQueryBuilder subscribe callback timing", () => {
2221
1592
  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.
1593
+ // This test verifies that subscribe() uses the Rust model subscription endpoint
1594
+ // and properly handles the subscription lifecycle.
2225
1595
 
1596
+ const mockSubscriptionId = "test-sub-123";
1597
+ let updateCallback: ((result: any) => void) | null = null;
1598
+
1599
+ const mockClient = {
1600
+ modelSubscribe: jest.fn().mockResolvedValue({
1601
+ subscriptionId: mockSubscriptionId,
1602
+ result: { instances: [], totalCount: 0 },
1603
+ }),
1604
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1605
+ updateCallback = cb;
1606
+ return () => {}; // unsubscribe function
1607
+ }),
1608
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1609
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1610
+ };
1611
+
2226
1612
  const mockPerspective = {
2227
- getLinks: jest.fn().mockResolvedValue([]),
2228
- subscribeQuery: jest.fn().mockResolvedValue({
2229
- result: '[]',
2230
- onResult: jest.fn(),
2231
- dispose: jest.fn(),
1613
+ uuid: "test-uuid",
1614
+ client: mockClient,
1615
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1616
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
2232
1617
  }),
2233
- querySparql: jest.fn().mockResolvedValue('[]'),
1618
+ getLinks: jest.fn().mockResolvedValue([]),
1619
+ modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
2234
1620
  } as any;
2235
1621
 
2236
1622
  const { Ad4mModel, Model, Property, Flag } = require("./index");
@@ -2257,12 +1643,189 @@ describe("ModelQueryBuilder subscribe callback timing", () => {
2257
1643
  // The callback should NOT have fired synchronously
2258
1644
  expect(callbackInvokedBeforeResolve).toBe(false);
2259
1645
 
2260
- await promise;
1646
+ const initialResults = await promise;
2261
1647
  promiseResolved = true;
2262
1648
 
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
1649
+ expect(initialResults).toEqual([]);
1650
+ expect(mockPerspective.modelSubscribe).toHaveBeenCalled();
1651
+ });
1652
+ });
1653
+
1654
+ describe("ModelQueryBuilder paginateSubscribe", () => {
1655
+ it("paginateSubscribe should use a single query with count: true", async () => {
1656
+ const mockSubscriptionId = "paginate-sub-123";
1657
+
1658
+ const mockClient = {
1659
+ modelSubscribe: jest.fn().mockResolvedValue({
1660
+ subscriptionId: mockSubscriptionId,
1661
+ result: { instances: [], totalCount: 0 },
1662
+ }),
1663
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, _cb: any) => {
1664
+ return () => {};
1665
+ }),
1666
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1667
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1668
+ };
1669
+
1670
+ const mockPerspective = {
1671
+ uuid: "test-uuid",
1672
+ client: mockClient,
1673
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1674
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1675
+ }),
1676
+ modelQuery: jest.fn().mockResolvedValue({ instances: [{ id: "item1", type: "test://paginate" }], totalCount: 42 }),
1677
+ } as any;
1678
+
1679
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1680
+
1681
+ @Model({ name: "PaginateTest" })
1682
+ class PaginateTest extends Ad4mModel {
1683
+ @Flag({ through: "test://type", value: "test://paginate" })
1684
+ type: string = "test://paginate";
1685
+ @Property({ through: "test://name" })
1686
+ name: string = "";
1687
+ }
1688
+
1689
+ const builder = PaginateTest.query(mockPerspective);
1690
+ const result = await builder.paginateSubscribe(10, 1, () => {});
1691
+
1692
+ // Should return paginated result structure
1693
+ expect(result).toHaveProperty("results");
1694
+ expect(result).toHaveProperty("totalCount");
1695
+ expect(result).toHaveProperty("pageSize", 10);
1696
+ expect(result).toHaveProperty("pageNumber", 1);
1697
+
1698
+ // modelQuery should be called exactly once (not twice — no separate count query)
1699
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1700
+
1701
+ // The query should have count: true
1702
+ const callArgs = mockPerspective.modelQuery.mock.calls[0];
1703
+ const queryJson = JSON.parse(callArgs[1]);
1704
+ expect(queryJson.count).toBe(true);
1705
+ expect(queryJson.limit).toBe(10);
1706
+ expect(queryJson.offset).toBe(0);
1707
+ });
1708
+
1709
+ it("paginateSubscribe should skip isInit messages from subscription", async () => {
1710
+ const mockSubscriptionId = "paginate-init-sub";
1711
+ let capturedCallback: ((result: any) => void) | null = null;
1712
+
1713
+ const mockClient = {
1714
+ modelSubscribe: jest.fn().mockResolvedValue({
1715
+ subscriptionId: mockSubscriptionId,
1716
+ result: { instances: [], totalCount: 0 },
1717
+ }),
1718
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1719
+ capturedCallback = cb;
1720
+ return () => {};
1721
+ }),
1722
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1723
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1724
+ };
1725
+
1726
+ let modelQueryCallCount = 0;
1727
+ const mockPerspective = {
1728
+ uuid: "test-uuid",
1729
+ client: mockClient,
1730
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1731
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1732
+ }),
1733
+ modelQuery: jest.fn().mockImplementation(async () => {
1734
+ modelQueryCallCount++;
1735
+ return { instances: [], totalCount: 0 };
1736
+ }),
1737
+ } as any;
1738
+
1739
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1740
+
1741
+ @Model({ name: "InitGuardTest" })
1742
+ class InitGuardTest extends Ad4mModel {
1743
+ @Flag({ through: "test://type", value: "test://init" })
1744
+ type: string = "test://init";
1745
+ @Property({ through: "test://name" })
1746
+ name: string = "";
1747
+ }
1748
+
1749
+ const userCallback = jest.fn();
1750
+ const builder = InitGuardTest.query(mockPerspective);
1751
+ await builder.paginateSubscribe(10, 1, userCallback);
1752
+
1753
+ // Reset the count after initial fetch
1754
+ const initialCallCount = modelQueryCallCount;
1755
+
1756
+ // Simulate an isInit message from subscription
1757
+ expect(capturedCallback).not.toBeNull();
1758
+ capturedCallback!({ isInit: true });
1759
+
1760
+ // Wait for any async processing
1761
+ await new Promise(r => setTimeout(r, 50));
1762
+
1763
+ // modelQuery should NOT have been called again (isInit was filtered)
1764
+ expect(modelQueryCallCount).toBe(initialCallCount);
1765
+ // User callback should NOT have been invoked by isInit
1766
+ expect(userCallback).not.toHaveBeenCalled();
1767
+ });
1768
+
1769
+ it("paginateSubscribe should re-fetch on real subscription updates", async () => {
1770
+ const mockSubscriptionId = "paginate-update-sub";
1771
+ let capturedCallback: ((result: any) => void) | null = null;
1772
+
1773
+ const mockClient = {
1774
+ modelSubscribe: jest.fn().mockResolvedValue({
1775
+ subscriptionId: mockSubscriptionId,
1776
+ result: { instances: [], totalCount: 0 },
1777
+ }),
1778
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1779
+ capturedCallback = cb;
1780
+ return () => {};
1781
+ }),
1782
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1783
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1784
+ };
1785
+
1786
+ let modelQueryCallCount = 0;
1787
+ const mockPerspective = {
1788
+ uuid: "test-uuid",
1789
+ client: mockClient,
1790
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1791
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1792
+ }),
1793
+ modelQuery: jest.fn().mockImplementation(async () => {
1794
+ modelQueryCallCount++;
1795
+ return { instances: [{ id: "new-item", type: "test://update" }], totalCount: 1 };
1796
+ }),
1797
+ } as any;
1798
+
1799
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1800
+
1801
+ @Model({ name: "UpdateTest" })
1802
+ class UpdateTest extends Ad4mModel {
1803
+ @Flag({ through: "test://type", value: "test://update" })
1804
+ type: string = "test://update";
1805
+ @Property({ through: "test://name" })
1806
+ name: string = "";
1807
+ }
1808
+
1809
+ const userCallback = jest.fn();
1810
+ const builder = UpdateTest.query(mockPerspective);
1811
+ await builder.paginateSubscribe(10, 1, userCallback);
1812
+
1813
+ const initialCallCount = modelQueryCallCount;
1814
+
1815
+ // Simulate a real subscription update (not isInit)
1816
+ capturedCallback!({ instances: [{ id: "new-item" }], totalCount: 1 });
1817
+
1818
+ // Wait for async processing
1819
+ await new Promise(r => setTimeout(r, 100));
1820
+
1821
+ // modelQuery should have been called again for the re-fetch
1822
+ expect(modelQueryCallCount).toBeGreaterThan(initialCallCount);
1823
+ // User callback should have been invoked with paginated results
1824
+ expect(userCallback).toHaveBeenCalled();
1825
+ const callArg = userCallback.mock.calls[0][0];
1826
+ expect(callArg).toHaveProperty("totalCount");
1827
+ expect(callArg).toHaveProperty("pageSize", 10);
1828
+ expect(callArg).toHaveProperty("pageNumber", 1);
2266
1829
  });
2267
1830
  });
2268
1831
 
@@ -2271,7 +1834,6 @@ describe("ModelQueryBuilder subscribe callback timing", () => {
2271
1834
  // ============================================================================
2272
1835
 
2273
1836
  import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
2274
- import { clearSubscriptionPool, subscriptionPoolSize } from "./subscription-pool";
2275
1837
  import { getPropertiesMetadata, getRelationsMetadata, getMemoizedSHACL } from "./decorators";
2276
1838
 
2277
1839
  describe("QueryCache", () => {
@@ -2398,61 +1960,6 @@ describe("Lazy Conformance Filters", () => {
2398
1960
  });
2399
1961
  });
2400
1962
 
2401
- // ──────────────────────────────────────────────────────────
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
1963
  // ──────────────────────────────────────────────────────────
2457
1964
  // deepQuery opt-in — getter evaluation on collection queries
2458
1965
  // ──────────────────────────────────────────────────────────
@@ -2485,6 +1992,18 @@ describe("deepQuery opt-in — getter evaluation", () => {
2485
1992
  let sparqlCalls: string[];
2486
1993
  const mockPerspective: any = {
2487
1994
  uuid: "test-uuid",
1995
+ modelQuery: jest.fn(async (className: string, queryJson: string, shapeJson: string) => {
1996
+ // Return a basic result for the single-instance getData() path
1997
+ const query = JSON.parse(queryJson);
1998
+ const id = query?.where?.id;
1999
+ if (id) {
2000
+ return {
2001
+ instances: [{ id, body: "Hello" }],
2002
+ totalCount: 1,
2003
+ };
2004
+ }
2005
+ return { instances: [], totalCount: 0 };
2006
+ }),
2488
2007
  querySparql: jest.fn(async (q: string) => {
2489
2008
  sparqlCalls.push(q);
2490
2009
  return [];
@@ -2500,39 +2019,13 @@ describe("deepQuery opt-in — getter evaluation", () => {
2500
2019
  mockPerspective.get.mockClear();
2501
2020
  });
2502
2021
 
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")
2520
- );
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")
2022
+ function makeInstances(count: number): InstanceType<typeof DeepQueryTestMessage>[] {
2023
+ return Array.from({ length: count }, (_, i) =>
2024
+ new DeepQueryTestMessage(mockPerspective, `flux://msg-${i}`)
2531
2025
  );
2532
- expect(getterCalls.length).toBe(6); // 3 instances × 2 getters
2533
- });
2026
+ }
2534
2027
 
2535
- it("single-instance get() still evaluates getters by default", async () => {
2028
+ it("single-instance get() delegates getter evaluation to Rust (no JS-side SPARQL)", async () => {
2536
2029
  const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
2537
2030
  mockPerspective.querySparql.mockImplementation(async (q: string) => {
2538
2031
  sparqlCalls.push(q);
@@ -2546,19 +2039,19 @@ describe("deepQuery opt-in — getter evaluation", () => {
2546
2039
  });
2547
2040
 
2548
2041
  await instance.get();
2042
+ // Getter evaluation now happens Rust-side via evaluate_getters() — no JS SPARQL calls
2549
2043
  const getterCalls = sparqlCalls.filter(
2550
2044
  (q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
2551
2045
  );
2552
- expect(getterCalls.length).toBe(2);
2046
+ expect(getterCalls.length).toBe(0);
2553
2047
  });
2554
2048
 
2555
2049
  describe("Ad4mModel.evaluateGetters()", () => {
2556
2050
  it("resolves getters for a batch of instances", async () => {
2557
- const grouped = makeMessageRows(4);
2558
- const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
2051
+ const instances = makeInstances(4);
2559
2052
  sparqlCalls = [];
2560
2053
 
2561
- await DeepQueryTestMessage.evaluateGetters(result.results.slice(0, 2), mockPerspective, ["replyingTo"]);
2054
+ await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
2562
2055
 
2563
2056
  const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2564
2057
  expect(replyCalls.length).toBe(2);
@@ -2567,11 +2060,10 @@ describe("deepQuery opt-in — getter evaluation", () => {
2567
2060
  });
2568
2061
 
2569
2062
  it("evaluates all getters when propertyNames is omitted", async () => {
2570
- const grouped = makeMessageRows(2);
2571
- const result = await (DeepQueryTestMessage as any).instancesFromQueryResult(mockPerspective, {}, grouped);
2063
+ const instances = makeInstances(2);
2572
2064
  sparqlCalls = [];
2573
2065
 
2574
- await DeepQueryTestMessage.evaluateGetters(result.results, mockPerspective);
2066
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
2575
2067
 
2576
2068
  const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2577
2069
  const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
@@ -2594,3 +2086,343 @@ describe("deepQuery opt-in — getter evaluation", () => {
2594
2086
  });
2595
2087
  });
2596
2088
  });
2089
+
2090
+ // ─── Ad4mModel.fromSHACL() ───────────────────────────────────────────────────
2091
+
2092
+ describe("Ad4mModel.fromSHACL()", () => {
2093
+ function makeShape(targetClass: string, props: Array<import("../shacl/SHACLShape").SHACLPropertyShape>) {
2094
+ const shape = new SHACLShape(targetClass);
2095
+ for (const p of props) shape.addProperty(p);
2096
+ return shape;
2097
+ }
2098
+
2099
+ it("assigns the given name as className", () => {
2100
+ const shape = makeShape("flux://Channel", []);
2101
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2102
+ expect((Cls as any).className).toBe("Channel");
2103
+ expect((new (Cls as any)({}, "flux://1")).className).toBe("Channel");
2104
+ });
2105
+
2106
+ it("registers scalar property (maxCount=1) via setPropertyRegistryEntry", () => {
2107
+ const shape = makeShape("flux://Channel", [
2108
+ { name: "title", path: "flux://has_title", maxCount: 1, writable: true },
2109
+ ]);
2110
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2111
+ const meta = Cls.getModelMetadata();
2112
+ expect(meta.properties["title"]).toBeDefined();
2113
+ expect(meta.properties["title"].predicate).toBe("flux://has_title");
2114
+ expect(meta.properties["title"].readOnly).toBe(false);
2115
+ });
2116
+
2117
+ it("registers collection property (no maxCount) as hasMany relation", () => {
2118
+ const shape = makeShape("flux://Channel", [
2119
+ { name: "messages", path: "flux://has_message" },
2120
+ ]);
2121
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2122
+ const meta = Cls.getModelMetadata();
2123
+ expect(meta.relations["messages"]).toBeDefined();
2124
+ expect(meta.relations["messages"].predicate).toBe("flux://has_message");
2125
+ expect(meta.relations["messages"].direction).toBe("forward");
2126
+ });
2127
+
2128
+ it("registers collection property (maxCount=5) as hasMany relation", () => {
2129
+ const shape = makeShape("flux://Channel", [
2130
+ { name: "participants", path: "flux://participant", maxCount: 5 },
2131
+ ]);
2132
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2133
+ const meta = Cls.getModelMetadata();
2134
+ expect(meta.relations["participants"]).toBeDefined();
2135
+ expect(meta.relations["participants"].direction).toBe("forward");
2136
+ });
2137
+
2138
+ it("propagates resolveLanguage onto scalar properties", () => {
2139
+ const shape = makeShape("flux://Post", [
2140
+ { name: "body", path: "flux://body", maxCount: 1, resolveLanguage: "literal" },
2141
+ ]);
2142
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2143
+ const meta = Cls.getModelMetadata();
2144
+ expect(meta.properties["body"].resolveLanguage).toBe("literal");
2145
+ });
2146
+
2147
+ it("defaults writable to true when not specified", () => {
2148
+ const shape = makeShape("flux://Post", [
2149
+ { name: "body", path: "flux://body", maxCount: 1 },
2150
+ ]);
2151
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2152
+ const meta = Cls.getModelMetadata();
2153
+ expect(meta.properties["body"].readOnly).toBe(false);
2154
+ });
2155
+
2156
+ it("respects writable:false", () => {
2157
+ const shape = makeShape("flux://Post", [
2158
+ { name: "id", path: "flux://id", maxCount: 1, writable: false },
2159
+ ]);
2160
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2161
+ const meta = Cls.getModelMetadata();
2162
+ expect(meta.properties["id"].readOnly).toBe(true);
2163
+ });
2164
+
2165
+ it("registers flag properties (hasValue) as type-discrimination entries", () => {
2166
+ const shape = makeShape("flux://Message", [
2167
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2168
+ { name: "body", path: "flux://body", maxCount: 1 },
2169
+ ]);
2170
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2171
+ const meta = Cls.getModelMetadata();
2172
+ expect(meta.properties["type"]).toBeDefined();
2173
+ expect(meta.properties["type"].predicate).toBe("flux://entry_type");
2174
+ expect(meta.properties["type"].flag).toBe(true);
2175
+ expect(meta.properties["type"].required).toBe(true);
2176
+ expect(meta.properties["type"].initial).toBe("flux://message");
2177
+ expect(meta.properties["body"]).toBeDefined();
2178
+ });
2179
+
2180
+ it("flag property from fromSHACL produces SPARQL type-discriminator triple", () => {
2181
+ const shape = makeShape("flux://Message", [
2182
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2183
+ { name: "body", path: "flux://body", maxCount: 1 },
2184
+ ]);
2185
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2186
+ const meta = Cls.getModelMetadata();
2187
+ const allRelsMeta = {} as any;
2188
+ const sparql = buildSPARQLQuery(meta, allRelsMeta, {}, Cls);
2189
+ expect(sparql).toContain("<flux://entry_type>");
2190
+ expect(sparql).toContain("<flux://message>");
2191
+ });
2192
+
2193
+ it("recovers flag value from constructor_actions (backward-compat for old shapes)", () => {
2194
+ const shape = new SHACLShape("flux://Channel");
2195
+ // An old shape: property has NO hasValue, but constructor_actions carries it
2196
+ shape.addProperty({ name: "type", path: "flux://entry_type", maxCount: 1 });
2197
+ shape.addProperty({ name: "name", path: "flux://name", maxCount: 1 });
2198
+ shape.constructor_actions = [
2199
+ { action: "addLink", source: "this", predicate: "flux://entry_type", target: "flux://channel" },
2200
+ ];
2201
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2202
+ const meta = Cls.getModelMetadata();
2203
+ expect(meta.properties["type"]).toBeDefined();
2204
+ expect(meta.properties["type"].flag).toBe(true);
2205
+ expect(meta.properties["type"].initial).toBe("flux://channel");
2206
+ });
2207
+
2208
+ it("skips properties without a name field", () => {
2209
+ const shape = makeShape("flux://Message", [
2210
+ { path: "flux://anonymous" } as any,
2211
+ { name: "body", path: "flux://body", maxCount: 1 },
2212
+ ]);
2213
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2214
+ const meta = Cls.getModelMetadata();
2215
+ expect(Object.keys(meta.properties)).toEqual(["body"]);
2216
+ });
2217
+
2218
+ it("propagates local flag onto relations", () => {
2219
+ const shape = makeShape("flux://Channel", [
2220
+ { name: "drafts", path: "flux://draft", local: true },
2221
+ ]);
2222
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2223
+ const meta = Cls.getModelMetadata();
2224
+ expect(meta.relations["drafts"].local).toBe(true);
2225
+ });
2226
+
2227
+ it("applies Model decorator so generateSHACL and generateSDNA are available", () => {
2228
+ const shape = makeShape("flux://Channel", [
2229
+ { name: "title", path: "flux://has_title", maxCount: 1 },
2230
+ ]);
2231
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2232
+ expect(typeof (Cls as any).generateSDNA).toBe("function");
2233
+ expect(typeof (Cls as any).generateSHACL).toBe("function");
2234
+ });
2235
+
2236
+ it("handles shapes with no properties", () => {
2237
+ const shape = makeShape("flux://Empty", []);
2238
+ const Cls = Ad4mModel.fromSHACL(shape, "Empty");
2239
+ const meta = Cls.getModelMetadata();
2240
+ expect(Object.keys(meta.properties)).toHaveLength(0);
2241
+ expect(Object.keys(meta.relations)).toHaveLength(0);
2242
+ });
2243
+ });
2244
+
2245
+ // ---------------------------------------------------------------------------
2246
+ // IncludeProjection — key splitting and query routing
2247
+ // ---------------------------------------------------------------------------
2248
+
2249
+ describe("IncludeProjection type guard and key splitting", () => {
2250
+ // Shared test models
2251
+ @Model({ name: "Signal" })
2252
+ class Signal extends Ad4mModel {
2253
+ @Property({ through: "signal://type" })
2254
+ signalTypeId: string = "";
2255
+
2256
+ @Property({ through: "signal://author" })
2257
+ author: string = "";
2258
+ }
2259
+
2260
+ @Model({ name: "Post" })
2261
+ class Post extends Ad4mModel {
2262
+ @Property({ through: "post://title" })
2263
+ title: string = "";
2264
+
2265
+ @HasMany({ through: "post://signal", target: () => Signal })
2266
+ signals: Signal[] = [];
2267
+
2268
+ @HasMany({ through: "post://comment" })
2269
+ comments: string[] = [];
2270
+ }
2271
+
2272
+ const mockPerspective = {
2273
+ querySparql: jest.fn(),
2274
+ modelQuery: jest.fn(),
2275
+ infer: jest.fn(),
2276
+ uuid: "test-perspective-uuid",
2277
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("Post"),
2278
+ } as any;
2279
+
2280
+ beforeEach(() => {
2281
+ jest.clearAllMocks();
2282
+ mockPerspective.modelQuery.mockResolvedValue({
2283
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 3 }],
2284
+ totalCount: 1,
2285
+ });
2286
+ });
2287
+
2288
+ // --- isIncludeProjection type guard ---
2289
+
2290
+ it("isIncludeProjection returns true for objects with a 'from' field", () => {
2291
+ expect(isIncludeProjection({ from: "signals", count: true })).toBe(true);
2292
+ expect(isIncludeProjection({ from: "comments", limit: 1 })).toBe(true);
2293
+ });
2294
+
2295
+ it("isIncludeProjection returns false for non-projection values", () => {
2296
+ expect(isIncludeProjection(true)).toBe(false);
2297
+ expect(isIncludeProjection(false)).toBe(false);
2298
+ expect(isIncludeProjection(null)).toBe(false);
2299
+ expect(isIncludeProjection(undefined)).toBe(false);
2300
+ expect(isIncludeProjection(42)).toBe(false);
2301
+ // RelationSubQuery (has no 'from' key)
2302
+ expect(isIncludeProjection({ limit: 5, order: { timestamp: "DESC" } })).toBe(false);
2303
+ });
2304
+
2305
+ // --- $-key splitting ---
2306
+
2307
+ it("routes $-prefixed keys to queryInput.projections, not queryInput.include", async () => {
2308
+ await Post.findAll(mockPerspective, {
2309
+ include: {
2310
+ $signalCount: { from: "signals", count: true },
2311
+ comments: true,
2312
+ },
2313
+ });
2314
+
2315
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2316
+ const qi = JSON.parse(queryJson);
2317
+
2318
+ // Normal relation goes to include
2319
+ expect(qi.include?.comments).toBe(true);
2320
+ expect(qi.include?.$signalCount).toBeUndefined();
2321
+
2322
+ // Projection goes to projections
2323
+ expect(qi.projections?.$signalCount).toMatchObject({ from: "signals", count: true });
2324
+ expect(qi.projections?.comments).toBeUndefined();
2325
+ });
2326
+
2327
+ it("routes $-prefixed IncludeProjection values to projections ($ prefix required)", async () => {
2328
+ await Post.findAll(mockPerspective, {
2329
+ include: {
2330
+ $mySignals: { from: "signals", limit: 1 },
2331
+ comments: true,
2332
+ },
2333
+ });
2334
+
2335
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2336
+ const qi = JSON.parse(queryJson);
2337
+
2338
+ expect(qi.projections?.$mySignals).toMatchObject({ from: "signals", limit: 1 });
2339
+ expect(qi.include?.comments).toBe(true);
2340
+ });
2341
+
2342
+ it("does NOT route non-$ keys to projections even if value has 'from' shape", async () => {
2343
+ // $ prefix is required — a key without it goes to include, not projections
2344
+ await Post.findAll(mockPerspective, {
2345
+ include: {
2346
+ mySignals: { from: "signals", limit: 1 } as any,
2347
+ comments: true,
2348
+ },
2349
+ });
2350
+
2351
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2352
+ const qi = JSON.parse(queryJson);
2353
+
2354
+ // Without $ prefix it stays in include (behaviour is undefined/broken but not silently rerouted)
2355
+ expect(qi.projections?.mySignals).toBeUndefined();
2356
+ expect(qi.include?.mySignals).toBeDefined();
2357
+ });
2358
+
2359
+ it("omits queryInput.include when all keys are projections", async () => {
2360
+ await Post.findAll(mockPerspective, {
2361
+ include: {
2362
+ $count: { from: "signals", count: true },
2363
+ },
2364
+ });
2365
+
2366
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2367
+ const qi = JSON.parse(queryJson);
2368
+
2369
+ expect(qi.include).toBeUndefined();
2370
+ expect(qi.projections?.$count).toMatchObject({ from: "signals", count: true });
2371
+ });
2372
+
2373
+ it("omits queryInput.projections when all keys are normal includes", async () => {
2374
+ await Post.findAll(mockPerspective, {
2375
+ include: { comments: true },
2376
+ });
2377
+
2378
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2379
+ const qi = JSON.parse(queryJson);
2380
+
2381
+ expect(qi.projections).toBeUndefined();
2382
+ expect(qi.include?.comments).toBe(true);
2383
+ });
2384
+
2385
+ it("enriches projection with targetShape when relation target is registered", async () => {
2386
+ await Post.findAll(mockPerspective, {
2387
+ include: {
2388
+ $signalCount: { from: "signals", count: true },
2389
+ },
2390
+ });
2391
+
2392
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2393
+ const qi = JSON.parse(queryJson);
2394
+
2395
+ // targetShape should have been injected from the Signal model
2396
+ // ($ prefix is required for projection enrichment to apply)
2397
+ expect(qi.projections?.$signalCount?.targetShape?.className).toBe("Signal");
2398
+ });
2399
+
2400
+ it("leaves targetShape absent when relation has no target decorator", async () => {
2401
+ await Post.findAll(mockPerspective, {
2402
+ include: {
2403
+ $commentCount: { from: "comments", count: true },
2404
+ },
2405
+ });
2406
+
2407
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2408
+ const qi = JSON.parse(queryJson);
2409
+
2410
+ // 'comments' HasMany has no target() thunk → no targetShape
2411
+ expect(qi.projections?.$commentCount?.targetShape).toBeUndefined();
2412
+ });
2413
+
2414
+ // --- result passthrough ---
2415
+
2416
+ it("returns $-keyed projection values attached by Rust on instances", async () => {
2417
+ mockPerspective.modelQuery.mockResolvedValue({
2418
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 7 }],
2419
+ totalCount: 1,
2420
+ });
2421
+
2422
+ const results = await Post.findAll(mockPerspective, {
2423
+ include: { $signalCount: { from: "signals", count: true } },
2424
+ });
2425
+
2426
+ expect((results[0] as any).$signalCount).toBe(7);
2427
+ });
2428
+ });