@coasys/ad4m 0.12.0 → 0.13.0-postmessage-ws-proxy.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (388) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +7444 -13939
  4. package/lib/index.js +5322 -11888
  5. package/lib/src/Ad4mClient.d.ts +9 -3
  6. package/lib/src/Ad4mClient.js +40 -13
  7. package/lib/src/Literal.js +6 -5
  8. package/lib/src/agent/Agent.js +26 -272
  9. package/lib/src/agent/AgentClient.d.ts +33 -21
  10. package/lib/src/agent/AgentClient.js +180 -373
  11. package/lib/src/agent/AgentStatus.js +2 -37
  12. package/lib/src/ai/AIClient.d.ts +12 -4
  13. package/lib/src/ai/AIClient.js +81 -285
  14. package/lib/src/ai/AITypes.d.ts +55 -0
  15. package/lib/src/ai/AITypes.js +18 -0
  16. package/lib/src/ai/Tasks.js +10 -133
  17. package/lib/src/apiClient.d.ts +53 -0
  18. package/lib/src/apiClient.js +234 -0
  19. package/lib/src/cache/PersistentCache.d.ts +40 -0
  20. package/lib/src/cache/PersistentCache.js +139 -0
  21. package/lib/src/expression/Expression.d.ts +1 -1
  22. package/lib/src/expression/Expression.js +13 -122
  23. package/lib/src/expression/ExpressionClient.d.ts +11 -3
  24. package/lib/src/expression/ExpressionClient.js +120 -75
  25. package/lib/src/expression/ExpressionRef.js +4 -27
  26. package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
  27. package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
  28. package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
  29. package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
  30. package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
  31. package/lib/src/generated/api/AddLinkRequest.js +1 -0
  32. package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
  33. package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
  34. package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
  35. package/lib/src/generated/api/AddSdnaRequest.js +2 -0
  36. package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
  37. package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
  38. package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
  39. package/lib/src/generated/api/AuthInfoInput.js +1 -0
  40. package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
  41. package/lib/src/generated/api/CapabilityInput.js +1 -0
  42. package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
  43. package/lib/src/generated/api/CommitBatchRequest.js +2 -0
  44. package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
  45. package/lib/src/generated/api/ComputeLogEntry.js +2 -0
  46. package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
  47. package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
  48. package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
  49. package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
  50. package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
  51. package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
  52. package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
  53. package/lib/src/generated/api/EmbedRequest.js +2 -0
  54. package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
  55. package/lib/src/generated/api/EntanglementProofInput.js +2 -0
  56. package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
  57. package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
  58. package/lib/src/generated/api/ExportRequest.d.ts +5 -0
  59. package/lib/src/generated/api/ExportRequest.js +2 -0
  60. package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
  61. package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
  62. package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
  63. package/lib/src/generated/api/ExpressionProof.js +2 -0
  64. package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
  65. package/lib/src/generated/api/ExpressionProofInput.js +2 -0
  66. package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
  67. package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
  68. package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
  69. package/lib/src/generated/api/FriendsListRequest.js +2 -0
  70. package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
  71. package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
  72. package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
  73. package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
  74. package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
  75. package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
  76. package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
  77. package/lib/src/generated/api/ImportAgentRequest.js +2 -0
  78. package/lib/src/generated/api/ImportRequest.d.ts +4 -0
  79. package/lib/src/generated/api/ImportRequest.js +2 -0
  80. package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
  81. package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
  82. package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
  83. package/lib/src/generated/api/LanguageMetaInput.js +2 -0
  84. package/lib/src/generated/api/Link.d.ts +5 -0
  85. package/lib/src/generated/api/Link.js +2 -0
  86. package/lib/src/generated/api/LinkExpression.d.ts +10 -0
  87. package/lib/src/generated/api/LinkExpression.js +1 -0
  88. package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
  89. package/lib/src/generated/api/LinkExpressionInput.js +1 -0
  90. package/lib/src/generated/api/LinkInput.d.ts +5 -0
  91. package/lib/src/generated/api/LinkInput.js +2 -0
  92. package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
  93. package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
  94. package/lib/src/generated/api/LinkMutations.d.ts +6 -0
  95. package/lib/src/generated/api/LinkMutations.js +1 -0
  96. package/lib/src/generated/api/LinkStatus.d.ts +1 -0
  97. package/lib/src/generated/api/LinkStatus.js +2 -0
  98. package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
  99. package/lib/src/generated/api/LockAgentRequest.js +2 -0
  100. package/lib/src/generated/api/ModelType.d.ts +1 -0
  101. package/lib/src/generated/api/ModelType.js +2 -0
  102. package/lib/src/generated/api/NotificationInput.d.ts +10 -0
  103. package/lib/src/generated/api/NotificationInput.js +2 -0
  104. package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
  105. package/lib/src/generated/api/OpenLinkRequest.js +2 -0
  106. package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
  107. package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
  108. package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
  109. package/lib/src/generated/api/PerspectiveInput.js +1 -0
  110. package/lib/src/generated/api/PromptRequest.d.ts +4 -0
  111. package/lib/src/generated/api/PromptRequest.js +2 -0
  112. package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
  113. package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
  114. package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
  115. package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
  116. package/lib/src/generated/api/QueryRequest.d.ts +7 -0
  117. package/lib/src/generated/api/QueryRequest.js +2 -0
  118. package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
  119. package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
  120. package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
  121. package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
  122. package/lib/src/generated/api/ResourceInput.d.ts +4 -0
  123. package/lib/src/generated/api/ResourceInput.js +2 -0
  124. package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
  125. package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
  126. package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
  127. package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
  128. package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
  129. package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
  130. package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
  131. package/lib/src/generated/api/SetStatusRequest.js +2 -0
  132. package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
  133. package/lib/src/generated/api/SignMessageRequest.js +2 -0
  134. package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
  135. package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
  136. package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
  137. package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
  138. package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
  139. package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
  140. package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
  141. package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
  142. package/lib/src/generated/api/UserStatistics.d.ts +9 -0
  143. package/lib/src/generated/api/UserStatistics.js +2 -0
  144. package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
  145. package/lib/src/generated/api/VerificationRequestResult.js +2 -0
  146. package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
  147. package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
  148. package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
  149. package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
  150. package/lib/src/generated/api/index.d.ts +42 -0
  151. package/lib/src/generated/api/index.js +7 -0
  152. package/lib/src/index.d.ts +7 -2
  153. package/lib/src/index.js +7 -2
  154. package/lib/src/jestSetup.d.ts +0 -1
  155. package/lib/src/jestSetup.js +1 -1
  156. package/lib/src/language/Icon.js +2 -21
  157. package/lib/src/language/Language.d.ts +26 -176
  158. package/lib/src/language/Language.js +32 -72
  159. package/lib/src/language/LanguageClient.d.ts +2 -2
  160. package/lib/src/language/LanguageClient.js +15 -105
  161. package/lib/src/language/LanguageHandle.js +2 -41
  162. package/lib/src/language/LanguageMeta.js +4 -75
  163. package/lib/src/language/LanguageRef.js +2 -25
  164. package/lib/src/links/Links.js +14 -111
  165. package/lib/src/model/Ad4mModel.d.ts +150 -62
  166. package/lib/src/model/Ad4mModel.js +689 -417
  167. package/lib/src/model/Ad4mModel.test.js +1434 -688
  168. package/lib/src/model/ModelQueryBuilder.d.ts +59 -38
  169. package/lib/src/model/ModelQueryBuilder.js +317 -153
  170. package/lib/src/model/Subject.js +6 -6
  171. package/lib/src/model/decorators.d.ts +36 -8
  172. package/lib/src/model/decorators.js +41 -14
  173. package/lib/src/model/hydration-batch.d.ts +34 -0
  174. package/lib/src/model/hydration-batch.js +147 -0
  175. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  176. package/lib/src/model/hydration-batching.test.js +456 -0
  177. package/lib/src/model/hydration.d.ts +3 -92
  178. package/lib/src/model/hydration.js +3 -691
  179. package/lib/src/model/index.d.ts +3 -4
  180. package/lib/src/model/index.js +3 -4
  181. package/lib/src/model/json-schema.js +2 -2
  182. package/lib/src/model/model-manifest.d.ts +41 -0
  183. package/lib/src/model/model-manifest.js +11 -0
  184. package/lib/src/model/query-cache.d.ts +30 -0
  185. package/lib/src/model/query-cache.js +66 -0
  186. package/lib/src/model/query-cache.test.d.ts +1 -0
  187. package/lib/src/model/query-cache.test.js +43 -0
  188. package/lib/src/model/query-common.d.ts +1 -1
  189. package/lib/src/model/query-common.js +1 -1
  190. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  191. package/lib/src/model/query-sparql-batch.js +260 -0
  192. package/lib/src/model/query-sparql.d.ts +51 -0
  193. package/lib/src/model/query-sparql.js +466 -0
  194. package/lib/src/model/query-sparql.test.d.ts +1 -0
  195. package/lib/src/model/query-sparql.test.js +312 -0
  196. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +13 -9
  197. package/lib/src/model/query-utils.js +189 -0
  198. package/lib/src/model/relation-filtering.test.js +15 -15
  199. package/lib/src/model/sdna.js +1 -1
  200. package/lib/src/model/shacl-gen.js +46 -18
  201. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  202. package/lib/src/model/subscription-delta.test.js +180 -0
  203. package/lib/src/model/subscription-pool.d.ts +39 -0
  204. package/lib/src/model/subscription-pool.js +165 -0
  205. package/lib/src/model/types.d.ts +60 -5
  206. package/lib/src/model/types.js +5 -2
  207. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  208. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  209. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  210. package/lib/src/perspectives/LinkQuery.js +2 -42
  211. package/lib/src/perspectives/Perspective.d.ts +1 -1
  212. package/lib/src/perspectives/Perspective.js +10 -52
  213. package/lib/src/perspectives/PerspectiveClient.d.ts +22 -32
  214. package/lib/src/perspectives/PerspectiveClient.js +189 -454
  215. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  216. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  217. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  218. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  219. package/lib/src/perspectives/PerspectiveProxy.d.ts +156 -78
  220. package/lib/src/perspectives/PerspectiveProxy.js +474 -389
  221. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  222. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  223. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  224. package/lib/src/perspectives/WakerSubscriptionManager.js +12 -12
  225. package/lib/src/runtime/RuntimeClient.d.ts +34 -6
  226. package/lib/src/runtime/RuntimeClient.js +131 -362
  227. package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
  228. package/lib/src/runtime/RuntimeResolver.js +197 -4
  229. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  230. package/lib/src/runtime/RuntimeTypes.js +45 -0
  231. package/lib/src/schema.gql +27 -1
  232. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  233. package/lib/src/shacl/SHACLFlow.js +9 -9
  234. package/lib/src/shacl/SHACLShape.d.ts +8 -1
  235. package/lib/src/shacl/SHACLShape.js +57 -38
  236. package/lib/src/shacl/SHACLShape.test.js +82 -0
  237. package/lib/src/typeDefs.js +3 -602
  238. package/lib/src/utils.d.ts +6 -6
  239. package/lib/src/utils.js +6 -6
  240. package/package.json +6 -18
  241. package/rollup.config.js +0 -7
  242. package/src/Ad4mClient.test.ts +1192 -1288
  243. package/src/Ad4mClient.ts +46 -15
  244. package/src/Literal.test.ts +10 -5
  245. package/src/Literal.ts +6 -5
  246. package/src/agent/Agent.ts +0 -99
  247. package/src/agent/AgentClient.ts +238 -465
  248. package/src/agent/AgentStatus.ts +0 -12
  249. package/src/ai/AIClient.ts +96 -296
  250. package/src/ai/AITypes.ts +66 -0
  251. package/src/ai/Tasks.ts +0 -52
  252. package/src/apiClient.ts +287 -0
  253. package/src/cache/PersistentCache.ts +145 -0
  254. package/src/cache/cache.test.ts +713 -0
  255. package/src/expression/Expression.ts +3 -43
  256. package/src/expression/ExpressionClient.ts +148 -77
  257. package/src/expression/ExpressionRef.ts +2 -8
  258. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  259. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  260. package/src/generated/api/AddLinkRequest.ts +4 -0
  261. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  262. package/src/generated/api/AddSdnaRequest.ts +3 -0
  263. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  264. package/src/generated/api/AuthInfoInput.ts +4 -0
  265. package/src/generated/api/CapabilityInput.ts +4 -0
  266. package/src/generated/api/CommitBatchRequest.ts +3 -0
  267. package/src/generated/api/ComputeLogEntry.ts +3 -0
  268. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  269. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  270. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  271. package/src/generated/api/EmbedRequest.ts +3 -0
  272. package/src/generated/api/EntanglementProofInput.ts +3 -0
  273. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  274. package/src/generated/api/ExportRequest.ts +3 -0
  275. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  276. package/src/generated/api/ExpressionProof.ts +3 -0
  277. package/src/generated/api/ExpressionProofInput.ts +3 -0
  278. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  279. package/src/generated/api/FriendsListRequest.ts +3 -0
  280. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  281. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  282. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  283. package/src/generated/api/ImportAgentRequest.ts +3 -0
  284. package/src/generated/api/ImportRequest.ts +3 -0
  285. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  286. package/src/generated/api/LanguageMetaInput.ts +3 -0
  287. package/src/generated/api/Link.ts +3 -0
  288. package/src/generated/api/LinkExpression.ts +6 -0
  289. package/src/generated/api/LinkExpressionInput.ts +6 -0
  290. package/src/generated/api/LinkInput.ts +3 -0
  291. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  292. package/src/generated/api/LinkMutations.ts +5 -0
  293. package/src/generated/api/LinkStatus.ts +3 -0
  294. package/src/generated/api/LockAgentRequest.ts +3 -0
  295. package/src/generated/api/ModelType.ts +3 -0
  296. package/src/generated/api/NotificationInput.ts +3 -0
  297. package/src/generated/api/OpenLinkRequest.ts +3 -0
  298. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  299. package/src/generated/api/PerspectiveInput.ts +4 -0
  300. package/src/generated/api/PromptRequest.ts +3 -0
  301. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  302. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  303. package/src/generated/api/QueryRequest.ts +6 -0
  304. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  305. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  306. package/src/generated/api/ResourceInput.ts +3 -0
  307. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  308. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  309. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  310. package/src/generated/api/SetStatusRequest.ts +3 -0
  311. package/src/generated/api/SignMessageRequest.ts +3 -0
  312. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  313. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  314. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  315. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  316. package/src/generated/api/UserStatistics.ts +3 -0
  317. package/src/generated/api/VerificationRequestResult.ts +3 -0
  318. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  319. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  320. package/src/generated/api/index.ts +49 -0
  321. package/src/index.ts +7 -2
  322. package/src/jestSetup.ts +1 -1
  323. package/src/language/Icon.ts +0 -4
  324. package/src/language/Language.ts +51 -248
  325. package/src/language/LanguageClient.ts +21 -132
  326. package/src/language/LanguageHandle.ts +0 -14
  327. package/src/language/LanguageMeta.ts +0 -29
  328. package/src/language/LanguageRef.ts +0 -7
  329. package/src/links/Links.ts +0 -37
  330. package/src/model/Ad4mModel.test.ts +1690 -777
  331. package/src/model/Ad4mModel.ts +749 -477
  332. package/src/model/ModelQueryBuilder.ts +356 -171
  333. package/src/model/decorators.ts +71 -22
  334. package/src/model/hydration.ts +3 -772
  335. package/src/model/index.ts +3 -4
  336. package/src/model/json-schema.ts +2 -2
  337. package/src/model/query-cache.test.ts +54 -0
  338. package/src/model/query-cache.ts +79 -0
  339. package/src/model/query-common.ts +1 -1
  340. package/src/model/query-sparql.test.ts +376 -0
  341. package/src/model/query-sparql.ts +504 -0
  342. package/src/model/query-utils.ts +209 -0
  343. package/src/model/relation-filtering.test.ts +15 -15
  344. package/src/model/sdna.ts +1 -1
  345. package/src/model/shacl-gen.ts +47 -17
  346. package/src/model/types.ts +65 -5
  347. package/src/neighbourhood/Neighbourhood.ts +0 -9
  348. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  349. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  350. package/src/perspectives/LinkQuery.ts +0 -15
  351. package/src/perspectives/Perspective.ts +1 -12
  352. package/src/perspectives/PerspectiveClient.test.ts +262 -0
  353. package/src/perspectives/PerspectiveClient.ts +254 -468
  354. package/src/perspectives/PerspectiveDiff.ts +0 -8
  355. package/src/perspectives/PerspectiveHandle.ts +1 -12
  356. package/src/perspectives/PerspectiveProxy.test.ts +125 -0
  357. package/src/perspectives/PerspectiveProxy.ts +522 -434
  358. package/src/perspectives/WakerSubscriptionManager.ts +13 -13
  359. package/src/runtime/RuntimeClient.ts +166 -369
  360. package/src/runtime/RuntimeTypes.ts +144 -0
  361. package/src/shacl/SHACLFlow.ts +9 -9
  362. package/src/shacl/SHACLShape.test.ts +94 -0
  363. package/src/shacl/SHACLShape.ts +66 -39
  364. package/src/typeDefs.ts +3 -5
  365. package/src/utils.ts +6 -6
  366. package/tsconfig.json +3 -7
  367. package/lib/src/model/query-surreal.d.ts +0 -44
  368. package/lib/src/model/query-surreal.js +0 -249
  369. package/lib/src/model/surreal-utils.js +0 -128
  370. package/shims/reflect-metadata.ts +0 -0
  371. package/shims/type-graphql.ts +0 -75
  372. package/src/PubSub.ts +0 -17
  373. package/src/agent/AgentResolver.ts +0 -263
  374. package/src/ai/AIResolver.ts +0 -372
  375. package/src/buildSchema.ts +0 -43
  376. package/src/expression/ExpressionResolver.ts +0 -64
  377. package/src/language/LanguageContext.ts +0 -37
  378. package/src/language/LanguageResolver.ts +0 -98
  379. package/src/model/Subject.ts +0 -159
  380. package/src/model/prolog-facts.ts +0 -145
  381. package/src/model/query-prolog.ts +0 -148
  382. package/src/model/query-surreal.ts +0 -280
  383. package/src/model/surreal-utils.ts +0 -147
  384. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  385. package/src/perspectives/PerspectiveResolver.ts +0 -372
  386. package/src/runtime/RuntimeResolver.ts +0 -617
  387. package/src/unwrapApolloResult.ts +0 -16
  388. package/tsconfig-browser.json +0 -82
@@ -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", () => {
@@ -430,16 +431,16 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
430
431
  });
431
432
  });
432
433
 
433
- describe("Ad4mModel.queryToSurrealQL()", () => {
434
- // Mock perspective proxy (minimal since queryToSurrealQL doesn't actually call it)
434
+
435
+
436
+
437
+ describe("Ad4mModel.queryToSPARQL()", () => {
435
438
  const mockPerspective = {} as any;
436
439
 
437
- // Helper function to normalize whitespace in queries for easier comparison
438
440
  function normalizeQuery(query: string): string {
439
441
  return query.replace(/\s+/g, ' ').trim();
440
442
  }
441
443
 
442
- // Test Recipe model — explicit required: true to test required-property query filters
443
444
  @Model({ name: "Recipe" })
444
445
  class Recipe extends Ad4mModel {
445
446
  @Property({ through: "recipe://name", required: true })
@@ -452,403 +453,172 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
452
453
  ingredients: string[] = [];
453
454
  }
454
455
 
455
- it("should generate basic query with no filters", async () => {
456
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
456
+ it("should generate basic SPARQL query with no filters", async () => {
457
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, {});
458
+ const norm = normalizeQuery(query);
457
459
 
458
- expect(query).toContain("id AS source");
459
- expect(query).toContain("uri AS source_uri");
460
- expect(query).toContain("FROM node");
461
- expect(query).toContain("->link AS links");
462
- expect(query).toContain("WHERE");
463
- // Should have graph traversal filters for required properties
464
- expect(query).toContain("count(->link[WHERE");
460
+ // Must be a SPARQL SELECT
461
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
462
+ // Must have conformance JOIN for required properties using direct triple patterns
463
+ expect(norm).toContain("cfTarget_name");
464
+ expect(norm).toContain("recipe://name");
465
465
  });
466
466
 
467
467
  it("should generate query with simple property filter", async () => {
468
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta" } });
469
-
470
- // Should have graph traversal filters for required properties and user filter
471
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
472
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
473
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
474
- });
475
-
476
- it("should generate query with multiple property filters", async () => {
477
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
478
-
479
- expect(query).toContain("WHERE");
480
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
481
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0");
482
- expect(query).toContain("AND");
483
- });
484
-
485
- it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
486
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
487
-
488
- // Comparison operators for regular properties are now filtered in JavaScript post-query
489
- // The SQL just filters on the predicate existing
490
- expect(query).toContain("FROM node");
491
-
492
- // Should NOT contain comparison operators in SQL for regular properties
493
- expect(query).not.toContain("target > 4");
494
- });
495
-
496
- it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
497
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
498
-
499
- // Comparison operators are filtered in JavaScript post-query
500
- expect(query).toContain("FROM node");
501
- expect(query).not.toContain("target < 3");
502
- });
503
-
504
- it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
505
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
506
-
507
- // Comparison operators are filtered in JavaScript post-query
508
- expect(query).toContain("FROM node");
509
- expect(query).not.toContain("target >= 3");
510
- expect(query).not.toContain("target <= 5");
511
- });
512
-
513
- it("should handle not operator with single value", async () => {
514
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
515
-
516
- // Not operator uses graph traversal with count = 0
517
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0");
518
- });
519
-
520
- it("should handle not operator with array (NOT IN)", async () => {
521
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
522
-
523
- // Not operator with array uses graph traversal with count = 0
524
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Salad', 'Soup']]) = 0");
525
- });
526
-
527
- it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
528
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
529
-
530
- // Between operator for regular properties is now filtered in JavaScript post-query
531
- expect(query).toContain("FROM node");
532
- expect(query).not.toContain("target >= 3");
533
- expect(query).not.toContain("target <= 5");
534
- });
535
-
536
- it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
537
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
538
-
539
- // Contains operator for regular properties is now filtered in JavaScript post-query
540
- expect(query).toContain("FROM node");
541
- expect(query).not.toContain("target CONTAINS 'Past'");
542
- });
543
-
544
- it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
545
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
546
-
547
- // Contains operator is filtered in JavaScript post-query
548
- expect(query).toContain("FROM node");
549
- expect(query).not.toContain("target CONTAINS 'Salad'");
550
- });
551
-
552
- it.skip("should handle contains operator on special field (author)", async () => {
553
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
554
-
555
- expect(query).toContain("WHERE author CONTAINS 'alice'");
556
- // Should not use a subquery pattern
557
- expect(query).not.toContain("SELECT source FROM node");
558
- });
559
-
560
- it.skip("should handle contains operator on special field (id)", async () => {
561
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { contains: "test" } } });
562
-
563
- expect(query).toContain("WHERE source CONTAINS 'test'");
564
- });
565
-
566
- it("should handle array values (IN clause)", async () => {
567
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
568
-
569
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0");
570
- });
571
-
572
- it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
573
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
574
-
575
- expect(query).toContain("WHERE author = 'did:key:alice'");
576
- // Ensure it's NOT using a subquery pattern for author in WHERE clause
577
- expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
578
- });
579
-
580
- it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
581
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
582
-
583
- // ORDER BY is now handled in JavaScript post-query
584
- expect(query).toContain("FROM node");
585
- expect(query).not.toContain("ORDER BY");
586
- });
468
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: "Pasta" } });
469
+ const norm = normalizeQuery(query);
587
470
 
588
- it("should not generate LIMIT clause in SQL (handled in JavaScript)", async () => {
589
- const query = await Recipe.queryToSurrealQL(mockPerspective, { limit: 10 });
590
-
591
- // LIMIT is now handled in JavaScript post-query
592
- expect(query).toContain("FROM node");
593
- expect(query).not.toContain("LIMIT");
471
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
472
+ // For literal-stored properties, SPARQL only adds a JOIN (no FILTER value) — filtering is in JS
473
+ expect(norm).toContain("recipe://name");
474
+ // Value should NOT be in SPARQL — filtering happens in JS post-filter
475
+ expect(norm).toContain("?wTarget_name");
594
476
  });
595
477
 
596
- it("should not generate START clause in SQL (handled in JavaScript)", async () => {
597
- const query = await Recipe.queryToSurrealQL(mockPerspective, { offset: 20 });
478
+ it("should generate query with NOT operator", async () => {
479
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: "Salad" } } });
480
+ const norm = normalizeQuery(query);
598
481
 
599
- // START/offset is now handled in JavaScript post-query
600
- expect(query).toContain("FROM node");
601
- expect(query).not.toContain("START");
482
+ // For literal-stored properties, NOT filtering is done in JS — no NOT EXISTS in SPARQL
483
+ expect(norm).toContain("recipe://name");
602
484
  });
603
485
 
604
- it("should generate complete query with all options (ORDER BY, LIMIT, START handled in JS)", async () => {
605
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
606
- where: { name: "Pasta", rating: { gt: 4 } },
607
- order: { timestamp: "DESC" },
608
- limit: 10,
609
- offset: 20
610
- });
486
+ it("should generate query with NOT IN operator (array)", async () => {
487
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
488
+ const norm = normalizeQuery(query);
611
489
 
612
- // WHERE clause uses graph traversal filters
613
- expect(query).toContain("WHERE");
614
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
615
- // Comparison operators (gt) are filtered in JavaScript, not SQL
616
- expect(query).not.toContain("out.uri > 4");
617
- expect(query).not.toContain("target > 4");
618
- // ORDER BY, LIMIT, START are now handled in JavaScript post-query
619
- expect(query).not.toContain("ORDER BY");
620
- expect(query).not.toContain("LIMIT");
621
- expect(query).not.toContain("START");
490
+ // For literal-stored properties, NOT IN filtering is done in JS — no filter values in SPARQL
491
+ expect(norm).toContain("recipe://name");
622
492
  });
623
493
 
624
- it("should only select requested properties", async () => {
625
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name"] });
494
+ it("should generate query with IN clause (array values)", async () => {
495
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
496
+ const norm = normalizeQuery(query);
626
497
 
627
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
628
- expect(query).toContain("->link AS links");
629
-
498
+ // For literal-stored properties, IN filtering is done in JS — only a JOIN exists
499
+ expect(norm).toContain("recipe://name");
500
+ expect(norm).toContain("?wTarget_name");
630
501
  });
631
502
 
632
- it("should select all link data for relations", async () => {
633
- @Model({ name: "MultiRelationModel" })
634
- class MultiRelationModel extends Ad4mModel {
635
- @HasMany({ through: "test://coll1" })
636
- coll1: string[] = [];
637
-
638
- @HasMany({ through: "test://coll2" })
639
- coll2: string[] = [];
640
- }
641
-
642
- const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
503
+ it("should generate query with base filter", async () => {
504
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { base: "ad4m://test123" } });
505
+ const norm = normalizeQuery(query);
643
506
 
644
- // With array::group(), all link data is selected
645
- expect(query).toContain("->link AS links");
646
-
507
+ expect(norm).toContain("?source =");
508
+ expect(norm).toContain("ad4m://test123");
647
509
  });
648
510
 
649
- it("should escape single quotes in string values", async () => {
650
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
651
-
652
- // Single quotes are escaped with backslash in SurrealDB
653
- expect(query).toContain("O\\'Brien\\'s Recipe");
654
- });
511
+ it("should escape special characters in SPARQL strings", async () => {
512
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: 'O\'Brien' } });
513
+ const norm = normalizeQuery(query);
655
514
 
656
- it("should handle numeric values without quotes", async () => {
657
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
658
-
659
- // Numeric values should not have quotes around them
660
- expect(query).toContain("fn::parse_literal(out.uri) = 5");
661
- expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
515
+ // Should not break the query
516
+ expect(norm).toContain("SELECT ?source");
662
517
  });
663
518
 
664
- it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
665
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
666
- where: {
667
- name: "Pasta",
668
- rating: { gte: 4, lte: 5 },
669
- author: "did:key:alice"
670
- },
671
- order: { rating: "DESC" },
672
- limit: 5
673
- });
519
+ // =========================================================================
520
+ // Additional models for thorough SPARQL structure tests
521
+ // =========================================================================
674
522
 
675
- const normalized = normalizeQuery(query);
523
+ @Model({ name: "Task" })
524
+ class Task extends Ad4mModel {
525
+ @Property({ through: "task://title", resolveLanguage: "literal", required: true })
526
+ title: string = "";
676
527
 
677
- // Verify graph traversal filters are present
678
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
679
- // Comparison operators (gte, lte) are filtered in JavaScript, not SQL
680
- expect(normalized).not.toContain("out.uri >= 4");
681
- expect(normalized).not.toContain("target >= 4");
682
- expect(normalized).not.toContain("out.uri <= 5");
683
- expect(normalized).not.toContain("target <= 5");
684
- // author and timestamp filtering is done in JavaScript post-query
685
- expect(normalized).not.toContain("author = 'did:key:alice'");
528
+ @Property({ through: "task://priority", resolveLanguage: "literal" })
529
+ priority: number = 0;
686
530
 
687
- // ORDER BY and LIMIT are handled in JavaScript post-query
688
- expect(normalized).not.toContain("ORDER BY");
689
- expect(normalized).not.toContain("LIMIT");
531
+ @Property({ through: "task://done", resolveLanguage: "literal" })
532
+ done: boolean = false;
690
533
 
691
- // Verify query structure (FROM node, no GROUP BY)
692
- expect(normalized).toContain("FROM node");
693
- });
534
+ @Optional({ through: "task://description" })
535
+ description: string = "";
694
536
 
695
- it("should handle empty query object", async () => {
696
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
697
-
698
- // Should generate valid query with WHERE clause for required properties (name and rating)
699
- expect(query).toContain("id AS source");
700
- expect(query).toContain("uri AS source_uri");
701
- expect(query).toContain("FROM node");
702
-
703
- // Should have WHERE clause filtering for required properties using graph traversal
704
- expect(query).toContain("WHERE");
705
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
706
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
707
- expect(query).not.toContain("ORDER BY");
708
- expect(query).not.toContain("START");
709
- });
537
+ @HasMany({ through: "task://tag" })
538
+ tags: string[] = [];
710
539
 
711
- it("should handle id special field", async () => {
712
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: "literal://test" } });
713
-
714
- expect(query).toContain("uri = 'literal://test'");
715
- });
540
+ @HasMany({ through: "task://assignee" })
541
+ assignees: string[] = [];
542
+ }
716
543
 
717
- it("should handle id special field with array (IN clause)", async () => {
718
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: ["literal://test1", "literal://test2"] } });
719
-
720
- expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
721
- });
544
+ @Model({ name: "EmptyModel" })
545
+ class EmptyModel extends Ad4mModel {
546
+ @Optional({ through: "empty://optField" })
547
+ optField: string = "";
548
+ }
722
549
 
723
- it("should handle id special field with not operator", async () => {
724
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: "literal://test" } } });
725
-
726
- expect(query).toContain("uri != 'literal://test'");
727
- });
550
+ // ---- Comparison operators (gt, lt, gte, lte, between, contains) ----
551
+ // These are handled in JS post-processing, NOT in SPARQL.
552
+ // The tests verify that the SPARQL still generates valid output (conformance filters)
553
+ // but does NOT inject FILTER clauses for these operators.
728
554
 
729
- it("should handle id special field with not operator and array (NOT IN)", async () => {
730
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: ["literal://test1", "literal://test2"] } } });
731
-
732
- expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
555
+ it("should inject SPARQL FILTER for gt operator", async () => {
556
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 3 } } });
557
+ const norm = normalizeQuery(query);
558
+ expect(norm).toContain("SELECT ?source");
559
+ // gt is now handled via JS post-filter — SPARQL just joins the property
560
+ expect(norm).toContain("wTarget_cmp_rating");
733
561
  });
734
562
 
735
- it("should handle id special field with between operator", async () => {
736
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { between: ["literal://a", "literal://z"] } } } as any);
737
-
738
- const normalized = normalizeQuery(query);
739
- expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
563
+ it("should inject SPARQL FILTER for lt operator", async () => {
564
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { lt: 5 } } });
565
+ const norm = normalizeQuery(query);
566
+ expect(norm).toContain("SELECT ?source");
567
+ // lt is now handled via JS post-filter
568
+ expect(norm).toContain("wTarget_cmp_rating");
740
569
  });
741
570
 
742
- it("should handle id special field with gt operator", async () => {
743
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gt: "literal://m" } } } as any);
744
-
745
- expect(query).toContain("uri > 'literal://m'");
571
+ it("should inject SPARQL FILTER for gte/lte combined", async () => {
572
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gte: 2, lte: 8 } } });
573
+ const norm = normalizeQuery(query);
574
+ expect(norm).toContain("SELECT ?source");
575
+ // gte/lte are now handled via JS post-filter
576
+ expect(norm).toContain("wTarget_cmp_rating");
746
577
  });
747
578
 
748
- it("should handle id special field with gte and lte operators", async () => {
749
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gte: "literal://a", lte: "literal://z" } } } as any);
750
-
751
- const normalized = normalizeQuery(query);
752
- expect(normalized).toContain("uri >= 'literal://a'");
753
- expect(normalized).toContain("uri <= 'literal://z'");
579
+ it("should inject SPARQL FILTER for between operator", async () => {
580
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { between: [1, 10] } } });
581
+ const norm = normalizeQuery(query);
582
+ expect(norm).toContain("SELECT ?source");
583
+ // between is now handled via JS post-filter
584
+ expect(norm).toContain("wTarget_cmp_rating");
754
585
  });
755
586
 
756
- it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
757
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
758
-
759
- // timestamp filtering is done in JavaScript post-query
760
- expect(query).toContain("FROM node");
761
- expect(query).not.toContain("timestamp > 1234567890");
587
+ it("should inject SPARQL FILTER for contains operator", async () => {
588
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { contains: "pasta" } } });
589
+ const norm = normalizeQuery(query);
590
+ expect(norm).toContain("SELECT ?source");
591
+ // contains is now handled via JS post-filter
592
+ expect(norm).toContain("wTarget_cmp_name");
762
593
  });
763
594
 
764
- it("should handle multiple special fields (filtered in JavaScript)", async () => {
765
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
766
- where: {
767
- author: "did:key:alice",
768
- timestamp: { gt: 1000 }
769
- }
770
- });
771
-
772
- // author and timestamp filtering is done in JavaScript post-query
773
- expect(query).toContain("FROM node");
774
- expect(query).not.toContain("author = 'did:key:alice'");
775
- expect(query).not.toContain("timestamp > 1000");
776
- });
595
+ // ---- Multiple property filters combined ----
777
596
 
778
- it("should handle mixed special and regular properties", async () => {
779
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
780
- where: {
781
- name: "Pasta",
782
- author: "did:key:alice",
783
- rating: { gt: 4 }
784
- }
597
+ it("should combine multiple property equality filters with &&", async () => {
598
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, {
599
+ where: { name: "Pasta", rating: ["4", "5"] }
785
600
  });
786
-
787
- const normalized = normalizeQuery(query);
788
- // Regular properties use graph traversal filters
789
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
790
- // Comparison operators (gt) are filtered in JavaScript, not SQL
791
- expect(normalized).not.toContain("out.uri > 4");
792
- expect(normalized).not.toContain("target > 4");
793
- // author filtering is done in JavaScript post-query
794
- expect(normalized).not.toContain("author = 'did:key:alice'");
795
- });
796
-
797
- it("should handle boolean values", async () => {
798
- @Model({ name: "Task" })
799
- class Task extends Ad4mModel {
800
- @Property({ through: "task://completed" })
801
- completed: boolean = false;
802
- }
803
-
804
- const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
805
-
806
- expect(query).toContain("fn::parse_literal(out.uri) = true");
807
- });
808
-
809
- it("should handle array of numbers", async () => {
810
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
811
-
812
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
813
- });
814
-
815
- it("should skip unknown properties in where clause", async () => {
816
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } as any });
817
-
818
- // Should not throw error, just skip the unknown property
819
- expect(query).toContain("source");
820
-
821
- // Should not contain any condition for unknownProp
822
- expect(query).not.toContain("unknownProp");
823
- });
824
-
825
- it.skip("should skip unknown properties in select clause", async () => {
826
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] as any });
827
-
828
- // Should include name using aggregation
829
- expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
830
- // Should not error on unknownProp, just skip it
831
- expect(query).not.toContain("unknownProp");
601
+ const norm = normalizeQuery(query);
602
+ // Should have EXISTS blocks for both name and rating
603
+ expect(norm).toContain("recipe://name");
604
+ expect(norm).toContain("recipe://rating");
605
+ expect(norm).toContain("&&");
832
606
  });
833
607
 
834
- it("should handle order by regular property (handled in JavaScript)", async () => {
835
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
608
+ // ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
836
609
 
837
- // ORDER BY is now handled in JavaScript post-query
838
- expect(query).toContain("FROM node");
839
- expect(query).not.toContain("ORDER BY");
840
- });
841
-
842
- it("should generate query with only properties specified", async () => {
843
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"] });
844
-
845
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
846
- expect(query).toContain("->link AS links");
847
-
610
+ it("should include ORDER BY/LIMIT/OFFSET in SPARQL pagination subquery", async () => {
611
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { order: { name: "ASC" }, limit: 10, offset: 5 });
612
+ const norm = normalizeQuery(query);
613
+ expect(norm).toContain("SELECT ?source");
614
+ // SPARQL-level pagination via subquery
615
+ expect(norm).toContain("ORDER BY");
616
+ expect(norm).toContain("LIMIT 10");
617
+ expect(norm).toContain("OFFSET 5");
618
+ expect(norm).toContain("SELECT DISTINCT ?source");
848
619
  });
849
620
  });
850
-
851
- describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
621
+ describe("Ad4mModel query methods (modelQuery integration)", () => {
852
622
  // Test Recipe model
853
623
  @Model({ name: "Recipe" })
854
624
  class Recipe extends Ad4mModel {
@@ -862,9 +632,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
862
632
  ingredients: string[] = [];
863
633
  }
864
634
 
865
- // Mock perspective with both querySurrealDB and infer methods
635
+ // Mock perspective with querySparql, modelQuery, and infer methods
866
636
  const mockPerspective = {
867
- querySurrealDB: jest.fn(),
637
+ querySparql: jest.fn(),
638
+ modelQuery: jest.fn(),
868
639
  infer: jest.fn(),
869
640
  uuid: 'test-perspective-uuid',
870
641
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -874,337 +645,166 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
874
645
  jest.clearAllMocks();
875
646
  });
876
647
 
877
- it("should convert empty SurrealDB results correctly", async () => {
878
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, []);
879
-
880
- expect(result.results).toEqual([]);
881
- expect(result.totalCount).toBe(0);
882
- });
883
-
884
- it("should convert SurrealDB results to model instances", async () => {
885
- const surrealResults = [
886
- {
887
- source: "node:abc123",
888
- source_uri: "literal://recipe1",
889
- links: [
890
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
891
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
892
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
893
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
894
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
895
- ]
896
- },
897
- {
898
- source: "node:def456",
899
- source_uri: "literal://recipe2",
900
- links: [
901
- { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
902
- { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
903
- { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
904
- { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
905
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
906
- ]
907
- }
908
- ];
909
-
910
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
911
-
912
- expect(result.results).toHaveLength(2);
913
- expect(result.totalCount).toBe(2);
914
-
915
- const recipe1 = result.results[0];
916
- expect(recipe1).toBeInstanceOf(Recipe);
917
- expect(recipe1.name).toBe("Pasta");
918
- expect(recipe1.rating).toBe(5);
919
- expect(recipe1.ingredients).toEqual(["pasta", "tomato", "cheese"]);
920
-
921
- const recipe2 = result.results[1];
922
- expect(recipe2).toBeInstanceOf(Recipe);
923
- expect(recipe2.name).toBe("Pizza");
924
- expect(recipe2.rating).toBe(4);
925
- });
926
-
927
- it("should filter properties when query specifies properties", async () => {
928
- const surrealResults = [
929
- {
930
- source: "node:abc123",
931
- source_uri: "literal://recipe1",
932
- links: [
933
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
934
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
935
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
936
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
937
- ]
938
- }
939
- ];
940
-
941
- const result = await Recipe.instancesFromSurrealResult(
942
- mockPerspective,
943
- { properties: ["name"] },
944
- surrealResults
945
- );
946
-
947
- expect(result.results).toHaveLength(1);
948
- const recipe = result.results[0];
949
- expect(recipe.name).toBe("Pasta");
950
- // rating and ingredients should be removed since only "name" was requested
951
- expect(recipe.rating).toBeUndefined();
952
- expect(recipe.ingredients).toBeUndefined();
953
- // author, createdAt, updatedAt are also stripped unless explicitly requested
954
- expect(recipe.author).toBeUndefined();
955
- expect(recipe.timestamp).toBeUndefined();
956
- });
957
-
958
- it("should filter properties when query specifies properties", async () => {
959
- const surrealResults = [
960
- {
961
- source: "node:abc123",
962
- source_uri: "literal://recipe1",
963
- links: [
964
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
965
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
966
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
967
- { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
968
- ]
969
- }
970
- ];
971
-
972
- const result = await Recipe.instancesFromSurrealResult(
973
- mockPerspective,
974
- { properties: ["name"] },
975
- surrealResults
976
- );
977
-
978
- expect(result.results).toHaveLength(1);
979
- const recipe = result.results[0];
980
- expect(recipe.name).toBe("Pasta");
981
- // rating and ingredients should be removed since only "name" was requested
982
- expect(recipe.rating).toBeUndefined();
983
- });
984
-
985
- it("should handle results missing base field", async () => {
986
- const surrealResults = [
987
- {
988
- links: [
989
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
990
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
991
- ]
992
- // Missing source field
993
- } as any
994
- ];
995
-
996
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
997
-
998
- // Should filter out the invalid result (or handle gracefully)
999
- expect(result.results).toHaveLength(0);
1000
- expect(result.totalCount).toBe(0);
1001
- });
1002
-
1003
- it("should use SurrealDB by default in findAll()", async () => {
1004
- const surrealResults = [
1005
- {
1006
- source: "node:abc123",
1007
- source_uri: "literal://recipe1",
1008
- links: [
1009
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1010
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1011
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1012
- ]
1013
- }
1014
- ];
1015
-
1016
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
648
+ it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
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
+ });
1017
656
 
1018
- const results = await Recipe.findAll(mockPerspective, {});
657
+ const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
1019
658
 
1020
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
659
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1021
660
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1022
661
  expect(results).toHaveLength(1);
1023
662
  expect(results[0].name).toBe("Pasta");
1024
663
  });
1025
664
 
1026
- it("should use Prolog when useSurrealDB is false in findAll()", async () => {
1027
- const prologResults = [{
1028
- AllInstances: [
1029
- ["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"] }
1030
669
  ],
1031
- TotalCount: 1
1032
- }];
1033
-
1034
- mockPerspective.infer.mockResolvedValue(prologResults);
670
+ totalCount: 1
671
+ });
1035
672
 
1036
673
  const results = await Recipe.findAll(mockPerspective, {}, false);
1037
674
 
1038
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1039
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
675
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
676
+ expect(mockPerspective.infer).not.toHaveBeenCalled();
1040
677
  expect(results).toHaveLength(1);
1041
678
  });
1042
679
 
1043
- it("should use SurrealDB by default in findAllAndCount()", async () => {
1044
- const surrealResults = [
1045
- {
1046
- source: "node:abc123",
1047
- source_uri: "literal://recipe1",
1048
- links: [
1049
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1050
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1051
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1052
- ]
1053
- }
1054
- ];
1055
-
1056
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
680
+ it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
681
+ mockPerspective.modelQuery.mockResolvedValue({
682
+ instances: [
683
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
684
+ ],
685
+ totalCount: 1
686
+ });
1057
687
 
1058
688
  const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
1059
689
 
1060
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
690
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1061
691
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1062
692
  expect(results).toHaveLength(1);
1063
693
  expect(totalCount).toBe(1);
1064
694
  });
1065
695
 
1066
- it("should use SurrealDB by default in paginate()", async () => {
1067
- const surrealResults = [
1068
- {
1069
- source: "node:abc123",
1070
- source_uri: "literal://recipe1",
1071
- links: [
1072
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1073
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1074
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1075
- ]
1076
- }
1077
- ];
1078
-
1079
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
696
+ it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
697
+ mockPerspective.modelQuery.mockResolvedValue({
698
+ instances: [
699
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
700
+ ],
701
+ totalCount: 1
702
+ });
1080
703
 
1081
704
  const page = await Recipe.paginate(mockPerspective, 10, 1, {});
1082
705
 
1083
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
706
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1084
707
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1085
708
  expect(page.results).toHaveLength(1);
1086
709
  expect(page.pageSize).toBe(10);
1087
710
  expect(page.pageNumber).toBe(1);
711
+ expect(page.totalCount).toBe(1);
1088
712
  });
1089
713
 
1090
- it("should use SurrealDB by default in count()", async () => {
1091
- // Since count() uses result.length and GROUP BY returns one row per source,
1092
- // mock 5 recipe sources
1093
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1094
- source: `node:abc${i+1}`,
1095
- source_uri: `literal://recipe${i+1}`,
1096
- links: [
1097
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1098
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1099
- ]
1100
- }));
1101
-
1102
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
714
+ it("should use SPARQL in count()", async () => {
715
+ mockPerspective.modelQuery.mockResolvedValue({
716
+ instances: [],
717
+ totalCount: 5
718
+ });
1103
719
 
1104
720
  const count = await Recipe.count(mockPerspective, {});
1105
721
 
1106
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
722
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1107
723
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1108
724
  expect(count).toBe(5);
1109
725
  });
1110
726
 
1111
- it("should use Prolog when useSurrealDB is false in count()", async () => {
1112
- const prologResults = [{ TotalCount: 10 }];
1113
- mockPerspective.infer.mockResolvedValue(prologResults);
727
+ it("should return count from modelQuery", async () => {
728
+ mockPerspective.modelQuery.mockResolvedValue({
729
+ instances: [],
730
+ totalCount: 10
731
+ });
1114
732
 
1115
- const count = await Recipe.count(mockPerspective, {}, false);
733
+ const count = await Recipe.count(mockPerspective, {});
1116
734
 
1117
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1118
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
735
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
736
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1119
737
  expect(count).toBe(10);
1120
738
  });
1121
739
 
1122
- it("should use SurrealDB by default in ModelQueryBuilder.get()", async () => {
1123
- const surrealResults = [
1124
- {
1125
- source: "node:abc123",
1126
- source_uri: "literal://recipe1",
1127
- links: [
1128
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1129
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1130
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1131
- ]
1132
- }
1133
- ];
1134
-
1135
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
740
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
741
+ mockPerspective.modelQuery.mockResolvedValue({
742
+ instances: [
743
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
744
+ ],
745
+ totalCount: 1
746
+ });
1136
747
 
1137
748
  const results = await Recipe.query(mockPerspective)
1138
749
  .where({ name: "Pasta" })
750
+ .engine('sparql')
1139
751
  .get();
1140
752
 
1141
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
753
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1142
754
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1143
755
  expect(results).toHaveLength(1);
1144
756
  expect(results[0].name).toBe("Pasta");
1145
757
  });
1146
758
 
1147
- it("should use Prolog when useSurrealDB(false) in ModelQueryBuilder.get()", async () => {
1148
- const prologResults = [{
1149
- AllInstances: [
1150
- ["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"] }
1151
763
  ],
1152
- TotalCount: 1
1153
- }];
1154
-
1155
- mockPerspective.infer.mockResolvedValue(prologResults);
764
+ totalCount: 1
765
+ });
1156
766
 
1157
767
  const results = await Recipe.query(mockPerspective)
1158
768
  .where({ name: "Pasta" })
1159
- .useSurrealDB(false)
769
+ .engine('prolog')
1160
770
  .get();
1161
771
 
1162
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1163
- expect(mockPerspective.querySurrealDB).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();
1164
775
  expect(results).toHaveLength(1);
1165
776
  });
1166
777
 
1167
- it("should use SurrealDB by default in ModelQueryBuilder.count()", async () => {
1168
- // count() counts the number of rows returned by the query (one row per source)
1169
- const surrealResults = Array.from({ length: 3 }, (_, i) => ({
1170
- source: `node:abc${i+1}`,
1171
- source_uri: `literal://recipe${i+1}`,
1172
- links: [
1173
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1174
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1175
- ]
1176
- }));
1177
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
778
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
779
+ mockPerspective.modelQuery.mockResolvedValue({
780
+ instances: [],
781
+ totalCount: 3
782
+ });
1178
783
 
1179
784
  const count = await Recipe.query(mockPerspective)
1180
785
  .where({ rating: { gt: 4 } })
786
+ .engine('sparql')
1181
787
  .count();
1182
788
 
1183
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
789
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1184
790
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1185
791
  expect(count).toBe(3);
1186
792
  });
1187
793
 
1188
- it("should use SurrealDB by default in ModelQueryBuilder.paginate()", async () => {
1189
- const surrealResults = [
1190
- {
1191
- source: "node:abc123",
1192
- source_uri: "literal://recipe1",
1193
- links: [
1194
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1195
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1196
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1197
- ]
1198
- }
1199
- ];
1200
-
1201
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
794
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
795
+ mockPerspective.modelQuery.mockResolvedValue({
796
+ instances: [
797
+ { id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
798
+ ],
799
+ totalCount: 1
800
+ });
1202
801
 
1203
802
  const page = await Recipe.query(mockPerspective)
1204
803
  .where({ rating: { gt: 3 } })
804
+ .engine('sparql')
1205
805
  .paginate(10, 1);
1206
806
 
1207
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
807
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1208
808
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1209
809
  expect(page.results).toHaveLength(1);
1210
810
  expect(page.pageSize).toBe(10);
@@ -1228,7 +828,8 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1228
828
 
1229
829
  // Mock perspective
1230
830
  const mockPerspective = {
1231
- querySurrealDB: jest.fn(),
831
+ querySparql: jest.fn(),
832
+ modelQuery: jest.fn(),
1232
833
  infer: jest.fn(),
1233
834
  uuid: 'test-perspective-uuid',
1234
835
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -1238,177 +839,96 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1238
839
  jest.clearAllMocks();
1239
840
  });
1240
841
 
1241
- it("should apply JS-level filtering for gt operator on properties in SurrealDB count()", async () => {
1242
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1243
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1244
- source: `node:abc${i+1}`,
1245
- source_uri: `literal://recipe${i+1}`,
1246
- links: [
1247
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1248
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1249
- ]
1250
- }));
1251
-
1252
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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
+ });
1253
848
 
1254
849
  // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1255
850
  const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
1256
851
 
1257
- // Verify count matches the number of instances that would be returned by findAll
1258
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
1259
-
1260
852
  expect(count).toBe(2);
1261
- expect(count).toBe(findAllResults.length);
1262
- });
1263
-
1264
- it("should apply JS-level filtering for between operator on properties in SurrealDB count()", async () => {
1265
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1266
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1267
- source: `node:abc${i+1}`,
1268
- source_uri: `literal://recipe${i+1}`,
1269
- links: [
1270
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1271
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1272
- ]
1273
- }));
1274
-
1275
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
853
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
854
+ });
855
+
856
+ it("should apply filtering for between operator on properties in SPARQL count()", async () => {
857
+ mockPerspective.modelQuery.mockResolvedValue({
858
+ instances: [],
859
+ totalCount: 3
860
+ });
1276
861
 
1277
862
  // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1278
863
  const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1279
864
 
1280
- // Verify count matches the number of instances that would be returned by findAll
1281
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
1282
-
1283
865
  expect(count).toBe(3);
1284
- expect(count).toBe(findAllResults.length);
1285
- });
1286
-
1287
- it("should apply JS-level filtering for timestamp gt operator in SurrealDB count()", async () => {
1288
- // Mock SurrealDB results: 5 recipes with different timestamps
1289
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1290
- source: `node:abc${i+1}`,
1291
- source_uri: `literal://recipe${i+1}`,
1292
- links: [
1293
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1294
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1295
- ]
1296
- }));
1297
-
1298
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
866
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
867
+ });
868
+
869
+ it("should apply filtering for timestamp gt operator in SPARQL count()", async () => {
870
+ mockPerspective.modelQuery.mockResolvedValue({
871
+ instances: [],
872
+ totalCount: 2
873
+ });
1299
874
 
1300
- // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1301
875
  const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1302
876
  const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1303
877
 
1304
- // Verify count matches the number of instances that would be returned by findAll
1305
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1306
-
1307
878
  expect(count).toBe(2);
1308
- expect(count).toBe(findAllResults.length);
1309
- });
1310
-
1311
- it("should apply JS-level filtering for timestamp between operator in SurrealDB count()", async () => {
1312
- // Mock SurrealDB results: 5 recipes with different timestamps
1313
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1314
- source: `node:abc${i+1}`,
1315
- source_uri: `literal://recipe${i+1}`,
1316
- links: [
1317
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1318
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1319
- ]
1320
- }));
1321
-
1322
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
879
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
880
+ });
881
+
882
+ it("should apply filtering for timestamp between operator in SPARQL count()", async () => {
883
+ mockPerspective.modelQuery.mockResolvedValue({
884
+ instances: [],
885
+ totalCount: 3
886
+ });
1323
887
 
1324
- // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1325
888
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1326
889
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1327
890
  const count = await Recipe.count(mockPerspective, {
1328
891
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1329
892
  });
1330
893
 
1331
- // Verify count matches the number of instances that would be returned by findAll
1332
- const findAllResults = await Recipe.findAll(mockPerspective, {
1333
- where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1334
- });
1335
-
1336
894
  expect(count).toBe(3);
1337
- expect(count).toBe(findAllResults.length);
1338
- });
1339
-
1340
- it("should apply JS-level filtering for author filtering in SurrealDB count()", async () => {
1341
- // Mock SurrealDB results: 3 recipes by Alice and 2 by Bob
1342
- const surrealResults = [
1343
- ...Array.from({ length: 3 }, (_, i) => ({
1344
- source: `node:abc${i+1}`,
1345
- source_uri: `literal://recipe${i+1}`,
1346
- links: [
1347
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1348
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1349
- ]
1350
- })),
1351
- ...Array.from({ length: 2 }, (_, i) => ({
1352
- source: `node:def${i+4}`,
1353
- source_uri: `literal://recipe${i+4}`,
1354
- links: [
1355
- { predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1356
- { predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1357
- ]
1358
- }))
1359
- ];
1360
-
1361
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
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
+ });
1362
903
 
1363
904
  // Count recipes by Alice (should match 3 recipes)
1364
905
  const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1365
906
 
1366
- // Verify count matches the number of instances that would be returned by findAll
1367
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
1368
-
1369
907
  expect(count).toBe(3);
1370
- expect(count).toBe(findAllResults.length);
1371
- });
1372
-
1373
- it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1374
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1375
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1376
- source: `node:abc${i+1}`,
1377
- source_uri: `literal://recipe${i+1}`,
1378
- links: [
1379
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1380
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1381
- ]
1382
- }));
1383
-
1384
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
908
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
909
+ });
910
+
911
+ it("should apply filtering in ModelQueryBuilder.count() with gt operator", async () => {
912
+ mockPerspective.modelQuery.mockResolvedValue({
913
+ instances: [],
914
+ totalCount: 2
915
+ });
1385
916
 
1386
917
  // Count recipes with rating > 3 using ModelQueryBuilder
1387
918
  const count = await Recipe.query(mockPerspective)
1388
919
  .where({ rating: { gt: 3 } })
920
+ .engine('sparql')
1389
921
  .count();
1390
922
 
1391
- // Verify count matches the number of instances that would be returned by get()
1392
- const getResults = await Recipe.query(mockPerspective)
1393
- .where({ rating: { gt: 3 } })
1394
- .get();
1395
-
1396
923
  expect(count).toBe(2);
1397
- expect(count).toBe(getResults.length);
1398
- });
1399
-
1400
- it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1401
- // Mock SurrealDB results: 5 recipes with different timestamps
1402
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1403
- source: `node:abc${i+1}`,
1404
- source_uri: `literal://recipe${i+1}`,
1405
- links: [
1406
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1407
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1408
- ]
1409
- }));
1410
-
1411
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
924
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
925
+ });
926
+
927
+ it("should apply filtering in ModelQueryBuilder.count() with timestamp between", async () => {
928
+ mockPerspective.modelQuery.mockResolvedValue({
929
+ instances: [],
930
+ totalCount: 3
931
+ });
1412
932
 
1413
933
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1414
934
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
@@ -1416,44 +936,1437 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1416
936
  // Count using ModelQueryBuilder
1417
937
  const count = await Recipe.query(mockPerspective)
1418
938
  .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
939
+ .engine('sparql')
1419
940
  .count();
1420
941
 
1421
- // Verify count matches the number of instances that would be returned by get()
1422
- const getResults = await Recipe.query(mockPerspective)
1423
- .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1424
- .get();
1425
-
1426
942
  expect(count).toBe(3);
1427
- expect(count).toBe(getResults.length);
943
+ expect(mockPerspective.modelQuery).toHaveBeenCalled();
1428
944
  });
1429
945
 
1430
- it("should handle count() with Prolog for gt operator (legacy)", async () => {
1431
- const prologResults = [{ TotalCount: 2 }];
1432
- mockPerspective.infer.mockResolvedValue(prologResults);
946
+ });
1433
947
 
1434
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1435
-
1436
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1437
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1438
- expect(count).toBe(2);
948
+
949
+ describe("SPARQL comparison filters", () => {
950
+ @Model({ name: "Item" })
951
+ class Item extends Ad4mModel {
952
+ @Property({ through: "item://price", required: true })
953
+ price!: string;
954
+
955
+ @Property({ through: "item://name", required: true })
956
+ name!: string;
957
+ }
958
+
959
+ it("should generate gt filter", async () => {
960
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
961
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { gt: 10 } } });
962
+ // gt is now JS post-filter — SPARQL just joins the property
963
+ expect(query).toContain("item://price");
1439
964
  });
1440
965
 
1441
- it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1442
- const prologResults = [{ TotalCount: 3 }];
1443
- mockPerspective.infer.mockResolvedValue(prologResults);
966
+ it("should generate between filter", async () => {
967
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
968
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { between: [5, 20] } } });
969
+ // between is now JS post-filter
970
+ expect(query).toContain("item://price");
971
+ });
1444
972
 
1445
- const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1446
- const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1447
-
1448
- const count = await Recipe.count(
1449
- mockPerspective,
1450
- { where: { timestamp: { between: [startTimestamp, endTimestamp] } } },
1451
- false
1452
- );
1453
-
1454
- expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1455
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1456
- expect(count).toBe(3);
973
+ it("should generate contains filter", async () => {
974
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
975
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { name: { contains: "widget" } } });
976
+ // contains is now JS post-filter
977
+ expect(query).toContain("item://name");
978
+ });
979
+ });
980
+
981
+ // ──────────────────────────────────────────────────────────
982
+ // SPARQL Direct Triple Pattern & IRI Tests
983
+ // ──────────────────────────────────────────────────────────
984
+
985
+ import { buildSPARQLQuery, formatSPARQLValue } from "./query-sparql";
986
+ import { SHACLShape } from "../shacl/SHACLShape";
987
+
988
+ describe("SPARQL direct triple pattern generation", () => {
989
+ @Model({ name: "Channel" })
990
+ class Channel extends Ad4mModel {
991
+ @Flag({ through: "flux://entry_type", value: "flux://channel" })
992
+ type: string = "";
993
+
994
+ @Property({ through: "flux://name", resolveLanguage: "literal", required: true })
995
+ name: string = "";
996
+
997
+ @Optional({ through: "flux://description" })
998
+ description: string = "";
999
+
1000
+ @HasMany({ through: "flux://has_message" })
1001
+ messages: string[] = [];
1002
+ }
1003
+
1004
+ const mockPersp = {} as any;
1005
+
1006
+ it("generates direct triple pattern with ?source ?predicate ?target", async () => {
1007
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1008
+ // Must use direct triple pattern, not link-node reification
1009
+ expect(query).toContain("?source ?predicate ?target");
1010
+ expect(query).not.toContain("rdf:type");
1011
+ expect(query).not.toContain("ad4m:Link");
1012
+ });
1013
+
1014
+ it("generates Flag filter as ?source <predicate> <value>", async () => {
1015
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1016
+ expect(query).toContain("<flux://entry_type>");
1017
+ expect(query).toContain("<flux://channel>");
1018
+ });
1019
+
1020
+ it("generates Property binding as ?source <predicate> ?varName", async () => {
1021
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1022
+ expect(query).toContain("<flux://name>");
1023
+ expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
1024
+ });
1025
+
1026
+ it("uses RDF 1.2 reifier pattern for author/timestamp", async () => {
1027
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
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");
1034
+ });
1035
+
1036
+ it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
1037
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1038
+ expect(query).toContain("FILTER(isIRI(?source)");
1039
+ });
1040
+ });
1041
+
1042
+
1043
+
1044
+ describe("formatSPARQLValue", () => {
1045
+ it("wraps strings in double quotes", () => {
1046
+ expect(formatSPARQLValue("hello")).toBe('"hello"');
1047
+ });
1048
+
1049
+ it("escapes special characters", () => {
1050
+ expect(formatSPARQLValue('say "hi"')).toBe('"say \\"hi\\""');
1051
+ });
1052
+
1053
+ it("converts numbers to quoted strings", () => {
1054
+ expect(formatSPARQLValue(42)).toBe('"42"');
1457
1055
  });
1458
1056
  });
1459
1057
 
1058
+ // ──────────────────────────────────────────────────────────
1059
+ // Comprehensive SPARQL migration unit tests
1060
+ // ──────────────────────────────────────────────────────────
1061
+
1062
+ import { Literal } from "../Literal";
1063
+
1064
+ // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
1065
+ function literalUrl(value: any): string {
1066
+ if (typeof value === 'string') return Literal.from(value).toUrl();
1067
+ // Use JSON encoding for numbers and booleans since Literal.get() doesn't handle boolean: prefix
1068
+ return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
1069
+ }
1070
+
1071
+ describe("buildSPARQLQuery edge cases", () => {
1072
+ @Model({ name: "FlagModel" })
1073
+ class FlagModel extends Ad4mModel {
1074
+ @Flag({ through: "flag://type", value: "flag://FlagModel" })
1075
+ type: string = "";
1076
+
1077
+ @Property({ through: "flag://name", resolveLanguage: "literal", required: true })
1078
+ name: string = "";
1079
+ }
1080
+
1081
+ @Model({ name: "NoFlagModel" })
1082
+ class NoFlagModel extends Ad4mModel {
1083
+ @Property({ through: "noflag://title", resolveLanguage: "literal" })
1084
+ title: string = "";
1085
+ }
1086
+
1087
+ it("adds conformance JOIN for flag + required properties", () => {
1088
+ const metadata = FlagModel.getModelMetadata();
1089
+ const allRelsMeta = {} as any;
1090
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, FlagModel);
1091
+ // Should contain flag triple pattern
1092
+ expect(sparql).toContain("<flag://type>");
1093
+ expect(sparql).toContain("<flag://FlagModel>");
1094
+ // Should contain required property pattern
1095
+ expect(sparql).toContain("<flag://name>");
1096
+ });
1097
+
1098
+ it("uses structural subquery when no conformance patterns exist", () => {
1099
+ const metadata = NoFlagModel.getModelMetadata();
1100
+ const allRelsMeta = {} as any;
1101
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, NoFlagModel);
1102
+ // Should contain structural subquery with DISTINCT
1103
+ expect(sparql).toContain("SELECT DISTINCT ?source");
1104
+ expect(sparql).toContain("<noflag://title>");
1105
+ });
1106
+
1107
+ it("adds JOIN for where-clause on literal-stored fields", () => {
1108
+ const metadata = FlagModel.getModelMetadata();
1109
+ const allRelsMeta = {} as any;
1110
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { name: "test" } }, FlagModel);
1111
+ // Where clause should add a join pattern for name
1112
+ expect(sparql).toContain("flag://name");
1113
+ });
1114
+
1115
+ it("handles where: {id: 'specific-id'} with FILTER on ?source", () => {
1116
+ const metadata = FlagModel.getModelMetadata();
1117
+ const allRelsMeta = {} as any;
1118
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { id: "expr:123" } as any }, FlagModel);
1119
+ // Should filter by source
1120
+ expect(sparql).toContain("expr:123");
1121
+ });
1122
+ });
1123
+
1124
+ // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1125
+ describe("Batch hydration for reverse relations", () => {
1126
+ it("batch hydration should correctly group targets by parent instance ID", () => {
1127
+ // Test the grouping logic used in batch SPARQL hydration
1128
+ const sparqlResults = [
1129
+ { target: "inst:1", source: "child:a" },
1130
+ { target: "inst:1", source: "child:b" },
1131
+ { target: "inst:2", source: "child:c" },
1132
+ { target: "inst:3", source: "child:d" },
1133
+ { target: "inst:3", source: "child:e" },
1134
+ { target: "inst:3", source: "child:f" },
1135
+ ];
1136
+
1137
+ const reverseLinksMap = new Map<string, string[]>();
1138
+ for (const row of sparqlResults) {
1139
+ if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
1140
+ reverseLinksMap.get(row.target)!.push(row.source);
1141
+ }
1142
+
1143
+ expect(reverseLinksMap.get("inst:1")).toEqual(["child:a", "child:b"]);
1144
+ expect(reverseLinksMap.get("inst:2")).toEqual(["child:c"]);
1145
+ expect(reverseLinksMap.get("inst:3")).toEqual(["child:d", "child:e", "child:f"]);
1146
+ });
1147
+
1148
+ it("batch hydration should handle empty relation sets without error", () => {
1149
+ const sparqlResults: any[] = [];
1150
+ const reverseLinksMap = new Map<string, string[]>();
1151
+ for (const row of sparqlResults) {
1152
+ if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
1153
+ reverseLinksMap.get(row.target)!.push(row.source);
1154
+ }
1155
+
1156
+ expect(reverseLinksMap.size).toBe(0);
1157
+ expect(reverseLinksMap.get("nonexistent") || []).toEqual([]);
1158
+ });
1159
+
1160
+ it("batch hydration should return identical results to N+1 hydration (grouping equivalence)", () => {
1161
+ // Simulate N+1: each instance queries separately
1162
+ const instances = [{ id: "inst:1" }, { id: "inst:2" }];
1163
+ const allLinks = [
1164
+ { data: { source: "child:a", predicate: "rel://has", target: "inst:1" } },
1165
+ { data: { source: "child:b", predicate: "rel://has", target: "inst:1" } },
1166
+ { data: { source: "child:c", predicate: "rel://has", target: "inst:2" } },
1167
+ ];
1168
+
1169
+ // N+1 approach
1170
+ const n1Results = new Map<string, string[]>();
1171
+ for (const inst of instances) {
1172
+ const links = allLinks.filter(l => l.data.target === inst.id);
1173
+ n1Results.set(inst.id, links.map(l => l.data.source));
1174
+ }
1175
+
1176
+ // Batch approach
1177
+ const batchResults = new Map<string, string[]>();
1178
+ const sparqlRows = allLinks.map(l => ({ target: l.data.target, source: l.data.source }));
1179
+ for (const row of sparqlRows) {
1180
+ if (!batchResults.has(row.target)) batchResults.set(row.target, []);
1181
+ batchResults.get(row.target)!.push(row.source);
1182
+ }
1183
+
1184
+ // Results should be identical
1185
+ for (const inst of instances) {
1186
+ expect(batchResults.get(inst.id)).toEqual(n1Results.get(inst.id));
1187
+ }
1188
+ });
1189
+
1190
+ it("batch hydration with nested includes should use batched queries at each level", () => {
1191
+ // This test verifies the structure: nested includes result in multiple
1192
+ // batch operations, one per relation depth level
1193
+ const depth0Rows = [
1194
+ { target: "root:1", source: "mid:a" },
1195
+ { target: "root:1", source: "mid:b" },
1196
+ ];
1197
+ const depth1Rows = [
1198
+ { target: "mid:a", source: "leaf:x" },
1199
+ { target: "mid:b", source: "leaf:y" },
1200
+ ];
1201
+
1202
+ // Group each level
1203
+ const level0Map = new Map<string, string[]>();
1204
+ for (const r of depth0Rows) {
1205
+ if (!level0Map.has(r.target)) level0Map.set(r.target, []);
1206
+ level0Map.get(r.target)!.push(r.source);
1207
+ }
1208
+
1209
+ const level1Map = new Map<string, string[]>();
1210
+ for (const r of depth1Rows) {
1211
+ if (!level1Map.has(r.target)) level1Map.set(r.target, []);
1212
+ level1Map.get(r.target)!.push(r.source);
1213
+ }
1214
+
1215
+ expect(level0Map.get("root:1")).toEqual(["mid:a", "mid:b"]);
1216
+ expect(level1Map.get("mid:a")).toEqual(["leaf:x"]);
1217
+ expect(level1Map.get("mid:b")).toEqual(["leaf:y"]);
1218
+ });
1219
+ });
1220
+
1221
+ // ── Push-down FILTER for literal equality (3.5) ──────────────────────────────
1222
+ describe("Push-down FILTER for literal equality", () => {
1223
+ const mockPerspective = {} as any;
1224
+
1225
+ @Model({ name: "FilterTest" })
1226
+ class FilterTest extends Ad4mModel {
1227
+ @Property({ through: "ft://name", required: true })
1228
+ name: string = "";
1229
+ @Property({ through: "ft://rating", required: true })
1230
+ rating: number = 0;
1231
+ }
1232
+
1233
+ const normalizeQuery = (q: string) => q.replace(/\s+/g, " ").trim();
1234
+
1235
+ it("SPARQL query for where: { name: 'Alice' } should use <ad4m://fn/parse_literal> FILTER", async () => {
1236
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1237
+ const norm = normalizeQuery(query);
1238
+ // JOIN pattern exists
1239
+ expect(norm).toContain("?wTarget_name");
1240
+ // parse_literal push-down FILTER is present (using correct SPARQL IRI syntax)
1241
+ expect(norm).toContain("ad4m://fn/parse_literal");
1242
+ expect(norm).not.toContain("fn::parse_literal");
1243
+ });
1244
+
1245
+ it("SPARQL query for where: { name: ['Alice', 'Bob'] } should use <ad4m://fn/parse_literal> IN FILTER", async () => {
1246
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: ["Alice", "Bob"] } });
1247
+ const norm = normalizeQuery(query);
1248
+ expect(norm).toContain("?wTarget_name");
1249
+ expect(norm).toContain("ad4m://fn/parse_literal");
1250
+ expect(norm).not.toContain("fn::parse_literal");
1251
+ });
1252
+
1253
+ it("SPARQL query for where: { rating: { gt: 5 } } should NOT include parse_literal FILTER", async () => {
1254
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 5 } } });
1255
+ const norm = normalizeQuery(query);
1256
+ expect(norm).not.toContain("parse_literal");
1257
+ });
1258
+
1259
+ it("literal property where clause adds JOIN for JS post-filter", async () => {
1260
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1261
+ const norm = normalizeQuery(query);
1262
+ expect(norm).toContain("?wTarget_name");
1263
+ });
1264
+ });
1265
+
1266
+ // ── Lightweight fingerprint (3.7) ────────────────────────────────────────────
1267
+ describe("Lightweight fingerprint optimization", () => {
1268
+ // Replicate the buildFingerprint logic for testing
1269
+ const buildFingerprint = (results: any[]) => {
1270
+ if (results.length === 0) return '0:';
1271
+ const ids = results.map((r: any) => r.id || '').sort().join(',');
1272
+ const ts = results.map((r: any) => r.updatedAt || r.timestamp || '').join(',');
1273
+ return `${results.length}:${ids}:${ts}`;
1274
+ };
1275
+
1276
+ const base = [
1277
+ { id: "a", updatedAt: "100" },
1278
+ { id: "b", updatedAt: "200" },
1279
+ ];
1280
+
1281
+ it("lightweight fingerprint should detect instance addition", () => {
1282
+ const fp1 = buildFingerprint(base);
1283
+ const fp2 = buildFingerprint([...base, { id: "c", updatedAt: "300" }]);
1284
+ expect(fp1).not.toBe(fp2);
1285
+ });
1286
+
1287
+ it("lightweight fingerprint should detect instance removal", () => {
1288
+ const fp1 = buildFingerprint(base);
1289
+ const fp2 = buildFingerprint([base[0]]);
1290
+ expect(fp1).not.toBe(fp2);
1291
+ });
1292
+
1293
+ it("lightweight fingerprint should detect timestamp change", () => {
1294
+ const fp1 = buildFingerprint(base);
1295
+ const fp2 = buildFingerprint([{ id: "a", updatedAt: "999" }, base[1]]);
1296
+ expect(fp1).not.toBe(fp2);
1297
+ });
1298
+
1299
+ it("lightweight fingerprint should NOT false-positive for identical sets", () => {
1300
+ const fp1 = buildFingerprint(base);
1301
+ const fp2 = buildFingerprint([...base]); // same data, new array
1302
+ expect(fp1).toBe(fp2);
1303
+ });
1304
+ });
1305
+
1306
+
1307
+
1308
+ // ── Subscribe callback timing ──────────────────────────────────────────
1309
+ describe("ModelQueryBuilder subscribe callback timing", () => {
1310
+ it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
1311
+ // This test verifies that subscribe() uses the Rust model subscription endpoint
1312
+ // and properly handles the subscription lifecycle.
1313
+
1314
+ const mockSubscriptionId = "test-sub-123";
1315
+ let updateCallback: ((result: any) => void) | null = null;
1316
+
1317
+ const mockClient = {
1318
+ modelSubscribe: jest.fn().mockResolvedValue({
1319
+ subscriptionId: mockSubscriptionId,
1320
+ result: { instances: [], totalCount: 0 },
1321
+ }),
1322
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1323
+ updateCallback = cb;
1324
+ return () => {}; // unsubscribe function
1325
+ }),
1326
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1327
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1328
+ };
1329
+
1330
+ const mockPerspective = {
1331
+ uuid: "test-uuid",
1332
+ client: mockClient,
1333
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1334
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1335
+ }),
1336
+ getLinks: jest.fn().mockResolvedValue([]),
1337
+ modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
1338
+ } as any;
1339
+
1340
+ const { Ad4mModel, Model, Property, Flag } = require("./index");
1341
+
1342
+ @Model({ name: "TimingTest" })
1343
+ class TimingTest extends Ad4mModel {
1344
+ @Flag({ through: "test://type", value: "test://timing" })
1345
+ type: string = "test://timing";
1346
+ @Property({ through: "test://name" })
1347
+ name: string = "";
1348
+ }
1349
+
1350
+ let callbackInvokedBeforeResolve = false;
1351
+ let promiseResolved = false;
1352
+
1353
+ const query = TimingTest.query(mockPerspective);
1354
+ const promise = query.subscribe((results: any[]) => {
1355
+ if (!promiseResolved) {
1356
+ callbackInvokedBeforeResolve = true;
1357
+ }
1358
+ });
1359
+
1360
+ // At this point the Promise hasn't resolved yet
1361
+ // The callback should NOT have fired synchronously
1362
+ expect(callbackInvokedBeforeResolve).toBe(false);
1363
+
1364
+ const initialResults = await promise;
1365
+ promiseResolved = true;
1366
+
1367
+ expect(initialResults).toEqual([]);
1368
+ expect(mockPerspective.modelSubscribe).toHaveBeenCalled();
1369
+ });
1370
+ });
1371
+
1372
+ describe("ModelQueryBuilder paginateSubscribe", () => {
1373
+ it("paginateSubscribe should use a single query with count: true", async () => {
1374
+ const mockSubscriptionId = "paginate-sub-123";
1375
+
1376
+ const mockClient = {
1377
+ modelSubscribe: jest.fn().mockResolvedValue({
1378
+ subscriptionId: mockSubscriptionId,
1379
+ result: { instances: [], totalCount: 0 },
1380
+ }),
1381
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, _cb: any) => {
1382
+ return () => {};
1383
+ }),
1384
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1385
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1386
+ };
1387
+
1388
+ const mockPerspective = {
1389
+ uuid: "test-uuid",
1390
+ client: mockClient,
1391
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1392
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1393
+ }),
1394
+ modelQuery: jest.fn().mockResolvedValue({ instances: [{ id: "item1", type: "test://paginate" }], totalCount: 42 }),
1395
+ } as any;
1396
+
1397
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1398
+
1399
+ @Model({ name: "PaginateTest" })
1400
+ class PaginateTest extends Ad4mModel {
1401
+ @Flag({ through: "test://type", value: "test://paginate" })
1402
+ type: string = "test://paginate";
1403
+ @Property({ through: "test://name" })
1404
+ name: string = "";
1405
+ }
1406
+
1407
+ const builder = PaginateTest.query(mockPerspective);
1408
+ const result = await builder.paginateSubscribe(10, 1, () => {});
1409
+
1410
+ // Should return paginated result structure
1411
+ expect(result).toHaveProperty("results");
1412
+ expect(result).toHaveProperty("totalCount");
1413
+ expect(result).toHaveProperty("pageSize", 10);
1414
+ expect(result).toHaveProperty("pageNumber", 1);
1415
+
1416
+ // modelQuery should be called exactly once (not twice — no separate count query)
1417
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1418
+
1419
+ // The query should have count: true
1420
+ const callArgs = mockPerspective.modelQuery.mock.calls[0];
1421
+ const queryJson = JSON.parse(callArgs[1]);
1422
+ expect(queryJson.count).toBe(true);
1423
+ expect(queryJson.limit).toBe(10);
1424
+ expect(queryJson.offset).toBe(0);
1425
+ });
1426
+
1427
+ it("paginateSubscribe should re-fetch on real subscription updates", async () => {
1428
+ const mockSubscriptionId = "paginate-update-sub";
1429
+ let capturedCallback: ((result: any) => void) | null = null;
1430
+
1431
+ const mockClient = {
1432
+ modelSubscribe: jest.fn().mockResolvedValue({
1433
+ subscriptionId: mockSubscriptionId,
1434
+ result: { instances: [], totalCount: 0 },
1435
+ }),
1436
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1437
+ capturedCallback = cb;
1438
+ return () => {};
1439
+ }),
1440
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1441
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1442
+ };
1443
+
1444
+ let modelQueryCallCount = 0;
1445
+ const mockPerspective = {
1446
+ uuid: "test-uuid",
1447
+ client: mockClient,
1448
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1449
+ return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1450
+ }),
1451
+ modelQuery: jest.fn().mockImplementation(async () => {
1452
+ modelQueryCallCount++;
1453
+ return { instances: [{ id: "new-item", type: "test://update" }], totalCount: 1 };
1454
+ }),
1455
+ } as any;
1456
+
1457
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1458
+
1459
+ @Model({ name: "UpdateTest" })
1460
+ class UpdateTest extends Ad4mModel {
1461
+ @Flag({ through: "test://type", value: "test://update" })
1462
+ type: string = "test://update";
1463
+ @Property({ through: "test://name" })
1464
+ name: string = "";
1465
+ }
1466
+
1467
+ const userCallback = jest.fn();
1468
+ const builder = UpdateTest.query(mockPerspective);
1469
+ await builder.paginateSubscribe(10, 1, userCallback);
1470
+
1471
+ const initialCallCount = modelQueryCallCount;
1472
+
1473
+ // Simulate a subscription update
1474
+ capturedCallback!({ instances: [{ id: "new-item" }], totalCount: 1 });
1475
+
1476
+ // Wait for async processing
1477
+ await new Promise(r => setTimeout(r, 100));
1478
+
1479
+ // modelQuery should have been called again for the re-fetch
1480
+ expect(modelQueryCallCount).toBeGreaterThan(initialCallCount);
1481
+ // User callback should have been invoked with paginated results
1482
+ expect(userCallback).toHaveBeenCalled();
1483
+ const callArg = userCallback.mock.calls[0][0];
1484
+ expect(callArg).toHaveProperty("totalCount");
1485
+ expect(callArg).toHaveProperty("pageSize", 10);
1486
+ expect(callArg).toHaveProperty("pageNumber", 1);
1487
+ });
1488
+ });
1489
+
1490
+ // ============================================================================
1491
+ // Subscription keepalive recovery tests
1492
+ // ============================================================================
1493
+
1494
+ describe("ModelQueryBuilder keepalive recovery", () => {
1495
+ beforeEach(() => jest.useFakeTimers());
1496
+ afterEach(() => jest.useRealTimers());
1497
+
1498
+ /**
1499
+ * Helper: build a mock perspective whose keepAliveQuery rejects after
1500
+ * `failAfter` successful calls, simulating a server-side subscription
1501
+ * eviction (returns "Subscription not found"). On resubscribe (a second
1502
+ * modelSubscribe call) it returns a *new* subscription ID.
1503
+ */
1504
+ function buildMocks(failAfter = 0) {
1505
+ let keepaliveCallCount = 0;
1506
+ let modelSubscribeCallCount = 0;
1507
+
1508
+ const mockClient = {
1509
+ modelSubscribe: jest.fn().mockImplementation(async () => {
1510
+ modelSubscribeCallCount++;
1511
+ return {
1512
+ subscriptionId: `sub-${modelSubscribeCallCount}`,
1513
+ result: { instances: [], totalCount: 0 },
1514
+ };
1515
+ }),
1516
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, _cb: any) => {
1517
+ return () => {};
1518
+ }),
1519
+ keepAliveQuery: jest.fn().mockImplementation(async () => {
1520
+ keepaliveCallCount++;
1521
+ if (keepaliveCallCount > failAfter) {
1522
+ throw new Error("RPC error 500: Subscription not found");
1523
+ }
1524
+ return true;
1525
+ }),
1526
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1527
+ };
1528
+
1529
+ const mockPerspective = {
1530
+ uuid: "test-uuid",
1531
+ client: mockClient,
1532
+ modelSubscribe: jest.fn().mockImplementation(
1533
+ async (className: string, queryJson: string, shapeJson?: string) =>
1534
+ mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson)
1535
+ ),
1536
+ modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
1537
+ getLinks: jest.fn().mockResolvedValue([]),
1538
+ } as any;
1539
+
1540
+ return { mockClient, mockPerspective, getKeepaliveCount: () => keepaliveCallCount, getSubscribeCount: () => modelSubscribeCallCount };
1541
+ }
1542
+
1543
+ it("subscribe: resubscribes when keepalive gets 'Subscription not found'", async () => {
1544
+ const { mockClient, mockPerspective, getSubscribeCount } = buildMocks(/* failAfter */ 1);
1545
+
1546
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1547
+
1548
+ @Model({ name: "KeepaliveRecoveryTest" })
1549
+ class KeepaliveRecoveryTest extends Ad4mModel {
1550
+ @Flag({ through: "test://type", value: "test://ka" })
1551
+ type: string = "test://ka";
1552
+ @Property({ through: "test://name" })
1553
+ name: string = "";
1554
+ }
1555
+
1556
+ const builder = KeepaliveRecoveryTest.query(mockPerspective);
1557
+ await builder.subscribe(() => {});
1558
+
1559
+ // Initial subscription
1560
+ expect(getSubscribeCount()).toBe(1);
1561
+
1562
+ // First keepalive at 30s — succeeds (failAfter=1)
1563
+ await jest.advanceTimersByTimeAsync(30_000);
1564
+ expect(mockClient.keepAliveQuery).toHaveBeenCalledTimes(1);
1565
+
1566
+ // Second keepalive at 60s — fails → should trigger resubscribe
1567
+ await jest.advanceTimersByTimeAsync(30_000);
1568
+ expect(mockClient.keepAliveQuery).toHaveBeenCalledTimes(2);
1569
+
1570
+ // Allow exponential backoff (2000ms for first retry) + microtask queue to settle
1571
+ await jest.advanceTimersByTimeAsync(2500);
1572
+
1573
+ // A second modelSubscribe call means recovery happened
1574
+ expect(getSubscribeCount()).toBe(2);
1575
+
1576
+ // Clean up
1577
+ builder.dispose();
1578
+ });
1579
+
1580
+ it("countSubscribe: resubscribes when keepalive gets 'Subscription not found'", async () => {
1581
+ const { mockClient, mockPerspective, getSubscribeCount } = buildMocks(0); // fail immediately
1582
+
1583
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1584
+
1585
+ @Model({ name: "CountKeepaliveTest" })
1586
+ class CountKeepaliveTest extends Ad4mModel {
1587
+ @Flag({ through: "test://type", value: "test://cka" })
1588
+ type: string = "test://cka";
1589
+ @Property({ through: "test://name" })
1590
+ name: string = "";
1591
+ }
1592
+
1593
+ const builder = CountKeepaliveTest.query(mockPerspective);
1594
+ await builder.countSubscribe(() => {});
1595
+
1596
+ expect(getSubscribeCount()).toBe(1);
1597
+
1598
+ // First keepalive at 30s — fails immediately → should trigger resubscribe
1599
+ await jest.advanceTimersByTimeAsync(30_000);
1600
+ // Allow exponential backoff (2000ms for first retry) + microtask queue to settle
1601
+ await jest.advanceTimersByTimeAsync(2500);
1602
+
1603
+ expect(getSubscribeCount()).toBe(2);
1604
+
1605
+ builder.dispose();
1606
+ });
1607
+
1608
+ it("paginateSubscribe: resubscribes when keepalive gets 'Subscription not found'", async () => {
1609
+ const { mockClient, mockPerspective, getSubscribeCount } = buildMocks(0);
1610
+
1611
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1612
+
1613
+ @Model({ name: "PaginateKeepaliveTest" })
1614
+ class PaginateKeepaliveTest extends Ad4mModel {
1615
+ @Flag({ through: "test://type", value: "test://pka" })
1616
+ type: string = "test://pka";
1617
+ @Property({ through: "test://name" })
1618
+ name: string = "";
1619
+ }
1620
+
1621
+ const builder = PaginateKeepaliveTest.query(mockPerspective);
1622
+ await builder.paginateSubscribe(10, 1, () => {});
1623
+
1624
+ expect(getSubscribeCount()).toBe(1);
1625
+
1626
+ await jest.advanceTimersByTimeAsync(30_000);
1627
+ // Allow exponential backoff (2000ms for first retry) + microtask queue to settle
1628
+ await jest.advanceTimersByTimeAsync(2500);
1629
+
1630
+ expect(getSubscribeCount()).toBe(2);
1631
+
1632
+ builder.dispose();
1633
+ });
1634
+
1635
+ it("subscribe: stops retrying after dispose()", async () => {
1636
+ const { mockClient, mockPerspective } = buildMocks(Infinity); // keepalive always succeeds
1637
+
1638
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1639
+
1640
+ @Model({ name: "DisposeTest" })
1641
+ class DisposeTest extends Ad4mModel {
1642
+ @Flag({ through: "test://type", value: "test://disp" })
1643
+ type: string = "test://disp";
1644
+ @Property({ through: "test://name" })
1645
+ name: string = "";
1646
+ }
1647
+
1648
+ const builder = DisposeTest.query(mockPerspective);
1649
+ await builder.subscribe(() => {});
1650
+
1651
+ builder.dispose();
1652
+
1653
+ // Advance well past multiple keepalive intervals
1654
+ await jest.advanceTimersByTimeAsync(120_000);
1655
+
1656
+ // No keepalive calls should have happened after dispose
1657
+ expect(mockClient.keepAliveQuery).toHaveBeenCalledTimes(0);
1658
+ });
1659
+ });
1660
+
1661
+ // ============================================================================
1662
+ // Performance Optimisation Tests
1663
+ // ============================================================================
1664
+
1665
+ import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
1666
+ import { getPropertiesMetadata, getRelationsMetadata, getMemoizedSHACL } from "./decorators";
1667
+
1668
+ describe("QueryCache", () => {
1669
+ beforeEach(() => clearQueryCache());
1670
+
1671
+ it("should return undefined for cache miss", () => {
1672
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
1673
+ });
1674
+
1675
+ it("should return cached result within TTL", () => {
1676
+ const result = [{ s: "test" }];
1677
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", result);
1678
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe(result);
1679
+ });
1680
+
1681
+ it("should expire after TTL", async () => {
1682
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", [{ s: "test" }], 50);
1683
+ await new Promise(r => setTimeout(r, 60));
1684
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
1685
+ });
1686
+
1687
+ it("should cache independently per perspective", () => {
1688
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", "result1");
1689
+ setCachedResult("uuid2", "SELECT ?s WHERE {}", "result2");
1690
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe("result1");
1691
+ expect(getCachedResult("uuid2", "SELECT ?s WHERE {}")).toBe("result2");
1692
+ });
1693
+
1694
+ it("should cache independently per query", () => {
1695
+ setCachedResult("uuid1", "query1", "r1");
1696
+ setCachedResult("uuid1", "query2", "r2");
1697
+ expect(getCachedResult("uuid1", "query1")).toBe("r1");
1698
+ expect(getCachedResult("uuid1", "query2")).toBe("r2");
1699
+ });
1700
+
1701
+ it("should clear all entries", () => {
1702
+ setCachedResult("uuid1", "q1", "r1");
1703
+ setCachedResult("uuid2", "q2", "r2");
1704
+ expect(queryCacheSize()).toBe(2);
1705
+ clearQueryCache();
1706
+ expect(queryCacheSize()).toBe(0);
1707
+ });
1708
+ });
1709
+
1710
+ describe("SHACL Memoisation", () => {
1711
+ it("should memoise generateSHACL() per class", () => {
1712
+ @Model({ name: "MemoTest1" })
1713
+ class MemoTest1 extends Ad4mModel {
1714
+ @Property({ through: "test://name" })
1715
+ name: string = "";
1716
+ }
1717
+
1718
+ const result1 = (MemoTest1 as any).generateSHACL();
1719
+ const result2 = (MemoTest1 as any).generateSHACL();
1720
+ expect(result1).toBe(result2); // Same reference = memoised
1721
+ });
1722
+
1723
+ it("should memoise getPropertiesMetadata per class", () => {
1724
+ @Model({ name: "PropMemoTest" })
1725
+ class PropMemoTest extends Ad4mModel {
1726
+ @Property({ through: "test://x" })
1727
+ x: string = "";
1728
+ }
1729
+
1730
+ const r1 = getPropertiesMetadata(PropMemoTest);
1731
+ const r2 = getPropertiesMetadata(PropMemoTest);
1732
+ expect(r1).toBe(r2); // Same reference
1733
+ });
1734
+
1735
+ it("should memoise getRelationsMetadata per class", () => {
1736
+ @Model({ name: "RelMemoTest" })
1737
+ class RelMemoTest extends Ad4mModel {
1738
+ @HasMany({ through: "test://items" })
1739
+ items: string[] = [];
1740
+ }
1741
+
1742
+ const r1 = getRelationsMetadata(RelMemoTest);
1743
+ const r2 = getRelationsMetadata(RelMemoTest);
1744
+ expect(r1).toBe(r2); // Same reference
1745
+ });
1746
+
1747
+ it("should return different results for different classes", () => {
1748
+ @Model({ name: "ClassA" })
1749
+ class ClassA extends Ad4mModel {
1750
+ @Property({ through: "test://a" })
1751
+ a: string = "";
1752
+ }
1753
+
1754
+ @Model({ name: "ClassB" })
1755
+ class ClassB extends Ad4mModel {
1756
+ @Property({ through: "test://b" })
1757
+ b: string = "";
1758
+ }
1759
+
1760
+ const propsA = getPropertiesMetadata(ClassA);
1761
+ const propsB = getPropertiesMetadata(ClassB);
1762
+ expect(propsA).not.toBe(propsB);
1763
+ expect(propsA).toHaveProperty("a");
1764
+ expect(propsB).toHaveProperty("b");
1765
+ });
1766
+ });
1767
+
1768
+ describe("Lazy Conformance Filters", () => {
1769
+ it("should defer conformance filter resolution until property access", () => {
1770
+ @Model({ name: "LazyTarget2" })
1771
+ class LazyTarget2 extends Ad4mModel {
1772
+ @Flag({ through: "test://type", value: "test://lazy" })
1773
+ type: string = "test://lazy";
1774
+ @Property({ through: "test://name", required: true })
1775
+ name: string = "";
1776
+ }
1777
+
1778
+ @Model({ name: "LazyParent2" })
1779
+ class LazyParent2 extends Ad4mModel {
1780
+ @HasMany(() => LazyTarget2, { through: "test://children" })
1781
+ children: string[] = [];
1782
+ }
1783
+
1784
+ // generateSHACL was called during @Model — the shape exists
1785
+ const shacl = (LazyParent2 as any).generateSHACL();
1786
+ expect(shacl).toBeDefined();
1787
+ expect(shacl.shape).toBeDefined();
1788
+ expect(shacl.name).toBe("LazyParent2");
1789
+ });
1790
+ });
1791
+
1792
+ // ──────────────────────────────────────────────────────────
1793
+ // deepQuery — getter evaluation on collection queries
1794
+ // ──────────────────────────────────────────────────────────
1795
+
1796
+ describe("deepQuery — getter evaluation", () => {
1797
+ @Model({ name: "DeepQueryTestMessage" })
1798
+ class DeepQueryTestMessage extends Ad4mModel {
1799
+ @Flag({ through: "flux://entry_type", value: "flux://message" })
1800
+ type: string = "";
1801
+
1802
+ @Property({ through: "flux://body", resolveLanguage: "literal" })
1803
+ body: string = "";
1804
+
1805
+ @Property({
1806
+ through: "flux://has_reply",
1807
+ getter: `SELECT ?target WHERE { ?source <flux://has_reply> ?target . } LIMIT 1`,
1808
+ })
1809
+ replyingTo?: string;
1810
+
1811
+ @ReadOnly({
1812
+ through: "flux://is_popular",
1813
+ getter: `ASK WHERE { ?source <flux://is_popular> "true" . }`,
1814
+ })
1815
+ isPopular: boolean = false;
1816
+
1817
+ @HasMany({ through: "flux://reaction" })
1818
+ reactions: string[] = [];
1819
+ }
1820
+
1821
+ let sparqlCalls: string[];
1822
+ const mockPerspective: any = {
1823
+ uuid: "test-uuid",
1824
+ modelQuery: jest.fn(async (className: string, queryJson: string, shapeJson: string) => {
1825
+ // Return a basic result for the single-instance getData() path
1826
+ const query = JSON.parse(queryJson);
1827
+ const id = query?.where?.id;
1828
+ if (id) {
1829
+ return {
1830
+ instances: [{ id, body: "Hello" }],
1831
+ totalCount: 1,
1832
+ };
1833
+ }
1834
+ return { instances: [], totalCount: 0 };
1835
+ }),
1836
+ evaluateGetters: jest.fn(async (className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]) => {
1837
+ // Return empty results by default — tests can override this mock
1838
+ const result: Record<string, Record<string, any>> = {};
1839
+ return result;
1840
+ }),
1841
+ querySparql: jest.fn(async (q: string) => {
1842
+ sparqlCalls.push(q);
1843
+ return [];
1844
+ }),
1845
+ get: jest.fn().mockResolvedValue([]),
1846
+ getExpression: jest.fn().mockResolvedValue(null),
1847
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("DeepQueryTestMessage"),
1848
+ };
1849
+
1850
+ beforeEach(() => {
1851
+ sparqlCalls = [];
1852
+ mockPerspective.querySparql.mockClear();
1853
+ mockPerspective.evaluateGetters.mockClear();
1854
+ mockPerspective.modelQuery.mockClear();
1855
+ mockPerspective.get.mockClear();
1856
+ });
1857
+
1858
+ function makeInstances(count: number): InstanceType<typeof DeepQueryTestMessage>[] {
1859
+ return Array.from({ length: count }, (_, i) =>
1860
+ new DeepQueryTestMessage(mockPerspective, `flux://msg-${i}`)
1861
+ );
1862
+ }
1863
+
1864
+ it("single-instance get() delegates getter evaluation to Rust (no JS-side SPARQL)", async () => {
1865
+ const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
1866
+ mockPerspective.querySparql.mockImplementation(async (q: string) => {
1867
+ sparqlCalls.push(q);
1868
+ if (q.includes("flux://msg-single") && !q.includes("flux://has_reply") && !q.includes("flux://is_popular")) {
1869
+ return [
1870
+ { source: "flux://msg-single", predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: "3000" },
1871
+ { source: "flux://msg-single", predicate: "flux://body", target: "literal:string:Hello", author: "did:key:a", timestamp: "3000" },
1872
+ ];
1873
+ }
1874
+ return [];
1875
+ });
1876
+
1877
+ await instance.get();
1878
+ // Getter evaluation now happens Rust-side via evaluate_getters() — no JS SPARQL calls
1879
+ const getterCalls = sparqlCalls.filter(
1880
+ (q) => q.includes("flux://has_reply") || q.includes("flux://is_popular")
1881
+ );
1882
+ expect(getterCalls.length).toBe(0);
1883
+ });
1884
+
1885
+ describe("Ad4mModel.evaluateGetters()", () => {
1886
+ it("resolves getters for a batch of instances via single RPC", async () => {
1887
+ const instances = makeInstances(4);
1888
+
1889
+ await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
1890
+
1891
+ // Should make exactly 1 RPC call via perspective.evaluateGetters
1892
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1893
+ const [className, instanceIds, shapeJson, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1894
+ expect(className).toBe("DeepQueryTestMessage");
1895
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1896
+ expect(propertyNames).toEqual(["replyingTo"]);
1897
+ // No querySparql calls — all done in-process
1898
+ expect(sparqlCalls.length).toBe(0);
1899
+ });
1900
+
1901
+ it("evaluates all getters when propertyNames is omitted", async () => {
1902
+ const instances = makeInstances(2);
1903
+
1904
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
1905
+
1906
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1907
+ const [className, instanceIds, shapeJson, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1908
+ expect(className).toBe("DeepQueryTestMessage");
1909
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1910
+ expect(propertyNames).toBeUndefined();
1911
+ });
1912
+
1913
+ it("applies results to instances and syncs snapshots", async () => {
1914
+ const instances = makeInstances(2);
1915
+ // Simulate Rust returning getter results
1916
+ mockPerspective.evaluateGetters.mockResolvedValueOnce({
1917
+ "flux://msg-0": { replyingTo: "flux://msg-99" },
1918
+ "flux://msg-1": { replyingTo: "flux://msg-88" },
1919
+ });
1920
+
1921
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective, ["replyingTo"]);
1922
+
1923
+ expect((instances[0] as any).replyingTo).toBe("flux://msg-99");
1924
+ expect((instances[1] as any).replyingTo).toBe("flux://msg-88");
1925
+ });
1926
+
1927
+ it("handles empty array gracefully", async () => {
1928
+ await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
1929
+ expect(mockPerspective.evaluateGetters).not.toHaveBeenCalled();
1930
+ });
1931
+ });
1932
+
1933
+ describe("deepQuery via ModelQueryBuilder", () => {
1934
+ it("deepQuery() method sets deepQuery flag on queryParams", () => {
1935
+ const builder = DeepQueryTestMessage.query(mockPerspective);
1936
+ (builder as any).deepQuery();
1937
+ expect((builder as any).queryParams.deepQuery).toBe(true);
1938
+ });
1939
+
1940
+ it("deepQuery defaults to true when not explicitly set", async () => {
1941
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1942
+ await DeepQueryTestMessage.query(mockPerspective).get();
1943
+
1944
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1945
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1946
+ const qi = JSON.parse(queryJson);
1947
+ expect(qi.deepQuery).toBe(true);
1948
+ });
1949
+
1950
+ it("deepQuery can be explicitly set to false", async () => {
1951
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1952
+ await DeepQueryTestMessage.query(mockPerspective).deepQuery(false).get();
1953
+
1954
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1955
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1956
+ const qi = JSON.parse(queryJson);
1957
+ expect(qi.deepQuery).toBe(false);
1958
+ });
1959
+ });
1960
+ });
1961
+
1962
+ // ─── Ad4mModel.fromSHACL() ───────────────────────────────────────────────────
1963
+
1964
+ describe("Ad4mModel.fromSHACL()", () => {
1965
+ function makeShape(targetClass: string, props: Array<import("../shacl/SHACLShape").SHACLPropertyShape>) {
1966
+ const shape = new SHACLShape(targetClass);
1967
+ for (const p of props) shape.addProperty(p);
1968
+ return shape;
1969
+ }
1970
+
1971
+ it("assigns the given name as className", () => {
1972
+ const shape = makeShape("flux://Channel", []);
1973
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1974
+ expect((Cls as any).className).toBe("Channel");
1975
+ expect((new (Cls as any)({}, "flux://1")).className).toBe("Channel");
1976
+ });
1977
+
1978
+ it("registers scalar property (maxCount=1) via setPropertyRegistryEntry", () => {
1979
+ const shape = makeShape("flux://Channel", [
1980
+ { name: "title", path: "flux://has_title", maxCount: 1, writable: true },
1981
+ ]);
1982
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1983
+ const meta = Cls.getModelMetadata();
1984
+ expect(meta.properties["title"]).toBeDefined();
1985
+ expect(meta.properties["title"].predicate).toBe("flux://has_title");
1986
+ expect(meta.properties["title"].readOnly).toBe(false);
1987
+ });
1988
+
1989
+ it("registers collection property (no maxCount) as hasMany relation", () => {
1990
+ const shape = makeShape("flux://Channel", [
1991
+ { name: "messages", path: "flux://has_message" },
1992
+ ]);
1993
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
1994
+ const meta = Cls.getModelMetadata();
1995
+ expect(meta.relations["messages"]).toBeDefined();
1996
+ expect(meta.relations["messages"].predicate).toBe("flux://has_message");
1997
+ expect(meta.relations["messages"].direction).toBe("forward");
1998
+ });
1999
+
2000
+ it("registers collection property (maxCount=5) as hasMany relation", () => {
2001
+ const shape = makeShape("flux://Channel", [
2002
+ { name: "participants", path: "flux://participant", maxCount: 5 },
2003
+ ]);
2004
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2005
+ const meta = Cls.getModelMetadata();
2006
+ expect(meta.relations["participants"]).toBeDefined();
2007
+ expect(meta.relations["participants"].direction).toBe("forward");
2008
+ });
2009
+
2010
+ it("propagates resolveLanguage onto scalar properties", () => {
2011
+ const shape = makeShape("flux://Post", [
2012
+ { name: "body", path: "flux://body", maxCount: 1, resolveLanguage: "literal" },
2013
+ ]);
2014
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2015
+ const meta = Cls.getModelMetadata();
2016
+ expect(meta.properties["body"].resolveLanguage).toBe("literal");
2017
+ });
2018
+
2019
+ it("defaults writable to true when not specified", () => {
2020
+ const shape = makeShape("flux://Post", [
2021
+ { name: "body", path: "flux://body", maxCount: 1 },
2022
+ ]);
2023
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2024
+ const meta = Cls.getModelMetadata();
2025
+ expect(meta.properties["body"].readOnly).toBe(false);
2026
+ });
2027
+
2028
+ it("respects writable:false", () => {
2029
+ const shape = makeShape("flux://Post", [
2030
+ { name: "id", path: "flux://id", maxCount: 1, writable: false },
2031
+ ]);
2032
+ const Cls = Ad4mModel.fromSHACL(shape, "Post");
2033
+ const meta = Cls.getModelMetadata();
2034
+ expect(meta.properties["id"].readOnly).toBe(true);
2035
+ });
2036
+
2037
+ it("registers flag properties (hasValue) as type-discrimination entries", () => {
2038
+ const shape = makeShape("flux://Message", [
2039
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2040
+ { name: "body", path: "flux://body", maxCount: 1 },
2041
+ ]);
2042
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2043
+ const meta = Cls.getModelMetadata();
2044
+ expect(meta.properties["type"]).toBeDefined();
2045
+ expect(meta.properties["type"].predicate).toBe("flux://entry_type");
2046
+ expect(meta.properties["type"].flag).toBe(true);
2047
+ expect(meta.properties["type"].required).toBe(true);
2048
+ expect(meta.properties["type"].initial).toBe("flux://message");
2049
+ expect(meta.properties["body"]).toBeDefined();
2050
+ });
2051
+
2052
+ it("flag property from fromSHACL produces SPARQL type-discriminator triple", () => {
2053
+ const shape = makeShape("flux://Message", [
2054
+ { name: "type", path: "flux://entry_type", hasValue: "flux://message" },
2055
+ { name: "body", path: "flux://body", maxCount: 1 },
2056
+ ]);
2057
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2058
+ const meta = Cls.getModelMetadata();
2059
+ const allRelsMeta = {} as any;
2060
+ const sparql = buildSPARQLQuery(meta, allRelsMeta, {}, Cls);
2061
+ expect(sparql).toContain("<flux://entry_type>");
2062
+ expect(sparql).toContain("<flux://message>");
2063
+ });
2064
+
2065
+ it("recovers flag value from constructor_actions (backward-compat for old shapes)", () => {
2066
+ const shape = new SHACLShape("flux://Channel");
2067
+ // An old shape: property has NO hasValue, but constructor_actions carries it
2068
+ shape.addProperty({ name: "type", path: "flux://entry_type", maxCount: 1 });
2069
+ shape.addProperty({ name: "name", path: "flux://name", maxCount: 1 });
2070
+ shape.constructor_actions = [
2071
+ { action: "addLink", source: "this", predicate: "flux://entry_type", target: "flux://channel" },
2072
+ ];
2073
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2074
+ const meta = Cls.getModelMetadata();
2075
+ expect(meta.properties["type"]).toBeDefined();
2076
+ expect(meta.properties["type"].flag).toBe(true);
2077
+ expect(meta.properties["type"].initial).toBe("flux://channel");
2078
+ });
2079
+
2080
+ it("skips properties without a name field", () => {
2081
+ const shape = makeShape("flux://Message", [
2082
+ { path: "flux://anonymous" } as any,
2083
+ { name: "body", path: "flux://body", maxCount: 1 },
2084
+ ]);
2085
+ const Cls = Ad4mModel.fromSHACL(shape, "Message");
2086
+ const meta = Cls.getModelMetadata();
2087
+ expect(Object.keys(meta.properties)).toEqual(["body"]);
2088
+ });
2089
+
2090
+ it("propagates local flag onto relations", () => {
2091
+ const shape = makeShape("flux://Channel", [
2092
+ { name: "drafts", path: "flux://draft", local: true },
2093
+ ]);
2094
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2095
+ const meta = Cls.getModelMetadata();
2096
+ expect(meta.relations["drafts"].local).toBe(true);
2097
+ });
2098
+
2099
+ it("applies Model decorator so generateSHACL and generateSDNA are available", () => {
2100
+ const shape = makeShape("flux://Channel", [
2101
+ { name: "title", path: "flux://has_title", maxCount: 1 },
2102
+ ]);
2103
+ const Cls = Ad4mModel.fromSHACL(shape, "Channel");
2104
+ expect(typeof (Cls as any).generateSDNA).toBe("function");
2105
+ expect(typeof (Cls as any).generateSHACL).toBe("function");
2106
+ });
2107
+
2108
+ it("handles shapes with no properties", () => {
2109
+ const shape = makeShape("flux://Empty", []);
2110
+ const Cls = Ad4mModel.fromSHACL(shape, "Empty");
2111
+ const meta = Cls.getModelMetadata();
2112
+ expect(Object.keys(meta.properties)).toHaveLength(0);
2113
+ expect(Object.keys(meta.relations)).toHaveLength(0);
2114
+ });
2115
+ });
2116
+
2117
+ // ---------------------------------------------------------------------------
2118
+ // IncludeProjection — key splitting and query routing
2119
+ // ---------------------------------------------------------------------------
2120
+
2121
+ describe("IncludeProjection type guard and key splitting", () => {
2122
+ // Shared test models
2123
+ @Model({ name: "Signal" })
2124
+ class Signal extends Ad4mModel {
2125
+ @Property({ through: "signal://type" })
2126
+ signalTypeId: string = "";
2127
+
2128
+ @Property({ through: "signal://author" })
2129
+ author: string = "";
2130
+ }
2131
+
2132
+ @Model({ name: "Post" })
2133
+ class Post extends Ad4mModel {
2134
+ @Property({ through: "post://title" })
2135
+ title: string = "";
2136
+
2137
+ @HasMany({ through: "post://signal", target: () => Signal })
2138
+ signals: Signal[] = [];
2139
+
2140
+ @HasMany({ through: "post://comment" })
2141
+ comments: string[] = [];
2142
+ }
2143
+
2144
+ const mockPerspective = {
2145
+ querySparql: jest.fn(),
2146
+ modelQuery: jest.fn(),
2147
+ infer: jest.fn(),
2148
+ uuid: "test-perspective-uuid",
2149
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("Post"),
2150
+ } as any;
2151
+
2152
+ beforeEach(() => {
2153
+ jest.clearAllMocks();
2154
+ mockPerspective.modelQuery.mockResolvedValue({
2155
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 3 }],
2156
+ totalCount: 1,
2157
+ });
2158
+ });
2159
+
2160
+ // --- isIncludeProjection type guard ---
2161
+
2162
+ it("isIncludeProjection returns true for objects with a 'from' field", () => {
2163
+ expect(isIncludeProjection({ from: "signals", count: true })).toBe(true);
2164
+ expect(isIncludeProjection({ from: "comments", limit: 1 })).toBe(true);
2165
+ });
2166
+
2167
+ it("isIncludeProjection returns false for non-projection values", () => {
2168
+ expect(isIncludeProjection(true)).toBe(false);
2169
+ expect(isIncludeProjection(false)).toBe(false);
2170
+ expect(isIncludeProjection(null)).toBe(false);
2171
+ expect(isIncludeProjection(undefined)).toBe(false);
2172
+ expect(isIncludeProjection(42)).toBe(false);
2173
+ // RelationSubQuery (has no 'from' key)
2174
+ expect(isIncludeProjection({ limit: 5, order: { timestamp: "DESC" } })).toBe(false);
2175
+ });
2176
+
2177
+ // --- $-key splitting ---
2178
+
2179
+ it("routes $-prefixed keys to queryInput.projections, not queryInput.include", async () => {
2180
+ await Post.findAll(mockPerspective, {
2181
+ include: {
2182
+ $signalCount: { from: "signals", count: true },
2183
+ comments: true,
2184
+ },
2185
+ });
2186
+
2187
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2188
+ const qi = JSON.parse(queryJson);
2189
+
2190
+ // Normal relation goes to include
2191
+ expect(qi.include?.comments).toBe(true);
2192
+ expect(qi.include?.$signalCount).toBeUndefined();
2193
+
2194
+ // Projection goes to projections
2195
+ expect(qi.projections?.$signalCount).toMatchObject({ from: "signals", count: true });
2196
+ expect(qi.projections?.comments).toBeUndefined();
2197
+ });
2198
+
2199
+ it("routes $-prefixed IncludeProjection values to projections ($ prefix required)", async () => {
2200
+ await Post.findAll(mockPerspective, {
2201
+ include: {
2202
+ $mySignals: { from: "signals", limit: 1 },
2203
+ comments: true,
2204
+ },
2205
+ });
2206
+
2207
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2208
+ const qi = JSON.parse(queryJson);
2209
+
2210
+ expect(qi.projections?.$mySignals).toMatchObject({ from: "signals", limit: 1 });
2211
+ expect(qi.include?.comments).toBe(true);
2212
+ });
2213
+
2214
+ it("does NOT route non-$ keys to projections even if value has 'from' shape", async () => {
2215
+ // $ prefix is required — a key without it goes to include, not projections
2216
+ await Post.findAll(mockPerspective, {
2217
+ include: {
2218
+ mySignals: { from: "signals", limit: 1 } as any,
2219
+ comments: true,
2220
+ },
2221
+ });
2222
+
2223
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2224
+ const qi = JSON.parse(queryJson);
2225
+
2226
+ // Without $ prefix it stays in include (behaviour is undefined/broken but not silently rerouted)
2227
+ expect(qi.projections?.mySignals).toBeUndefined();
2228
+ expect(qi.include?.mySignals).toBeDefined();
2229
+ });
2230
+
2231
+ it("omits queryInput.include when all keys are projections", async () => {
2232
+ await Post.findAll(mockPerspective, {
2233
+ include: {
2234
+ $count: { from: "signals", count: true },
2235
+ },
2236
+ });
2237
+
2238
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2239
+ const qi = JSON.parse(queryJson);
2240
+
2241
+ expect(qi.include).toBeUndefined();
2242
+ expect(qi.projections?.$count).toMatchObject({ from: "signals", count: true });
2243
+ });
2244
+
2245
+ it("omits queryInput.projections when all keys are normal includes", async () => {
2246
+ await Post.findAll(mockPerspective, {
2247
+ include: { comments: true },
2248
+ });
2249
+
2250
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2251
+ const qi = JSON.parse(queryJson);
2252
+
2253
+ expect(qi.projections).toBeUndefined();
2254
+ expect(qi.include?.comments).toBe(true);
2255
+ });
2256
+
2257
+ it("enriches projection with targetShape when relation target is registered", async () => {
2258
+ await Post.findAll(mockPerspective, {
2259
+ include: {
2260
+ $signalCount: { from: "signals", count: true },
2261
+ },
2262
+ });
2263
+
2264
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2265
+ const qi = JSON.parse(queryJson);
2266
+
2267
+ // targetShape should have been injected from the Signal model
2268
+ // ($ prefix is required for projection enrichment to apply)
2269
+ expect(qi.projections?.$signalCount?.targetShape?.className).toBe("Signal");
2270
+ });
2271
+
2272
+ it("leaves targetShape absent when relation has no target decorator", async () => {
2273
+ await Post.findAll(mockPerspective, {
2274
+ include: {
2275
+ $commentCount: { from: "comments", count: true },
2276
+ },
2277
+ });
2278
+
2279
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
2280
+ const qi = JSON.parse(queryJson);
2281
+
2282
+ // 'comments' HasMany has no target() thunk → no targetShape
2283
+ expect(qi.projections?.$commentCount?.targetShape).toBeUndefined();
2284
+ });
2285
+
2286
+ // --- result passthrough ---
2287
+
2288
+ it("returns $-keyed projection values attached by Rust on instances", async () => {
2289
+ mockPerspective.modelQuery.mockResolvedValue({
2290
+ instances: [{ id: "post://1", title: "Hello", $signalCount: 7 }],
2291
+ totalCount: 1,
2292
+ });
2293
+
2294
+ const results = await Post.findAll(mockPerspective, {
2295
+ include: { $signalCount: { from: "signals", count: true } },
2296
+ });
2297
+
2298
+ expect((results[0] as any).$signalCount).toBe(7);
2299
+ });
2300
+
2301
+ // --- hydration of non-count projections ---
2302
+
2303
+ it("passes through scalar non-count projection value hydrated by Rust", async () => {
2304
+ // Rust hydrates projection targets in-process and returns full JSON objects.
2305
+ // The TS layer receives an already-hydrated object and passes it through.
2306
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2307
+ instances: [{ id: "post://1", title: "Hello", $mySignal: { id: "signal://abc", signalTypeId: "type1" } }],
2308
+ totalCount: 1,
2309
+ });
2310
+
2311
+ const results = await Post.findAll(mockPerspective, {
2312
+ include: { $mySignal: { from: "signals", limit: 1 } },
2313
+ });
2314
+
2315
+ const mySignal = (results[0] as any).$mySignal;
2316
+ expect(mySignal).toMatchObject({ id: "signal://abc", signalTypeId: "type1" });
2317
+ });
2318
+
2319
+ it("passes through array non-count projection values hydrated by Rust", async () => {
2320
+ // Rust hydrates all IRIs in the list and returns full JSON objects.
2321
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2322
+ instances: [{
2323
+ id: "post://1", title: "Hello",
2324
+ $recentSignals: [
2325
+ { id: "signal://a", signalTypeId: "type1" },
2326
+ { id: "signal://b", signalTypeId: "type2" },
2327
+ ],
2328
+ }],
2329
+ totalCount: 1,
2330
+ });
2331
+
2332
+ const results = await Post.findAll(mockPerspective, {
2333
+ include: { $recentSignals: { from: "signals" } },
2334
+ });
2335
+
2336
+ const sigs = (results[0] as any).$recentSignals;
2337
+ expect(Array.isArray(sigs)).toBe(true);
2338
+ expect(sigs).toHaveLength(2);
2339
+ expect(sigs[0]).toMatchObject({ id: "signal://a", signalTypeId: "type1" });
2340
+ expect(sigs[1]).toMatchObject({ id: "signal://b", signalTypeId: "type2" });
2341
+ });
2342
+
2343
+ it("passes through raw IRI when Rust cannot hydrate the projection target", async () => {
2344
+ // When the target cannot be resolved, Rust keeps the raw IRI string.
2345
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2346
+ instances: [{ id: "post://1", title: "Hello", $mySignal: "signal://unknown" }],
2347
+ totalCount: 1,
2348
+ });
2349
+
2350
+ const results = await Post.findAll(mockPerspective, {
2351
+ include: { $mySignal: { from: "signals", limit: 1 } },
2352
+ });
2353
+
2354
+ // Raw IRI preserved when no matching target instance exists in the store.
2355
+ expect((results[0] as any).$mySignal).toBe("signal://unknown");
2356
+ });
2357
+
2358
+ it("does NOT attempt hydration for count projections (they return numbers)", async () => {
2359
+ mockPerspective.modelQuery.mockResolvedValueOnce({
2360
+ instances: [{ id: "post://1", $signalCount: 5 }],
2361
+ totalCount: 1,
2362
+ });
2363
+
2364
+ const results = await Post.findAll(mockPerspective, {
2365
+ include: { $signalCount: { from: "signals", count: true } },
2366
+ });
2367
+
2368
+ // Only one modelQuery call — no follow-up findAll for count projections.
2369
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
2370
+ expect((results[0] as any).$signalCount).toBe(5);
2371
+ });
2372
+ });