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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (334) hide show
  1. package/README.md +2 -25
  2. package/jest-setup.ts +1 -1
  3. package/lib/index.cjs +2406 -11070
  4. package/lib/index.js +2209 -10925
  5. package/lib/src/Ad4mClient.d.ts +7 -3
  6. package/lib/src/Ad4mClient.js +29 -13
  7. package/lib/src/agent/Agent.js +26 -272
  8. package/lib/src/agent/AgentClient.d.ts +10 -21
  9. package/lib/src/agent/AgentClient.js +75 -427
  10. package/lib/src/agent/AgentStatus.js +2 -37
  11. package/lib/src/ai/AIClient.d.ts +12 -4
  12. package/lib/src/ai/AIClient.js +81 -285
  13. package/lib/src/ai/AITypes.d.ts +55 -0
  14. package/lib/src/ai/AITypes.js +18 -0
  15. package/lib/src/ai/Tasks.js +10 -133
  16. package/lib/src/apiClient.d.ts +52 -0
  17. package/lib/src/apiClient.js +231 -0
  18. package/lib/src/expression/Expression.d.ts +1 -1
  19. package/lib/src/expression/Expression.js +13 -122
  20. package/lib/src/expression/ExpressionClient.d.ts +3 -3
  21. package/lib/src/expression/ExpressionClient.js +13 -76
  22. package/lib/src/expression/ExpressionRef.js +2 -25
  23. package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
  24. package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
  25. package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
  26. package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
  27. package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
  28. package/lib/src/generated/api/AddLinkRequest.js +1 -0
  29. package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
  30. package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
  31. package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
  32. package/lib/src/generated/api/AddSdnaRequest.js +2 -0
  33. package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
  34. package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
  35. package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
  36. package/lib/src/generated/api/AuthInfoInput.js +1 -0
  37. package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
  38. package/lib/src/generated/api/CapabilityInput.js +1 -0
  39. package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
  40. package/lib/src/generated/api/CommitBatchRequest.js +2 -0
  41. package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
  42. package/lib/src/generated/api/ComputeLogEntry.js +2 -0
  43. package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
  44. package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
  45. package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
  46. package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
  47. package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
  48. package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
  49. package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
  50. package/lib/src/generated/api/EmbedRequest.js +2 -0
  51. package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
  52. package/lib/src/generated/api/EntanglementProofInput.js +2 -0
  53. package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
  54. package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
  55. package/lib/src/generated/api/ExportRequest.d.ts +5 -0
  56. package/lib/src/generated/api/ExportRequest.js +2 -0
  57. package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
  58. package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
  59. package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
  60. package/lib/src/generated/api/ExpressionProof.js +2 -0
  61. package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
  62. package/lib/src/generated/api/ExpressionProofInput.js +2 -0
  63. package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
  64. package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
  65. package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
  66. package/lib/src/generated/api/FriendsListRequest.js +2 -0
  67. package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
  68. package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
  69. package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
  70. package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
  71. package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
  72. package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
  73. package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
  74. package/lib/src/generated/api/ImportAgentRequest.js +2 -0
  75. package/lib/src/generated/api/ImportRequest.d.ts +4 -0
  76. package/lib/src/generated/api/ImportRequest.js +2 -0
  77. package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
  78. package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
  79. package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
  80. package/lib/src/generated/api/LanguageMetaInput.js +2 -0
  81. package/lib/src/generated/api/Link.d.ts +5 -0
  82. package/lib/src/generated/api/Link.js +2 -0
  83. package/lib/src/generated/api/LinkExpression.d.ts +10 -0
  84. package/lib/src/generated/api/LinkExpression.js +1 -0
  85. package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
  86. package/lib/src/generated/api/LinkExpressionInput.js +1 -0
  87. package/lib/src/generated/api/LinkInput.d.ts +5 -0
  88. package/lib/src/generated/api/LinkInput.js +2 -0
  89. package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
  90. package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
  91. package/lib/src/generated/api/LinkMutations.d.ts +6 -0
  92. package/lib/src/generated/api/LinkMutations.js +1 -0
  93. package/lib/src/generated/api/LinkStatus.d.ts +1 -0
  94. package/lib/src/generated/api/LinkStatus.js +2 -0
  95. package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
  96. package/lib/src/generated/api/LockAgentRequest.js +2 -0
  97. package/lib/src/generated/api/ModelType.d.ts +1 -0
  98. package/lib/src/generated/api/ModelType.js +2 -0
  99. package/lib/src/generated/api/NotificationInput.d.ts +10 -0
  100. package/lib/src/generated/api/NotificationInput.js +2 -0
  101. package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
  102. package/lib/src/generated/api/OpenLinkRequest.js +2 -0
  103. package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
  104. package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
  105. package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
  106. package/lib/src/generated/api/PerspectiveInput.js +1 -0
  107. package/lib/src/generated/api/PromptRequest.d.ts +4 -0
  108. package/lib/src/generated/api/PromptRequest.js +2 -0
  109. package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
  110. package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
  111. package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
  112. package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
  113. package/lib/src/generated/api/QueryRequest.d.ts +7 -0
  114. package/lib/src/generated/api/QueryRequest.js +2 -0
  115. package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
  116. package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
  117. package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
  118. package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
  119. package/lib/src/generated/api/ResourceInput.d.ts +4 -0
  120. package/lib/src/generated/api/ResourceInput.js +2 -0
  121. package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
  122. package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
  123. package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
  124. package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
  125. package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
  126. package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
  127. package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
  128. package/lib/src/generated/api/SetStatusRequest.js +2 -0
  129. package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
  130. package/lib/src/generated/api/SignMessageRequest.js +2 -0
  131. package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
  132. package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
  133. package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
  134. package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
  135. package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
  136. package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
  137. package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
  138. package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
  139. package/lib/src/generated/api/UserStatistics.d.ts +9 -0
  140. package/lib/src/generated/api/UserStatistics.js +2 -0
  141. package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
  142. package/lib/src/generated/api/VerificationRequestResult.js +2 -0
  143. package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
  144. package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
  145. package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
  146. package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
  147. package/lib/src/generated/api/index.d.ts +42 -0
  148. package/lib/src/generated/api/index.js +7 -0
  149. package/lib/src/index.d.ts +6 -1
  150. package/lib/src/index.js +6 -1
  151. package/lib/src/jestSetup.d.ts +0 -1
  152. package/lib/src/jestSetup.js +1 -1
  153. package/lib/src/language/Icon.js +2 -21
  154. package/lib/src/language/Language.d.ts +1 -1
  155. package/lib/src/language/Language.js +10 -76
  156. package/lib/src/language/LanguageClient.d.ts +2 -2
  157. package/lib/src/language/LanguageClient.js +15 -105
  158. package/lib/src/language/LanguageHandle.js +2 -41
  159. package/lib/src/language/LanguageMeta.js +4 -75
  160. package/lib/src/language/LanguageRef.js +2 -25
  161. package/lib/src/links/Links.js +14 -111
  162. package/lib/src/model/Ad4mModel.d.ts +57 -38
  163. package/lib/src/model/Ad4mModel.js +594 -460
  164. package/lib/src/model/Ad4mModel.test.js +371 -815
  165. package/lib/src/model/ModelQueryBuilder.d.ts +9 -21
  166. package/lib/src/model/ModelQueryBuilder.js +138 -217
  167. package/lib/src/model/decorators.d.ts +22 -0
  168. package/lib/src/model/decorators.js +7 -0
  169. package/lib/src/model/hydration.d.ts +7 -60
  170. package/lib/src/model/hydration.js +7 -716
  171. package/lib/src/model/index.d.ts +0 -4
  172. package/lib/src/model/index.js +0 -4
  173. package/lib/src/model/model-manifest.d.ts +41 -0
  174. package/lib/src/model/model-manifest.js +11 -0
  175. package/lib/src/model/query-sparql.d.ts +4 -67
  176. package/lib/src/model/query-sparql.js +26 -322
  177. package/lib/src/model/query-sparql.test.js +35 -218
  178. package/lib/src/model/shacl-gen.js +4 -0
  179. package/lib/src/model/types.d.ts +47 -38
  180. package/lib/src/model/types.js +4 -1
  181. package/lib/src/neighbourhood/Neighbourhood.js +4 -32
  182. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
  183. package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
  184. package/lib/src/perspectives/LinkQuery.js +2 -42
  185. package/lib/src/perspectives/Perspective.d.ts +1 -1
  186. package/lib/src/perspectives/Perspective.js +10 -52
  187. package/lib/src/perspectives/PerspectiveClient.d.ts +12 -17
  188. package/lib/src/perspectives/PerspectiveClient.js +169 -429
  189. package/lib/src/perspectives/PerspectiveClient.test.js +55 -0
  190. package/lib/src/perspectives/PerspectiveDiff.js +4 -31
  191. package/lib/src/perspectives/PerspectiveHandle.js +3 -43
  192. package/lib/src/perspectives/PerspectiveProxy.d.ts +92 -71
  193. package/lib/src/perspectives/PerspectiveProxy.js +273 -310
  194. package/lib/src/runtime/RuntimeClient.d.ts +6 -6
  195. package/lib/src/runtime/RuntimeClient.js +93 -467
  196. package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
  197. package/lib/src/runtime/RuntimeTypes.js +45 -0
  198. package/lib/src/shacl/SHACLShape.d.ts +7 -0
  199. package/lib/src/shacl/SHACLShape.js +19 -0
  200. package/lib/src/shacl/SHACLShape.test.js +82 -0
  201. package/lib/src/typeDefs.js +3 -628
  202. package/package.json +9 -24
  203. package/rollup.config.js +0 -7
  204. package/src/Ad4mClient.test.ts +1179 -1340
  205. package/src/Ad4mClient.ts +30 -15
  206. package/src/agent/Agent.ts +0 -99
  207. package/src/agent/AgentClient.ts +112 -526
  208. package/src/agent/AgentStatus.ts +0 -12
  209. package/src/ai/AIClient.ts +96 -296
  210. package/src/ai/AITypes.ts +66 -0
  211. package/src/ai/Tasks.ts +0 -52
  212. package/src/apiClient.ts +283 -0
  213. package/src/expression/Expression.ts +3 -43
  214. package/src/expression/ExpressionClient.ts +14 -77
  215. package/src/expression/ExpressionRef.ts +0 -6
  216. package/src/generated/api/AIModelLoadingStatus.ts +3 -0
  217. package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
  218. package/src/generated/api/AddLinkRequest.ts +4 -0
  219. package/src/generated/api/AddLinksBulkRequest.ts +4 -0
  220. package/src/generated/api/AddSdnaRequest.ts +3 -0
  221. package/src/generated/api/ApplyTemplateRequest.ts +3 -0
  222. package/src/generated/api/AuthInfoInput.ts +4 -0
  223. package/src/generated/api/CapabilityInput.ts +4 -0
  224. package/src/generated/api/CommitBatchRequest.ts +3 -0
  225. package/src/generated/api/ComputeLogEntry.ts +3 -0
  226. package/src/generated/api/CreateExpressionRequest.ts +3 -0
  227. package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
  228. package/src/generated/api/CreateSubjectRequest.ts +3 -0
  229. package/src/generated/api/EmbedRequest.ts +3 -0
  230. package/src/generated/api/EntanglementProofInput.ts +3 -0
  231. package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
  232. package/src/generated/api/ExportRequest.ts +3 -0
  233. package/src/generated/api/ExpressionManyRequest.ts +3 -0
  234. package/src/generated/api/ExpressionProof.ts +3 -0
  235. package/src/generated/api/ExpressionProofInput.ts +3 -0
  236. package/src/generated/api/FriendSendMessageRequest.ts +3 -0
  237. package/src/generated/api/FriendsListRequest.ts +3 -0
  238. package/src/generated/api/GenerateAgentRequest.ts +3 -0
  239. package/src/generated/api/GenerateJwtRequest.ts +3 -0
  240. package/src/generated/api/GetSubjectDataRequest.ts +3 -0
  241. package/src/generated/api/ImportAgentRequest.ts +3 -0
  242. package/src/generated/api/ImportRequest.ts +3 -0
  243. package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
  244. package/src/generated/api/LanguageMetaInput.ts +3 -0
  245. package/src/generated/api/Link.ts +3 -0
  246. package/src/generated/api/LinkExpression.ts +6 -0
  247. package/src/generated/api/LinkExpressionInput.ts +6 -0
  248. package/src/generated/api/LinkInput.ts +3 -0
  249. package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
  250. package/src/generated/api/LinkMutations.ts +5 -0
  251. package/src/generated/api/LinkStatus.ts +3 -0
  252. package/src/generated/api/LockAgentRequest.ts +3 -0
  253. package/src/generated/api/ModelType.ts +3 -0
  254. package/src/generated/api/NotificationInput.ts +3 -0
  255. package/src/generated/api/OpenLinkRequest.ts +3 -0
  256. package/src/generated/api/PermitCapabilityRequest.ts +3 -0
  257. package/src/generated/api/PerspectiveInput.ts +4 -0
  258. package/src/generated/api/PromptRequest.ts +3 -0
  259. package/src/generated/api/PublishLanguageRequest.ts +4 -0
  260. package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
  261. package/src/generated/api/QueryRequest.ts +6 -0
  262. package/src/generated/api/RemoveLinkRequest.ts +4 -0
  263. package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
  264. package/src/generated/api/ResourceInput.ts +3 -0
  265. package/src/generated/api/SetDefaultModelRequest.ts +4 -0
  266. package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
  267. package/src/generated/api/SetMultiUserRequest.ts +3 -0
  268. package/src/generated/api/SetStatusRequest.ts +3 -0
  269. package/src/generated/api/SignMessageRequest.ts +3 -0
  270. package/src/generated/api/TrustedAgentsRequest.ts +3 -0
  271. package/src/generated/api/UnlockAgentRequest.ts +3 -0
  272. package/src/generated/api/UpdateLinkRequest.ts +5 -0
  273. package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
  274. package/src/generated/api/UserStatistics.ts +3 -0
  275. package/src/generated/api/VerificationRequestResult.ts +3 -0
  276. package/src/generated/api/VerifySignatureRequest.ts +3 -0
  277. package/src/generated/api/WriteSettingsRequest.ts +3 -0
  278. package/src/generated/api/index.ts +49 -0
  279. package/src/index.ts +6 -1
  280. package/src/jestSetup.ts +1 -1
  281. package/src/language/Icon.ts +0 -4
  282. package/src/language/Language.ts +2 -23
  283. package/src/language/LanguageClient.ts +21 -132
  284. package/src/language/LanguageHandle.ts +0 -14
  285. package/src/language/LanguageMeta.ts +0 -29
  286. package/src/language/LanguageRef.ts +0 -7
  287. package/src/links/Links.ts +0 -37
  288. package/src/model/Ad4mModel.test.ts +708 -876
  289. package/src/model/Ad4mModel.ts +613 -508
  290. package/src/model/ModelQueryBuilder.ts +178 -244
  291. package/src/model/decorators.ts +29 -0
  292. package/src/model/hydration.ts +9 -766
  293. package/src/model/index.ts +0 -4
  294. package/src/model/query-sparql.test.ts +34 -242
  295. package/src/model/query-sparql.ts +27 -337
  296. package/src/model/shacl-gen.ts +5 -0
  297. package/src/model/types.ts +51 -39
  298. package/src/neighbourhood/Neighbourhood.ts +0 -9
  299. package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
  300. package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
  301. package/src/perspectives/LinkQuery.ts +0 -15
  302. package/src/perspectives/Perspective.ts +1 -12
  303. package/src/perspectives/PerspectiveClient.test.ts +206 -148
  304. package/src/perspectives/PerspectiveClient.ts +228 -442
  305. package/src/perspectives/PerspectiveDiff.ts +0 -8
  306. package/src/perspectives/PerspectiveHandle.ts +1 -12
  307. package/src/perspectives/PerspectiveProxy.test.ts +41 -0
  308. package/src/perspectives/PerspectiveProxy.ts +307 -348
  309. package/src/runtime/RuntimeClient.ts +112 -474
  310. package/src/runtime/RuntimeTypes.ts +144 -0
  311. package/src/shacl/SHACLShape.test.ts +94 -0
  312. package/src/shacl/SHACLShape.ts +27 -0
  313. package/src/typeDefs.ts +3 -5
  314. package/tsconfig.json +3 -7
  315. package/shims/reflect-metadata.ts +0 -0
  316. package/shims/type-graphql.ts +0 -75
  317. package/src/PubSub.ts +0 -17
  318. package/src/agent/AgentResolver.ts +0 -263
  319. package/src/ai/AIResolver.ts +0 -372
  320. package/src/buildSchema.ts +0 -43
  321. package/src/expression/ExpressionResolver.ts +0 -64
  322. package/src/language/LanguageResolver.ts +0 -98
  323. package/src/model/Subject.ts +0 -159
  324. package/src/model/hydration-batch.ts +0 -205
  325. package/src/model/hydration-batching.test.ts +0 -563
  326. package/src/model/prolog-facts.ts +0 -145
  327. package/src/model/query-prolog.ts +0 -148
  328. package/src/model/query-sparql-batch.ts +0 -301
  329. package/src/model/subscription-delta.test.ts +0 -207
  330. package/src/model/subscription-pool.ts +0 -211
  331. package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
  332. package/src/perspectives/PerspectiveResolver.ts +0 -364
  333. package/src/runtime/RuntimeResolver.ts +0 -749
  334. package/src/unwrapApolloResult.ts +0 -16
@@ -2,13 +2,148 @@ import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { makeRandomId } from "./util";
5
- import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
5
+ import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
6
+ import { compileWhereClause } from "./query-utils";
6
7
  import { resolveParentPredicate } from "./query-common";
7
- import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
8
8
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
9
- import { buildSPARQLQuery, buildSPARQLGetDataQuery, groupSPARQLResults, buildSPARQLCountQuery, hasJsOnlyWhereFilters, parseSparqlCount } from "./query-sparql";
9
+ import { buildSPARQLQuery } from "./query-sparql";
10
10
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
11
- import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInstance as _assignValuesToInstance, evaluateCustomGettersForInstance, hydrateRelations, } from "./hydration";
11
+ import { normalizeValue, evaluateCustomGettersForInstance, } from "./hydration";
12
+ // ---------------------------------------------------------------------------
13
+ // Helpers for Rust-side include resolution
14
+ // ---------------------------------------------------------------------------
15
+ /**
16
+ * Recursively enrich relation metadata in the shape with target class shapes
17
+ * so the Rust endpoint can resolve includes in-process (no extra GraphQL
18
+ * round-trips per relation).
19
+ */
20
+ function enrichShapeForIncludes(metadata, include, allRelMeta) {
21
+ for (const [relName, includeVal] of Object.entries(include)) {
22
+ if (!includeVal)
23
+ continue;
24
+ const meta = allRelMeta[relName];
25
+ if (!meta?.target)
26
+ continue;
27
+ const TargetClass = meta.target();
28
+ // Deep-copy so we don't mutate the cached metadata
29
+ const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
30
+ // Ensure the relation is in metadata.relations (fallback for edge cases)
31
+ if (!metadata.relations[relName]) {
32
+ metadata.relations[relName] = {
33
+ name: relName,
34
+ predicate: meta.predicate,
35
+ direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
36
+ ? 'reverse'
37
+ : 'forward',
38
+ };
39
+ }
40
+ const rel = metadata.relations[relName];
41
+ rel.kind = meta.kind;
42
+ rel.maxCount = meta.maxCount;
43
+ rel.targetShape = targetMeta;
44
+ rel.targetClassName = targetMeta.className;
45
+ // Recurse for nested includes
46
+ const nested = typeof includeVal === 'object' && includeVal !== null
47
+ ? includeVal.include
48
+ : undefined;
49
+ if (nested) {
50
+ const targetRelMeta = getRelationsMetadata(TargetClass);
51
+ enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Construct a model class instance from a plain JSON object returned by the
57
+ * Rust endpoint. Recursively converts included relation values (which come
58
+ * back as plain JSON objects) into proper model class instances.
59
+ */
60
+ function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
61
+ const instance = new ModelClass(perspective, json.id || json.baseExpression);
62
+ // When a properties projection is active, remove own properties set by the
63
+ // constructor that are not in the projected JSON. This ensures assertions
64
+ // like `expect(r).to.not.have.own.property("body")` pass.
65
+ if (properties) {
66
+ const jsonKeys = new Set(Object.keys(json));
67
+ for (const key of Object.getOwnPropertyNames(instance)) {
68
+ // Keep internal fields (backing store for getters), id, baseExpression, perspective
69
+ if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_'))
70
+ continue;
71
+ if (!jsonKeys.has(key)) {
72
+ delete instance[key];
73
+ }
74
+ }
75
+ }
76
+ for (const [key, value] of Object.entries(json)) {
77
+ if (key === 'baseExpression' || key === 'id')
78
+ continue;
79
+ // Skip getter-only properties anywhere in the prototype chain
80
+ let isReadonly = false;
81
+ let proto = Object.getPrototypeOf(instance);
82
+ while (proto) {
83
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
84
+ if (desc) {
85
+ isReadonly = !!(desc.get && !desc.set);
86
+ break;
87
+ }
88
+ proto = Object.getPrototypeOf(proto);
89
+ }
90
+ if (isReadonly)
91
+ continue;
92
+ // Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
93
+ if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
94
+ instance[key] = new Date(value).getTime();
95
+ continue;
96
+ }
97
+ instance[key] = value;
98
+ }
99
+ // Apply property transform functions from decorators (only for literal-resolved
100
+ // or no-resolveLanguage properties; non-literal properties are resolved + transformed
101
+ // asynchronously in executeModelQuery).
102
+ try {
103
+ const propsMeta = getPropertiesMetadata(ModelClass);
104
+ for (const [propName, opts] of Object.entries(propsMeta)) {
105
+ const o = opts;
106
+ if (typeof o.transform !== 'function' || !(propName in json))
107
+ continue;
108
+ // Skip non-literal resolveLanguage props — they need async expression resolution first
109
+ if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
110
+ continue;
111
+ instance[propName] = o.transform(instance[propName]);
112
+ }
113
+ }
114
+ catch (_) { /* no metadata available */ }
115
+ // Recursively convert included relation values to class instances
116
+ if (include) {
117
+ const relMeta = getRelationsMetadata(ModelClass);
118
+ for (const [relName, includeVal] of Object.entries(include)) {
119
+ if (!includeVal)
120
+ continue;
121
+ const meta = relMeta[relName];
122
+ if (!meta?.target)
123
+ continue;
124
+ const TargetClass = meta.target();
125
+ const nestedInclude = typeof includeVal === 'object' && includeVal !== null
126
+ ? includeVal.include
127
+ : undefined;
128
+ const nestedProperties = typeof includeVal === 'object' && includeVal !== null
129
+ ? includeVal.properties
130
+ : undefined;
131
+ const raw = instance[relName];
132
+ if (Array.isArray(raw)) {
133
+ instance[relName] = raw.map((item) => {
134
+ if (typeof item === 'object' && item !== null && item.id) {
135
+ return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
136
+ }
137
+ return item;
138
+ });
139
+ }
140
+ else if (typeof raw === 'object' && raw !== null && raw.id) {
141
+ instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
142
+ }
143
+ }
144
+ }
145
+ return instance;
146
+ }
12
147
  /**
13
148
  * Base class for defining data models in AD4M.
14
149
  *
@@ -106,6 +241,13 @@ import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInsta
106
241
  * ```
107
242
  */
108
243
  export class Ad4mModel {
244
+ /**
245
+ * Backwards compatibility alias for createdAt.
246
+ * @deprecated Use createdAt instead. This will be removed in a future version.
247
+ */
248
+ get timestamp() {
249
+ return this.createdAt;
250
+ }
109
251
  /**
110
252
  * Generates the SDNA (Subject DNA) Prolog rules for this model class.
111
253
  * Injected at class-definition time by the `@Model` decorator.
@@ -143,13 +285,6 @@ export class Ad4mModel {
143
285
  }
144
286
  return classCache[perspectiveID];
145
287
  }
146
- /**
147
- * Backwards compatibility alias for createdAt.
148
- * @deprecated Use createdAt instead. This will be removed in a future version.
149
- */
150
- get timestamp() {
151
- return this.createdAt;
152
- }
153
288
  /**
154
289
  * Extracts metadata from decorators for query building.
155
290
  *
@@ -221,7 +356,7 @@ export class Ad4mModel {
221
356
  // Extract relations (relations) from WeakMap registry
222
357
  const relationsMetadata = {};
223
358
  const allRelationsMeta = getRelationsMetadata(this);
224
- const prototypeRelations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
359
+ const prototypeRelations = allRelationsMeta;
225
360
  for (const [relationName, opts] of Object.entries(prototypeRelations)) {
226
361
  const options = opts;
227
362
  relationsMetadata[relationName] = {
@@ -230,6 +365,8 @@ export class Ad4mModel {
230
365
  ...(options.local !== undefined && { local: options.local }),
231
366
  ...(options.getter !== undefined && { getter: options.getter }),
232
367
  direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
368
+ ...(options.kind !== undefined && { kind: options.kind }),
369
+ ...(options.maxCount !== undefined && { maxCount: options.maxCount }),
233
370
  ...(options.target !== undefined && { target: options.target }),
234
371
  ...(options.filter !== undefined && { filter: options.filter }),
235
372
  ...(options.where !== undefined && { where: options.where }),
@@ -304,12 +441,6 @@ export class Ad4mModel {
304
441
  get id() {
305
442
  return this._baseExpression;
306
443
  }
307
- /**
308
- * @deprecated Use `.id` instead. Will be removed in a future version.
309
- */
310
- get baseExpression() {
311
- return this._baseExpression;
312
- }
313
444
  /**
314
445
  * Protected getter for the perspective.
315
446
  * Allows subclasses to access the perspective while keeping it private from external code.
@@ -390,13 +521,6 @@ export class Ad4mModel {
390
521
  ...(metadata.local && { local: true })
391
522
  }];
392
523
  }
393
- /**
394
- * Assigns decoded Prolog property values to an instance.
395
- * Delegates to the standalone function in hydration.ts.
396
- */
397
- static async assignValuesToInstance(perspective, instance, values) {
398
- return _assignValuesToInstance(perspective, instance, values);
399
- }
400
524
  // ──────────────────────────────────────────────────────────
401
525
  // Snapshot / dirty tracking
402
526
  // ──────────────────────────────────────────────────────────
@@ -516,78 +640,52 @@ export class Ad4mModel {
516
640
  return changed;
517
641
  }
518
642
  async getData(opts) {
519
- // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
520
- // Use SPARQL for data queries
643
+ // Route through the Rust model query endpoint — same pipeline as executeModelQuery
644
+ // but for a single instance by ID.
521
645
  try {
522
646
  const ctor = this.constructor;
523
- const metadata = ctor.getModelMetadata();
524
- // Query for all links from this specific node (base expression)
525
- const linksQuery = buildSPARQLGetDataQuery(this._baseExpression);
526
- const links = await this._perspective.querySparql(linksQuery);
527
- if (links && links.length > 0) {
528
- // Core hydration: properties (latest-wins), relations, timestamps/author
529
- const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
530
- await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
531
- }
532
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
533
- const allRelsMeta = getRelationsMetadata(ctor);
534
- const requestedProps = opts?.properties && opts.properties.length > 0 ? new Set(opts.properties) : null;
535
- for (const [relName, relMeta] of Object.entries(allRelsMeta)) {
536
- if (relMeta.kind !== 'belongsToOne' && relMeta.kind !== 'belongsToMany')
537
- continue;
538
- if (requestedProps && !requestedProps.has(relName))
539
- continue;
540
- const reverseLinks = await this._perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: this._baseExpression }));
541
- const sourceIds = reverseLinks
542
- .filter((l) => l.data.target === this._baseExpression)
543
- .map((l) => l.data.source);
544
- if (relMeta.kind === 'belongsToOne') {
545
- this[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
546
- }
547
- else {
548
- this[relName] = sourceIds;
647
+ const query = {
648
+ where: { id: this._baseExpression },
649
+ limit: 1,
650
+ };
651
+ if (opts?.properties)
652
+ query.properties = opts.properties;
653
+ if (opts?.include)
654
+ query.include = opts.include;
655
+ const { results } = await ctor.executeModelQuery(this._perspective, query, null);
656
+ if (results.length > 0) {
657
+ const hydrated = results[0];
658
+ // Copy all hydrated values from the Rust-side result onto this instance
659
+ for (const [key, value] of Object.entries(hydrated)) {
660
+ if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot')
661
+ continue;
662
+ if (key.startsWith('_'))
663
+ continue;
664
+ // Check for readonly getters
665
+ let isReadonly = false;
666
+ let proto = Object.getPrototypeOf(this);
667
+ while (proto) {
668
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
669
+ if (desc) {
670
+ isReadonly = !!(desc.get && !desc.set);
671
+ break;
672
+ }
673
+ proto = Object.getPrototypeOf(proto);
674
+ }
675
+ if (isReadonly)
676
+ continue;
677
+ this[key] = value;
549
678
  }
550
679
  }
551
- // Evaluate SPARQL getters
552
- const getterOpts = opts?.properties || opts?.include
553
- ? { requestedProperties: opts?.properties, include: opts?.include }
554
- : undefined;
555
- await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
556
- // Eager-load relations if requested
557
- if (opts?.include) {
558
- await hydrateRelations(ctor, [this], this._perspective, opts.include);
559
- }
680
+ // Property getters and relation conformance getters are now evaluated
681
+ // Rust-side via evaluate_getters() in model_query.rs.
560
682
  }
561
683
  catch (e) {
562
- console.error(`SPARQL getData also failed for ${this._baseExpression}:`, e);
684
+ console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
563
685
  }
564
- this.takeSnapshot();
686
+ this.takeSnapshot(opts?.include);
565
687
  return this;
566
688
  }
567
- static async queryToProlog(perspective, query, modelClassName) {
568
- const { properties, where, order, offset, limit, count } = query;
569
- const className = modelClassName || (await this.getClassName(perspective));
570
- // Resolve parent predicate from model metadata if needed
571
- const resolvedParentPredicate = query.parent
572
- ? resolveParentPredicate(query.parent, this)
573
- : undefined;
574
- const instanceQueries = [
575
- buildAuthorAndTimestampQuery(),
576
- buildParentQuery(query.parent, resolvedParentPredicate),
577
- buildPropertiesQuery(properties),
578
- buildWhereQuery(where),
579
- ];
580
- const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
581
- const fullQuery = `
582
- findall([Base, Properties, Collections, Timestamp, Author], (
583
- subject_class("${className}", SubjectClass),
584
- instance(SubjectClass, Base),
585
- ${instanceQueries.filter((q) => q).join(", ")}
586
- ), UnsortedInstances),
587
- ${resultSetQueries.filter((q) => q).join(", ")}
588
- `;
589
- return fullQuery;
590
- }
591
689
  /**
592
690
  * Generates a SPARQL query from a Query object.
593
691
  *
@@ -629,301 +727,353 @@ export class Ad4mModel {
629
727
  const allRelMeta = getRelationsMetadata(this);
630
728
  return buildSPARQLQuery(metadata, allRelMeta, query, this);
631
729
  }
632
- static async instancesFromPrologResult(perspective, query, result) {
633
- if (!result?.[0]?.AllInstances)
634
- return { results: [], totalCount: 0 };
635
- // Map results to instances
636
- const requestedProperties = query?.properties || [];
637
- const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
638
- try {
639
- const instance = new this(perspective, Base);
640
- // Remove unrequested attributes from instance
641
- if (requestedProperties.length) {
642
- Object.keys(instance).forEach((key) => {
643
- if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
644
- delete instance[key];
645
- });
730
+ /**
731
+ * Build the JSON parameters needed for a model query/subscription endpoint.
732
+ * Returns the className, queryJson, and shapeJson that the Rust executor expects.
733
+ * @internal
734
+ */
735
+ static prepareModelQueryParams(query = {}, classNameOverride) {
736
+ const metadata = this.getModelMetadata();
737
+ const className = classNameOverride || metadata.className;
738
+ const queryInput = {};
739
+ if (query.parent) {
740
+ const parentPredicate = resolveParentPredicate(query.parent, this);
741
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
742
+ }
743
+ if (query.properties)
744
+ queryInput.properties = query.properties;
745
+ if (query.include)
746
+ queryInput.include = query.include;
747
+ if (query.where)
748
+ queryInput.where = query.where;
749
+ if (query.order) {
750
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
751
+ }
752
+ if (query.offset !== undefined)
753
+ queryInput.offset = query.offset;
754
+ if (query.limit !== undefined)
755
+ queryInput.limit = query.limit;
756
+ if (query.count !== undefined)
757
+ queryInput.count = query.count;
758
+ if (query.include) {
759
+ const allRelMeta = getRelationsMetadata(this);
760
+ enrichShapeForIncludes(metadata, query.include, allRelMeta);
761
+ }
762
+ // Pre-compute conformance getters (with where-clause support)
763
+ {
764
+ const allRelMeta = getRelationsMetadata(this);
765
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
766
+ const rel = relMeta;
767
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
768
+ continue;
769
+ const meta = allRelMeta[relName];
770
+ if (!meta?.target)
771
+ continue;
772
+ try {
773
+ const TargetClass = meta.target();
774
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
775
+ // Only compile where clauses to SPARQL when the target properties
776
+ // are stored as plain IRIs (not signed expressions). Properties
777
+ // without resolveLanguage or with resolveLanguage='literal' store
778
+ // values as signed JSON envelopes, so SPARQL exact-match fails.
779
+ let whereConditions = [];
780
+ if (rel.where) {
781
+ try {
782
+ const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
783
+ let allSparqlFilterable = true;
784
+ if (targetMetadata) {
785
+ for (const propName of Object.keys(rel.where)) {
786
+ if (['id', 'author', 'timestamp'].includes(propName))
787
+ continue;
788
+ const propMeta = targetMetadata.properties[propName];
789
+ if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
790
+ allSparqlFilterable = false;
791
+ break;
792
+ }
793
+ }
794
+ }
795
+ else {
796
+ allSparqlFilterable = false;
797
+ }
798
+ if (allSparqlFilterable) {
799
+ whereConditions = compileWhereClause(rel.where, targetMetadata);
800
+ }
801
+ }
802
+ catch (_) { }
803
+ }
804
+ if (filter) {
805
+ let getter = filter.getter;
806
+ if (whereConditions.length > 0) {
807
+ getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
808
+ }
809
+ rel.getter = getter;
810
+ }
811
+ else if (whereConditions.length > 0) {
812
+ const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
813
+ rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
814
+ }
646
815
  }
647
- // Collect values to assign to instance
648
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
649
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
650
- return instance;
651
- }
652
- catch (error) {
653
- console.error(`Failed to process instance ${Base}:`, error);
654
- // Return null for failed instances - we'll filter these out below
655
- return null;
816
+ catch (_) { }
656
817
  }
657
- }));
658
- const instances = allInstances.filter((instance) => instance !== null);
659
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
660
- if (query.include && instances.length > 0) {
661
- await hydrateRelations(this, instances, perspective, query.include);
662
- }
663
- // Take snapshots for dirty tracking after ALL hydration is complete
664
- // (including eager-loaded relations).
665
- // When `include` is specified, only snapshot those relations.
666
- // Otherwise snapshot ALL fields (properties + relations) since
667
- // hydrateFromLinks populates relations with stable raw IDs.
668
- const snapshotRelations = query.include;
669
- for (const inst of instances) {
670
- inst.takeSnapshot(snapshotRelations);
671
818
  }
672
- return { results: instances, totalCount: result[0].TotalCount };
819
+ return {
820
+ className,
821
+ queryJson: JSON.stringify(queryInput),
822
+ shapeJson: JSON.stringify(metadata),
823
+ };
673
824
  }
674
825
  /**
675
- * Converts SPARQL query results to Ad4mModel instances.
826
+ * Parse raw model query/subscription result JSON into typed model instances.
827
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
828
+ * @internal
829
+ */
830
+ static parseModelResult(perspective, raw, include, properties) {
831
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
832
+ const arr = data.instances || data;
833
+ if (!Array.isArray(arr))
834
+ return [];
835
+ return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
836
+ }
837
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
838
+ /**
839
+ * Execute a model query via the executor-side endpoint.
676
840
  *
677
- * @param perspective - The perspective context
678
- * @param query - The query parameters used
679
- * @param result - Array of result objects from SPARQL
680
- * @returns Promise resolving to results with total count
841
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
842
+ * with a single RPC to the executor that handles everything in Rust.
681
843
  *
682
844
  * @internal
683
845
  */
684
- static async instancesFromQueryResult(perspective, query, result, computeTotalCount = false) {
685
- if (!result || result.length === 0)
686
- return { results: [], totalCount: 0 };
846
+ static async executeModelQuery(perspective, query = {}, classNameOverride) {
687
847
  const metadata = this.getModelMetadata();
688
- const requestedProperties = query?.properties || [];
689
- // The query used GROUP BY with graph traversal, so each row has:
690
- // - source: the node ID (e.g., "node:abc123")
691
- // - source_uri: the actual URI (the base expression)
692
- // - links: array of link objects with {predicate, target, author, timestamp}
693
- const instances = [];
694
- for (const row of result) {
695
- let base;
696
- try {
697
- // Use source_uri as the base (the actual URI), not the node ID
698
- base = row.source_uri;
699
- // Skip rows without a source_uri field
700
- if (!base) {
701
- continue;
702
- }
703
- const links = row.links || [];
704
- const instance = new this(perspective, base);
705
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset).
706
- // Also hydrate any properties referenced in `where` so the JS post-filter can match them,
707
- // even if they're not in the user's `properties` projection.
708
- let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
709
- if (hydrationProps && query.where) {
710
- for (const key of Object.keys(query.where)) {
711
- if (!hydrationProps.includes(key)) {
712
- hydrationProps.push(key);
713
- }
714
- }
848
+ const className = classNameOverride || metadata.className;
849
+ // Expand includeAll: true to a full IncludeMap covering every forward relation.
850
+ // Done before queryInput is built so all downstream uses of query.include see the expansion.
851
+ if (query.includeAll) {
852
+ const allRelMeta = getRelationsMetadata(this);
853
+ const expanded = {};
854
+ for (const [relName, relMeta] of Object.entries(allRelMeta)) {
855
+ if (relMeta.direction !== 'reverse') {
856
+ expanded[relName] = true;
715
857
  }
716
- await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
717
- // NOTE: Property deletion for sparse fieldsets is deferred until AFTER
718
- // where-filtering so that where conditions can reference any property,
719
- // even ones not in the `properties` projection.
720
- instances.push(instance);
721
858
  }
722
- catch (error) {
723
- console.error(`Failed to process SPARQL instance ${base}:`, error);
859
+ // Explicit include entries take precedence over the expansion
860
+ query = { ...query, include: { ...expanded, ...query.include } };
861
+ }
862
+ // Build the query input that the Rust endpoint expects.
863
+ // Convert the TS Query type to the executor's ModelQueryInput format.
864
+ const queryInput = {};
865
+ if (query.parent) {
866
+ const parentPredicate = resolveParentPredicate(query.parent, this);
867
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
868
+ }
869
+ if (query.properties)
870
+ queryInput.properties = query.properties;
871
+ if (query.include) {
872
+ // Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
873
+ // All other keys (boolean | RelationSubQuery) → queryInput.include
874
+ const normalIncludes = {};
875
+ const projections = {};
876
+ for (const [key, val] of Object.entries(query.include)) {
877
+ if (key.startsWith('$')) {
878
+ projections[key] = val;
879
+ }
880
+ else {
881
+ normalIncludes[key] = val;
882
+ }
724
883
  }
725
- }
726
- // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
727
- // These relations point FROM other nodes TO this instance, so they cannot be resolved
728
- // from the node's own outgoing links fetched above. We do a reverse-link lookup here
729
- // so that these fields are populated as IDs even without an explicit include.
730
- const allRelsMeta = getRelationsMetadata(this);
731
- const reverseRelEntries = Object.entries(allRelsMeta).filter(([relName, meta]) => (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
732
- (requestedProperties.length === 0 || requestedProperties.includes(relName)));
733
- if (reverseRelEntries.length > 0 && instances.length > 0) {
734
- await Promise.all(instances.map(async (inst) => {
735
- for (const [relName, relMeta] of reverseRelEntries) {
736
- const reverseLinks = await perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: inst.id }));
737
- const sourceIds = reverseLinks
738
- .filter((l) => l.data.target === inst.id)
739
- .map((l) => l.data.source);
740
- if (relMeta.kind === 'belongsToOne') {
741
- inst[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
742
- }
743
- else {
744
- inst[relName] = sourceIds;
884
+ if (Object.keys(normalIncludes).length > 0)
885
+ queryInput.include = normalIncludes;
886
+ if (Object.keys(projections).length > 0) {
887
+ // Enrich projections with target shapes so Rust can apply where clause filtering
888
+ const allRelMeta = getRelationsMetadata(this);
889
+ for (const [, proj] of Object.entries(projections)) {
890
+ const relMeta = allRelMeta[proj.from];
891
+ if (!proj.targetShape && relMeta?.target) {
892
+ try {
893
+ const TargetClass = relMeta.target();
894
+ const targetMeta = TargetClass.getModelMetadata?.();
895
+ if (targetMeta) {
896
+ proj.targetShape = targetMeta;
897
+ }
898
+ }
899
+ catch (_) { /* target class may not be available */ }
745
900
  }
746
901
  }
747
- }));
748
- }
749
- // Evaluate custom getters for all instances.
750
- // Relation getters (type-conformance filtering) always run — they ensure
751
- // correctness of @HasMany/@HasOne targets. Property getters only run when
752
- // deepQuery is true or when where conditions reference getter-backed properties.
753
- const whereGetterProperties = query.where
754
- ? Object.keys(query.where).filter((propName) => metadata.properties[propName]?.getter)
755
- : [];
756
- const shouldEvaluatePropertyGetters = query.deepQuery === true || whereGetterProperties.length > 0;
757
- {
758
- const skipPropertyGetters = !shouldEvaluatePropertyGetters;
759
- const getterRequestedProperties = shouldEvaluatePropertyGetters
760
- ? (requestedProperties.length > 0
761
- ? Array.from(new Set([...requestedProperties, ...whereGetterProperties]))
762
- : query.deepQuery === true
763
- ? [] // deepQuery: evaluate all getters
764
- : whereGetterProperties) // only evaluate where-referenced getters
765
- : [];
766
- const getterOpts = {
767
- ...(getterRequestedProperties.length > 0 && { requestedProperties: getterRequestedProperties }),
768
- ...(query.include && { include: query.include }),
769
- skipPropertyGetters,
770
- };
771
- for (const instance of instances) {
772
- await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
902
+ queryInput.projections = projections;
773
903
  }
774
904
  }
775
- // Filter by where conditions that couldn't be filtered in SPARQL
776
- // This includes:
777
- // - author/timestamp (computed from grouped links)
778
- // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
779
- // because <ad4m://fn/parse_literal>() returns strings, making numeric/date
780
- // comparisons unreliable. Equality, IN, and NOT are pushed to SPARQL.
781
- // - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
782
- // which require reverse-link resolution before filtering
783
- let filteredInstances = instances;
784
- if (query.where) {
785
- filteredInstances = instances.filter(instance => {
786
- for (const [propertyName, condition] of Object.entries(query.where)) {
787
- // Skip 'base'/'id' as it's filtered in SPARQL
788
- if (propertyName === 'base' || propertyName === 'id')
789
- continue;
790
- // For author and timestamp, always filter in JS
791
- if (propertyName === 'author' || propertyName === 'timestamp') {
792
- if (!matchesCondition(instance[propertyName], condition)) {
793
- return false;
905
+ if (query.where)
906
+ queryInput.where = query.where;
907
+ if (query.order) {
908
+ // Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
909
+ queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
910
+ }
911
+ if (query.offset !== undefined)
912
+ queryInput.offset = query.offset;
913
+ if (query.limit !== undefined)
914
+ queryInput.limit = query.limit;
915
+ if (query.count !== undefined)
916
+ queryInput.count = query.count;
917
+ // Enrich relation metadata with target class shapes for Rust-side
918
+ // include resolution. This eliminates per-relation GraphQL round-trips
919
+ // by letting the Rust endpoint resolve includes in-process.
920
+ if (queryInput.include) {
921
+ const allRelMeta = getRelationsMetadata(this);
922
+ enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
923
+ }
924
+ // ── Pre-compute conformance getters for Rust-side evaluation ──────
925
+ // For each relation with a target class and filter !== false, compute
926
+ // the conformance getter SPARQL so Rust can evaluate it in-process
927
+ // (eliminating N × querySparql round-trips per instance).
928
+ // When a relation has a `where` clause, compile the where conditions
929
+ // into the getter SPARQL so Rust applies them during evaluation.
930
+ {
931
+ const allRelMeta = getRelationsMetadata(this);
932
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
933
+ const rel = relMeta;
934
+ if (rel.getter)
935
+ continue; // explicit getter already set
936
+ if (rel.direction === 'reverse')
937
+ continue; // reverse relations use reverse link lookup
938
+ if (rel.filter === false)
939
+ continue; // opt-out of conformance filtering
940
+ const meta = allRelMeta[relName];
941
+ if (!meta?.target)
942
+ continue;
943
+ try {
944
+ const TargetClass = meta.target();
945
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
946
+ // Only compile where clauses to SPARQL when the target properties
947
+ // are stored as plain IRIs (not signed expressions). Properties
948
+ // without resolveLanguage or with resolveLanguage='literal' store
949
+ // values as signed JSON envelopes, so SPARQL exact-match fails.
950
+ let whereConditions = [];
951
+ if (rel.where) {
952
+ try {
953
+ const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
954
+ let allSparqlFilterable = true;
955
+ if (targetMetadata) {
956
+ for (const propName of Object.keys(rel.where)) {
957
+ if (['id', 'author', 'timestamp'].includes(propName))
958
+ continue;
959
+ const propMeta = targetMetadata.properties[propName];
960
+ if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
961
+ allSparqlFilterable = false;
962
+ break;
963
+ }
964
+ }
965
+ }
966
+ else {
967
+ allSparqlFilterable = false;
968
+ }
969
+ if (allSparqlFilterable) {
970
+ whereConditions = compileWhereClause(rel.where, targetMetadata);
971
+ }
794
972
  }
795
- continue;
973
+ catch (_) { /* target metadata unavailable */ }
796
974
  }
797
- // Check if this is a relation field (not in properties metadata)
798
- const isPropField = propertyName in metadata.properties;
799
- if (!isPropField) {
800
- // Relation-based where — filter in JS against the populated field
801
- if (!matchesCondition(instance[propertyName], condition)) {
802
- return false;
975
+ if (filter) {
976
+ let getter = filter.getter;
977
+ if (whereConditions.length > 0) {
978
+ // Append where conditions before the closing }
979
+ getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
803
980
  }
804
- continue;
981
+ rel.getter = getter;
805
982
  }
806
- // Filter ALL property conditions in JS (safety net).
807
- // Equality/IN/NOT are also filtered in SPARQL via <ad4m://fn/parse_literal>()
808
- // but JS re-validates after hydration resolves values.
809
- if (!matchesCondition(instance[propertyName], condition)) {
810
- return false;
983
+ else if (whereConditions.length > 0) {
984
+ // No conformance filter but where clause exists — build getter from where alone
985
+ const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
986
+ rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
811
987
  }
812
988
  }
813
- return true;
814
- });
989
+ catch (e) {
990
+ // Target class may not be available; skip silently
991
+ }
992
+ }
815
993
  }
816
- // Apply ordering in JavaScript
817
- // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
818
- // This ensures consistent pagination behavior
819
- const effectiveOrder = query.order ||
820
- (query.limit !== undefined || query.offset !== undefined ? { createdAt: 'ASC' } : null);
821
- if (effectiveOrder) {
822
- const orderEntries = Object.entries(effectiveOrder);
823
- filteredInstances.sort((a, b) => {
824
- for (const [orderPropName, orderDirection] of orderEntries) {
825
- let aVal = a[orderPropName];
826
- let bVal = b[orderPropName];
827
- // Handle undefined values - push them to the end
828
- if (aVal === undefined && bVal === undefined)
994
+ // Send shape metadata to the executor so it knows the model structure.
995
+ // This is more reliable than reading SHACL from the store because
996
+ // the TS decorators are the definitive source of truth.
997
+ const shapeJson = JSON.stringify(metadata);
998
+ const queryJson = JSON.stringify(queryInput);
999
+ const result = await perspective.modelQuery(className, queryJson, shapeJson);
1000
+ // Convert JSON instances to model class instances, recursively constructing
1001
+ // class instances for any included relations resolved by Rust.
1002
+ const instances = result.instances.map((json) => {
1003
+ return jsonToModelInstance(this, perspective, json, query.include, query.properties);
1004
+ });
1005
+ // Resolve non-literal expressions (e.g. file languages where the stored
1006
+ // value is a content-addressed hash that must be fetched from the language
1007
+ // runtime). The Rust endpoint returns raw target URIs; we resolve them here.
1008
+ const propsMeta = getPropertiesMetadata(this);
1009
+ const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
1010
+ opts.resolveLanguage !== 'literal');
1011
+ if (resolveProps.length > 0) {
1012
+ await Promise.all(instances.map(async (inst) => {
1013
+ for (const [propName, opts] of resolveProps) {
1014
+ const val = inst[propName];
1015
+ if (typeof val !== 'string' || !val || val.startsWith('literal:'))
829
1016
  continue;
830
- if (aVal === undefined)
831
- return orderDirection === 'ASC' ? 1 : -1;
832
- if (bVal === undefined)
833
- return orderDirection === 'ASC' ? -1 : 1;
834
- // Compare values
835
- let comparison = 0;
836
- if (typeof aVal === 'number' && typeof bVal === 'number') {
837
- comparison = aVal - bVal;
838
- }
839
- else if (typeof aVal === 'string' && typeof bVal === 'string') {
840
- comparison = aVal.localeCompare(bVal);
841
- }
842
- else {
843
- comparison = String(aVal).localeCompare(String(bVal));
844
- }
845
- if (comparison !== 0) {
846
- return orderDirection === 'DESC' ? -comparison : comparison;
1017
+ try {
1018
+ const expression = await perspective.getExpression(val);
1019
+ if (expression) {
1020
+ let resolved;
1021
+ try {
1022
+ resolved = JSON.parse(expression.data);
1023
+ }
1024
+ catch {
1025
+ resolved = expression.data;
1026
+ }
1027
+ const transform = opts.transform;
1028
+ inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
1029
+ }
847
1030
  }
848
- // comparison === 0: continue to next sort field
1031
+ catch (_) { /* resolution failed — keep raw value */ }
849
1032
  }
850
- return 0;
851
- });
1033
+ }));
852
1034
  }
853
- // Determine if SPARQL already applied LIMIT/OFFSET (i.e., the pagination
854
- // subquery was used). When it was, skip JS-level slicing — instances are
855
- // already the correct page.
856
- const allRelsMeta2 = getRelationsMetadata(this);
857
- const sparqlPaginated = !hasJsOnlyWhereFilters(metadata, allRelsMeta2, query.where)
858
- && (query.limit !== undefined || query.offset !== undefined)
859
- && query.order !== undefined && Object.keys(query.order).length > 0;
860
- // Calculate totalCount BEFORE applying limit/offset.
861
- // When SPARQL already paginated, filteredInstances.length is the page size,
862
- // not the total — use a separate COUNT query for the real total.
863
- // Only run the COUNT query when the caller actually needs it (computeTotalCount=true).
864
- let totalCount;
865
- if (sparqlPaginated && computeTotalCount) {
866
- try {
867
- const countSparql = buildSPARQLCountQuery(metadata, allRelsMeta2, query, this);
868
- const countResult = await perspective.querySparql(countSparql);
869
- totalCount = parseSparqlCount(countResult) ?? filteredInstances.length;
1035
+ // Relation conformance getters are evaluated Rust-side via evaluate_getters()
1036
+ // in model_query.rs. However, for relations with non-SPARQL-filterable where
1037
+ // clauses (e.g. properties stored as signed expressions), we still need
1038
+ // TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
1039
+ // with skipPropertyGetters ensures conformance + JS post-filtering for
1040
+ // where clauses that couldn't be compiled to SPARQL.
1041
+ const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set();
1042
+ for (const inst of instances) {
1043
+ // Save included relation values that came from Rust hydration
1044
+ const savedIncluded = {};
1045
+ for (const relName of includedRelNames) {
1046
+ if (inst[relName] !== undefined) {
1047
+ savedIncluded[relName] = inst[relName];
1048
+ }
870
1049
  }
871
- catch {
872
- // Fallback: if count query fails, use what we have
873
- totalCount = filteredInstances.length;
1050
+ await evaluateCustomGettersForInstance(inst, perspective, metadata, {
1051
+ skipPropertyGetters: true,
1052
+ });
1053
+ // Restore hydrated include objects that were overwritten by conformance getters
1054
+ for (const [relName, value] of Object.entries(savedIncluded)) {
1055
+ inst[relName] = value;
874
1056
  }
875
- }
876
- else {
877
- totalCount = filteredInstances.length;
878
- }
879
- // Apply offset and limit in JavaScript only when SPARQL didn't already paginate.
880
- // Subscription queries use unpaginated SPARQL, so JS must apply pagination.
881
- // Direct queries use SPARQL-level pagination, so JS slicing would double-apply.
882
- let paginatedInstances = filteredInstances;
883
- if (!sparqlPaginated && (query.offset !== undefined || query.limit !== undefined)) {
884
- const start = query.offset || 0;
885
- const end = query.limit ? start + query.limit : undefined;
886
- paginatedInstances = filteredInstances.slice(start, end);
887
- }
888
- // Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
889
- // This must happen AFTER where-filtering so conditions can reference any property.
890
- if (requestedProperties.length > 0) {
891
- const requested = new Set(requestedProperties);
892
- for (const inst of paginatedInstances) {
893
- for (const propName of Object.keys(metadata.properties)) {
894
- if (!requested.has(propName)) {
895
- delete inst[propName];
896
- }
897
- }
898
- for (const relName of Object.keys(metadata.relations)) {
899
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
900
- delete inst[relName];
901
- }
902
- }
903
- for (const metaField of ['author', 'createdAt', 'updatedAt']) {
904
- if (!requested.has(metaField)) {
905
- delete inst[metaField];
906
- }
1057
+ // Fix cardinality for non-included HasOne/BelongsToOne relations:
1058
+ // The conformance getter always produces arrays; unwrap to scalar.
1059
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1060
+ if (includedRelNames.has(relName))
1061
+ continue;
1062
+ const kind = relMeta.kind;
1063
+ if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray(inst[relName])) {
1064
+ const arr = inst[relName];
1065
+ inst[relName] = arr.length > 0 ? arr[0] : null;
907
1066
  }
908
1067
  }
909
1068
  }
910
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
911
- if (query.include && paginatedInstances.length > 0) {
912
- await hydrateRelations(this, paginatedInstances, perspective, query.include);
913
- }
914
- // Take snapshots for dirty tracking after ALL hydration is complete
915
- // (including eager-loaded relations).
916
- // When `include` is specified, only snapshot those relations.
917
- // Otherwise snapshot ALL fields (properties + relations) since
918
- // hydrateFromLinks populates relations with stable raw IDs —
919
- // this ensures push-to-array + save() correctly detects dirty relations.
920
- const snapshotRelations = query.include;
921
- for (const inst of paginatedInstances) {
1069
+ // Take snapshots for dirty tracking
1070
+ const snapshotRelations = queryInput.include;
1071
+ for (const inst of instances) {
922
1072
  inst.takeSnapshot(snapshotRelations);
923
1073
  }
924
1074
  return {
925
- results: paginatedInstances,
926
- totalCount
1075
+ results: instances,
1076
+ totalCount: result.totalCount,
927
1077
  };
928
1078
  }
929
1079
  /**
@@ -953,31 +1103,12 @@ export class Ad4mModel {
953
1103
  * const recipesProlog = await Recipe.findAll(perspective, {}, false);
954
1104
  * ```
955
1105
  */
956
- static async findAll(perspective, query = {}, engine = 'sparql') {
1106
+ static async findAll(perspective, query = {}, _engine) {
957
1107
  if (query.properties && query.properties.length === 0) {
958
1108
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
959
1109
  }
960
- // Backward compatibility: boolean maps to sparql (true) or prolog (false)
961
- const resolvedEngine = typeof engine === 'boolean'
962
- ? (engine ? 'sparql' : 'prolog')
963
- : engine;
964
- if (resolvedEngine === 'sparql') {
965
- // Always use the regular SPARQL path + JS-level hydrateRelations for includes.
966
- // The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
967
- // non-conforming node filtering, and parse_literal compatibility.
968
- // hydrateRelations handles all of these correctly via per-relation findAll calls.
969
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
970
- const rawResult = await perspective.querySparql(sparqlQuery);
971
- const grouped = groupSPARQLResults(rawResult);
972
- const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
973
- return results;
974
- }
975
- else {
976
- const prologQuery = await this.queryToProlog(perspective, query);
977
- const result = await perspective.infer(prologQuery);
978
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
979
- return results;
980
- }
1110
+ const { results } = await this.executeModelQuery(perspective, query);
1111
+ return results;
981
1112
  }
982
1113
  /**
983
1114
  * Finds the first instance matching the query, or `null` if none exists.
@@ -999,9 +1130,9 @@ export class Ad4mModel {
999
1130
  * }
1000
1131
  * ```
1001
1132
  */
1002
- static async findOne(perspective, query = {}, engine = 'sparql') {
1133
+ static async findOne(perspective, query = {}, _engine) {
1003
1134
  const limitedQuery = { ...query, limit: 1 };
1004
- const results = await this.findAll(perspective, limitedQuery, engine);
1135
+ const results = await this.findAll(perspective, limitedQuery);
1005
1136
  return results[0] ?? null;
1006
1137
  }
1007
1138
  /**
@@ -1024,21 +1155,8 @@ export class Ad4mModel {
1024
1155
  * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
1025
1156
  * ```
1026
1157
  */
1027
- static async findAllAndCount(perspective, query = {}, engine = 'sparql') {
1028
- const resolvedEngine = typeof engine === 'boolean'
1029
- ? (engine ? 'sparql' : 'prolog')
1030
- : engine;
1031
- if (resolvedEngine === 'sparql') {
1032
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1033
- const rawResult = await perspective.querySparql(sparqlQuery);
1034
- const grouped = groupSPARQLResults(rawResult);
1035
- return await this.instancesFromQueryResult(perspective, query, grouped, true);
1036
- }
1037
- else {
1038
- const prologQuery = await this.queryToProlog(perspective, query);
1039
- const result = await perspective.infer(prologQuery);
1040
- return await this.instancesFromPrologResult(perspective, query, result);
1041
- }
1158
+ static async findAllAndCount(perspective, query = {}, _engine) {
1159
+ return await this.executeModelQuery(perspective, query);
1042
1160
  }
1043
1161
  /**
1044
1162
  * Helper function for pagination with explicit page size and number.
@@ -1047,7 +1165,6 @@ export class Ad4mModel {
1047
1165
  * @param pageSize - Number of items per page
1048
1166
  * @param pageNumber - Which page to retrieve (1-based)
1049
1167
  * @param query - Optional additional query parameters
1050
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1051
1168
  * @returns Paginated results with metadata
1052
1169
  *
1053
1170
  * @example
@@ -1056,47 +1173,12 @@ export class Ad4mModel {
1056
1173
  * where: { category: "Main Course" }
1057
1174
  * });
1058
1175
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
1059
- *
1060
- * // Use Prolog explicitly (legacy)
1061
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
1062
1176
  * ```
1063
1177
  */
1064
- static async paginate(perspective, pageSize, pageNumber, query, engine = 'sparql') {
1178
+ static async paginate(perspective, pageSize, pageNumber, query, _engine) {
1065
1179
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1066
- const resolvedEngine = typeof engine === 'boolean'
1067
- ? (engine ? 'sparql' : 'prolog')
1068
- : engine;
1069
- if (resolvedEngine === 'sparql') {
1070
- const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
1071
- const rawResult = await perspective.querySparql(sparqlQuery);
1072
- const grouped = groupSPARQLResults(rawResult);
1073
- const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped, true);
1074
- return { results, totalCount, pageSize, pageNumber };
1075
- }
1076
- else {
1077
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
1078
- const result = await perspective.infer(prologQuery);
1079
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
1080
- return { results, totalCount, pageSize, pageNumber };
1081
- }
1082
- }
1083
- static async countQueryToProlog(perspective, query = {}, modelClassName) {
1084
- const { where } = query;
1085
- const className = modelClassName || (await this.getClassName(perspective));
1086
- const resolvedParentPredicate = query.parent
1087
- ? resolveParentPredicate(query.parent, this)
1088
- : undefined;
1089
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
1090
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
1091
- const fullQuery = `
1092
- findall([Base, Properties, Collections, Timestamp, Author], (
1093
- subject_class("${className}", SubjectClass),
1094
- instance(SubjectClass, Base),
1095
- ${instanceQueries.filter((q) => q).join(", ")}
1096
- ), UnsortedInstances),
1097
- ${resultSetQueries.filter((q) => q).join(", ")}
1098
- `;
1099
- return fullQuery;
1180
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1181
+ return { results, totalCount, pageSize, pageNumber };
1100
1182
  }
1101
1183
  /**
1102
1184
  * Generates a SPARQL COUNT query for the model.
@@ -1107,17 +1189,12 @@ export class Ad4mModel {
1107
1189
  *
1108
1190
  * @private
1109
1191
  */
1110
- static async countQueryToSPARQL(perspective, query) {
1111
- const metadata = this.getModelMetadata();
1112
- const allRelMeta = getRelationsMetadata(this);
1113
- return buildSPARQLCountQuery(metadata, allRelMeta, query, this);
1114
- }
1192
+ // countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
1115
1193
  /**
1116
1194
  * Gets a count of all matching instances.
1117
1195
  *
1118
1196
  * @param perspective - The perspective to search in
1119
1197
  * @param query - Optional query parameters to filter results
1120
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
1121
1198
  * @returns Total count of matching entities
1122
1199
  *
1123
1200
  * @example
@@ -1126,37 +1203,11 @@ export class Ad4mModel {
1126
1203
  * const activeRecipes = await Recipe.count(perspective, {
1127
1204
  * where: { status: "active" }
1128
1205
  * });
1129
- *
1130
- * // Use Prolog explicitly (legacy)
1131
- * const countProlog = await Recipe.count(perspective, {}, false);
1132
1206
  * ```
1133
1207
  */
1134
- static async count(perspective, query = {}, engine = 'sparql') {
1135
- const resolvedEngine = typeof engine === 'boolean'
1136
- ? (engine ? 'sparql' : 'prolog')
1137
- : engine;
1138
- if (resolvedEngine === 'sparql') {
1139
- // When query has JS-only where filters (gt, between, author, timestamp, etc.),
1140
- // we must fall back to full hydration + JS filtering to get accurate count.
1141
- const metadata = this.getModelMetadata();
1142
- const allRelMeta = getRelationsMetadata(this);
1143
- if (hasJsOnlyWhereFilters(metadata, allRelMeta, query.where)) {
1144
- // Fall back to full query + JS filter path for accurate count
1145
- const sparqlQuery = await this.queryToSPARQL(perspective, query);
1146
- const rawResult = await perspective.querySparql(sparqlQuery);
1147
- const grouped = groupSPARQLResults(rawResult);
1148
- const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped, true);
1149
- return totalCount;
1150
- }
1151
- // No JS-only filters — use efficient COUNT query
1152
- const countSparql = await this.countQueryToSPARQL(perspective, query);
1153
- const countResult = await perspective.querySparql(countSparql);
1154
- return parseSparqlCount(countResult) ?? 0;
1155
- }
1156
- else {
1157
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
1158
- return result?.[0]?.TotalCount || 0;
1159
- }
1208
+ static async count(perspective, query = {}) {
1209
+ const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
1210
+ return totalCount;
1160
1211
  }
1161
1212
  async setProperty(key, value, batchId) {
1162
1213
  const metadata = this.getPropertyMetadata(key);
@@ -1861,5 +1912,88 @@ export class Ad4mModel {
1861
1912
  static fromJSONSchema(schema, options) {
1862
1913
  return buildModelFromJSONSchema(this, schema, options);
1863
1914
  }
1915
+ /**
1916
+ * Creates a fully functional Ad4mModel subclass from a SHACL shape.
1917
+ *
1918
+ * Unlike `fromJSONSchema()`, no predicate inference is required —
1919
+ * `SHACLShape` already contains the exact predicate URI in `path` for
1920
+ * every property. The method reads each property's `path`, `maxCount`,
1921
+ * `writable`, and `resolveLanguage` directly and writes them to the
1922
+ * WeakMap metadata registries.
1923
+ *
1924
+ * Properties with `hasValue` (flag / type-discrimination markers) are
1925
+ * registered as hidden flag entries so that the SPARQL query builder emits
1926
+ * the fixed triple `?source <predicate> <value>` needed for type discrimination.
1927
+ * Properties without a `name` field are skipped.
1928
+ *
1929
+ * **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
1930
+ * was persisted on property shapes) carry the flag value only in
1931
+ * `shape.constructor_actions` as the `target` of an `addLink` action.
1932
+ * This method recovers those values so that old perspectives are queried
1933
+ * with the correct type-discriminator triple.
1934
+ *
1935
+ * @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
1936
+ * @param name - Class name to assign (e.g. "Channel")
1937
+ * @returns Generated Ad4mModel subclass, ready for querying
1938
+ */
1939
+ static fromSHACL(shape, name) {
1940
+ const DynamicModelClass = class extends this {
1941
+ };
1942
+ DynamicModelClass.className = name;
1943
+ DynamicModelClass.prototype.className = name;
1944
+ // Build a backward-compat fallback map: predicate → fixed-IRI-value from
1945
+ // constructor actions. Old SHACL stores (created before sh:hasValue was
1946
+ // persisted on the property shape) don't carry sh:hasValue on properties,
1947
+ // but the shape-level constructor_actions always contain an addLink action
1948
+ // with the fixed flag value as the target.
1949
+ const flagValueFromConstructor = new Map();
1950
+ for (const action of shape.constructor_actions ?? []) {
1951
+ if (action.action === 'addLink' &&
1952
+ typeof action.predicate === 'string' &&
1953
+ typeof action.target === 'string' &&
1954
+ action.target !== 'value' &&
1955
+ !action.target.startsWith('literal:')) {
1956
+ flagValueFromConstructor.set(action.predicate, action.target);
1957
+ }
1958
+ }
1959
+ for (const prop of shape.properties) {
1960
+ const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
1961
+ if (resolvedHasValue !== undefined) {
1962
+ const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
1963
+ setPropertyRegistryEntry(DynamicModelClass, flagKey, {
1964
+ through: prop.path,
1965
+ required: true,
1966
+ initial: resolvedHasValue,
1967
+ flag: true,
1968
+ writable: false,
1969
+ readOnly: true,
1970
+ });
1971
+ continue;
1972
+ }
1973
+ // Skip properties without a declared name
1974
+ if (!prop.name)
1975
+ continue;
1976
+ const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
1977
+ if (isCollection) {
1978
+ setRelationRegistryEntry(DynamicModelClass, prop.name, {
1979
+ predicate: prop.path,
1980
+ kind: 'hasMany',
1981
+ ...(prop.local !== undefined && { local: prop.local }),
1982
+ ...(prop.getter !== undefined && { getter: prop.getter }),
1983
+ });
1984
+ }
1985
+ else {
1986
+ setPropertyRegistryEntry(DynamicModelClass, prop.name, {
1987
+ through: prop.path,
1988
+ writable: prop.writable ?? true,
1989
+ ...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
1990
+ ...(prop.local !== undefined && { local: prop.local }),
1991
+ });
1992
+ }
1993
+ }
1994
+ const ModelDecorator = Model({ name });
1995
+ ModelDecorator(DynamicModelClass);
1996
+ return DynamicModelClass;
1997
+ }
1864
1998
  }
1865
1999
  Ad4mModel.classNamesByClass = new WeakMap();