@coasys/ad4m 0.12.1-dev → 0.13.0-postmessage-ws-proxy.3
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.
- package/README.md +2 -25
- package/jest-setup.ts +1 -1
- package/lib/index.cjs +8677 -15318
- package/lib/index.js +14507 -21223
- package/lib/src/Ad4mClient.d.ts +9 -3
- package/lib/src/Ad4mClient.js +40 -13
- package/lib/src/Literal.js +6 -5
- package/lib/src/agent/Agent.js +26 -272
- package/lib/src/agent/AgentClient.d.ts +33 -21
- package/lib/src/agent/AgentClient.js +180 -374
- package/lib/src/agent/AgentStatus.js +2 -37
- package/lib/src/ai/AIClient.d.ts +12 -4
- package/lib/src/ai/AIClient.js +81 -285
- package/lib/src/ai/AITypes.d.ts +55 -0
- package/lib/src/ai/AITypes.js +18 -0
- package/lib/src/ai/Tasks.js +10 -133
- package/lib/src/apiClient.d.ts +53 -0
- package/lib/src/apiClient.js +234 -0
- package/lib/src/cache/PersistentCache.d.ts +40 -0
- package/lib/src/cache/PersistentCache.js +139 -0
- package/lib/src/expression/Expression.d.ts +1 -1
- package/lib/src/expression/Expression.js +13 -122
- package/lib/src/expression/ExpressionClient.d.ts +11 -3
- package/lib/src/expression/ExpressionClient.js +120 -75
- package/lib/src/expression/ExpressionRef.js +4 -27
- package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
- package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
- package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
- package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
- package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
- package/lib/src/generated/api/AddLinkRequest.js +1 -0
- package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
- package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
- package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
- package/lib/src/generated/api/AddSdnaRequest.js +2 -0
- package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
- package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
- package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
- package/lib/src/generated/api/AuthInfoInput.js +1 -0
- package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
- package/lib/src/generated/api/CapabilityInput.js +1 -0
- package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
- package/lib/src/generated/api/CommitBatchRequest.js +2 -0
- package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
- package/lib/src/generated/api/ComputeLogEntry.js +2 -0
- package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
- package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
- package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
- package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
- package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
- package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
- package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
- package/lib/src/generated/api/EmbedRequest.js +2 -0
- package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
- package/lib/src/generated/api/EntanglementProofInput.js +2 -0
- package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
- package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
- package/lib/src/generated/api/ExportRequest.d.ts +5 -0
- package/lib/src/generated/api/ExportRequest.js +2 -0
- package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
- package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
- package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
- package/lib/src/generated/api/ExpressionProof.js +2 -0
- package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
- package/lib/src/generated/api/ExpressionProofInput.js +2 -0
- package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
- package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
- package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
- package/lib/src/generated/api/FriendsListRequest.js +2 -0
- package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
- package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
- package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
- package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
- package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
- package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
- package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
- package/lib/src/generated/api/ImportAgentRequest.js +2 -0
- package/lib/src/generated/api/ImportRequest.d.ts +4 -0
- package/lib/src/generated/api/ImportRequest.js +2 -0
- package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
- package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
- package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
- package/lib/src/generated/api/LanguageMetaInput.js +2 -0
- package/lib/src/generated/api/Link.d.ts +5 -0
- package/lib/src/generated/api/Link.js +2 -0
- package/lib/src/generated/api/LinkExpression.d.ts +10 -0
- package/lib/src/generated/api/LinkExpression.js +1 -0
- package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
- package/lib/src/generated/api/LinkExpressionInput.js +1 -0
- package/lib/src/generated/api/LinkInput.d.ts +5 -0
- package/lib/src/generated/api/LinkInput.js +2 -0
- package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
- package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
- package/lib/src/generated/api/LinkMutations.d.ts +6 -0
- package/lib/src/generated/api/LinkMutations.js +1 -0
- package/lib/src/generated/api/LinkStatus.d.ts +1 -0
- package/lib/src/generated/api/LinkStatus.js +2 -0
- package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
- package/lib/src/generated/api/LockAgentRequest.js +2 -0
- package/lib/src/generated/api/ModelType.d.ts +1 -0
- package/lib/src/generated/api/ModelType.js +2 -0
- package/lib/src/generated/api/NotificationInput.d.ts +10 -0
- package/lib/src/generated/api/NotificationInput.js +2 -0
- package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
- package/lib/src/generated/api/OpenLinkRequest.js +2 -0
- package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
- package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
- package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
- package/lib/src/generated/api/PerspectiveInput.js +1 -0
- package/lib/src/generated/api/PromptRequest.d.ts +4 -0
- package/lib/src/generated/api/PromptRequest.js +2 -0
- package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
- package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
- package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
- package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
- package/lib/src/generated/api/QueryRequest.d.ts +7 -0
- package/lib/src/generated/api/QueryRequest.js +2 -0
- package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
- package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
- package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
- package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
- package/lib/src/generated/api/ResourceInput.d.ts +4 -0
- package/lib/src/generated/api/ResourceInput.js +2 -0
- package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
- package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
- package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
- package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
- package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
- package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
- package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
- package/lib/src/generated/api/SetStatusRequest.js +2 -0
- package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
- package/lib/src/generated/api/SignMessageRequest.js +2 -0
- package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
- package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
- package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
- package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
- package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
- package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
- package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
- package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
- package/lib/src/generated/api/UserStatistics.d.ts +9 -0
- package/lib/src/generated/api/UserStatistics.js +2 -0
- package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
- package/lib/src/generated/api/VerificationRequestResult.js +2 -0
- package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
- package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
- package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
- package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
- package/lib/src/generated/api/index.d.ts +42 -0
- package/lib/src/generated/api/index.js +7 -0
- package/lib/src/index.d.ts +8 -2
- package/lib/src/index.js +8 -2
- package/lib/src/jestSetup.d.ts +0 -1
- package/lib/src/jestSetup.js +1 -1
- package/lib/src/language/Icon.js +2 -21
- package/lib/src/language/Language.d.ts +26 -176
- package/lib/src/language/Language.js +32 -72
- package/lib/src/language/LanguageClient.d.ts +2 -2
- package/lib/src/language/LanguageClient.js +15 -105
- package/lib/src/language/LanguageHandle.js +2 -41
- package/lib/src/language/LanguageMeta.js +4 -75
- package/lib/src/language/LanguageRef.js +2 -25
- package/lib/src/links/Links.js +14 -111
- package/lib/src/model/Ad4mModel.d.ts +143 -63
- package/lib/src/model/Ad4mModel.js +583 -425
- package/lib/src/model/Ad4mModel.test.js +1434 -688
- package/lib/src/model/ModelQueryBuilder.d.ts +61 -45
- package/lib/src/model/ModelQueryBuilder.js +315 -157
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/decorators.d.ts +36 -8
- package/lib/src/model/decorators.js +41 -14
- package/lib/src/model/hydration-batch.d.ts +34 -0
- package/lib/src/model/hydration-batch.js +147 -0
- package/lib/src/model/hydration-batching.test.d.ts +7 -0
- package/lib/src/model/hydration-batching.test.js +456 -0
- package/lib/src/model/hydration.d.ts +3 -92
- package/lib/src/model/hydration.js +3 -691
- package/lib/src/model/index.d.ts +3 -4
- package/lib/src/model/index.js +3 -4
- package/lib/src/model/json-schema.js +2 -2
- package/lib/src/model/model-manifest.d.ts +41 -0
- package/lib/src/model/model-manifest.js +11 -0
- package/lib/src/model/query-cache.d.ts +30 -0
- package/lib/src/model/query-cache.js +66 -0
- package/lib/src/model/query-cache.test.d.ts +1 -0
- package/lib/src/model/query-cache.test.js +43 -0
- package/lib/src/model/query-common.d.ts +1 -1
- package/lib/src/model/query-common.js +1 -1
- package/lib/src/model/query-sparql-batch.d.ts +17 -0
- package/lib/src/model/query-sparql-batch.js +260 -0
- package/lib/src/model/query-sparql.d.ts +51 -0
- package/lib/src/model/query-sparql.js +466 -0
- package/lib/src/model/query-sparql.test.d.ts +1 -0
- package/lib/src/model/query-sparql.test.js +312 -0
- package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +13 -9
- package/lib/src/model/query-utils.js +189 -0
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/sdna.js +1 -1
- package/lib/src/model/shacl-gen.js +154 -57
- package/lib/src/model/subscription-delta.test.d.ts +24 -0
- package/lib/src/model/subscription-delta.test.js +180 -0
- package/lib/src/model/subscription-pool.d.ts +39 -0
- package/lib/src/model/subscription-pool.js +165 -0
- package/lib/src/model/types.d.ts +195 -5
- package/lib/src/model/types.js +5 -2
- package/lib/src/neighbourhood/Neighbourhood.js +4 -32
- package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
- package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
- package/lib/src/perspectives/LinkQuery.js +2 -42
- package/lib/src/perspectives/Perspective.d.ts +1 -1
- package/lib/src/perspectives/Perspective.js +10 -52
- package/lib/src/perspectives/PerspectiveClient.d.ts +22 -32
- package/lib/src/perspectives/PerspectiveClient.js +188 -454
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
- package/lib/src/perspectives/PerspectiveDiff.js +4 -31
- package/lib/src/perspectives/PerspectiveHandle.js +3 -43
- package/lib/src/perspectives/PerspectiveProxy.d.ts +157 -78
- package/lib/src/perspectives/PerspectiveProxy.js +475 -389
- package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveResolver.js +0 -11
- package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
- package/lib/src/perspectives/SparqlBindings.js +65 -0
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
- package/lib/src/perspectives/WakerSubscriptionManager.js +12 -12
- package/lib/src/runtime/RuntimeClient.d.ts +8 -6
- package/lib/src/runtime/RuntimeClient.js +97 -454
- package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
- package/lib/src/runtime/RuntimeResolver.js +84 -0
- package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
- package/lib/src/runtime/RuntimeTypes.js +45 -0
- package/lib/src/schema.gql +14 -1
- package/lib/src/shacl/SHACLFlow.d.ts +1 -1
- package/lib/src/shacl/SHACLFlow.js +9 -9
- package/lib/src/shacl/SHACLShape.d.ts +26 -1
- package/lib/src/shacl/SHACLShape.js +140 -38
- package/lib/src/shacl/SHACLShape.test.js +82 -0
- package/lib/src/typeDefs.js +3 -615
- package/lib/src/utils.d.ts +6 -6
- package/lib/src/utils.js +6 -6
- package/package.json +9 -24
- package/rollup.config.js +0 -7
- package/src/Ad4mClient.test.ts +1192 -1288
- package/src/Ad4mClient.ts +46 -15
- package/src/Literal.test.ts +10 -5
- package/src/Literal.ts +6 -5
- package/src/agent/Agent.ts +0 -99
- package/src/agent/AgentClient.ts +238 -467
- package/src/agent/AgentStatus.ts +0 -12
- package/src/ai/AIClient.ts +96 -296
- package/src/ai/AITypes.ts +66 -0
- package/src/ai/Tasks.ts +0 -52
- package/src/apiClient.ts +287 -0
- package/src/cache/PersistentCache.ts +145 -0
- package/src/cache/cache.test.ts +713 -0
- package/src/expression/Expression.ts +3 -43
- package/src/expression/ExpressionClient.ts +148 -77
- package/src/expression/ExpressionRef.ts +2 -8
- package/src/generated/api/AIModelLoadingStatus.ts +3 -0
- package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
- package/src/generated/api/AddLinkRequest.ts +4 -0
- package/src/generated/api/AddLinksBulkRequest.ts +4 -0
- package/src/generated/api/AddSdnaRequest.ts +3 -0
- package/src/generated/api/ApplyTemplateRequest.ts +3 -0
- package/src/generated/api/AuthInfoInput.ts +4 -0
- package/src/generated/api/CapabilityInput.ts +4 -0
- package/src/generated/api/CommitBatchRequest.ts +3 -0
- package/src/generated/api/ComputeLogEntry.ts +3 -0
- package/src/generated/api/CreateExpressionRequest.ts +3 -0
- package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
- package/src/generated/api/CreateSubjectRequest.ts +3 -0
- package/src/generated/api/EmbedRequest.ts +3 -0
- package/src/generated/api/EntanglementProofInput.ts +3 -0
- package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
- package/src/generated/api/ExportRequest.ts +3 -0
- package/src/generated/api/ExpressionManyRequest.ts +3 -0
- package/src/generated/api/ExpressionProof.ts +3 -0
- package/src/generated/api/ExpressionProofInput.ts +3 -0
- package/src/generated/api/FriendSendMessageRequest.ts +3 -0
- package/src/generated/api/FriendsListRequest.ts +3 -0
- package/src/generated/api/GenerateAgentRequest.ts +3 -0
- package/src/generated/api/GenerateJwtRequest.ts +3 -0
- package/src/generated/api/GetSubjectDataRequest.ts +3 -0
- package/src/generated/api/ImportAgentRequest.ts +3 -0
- package/src/generated/api/ImportRequest.ts +3 -0
- package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
- package/src/generated/api/LanguageMetaInput.ts +3 -0
- package/src/generated/api/Link.ts +3 -0
- package/src/generated/api/LinkExpression.ts +6 -0
- package/src/generated/api/LinkExpressionInput.ts +6 -0
- package/src/generated/api/LinkInput.ts +3 -0
- package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
- package/src/generated/api/LinkMutations.ts +5 -0
- package/src/generated/api/LinkStatus.ts +3 -0
- package/src/generated/api/LockAgentRequest.ts +3 -0
- package/src/generated/api/ModelType.ts +3 -0
- package/src/generated/api/NotificationInput.ts +3 -0
- package/src/generated/api/OpenLinkRequest.ts +3 -0
- package/src/generated/api/PermitCapabilityRequest.ts +3 -0
- package/src/generated/api/PerspectiveInput.ts +4 -0
- package/src/generated/api/PromptRequest.ts +3 -0
- package/src/generated/api/PublishLanguageRequest.ts +4 -0
- package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
- package/src/generated/api/QueryRequest.ts +6 -0
- package/src/generated/api/RemoveLinkRequest.ts +4 -0
- package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
- package/src/generated/api/ResourceInput.ts +3 -0
- package/src/generated/api/SetDefaultModelRequest.ts +4 -0
- package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
- package/src/generated/api/SetMultiUserRequest.ts +3 -0
- package/src/generated/api/SetStatusRequest.ts +3 -0
- package/src/generated/api/SignMessageRequest.ts +3 -0
- package/src/generated/api/TrustedAgentsRequest.ts +3 -0
- package/src/generated/api/UnlockAgentRequest.ts +3 -0
- package/src/generated/api/UpdateLinkRequest.ts +5 -0
- package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
- package/src/generated/api/UserStatistics.ts +3 -0
- package/src/generated/api/VerificationRequestResult.ts +3 -0
- package/src/generated/api/VerifySignatureRequest.ts +3 -0
- package/src/generated/api/WriteSettingsRequest.ts +3 -0
- package/src/generated/api/index.ts +49 -0
- package/src/index.ts +8 -2
- package/src/jestSetup.ts +1 -1
- package/src/language/Icon.ts +0 -4
- package/src/language/Language.ts +51 -248
- package/src/language/LanguageClient.ts +21 -132
- package/src/language/LanguageHandle.ts +0 -14
- package/src/language/LanguageMeta.ts +0 -29
- package/src/language/LanguageRef.ts +0 -7
- package/src/links/Links.ts +0 -37
- package/src/model/Ad4mModel.test.ts +1664 -792
- package/src/model/Ad4mModel.ts +664 -499
- package/src/model/ModelQueryBuilder.ts +362 -183
- package/src/model/decorators.ts +71 -22
- package/src/model/hydration.ts +3 -772
- package/src/model/index.ts +3 -4
- package/src/model/json-schema.ts +2 -2
- package/src/model/query-cache.test.ts +54 -0
- package/src/model/query-cache.ts +79 -0
- package/src/model/query-common.ts +1 -1
- package/src/model/query-sparql.test.ts +376 -0
- package/src/model/query-sparql.ts +504 -0
- package/src/model/query-utils.ts +209 -0
- package/src/model/relation-filtering.test.ts +60 -53
- package/src/model/sdna.ts +1 -1
- package/src/model/shacl-gen.ts +163 -64
- package/src/model/shacl-roundtrip.test.ts +197 -0
- package/src/model/types-typed-query.test.ts +360 -0
- package/src/model/types.ts +256 -5
- package/src/neighbourhood/Neighbourhood.ts +0 -9
- package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
- package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
- package/src/perspectives/LinkQuery.ts +0 -15
- package/src/perspectives/Perspective.ts +1 -12
- package/src/perspectives/PerspectiveClient.test.ts +262 -0
- package/src/perspectives/PerspectiveClient.ts +252 -468
- package/src/perspectives/PerspectiveDiff.ts +0 -8
- package/src/perspectives/PerspectiveHandle.ts +1 -12
- package/src/perspectives/PerspectiveProxy.test.ts +125 -0
- package/src/perspectives/PerspectiveProxy.ts +522 -434
- package/src/perspectives/SparqlBindings.ts +79 -0
- package/src/perspectives/WakerSubscriptionManager.ts +13 -13
- package/src/runtime/RuntimeClient.ts +118 -461
- package/src/runtime/RuntimeTypes.ts +144 -0
- package/src/shacl/SHACLFlow.ts +9 -9
- package/src/shacl/SHACLShape.test.ts +204 -0
- package/src/shacl/SHACLShape.ts +191 -39
- package/src/typeDefs.ts +3 -5
- package/src/utils.ts +6 -6
- package/tsconfig.json +3 -7
- package/lib/src/model/query-surreal.d.ts +0 -44
- package/lib/src/model/query-surreal.js +0 -249
- package/lib/src/model/surreal-utils.js +0 -128
- package/shims/reflect-metadata.ts +0 -0
- package/shims/type-graphql.ts +0 -75
- package/src/PubSub.ts +0 -17
- package/src/agent/AgentResolver.ts +0 -263
- package/src/ai/AIResolver.ts +0 -372
- package/src/buildSchema.ts +0 -43
- package/src/expression/ExpressionResolver.ts +0 -64
- package/src/language/LanguageContext.ts +0 -37
- package/src/language/LanguageResolver.ts +0 -98
- package/src/model/Subject.ts +0 -159
- package/src/model/prolog-facts.ts +0 -145
- package/src/model/query-prolog.ts +0 -148
- package/src/model/query-surreal.ts +0 -280
- package/src/model/surreal-utils.ts +0 -147
- package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
- package/src/perspectives/PerspectiveResolver.ts +0 -372
- package/src/runtime/RuntimeResolver.ts +0 -691
- package/src/unwrapApolloResult.ts +0 -16
- package/tsconfig-browser.json +0 -82
|
@@ -437,14 +437,11 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
|
|
|
437
437
|
expect(shape.destructor_actions).toEqual([]);
|
|
438
438
|
});
|
|
439
439
|
});
|
|
440
|
-
describe("Ad4mModel.
|
|
441
|
-
// Mock perspective proxy (minimal since queryToSurrealQL doesn't actually call it)
|
|
440
|
+
describe("Ad4mModel.queryToSPARQL()", () => {
|
|
442
441
|
const mockPerspective = {};
|
|
443
|
-
// Helper function to normalize whitespace in queries for easier comparison
|
|
444
442
|
function normalizeQuery(query) {
|
|
445
443
|
return query.replace(/\s+/g, ' ').trim();
|
|
446
444
|
}
|
|
447
|
-
// Test Recipe model — explicit required: true to test required-property query filters
|
|
448
445
|
let Recipe = class Recipe extends Ad4mModel {
|
|
449
446
|
constructor() {
|
|
450
447
|
super(...arguments);
|
|
@@ -468,328 +465,172 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
|
|
|
468
465
|
Recipe = __decorate([
|
|
469
466
|
Model({ name: "Recipe" })
|
|
470
467
|
], Recipe);
|
|
471
|
-
it("should generate basic query with no filters", async () => {
|
|
472
|
-
const query = await Recipe.
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
expect(
|
|
476
|
-
|
|
477
|
-
expect(
|
|
478
|
-
|
|
479
|
-
expect(query).toContain("count(->link[WHERE");
|
|
468
|
+
it("should generate basic SPARQL query with no filters", async () => {
|
|
469
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, {});
|
|
470
|
+
const norm = normalizeQuery(query);
|
|
471
|
+
// Must be a SPARQL SELECT
|
|
472
|
+
expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
|
|
473
|
+
// Must have conformance JOIN for required properties using direct triple patterns
|
|
474
|
+
expect(norm).toContain("cfTarget_name");
|
|
475
|
+
expect(norm).toContain("recipe://name");
|
|
480
476
|
});
|
|
481
477
|
it("should generate query with simple property filter", async () => {
|
|
482
|
-
const query = await Recipe.
|
|
483
|
-
|
|
484
|
-
expect(
|
|
485
|
-
|
|
486
|
-
expect(
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const
|
|
505
|
-
//
|
|
506
|
-
expect(
|
|
507
|
-
expect(
|
|
508
|
-
});
|
|
509
|
-
it("should
|
|
510
|
-
const query = await Recipe.
|
|
511
|
-
|
|
512
|
-
expect(
|
|
513
|
-
expect(
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
const
|
|
518
|
-
//
|
|
519
|
-
expect(
|
|
520
|
-
});
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
//
|
|
591
|
-
expect(
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
expect(
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
__decorate([
|
|
619
|
-
HasMany({ through: "test://coll2" }),
|
|
620
|
-
__metadata("design:type", Array)
|
|
621
|
-
], MultiRelationModel.prototype, "coll2", void 0);
|
|
622
|
-
MultiRelationModel = __decorate([
|
|
623
|
-
Model({ name: "MultiRelationModel" })
|
|
624
|
-
], MultiRelationModel);
|
|
625
|
-
const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
|
|
626
|
-
// With array::group(), all link data is selected
|
|
627
|
-
expect(query).toContain("->link AS links");
|
|
628
|
-
});
|
|
629
|
-
it("should escape single quotes in string values", async () => {
|
|
630
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
|
|
631
|
-
// Single quotes are escaped with backslash in SurrealDB
|
|
632
|
-
expect(query).toContain("O\\'Brien\\'s Recipe");
|
|
633
|
-
});
|
|
634
|
-
it("should handle numeric values without quotes", async () => {
|
|
635
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
|
|
636
|
-
// Numeric values should not have quotes around them
|
|
637
|
-
expect(query).toContain("fn::parse_literal(out.uri) = 5");
|
|
638
|
-
expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
|
|
639
|
-
});
|
|
640
|
-
it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
|
|
641
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, {
|
|
642
|
-
where: {
|
|
643
|
-
name: "Pasta",
|
|
644
|
-
rating: { gte: 4, lte: 5 },
|
|
645
|
-
author: "did:key:alice"
|
|
646
|
-
},
|
|
647
|
-
order: { rating: "DESC" },
|
|
648
|
-
limit: 5
|
|
649
|
-
});
|
|
650
|
-
const normalized = normalizeQuery(query);
|
|
651
|
-
// Verify graph traversal filters are present
|
|
652
|
-
expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
|
|
653
|
-
// Comparison operators (gte, lte) are filtered in JavaScript, not SQL
|
|
654
|
-
expect(normalized).not.toContain("out.uri >= 4");
|
|
655
|
-
expect(normalized).not.toContain("target >= 4");
|
|
656
|
-
expect(normalized).not.toContain("out.uri <= 5");
|
|
657
|
-
expect(normalized).not.toContain("target <= 5");
|
|
658
|
-
// author and timestamp filtering is done in JavaScript post-query
|
|
659
|
-
expect(normalized).not.toContain("author = 'did:key:alice'");
|
|
660
|
-
// ORDER BY and LIMIT are handled in JavaScript post-query
|
|
661
|
-
expect(normalized).not.toContain("ORDER BY");
|
|
662
|
-
expect(normalized).not.toContain("LIMIT");
|
|
663
|
-
// Verify query structure (FROM node, no GROUP BY)
|
|
664
|
-
expect(normalized).toContain("FROM node");
|
|
665
|
-
});
|
|
666
|
-
it("should handle empty query object", async () => {
|
|
667
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, {});
|
|
668
|
-
// Should generate valid query with WHERE clause for required properties (name and rating)
|
|
669
|
-
expect(query).toContain("id AS source");
|
|
670
|
-
expect(query).toContain("uri AS source_uri");
|
|
671
|
-
expect(query).toContain("FROM node");
|
|
672
|
-
// Should have WHERE clause filtering for required properties using graph traversal
|
|
673
|
-
expect(query).toContain("WHERE");
|
|
674
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
|
|
675
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
|
|
676
|
-
expect(query).not.toContain("ORDER BY");
|
|
677
|
-
expect(query).not.toContain("START");
|
|
678
|
-
});
|
|
679
|
-
it("should handle id special field", async () => {
|
|
680
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: "literal://test" } });
|
|
681
|
-
expect(query).toContain("uri = 'literal://test'");
|
|
682
|
-
});
|
|
683
|
-
it("should handle id special field with array (IN clause)", async () => {
|
|
684
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: ["literal://test1", "literal://test2"] } });
|
|
685
|
-
expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
|
|
686
|
-
});
|
|
687
|
-
it("should handle id special field with not operator", async () => {
|
|
688
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: "literal://test" } } });
|
|
689
|
-
expect(query).toContain("uri != 'literal://test'");
|
|
690
|
-
});
|
|
691
|
-
it("should handle id special field with not operator and array (NOT IN)", async () => {
|
|
692
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: ["literal://test1", "literal://test2"] } } });
|
|
693
|
-
expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
|
|
694
|
-
});
|
|
695
|
-
it("should handle id special field with between operator", async () => {
|
|
696
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { between: ["literal://a", "literal://z"] } } });
|
|
697
|
-
const normalized = normalizeQuery(query);
|
|
698
|
-
expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
|
|
699
|
-
});
|
|
700
|
-
it("should handle id special field with gt operator", async () => {
|
|
701
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gt: "literal://m" } } });
|
|
702
|
-
expect(query).toContain("uri > 'literal://m'");
|
|
703
|
-
});
|
|
704
|
-
it("should handle id special field with gte and lte operators", async () => {
|
|
705
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gte: "literal://a", lte: "literal://z" } } });
|
|
706
|
-
const normalized = normalizeQuery(query);
|
|
707
|
-
expect(normalized).toContain("uri >= 'literal://a'");
|
|
708
|
-
expect(normalized).toContain("uri <= 'literal://z'");
|
|
709
|
-
});
|
|
710
|
-
it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
|
|
711
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
|
|
712
|
-
// timestamp filtering is done in JavaScript post-query
|
|
713
|
-
expect(query).toContain("FROM node");
|
|
714
|
-
expect(query).not.toContain("timestamp > 1234567890");
|
|
715
|
-
});
|
|
716
|
-
it("should handle multiple special fields (filtered in JavaScript)", async () => {
|
|
717
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, {
|
|
718
|
-
where: {
|
|
719
|
-
author: "did:key:alice",
|
|
720
|
-
timestamp: { gt: 1000 }
|
|
721
|
-
}
|
|
722
|
-
});
|
|
723
|
-
// author and timestamp filtering is done in JavaScript post-query
|
|
724
|
-
expect(query).toContain("FROM node");
|
|
725
|
-
expect(query).not.toContain("author = 'did:key:alice'");
|
|
726
|
-
expect(query).not.toContain("timestamp > 1000");
|
|
727
|
-
});
|
|
728
|
-
it("should handle mixed special and regular properties", async () => {
|
|
729
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, {
|
|
730
|
-
where: {
|
|
731
|
-
name: "Pasta",
|
|
732
|
-
author: "did:key:alice",
|
|
733
|
-
rating: { gt: 4 }
|
|
734
|
-
}
|
|
478
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: "Pasta" } });
|
|
479
|
+
const norm = normalizeQuery(query);
|
|
480
|
+
expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
|
|
481
|
+
// For literal-stored properties, SPARQL only adds a JOIN (no FILTER value) — filtering is in JS
|
|
482
|
+
expect(norm).toContain("recipe://name");
|
|
483
|
+
// Value should NOT be in SPARQL — filtering happens in JS post-filter
|
|
484
|
+
expect(norm).toContain("?wTarget_name");
|
|
485
|
+
});
|
|
486
|
+
it("should generate query with NOT operator", async () => {
|
|
487
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: { not: "Salad" } } });
|
|
488
|
+
const norm = normalizeQuery(query);
|
|
489
|
+
// For literal-stored properties, NOT filtering is done in JS — no NOT EXISTS in SPARQL
|
|
490
|
+
expect(norm).toContain("recipe://name");
|
|
491
|
+
});
|
|
492
|
+
it("should generate query with NOT IN operator (array)", async () => {
|
|
493
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
|
|
494
|
+
const norm = normalizeQuery(query);
|
|
495
|
+
// For literal-stored properties, NOT IN filtering is done in JS — no filter values in SPARQL
|
|
496
|
+
expect(norm).toContain("recipe://name");
|
|
497
|
+
});
|
|
498
|
+
it("should generate query with IN clause (array values)", async () => {
|
|
499
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
|
|
500
|
+
const norm = normalizeQuery(query);
|
|
501
|
+
// For literal-stored properties, IN filtering is done in JS — only a JOIN exists
|
|
502
|
+
expect(norm).toContain("recipe://name");
|
|
503
|
+
expect(norm).toContain("?wTarget_name");
|
|
504
|
+
});
|
|
505
|
+
it("should generate query with base filter", async () => {
|
|
506
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { base: "ad4m://test123" } });
|
|
507
|
+
const norm = normalizeQuery(query);
|
|
508
|
+
expect(norm).toContain("?source =");
|
|
509
|
+
expect(norm).toContain("ad4m://test123");
|
|
510
|
+
});
|
|
511
|
+
it("should escape special characters in SPARQL strings", async () => {
|
|
512
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: 'O\'Brien' } });
|
|
513
|
+
const norm = normalizeQuery(query);
|
|
514
|
+
// Should not break the query
|
|
515
|
+
expect(norm).toContain("SELECT ?source");
|
|
516
|
+
});
|
|
517
|
+
// =========================================================================
|
|
518
|
+
// Additional models for thorough SPARQL structure tests
|
|
519
|
+
// =========================================================================
|
|
520
|
+
let Task = class Task extends Ad4mModel {
|
|
521
|
+
constructor() {
|
|
522
|
+
super(...arguments);
|
|
523
|
+
this.title = "";
|
|
524
|
+
this.priority = 0;
|
|
525
|
+
this.done = false;
|
|
526
|
+
this.description = "";
|
|
527
|
+
this.tags = [];
|
|
528
|
+
this.assignees = [];
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
__decorate([
|
|
532
|
+
Property({ through: "task://title", resolveLanguage: "literal", required: true }),
|
|
533
|
+
__metadata("design:type", String)
|
|
534
|
+
], Task.prototype, "title", void 0);
|
|
535
|
+
__decorate([
|
|
536
|
+
Property({ through: "task://priority", resolveLanguage: "literal" }),
|
|
537
|
+
__metadata("design:type", Number)
|
|
538
|
+
], Task.prototype, "priority", void 0);
|
|
539
|
+
__decorate([
|
|
540
|
+
Property({ through: "task://done", resolveLanguage: "literal" }),
|
|
541
|
+
__metadata("design:type", Boolean)
|
|
542
|
+
], Task.prototype, "done", void 0);
|
|
543
|
+
__decorate([
|
|
544
|
+
Optional({ through: "task://description" }),
|
|
545
|
+
__metadata("design:type", String)
|
|
546
|
+
], Task.prototype, "description", void 0);
|
|
547
|
+
__decorate([
|
|
548
|
+
HasMany({ through: "task://tag" }),
|
|
549
|
+
__metadata("design:type", Array)
|
|
550
|
+
], Task.prototype, "tags", void 0);
|
|
551
|
+
__decorate([
|
|
552
|
+
HasMany({ through: "task://assignee" }),
|
|
553
|
+
__metadata("design:type", Array)
|
|
554
|
+
], Task.prototype, "assignees", void 0);
|
|
555
|
+
Task = __decorate([
|
|
556
|
+
Model({ name: "Task" })
|
|
557
|
+
], Task);
|
|
558
|
+
let EmptyModel = class EmptyModel extends Ad4mModel {
|
|
559
|
+
constructor() {
|
|
560
|
+
super(...arguments);
|
|
561
|
+
this.optField = "";
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
__decorate([
|
|
565
|
+
Optional({ through: "empty://optField" }),
|
|
566
|
+
__metadata("design:type", String)
|
|
567
|
+
], EmptyModel.prototype, "optField", void 0);
|
|
568
|
+
EmptyModel = __decorate([
|
|
569
|
+
Model({ name: "EmptyModel" })
|
|
570
|
+
], EmptyModel);
|
|
571
|
+
// ---- Comparison operators (gt, lt, gte, lte, between, contains) ----
|
|
572
|
+
// These are handled in JS post-processing, NOT in SPARQL.
|
|
573
|
+
// The tests verify that the SPARQL still generates valid output (conformance filters)
|
|
574
|
+
// but does NOT inject FILTER clauses for these operators.
|
|
575
|
+
it("should inject SPARQL FILTER for gt operator", async () => {
|
|
576
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { gt: 3 } } });
|
|
577
|
+
const norm = normalizeQuery(query);
|
|
578
|
+
expect(norm).toContain("SELECT ?source");
|
|
579
|
+
// gt is now handled via JS post-filter — SPARQL just joins the property
|
|
580
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
581
|
+
});
|
|
582
|
+
it("should inject SPARQL FILTER for lt operator", async () => {
|
|
583
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { lt: 5 } } });
|
|
584
|
+
const norm = normalizeQuery(query);
|
|
585
|
+
expect(norm).toContain("SELECT ?source");
|
|
586
|
+
// lt is now handled via JS post-filter
|
|
587
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
588
|
+
});
|
|
589
|
+
it("should inject SPARQL FILTER for gte/lte combined", async () => {
|
|
590
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { gte: 2, lte: 8 } } });
|
|
591
|
+
const norm = normalizeQuery(query);
|
|
592
|
+
expect(norm).toContain("SELECT ?source");
|
|
593
|
+
// gte/lte are now handled via JS post-filter
|
|
594
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
595
|
+
});
|
|
596
|
+
it("should inject SPARQL FILTER for between operator", async () => {
|
|
597
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { rating: { between: [1, 10] } } });
|
|
598
|
+
const norm = normalizeQuery(query);
|
|
599
|
+
expect(norm).toContain("SELECT ?source");
|
|
600
|
+
// between is now handled via JS post-filter
|
|
601
|
+
expect(norm).toContain("wTarget_cmp_rating");
|
|
602
|
+
});
|
|
603
|
+
it("should inject SPARQL FILTER for contains operator", async () => {
|
|
604
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { where: { name: { contains: "pasta" } } });
|
|
605
|
+
const norm = normalizeQuery(query);
|
|
606
|
+
expect(norm).toContain("SELECT ?source");
|
|
607
|
+
// contains is now handled via JS post-filter
|
|
608
|
+
expect(norm).toContain("wTarget_cmp_name");
|
|
609
|
+
});
|
|
610
|
+
// ---- Multiple property filters combined ----
|
|
611
|
+
it("should combine multiple property equality filters with &&", async () => {
|
|
612
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, {
|
|
613
|
+
where: { name: "Pasta", rating: ["4", "5"] }
|
|
735
614
|
});
|
|
736
|
-
const
|
|
737
|
-
//
|
|
738
|
-
expect(
|
|
739
|
-
|
|
740
|
-
expect(
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
__decorate([
|
|
753
|
-
Property({ through: "task://completed" }),
|
|
754
|
-
__metadata("design:type", Boolean)
|
|
755
|
-
], Task.prototype, "completed", void 0);
|
|
756
|
-
Task = __decorate([
|
|
757
|
-
Model({ name: "Task" })
|
|
758
|
-
], Task);
|
|
759
|
-
const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
|
|
760
|
-
expect(query).toContain("fn::parse_literal(out.uri) = true");
|
|
761
|
-
});
|
|
762
|
-
it("should handle array of numbers", async () => {
|
|
763
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
|
|
764
|
-
expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
|
|
765
|
-
});
|
|
766
|
-
it("should skip unknown properties in where clause", async () => {
|
|
767
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } });
|
|
768
|
-
// Should not throw error, just skip the unknown property
|
|
769
|
-
expect(query).toContain("source");
|
|
770
|
-
// Should not contain any condition for unknownProp
|
|
771
|
-
expect(query).not.toContain("unknownProp");
|
|
772
|
-
});
|
|
773
|
-
it.skip("should skip unknown properties in select clause", async () => {
|
|
774
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] });
|
|
775
|
-
// Should include name using aggregation
|
|
776
|
-
expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
|
|
777
|
-
// Should not error on unknownProp, just skip it
|
|
778
|
-
expect(query).not.toContain("unknownProp");
|
|
779
|
-
});
|
|
780
|
-
it("should handle order by regular property (handled in JavaScript)", async () => {
|
|
781
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
|
|
782
|
-
// ORDER BY is now handled in JavaScript post-query
|
|
783
|
-
expect(query).toContain("FROM node");
|
|
784
|
-
expect(query).not.toContain("ORDER BY");
|
|
785
|
-
});
|
|
786
|
-
it("should generate query with only properties specified", async () => {
|
|
787
|
-
const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"] });
|
|
788
|
-
// With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
|
|
789
|
-
expect(query).toContain("->link AS links");
|
|
615
|
+
const norm = normalizeQuery(query);
|
|
616
|
+
// Should have EXISTS blocks for both name and rating
|
|
617
|
+
expect(norm).toContain("recipe://name");
|
|
618
|
+
expect(norm).toContain("recipe://rating");
|
|
619
|
+
expect(norm).toContain("&&");
|
|
620
|
+
});
|
|
621
|
+
// ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
|
|
622
|
+
it("should include ORDER BY/LIMIT/OFFSET in SPARQL pagination subquery", async () => {
|
|
623
|
+
const query = await Recipe.queryToSPARQL(mockPerspective, { order: { name: "ASC" }, limit: 10, offset: 5 });
|
|
624
|
+
const norm = normalizeQuery(query);
|
|
625
|
+
expect(norm).toContain("SELECT ?source");
|
|
626
|
+
// SPARQL-level pagination via subquery
|
|
627
|
+
expect(norm).toContain("ORDER BY");
|
|
628
|
+
expect(norm).toContain("LIMIT 10");
|
|
629
|
+
expect(norm).toContain("OFFSET 5");
|
|
630
|
+
expect(norm).toContain("SELECT DISTINCT ?source");
|
|
790
631
|
});
|
|
791
632
|
});
|
|
792
|
-
describe("Ad4mModel
|
|
633
|
+
describe("Ad4mModel query methods (modelQuery integration)", () => {
|
|
793
634
|
// Test Recipe model
|
|
794
635
|
let Recipe = class Recipe extends Ad4mModel {
|
|
795
636
|
constructor() {
|
|
@@ -814,9 +655,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
814
655
|
Recipe = __decorate([
|
|
815
656
|
Model({ name: "Recipe" })
|
|
816
657
|
], Recipe);
|
|
817
|
-
// Mock perspective with
|
|
658
|
+
// Mock perspective with querySparql, modelQuery, and infer methods
|
|
818
659
|
const mockPerspective = {
|
|
819
|
-
|
|
660
|
+
querySparql: jest.fn(),
|
|
661
|
+
modelQuery: jest.fn(),
|
|
820
662
|
infer: jest.fn(),
|
|
821
663
|
uuid: 'test-perspective-uuid',
|
|
822
664
|
stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
|
|
@@ -824,276 +666,137 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
|
|
|
824
666
|
beforeEach(() => {
|
|
825
667
|
jest.clearAllMocks();
|
|
826
668
|
});
|
|
827
|
-
it("should
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
links: [
|
|
838
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
839
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
840
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
841
|
-
{ predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
842
|
-
{ predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
843
|
-
]
|
|
844
|
-
},
|
|
845
|
-
{
|
|
846
|
-
source: "node:def456",
|
|
847
|
-
source_uri: "literal://recipe2",
|
|
848
|
-
links: [
|
|
849
|
-
{ predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
850
|
-
{ predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
851
|
-
{ predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
852
|
-
{ predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
853
|
-
{ predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
|
|
854
|
-
]
|
|
855
|
-
}
|
|
856
|
-
];
|
|
857
|
-
const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
|
|
858
|
-
expect(result.results).toHaveLength(2);
|
|
859
|
-
expect(result.totalCount).toBe(2);
|
|
860
|
-
const recipe1 = result.results[0];
|
|
861
|
-
expect(recipe1).toBeInstanceOf(Recipe);
|
|
862
|
-
expect(recipe1.name).toBe("Pasta");
|
|
863
|
-
expect(recipe1.rating).toBe(5);
|
|
864
|
-
expect(recipe1.ingredients).toEqual(["pasta", "tomato", "cheese"]);
|
|
865
|
-
const recipe2 = result.results[1];
|
|
866
|
-
expect(recipe2).toBeInstanceOf(Recipe);
|
|
867
|
-
expect(recipe2.name).toBe("Pizza");
|
|
868
|
-
expect(recipe2.rating).toBe(4);
|
|
869
|
-
});
|
|
870
|
-
it("should filter properties when query specifies properties", async () => {
|
|
871
|
-
const surrealResults = [
|
|
872
|
-
{
|
|
873
|
-
source: "node:abc123",
|
|
874
|
-
source_uri: "literal://recipe1",
|
|
875
|
-
links: [
|
|
876
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
877
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
878
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
879
|
-
{ predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
880
|
-
]
|
|
881
|
-
}
|
|
882
|
-
];
|
|
883
|
-
const result = await Recipe.instancesFromSurrealResult(mockPerspective, { properties: ["name"] }, surrealResults);
|
|
884
|
-
expect(result.results).toHaveLength(1);
|
|
885
|
-
const recipe = result.results[0];
|
|
886
|
-
expect(recipe.name).toBe("Pasta");
|
|
887
|
-
// rating and ingredients should be removed since only "name" was requested
|
|
888
|
-
expect(recipe.rating).toBeUndefined();
|
|
889
|
-
expect(recipe.ingredients).toBeUndefined();
|
|
890
|
-
// author, createdAt, updatedAt are also stripped unless explicitly requested
|
|
891
|
-
expect(recipe.author).toBeUndefined();
|
|
892
|
-
expect(recipe.timestamp).toBeUndefined();
|
|
893
|
-
});
|
|
894
|
-
it("should filter properties when query specifies properties", async () => {
|
|
895
|
-
const surrealResults = [
|
|
896
|
-
{
|
|
897
|
-
source: "node:abc123",
|
|
898
|
-
source_uri: "literal://recipe1",
|
|
899
|
-
links: [
|
|
900
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
901
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
902
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
903
|
-
{ predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
904
|
-
]
|
|
905
|
-
}
|
|
906
|
-
];
|
|
907
|
-
const result = await Recipe.instancesFromSurrealResult(mockPerspective, { properties: ["name"] }, surrealResults);
|
|
908
|
-
expect(result.results).toHaveLength(1);
|
|
909
|
-
const recipe = result.results[0];
|
|
910
|
-
expect(recipe.name).toBe("Pasta");
|
|
911
|
-
// rating and ingredients should be removed since only "name" was requested
|
|
912
|
-
expect(recipe.rating).toBeUndefined();
|
|
913
|
-
});
|
|
914
|
-
it("should handle results missing base field", async () => {
|
|
915
|
-
const surrealResults = [
|
|
916
|
-
{
|
|
917
|
-
links: [
|
|
918
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
919
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
920
|
-
]
|
|
921
|
-
// Missing source field
|
|
922
|
-
}
|
|
923
|
-
];
|
|
924
|
-
const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
|
|
925
|
-
// Should filter out the invalid result (or handle gracefully)
|
|
926
|
-
expect(result.results).toHaveLength(0);
|
|
927
|
-
expect(result.totalCount).toBe(0);
|
|
928
|
-
});
|
|
929
|
-
it("should use SurrealDB by default in findAll()", async () => {
|
|
930
|
-
const surrealResults = [
|
|
931
|
-
{
|
|
932
|
-
source: "node:abc123",
|
|
933
|
-
source_uri: "literal://recipe1",
|
|
934
|
-
links: [
|
|
935
|
-
{ predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
936
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
937
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
938
|
-
]
|
|
939
|
-
}
|
|
940
|
-
];
|
|
941
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
942
|
-
const results = await Recipe.findAll(mockPerspective, {});
|
|
943
|
-
expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
|
|
669
|
+
it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
|
|
670
|
+
// modelQuery returns already-hydrated instances from the Rust executor
|
|
671
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
672
|
+
instances: [
|
|
673
|
+
{ id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
|
|
674
|
+
],
|
|
675
|
+
totalCount: 1
|
|
676
|
+
});
|
|
677
|
+
const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
|
|
678
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
944
679
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
945
680
|
expect(results).toHaveLength(1);
|
|
946
681
|
expect(results[0].name).toBe("Pasta");
|
|
947
682
|
});
|
|
948
|
-
it("should
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
mockPerspective.infer.mockResolvedValue(prologResults);
|
|
683
|
+
it("should route through modelQuery when engine is 'prolog' in findAll() (prolog is now no-op)", async () => {
|
|
684
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
685
|
+
instances: [
|
|
686
|
+
{ id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
|
|
687
|
+
],
|
|
688
|
+
totalCount: 1
|
|
689
|
+
});
|
|
956
690
|
const results = await Recipe.findAll(mockPerspective, {}, false);
|
|
957
|
-
expect(mockPerspective.
|
|
958
|
-
expect(mockPerspective.
|
|
691
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
692
|
+
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
959
693
|
expect(results).toHaveLength(1);
|
|
960
694
|
});
|
|
961
|
-
it("should use
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
969
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
970
|
-
]
|
|
971
|
-
}
|
|
972
|
-
];
|
|
973
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
695
|
+
it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
|
|
696
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
697
|
+
instances: [
|
|
698
|
+
{ id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
|
|
699
|
+
],
|
|
700
|
+
totalCount: 1
|
|
701
|
+
});
|
|
974
702
|
const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
|
|
975
|
-
expect(mockPerspective.
|
|
703
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
976
704
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
977
705
|
expect(results).toHaveLength(1);
|
|
978
706
|
expect(totalCount).toBe(1);
|
|
979
707
|
});
|
|
980
|
-
it("should use
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
988
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
989
|
-
]
|
|
990
|
-
}
|
|
991
|
-
];
|
|
992
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
708
|
+
it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
|
|
709
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
710
|
+
instances: [
|
|
711
|
+
{ id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
|
|
712
|
+
],
|
|
713
|
+
totalCount: 1
|
|
714
|
+
});
|
|
993
715
|
const page = await Recipe.paginate(mockPerspective, 10, 1, {});
|
|
994
|
-
expect(mockPerspective.
|
|
716
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
995
717
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
996
718
|
expect(page.results).toHaveLength(1);
|
|
997
719
|
expect(page.pageSize).toBe(10);
|
|
998
720
|
expect(page.pageNumber).toBe(1);
|
|
721
|
+
expect(page.totalCount).toBe(1);
|
|
999
722
|
});
|
|
1000
|
-
it("should use
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
source_uri: `literal://recipe${i + 1}`,
|
|
1006
|
-
links: [
|
|
1007
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1008
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1009
|
-
]
|
|
1010
|
-
}));
|
|
1011
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
723
|
+
it("should use SPARQL in count()", async () => {
|
|
724
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
725
|
+
instances: [],
|
|
726
|
+
totalCount: 5
|
|
727
|
+
});
|
|
1012
728
|
const count = await Recipe.count(mockPerspective, {});
|
|
1013
|
-
expect(mockPerspective.
|
|
729
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
1014
730
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1015
731
|
expect(count).toBe(5);
|
|
1016
732
|
});
|
|
1017
|
-
it("should
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
733
|
+
it("should return count from modelQuery", async () => {
|
|
734
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
735
|
+
instances: [],
|
|
736
|
+
totalCount: 10
|
|
737
|
+
});
|
|
738
|
+
const count = await Recipe.count(mockPerspective, {});
|
|
739
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
740
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
1023
741
|
expect(count).toBe(10);
|
|
1024
742
|
});
|
|
1025
|
-
it("should use
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1033
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1034
|
-
]
|
|
1035
|
-
}
|
|
1036
|
-
];
|
|
1037
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
743
|
+
it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
|
|
744
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
745
|
+
instances: [
|
|
746
|
+
{ id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
|
|
747
|
+
],
|
|
748
|
+
totalCount: 1
|
|
749
|
+
});
|
|
1038
750
|
const results = await Recipe.query(mockPerspective)
|
|
1039
751
|
.where({ name: "Pasta" })
|
|
752
|
+
.engine('sparql')
|
|
1040
753
|
.get();
|
|
1041
|
-
expect(mockPerspective.
|
|
754
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
1042
755
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1043
756
|
expect(results).toHaveLength(1);
|
|
1044
757
|
expect(results[0].name).toBe("Pasta");
|
|
1045
758
|
});
|
|
1046
|
-
it("should use
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
mockPerspective.infer.mockResolvedValue(prologResults);
|
|
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"] }
|
|
763
|
+
],
|
|
764
|
+
totalCount: 1
|
|
765
|
+
});
|
|
1054
766
|
const results = await Recipe.query(mockPerspective)
|
|
1055
767
|
.where({ name: "Pasta" })
|
|
1056
|
-
.
|
|
768
|
+
.engine('prolog')
|
|
1057
769
|
.get();
|
|
1058
|
-
|
|
1059
|
-
expect(mockPerspective.
|
|
770
|
+
// engine('prolog') is now a no-op — everything goes through modelQuery
|
|
771
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
772
|
+
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1060
773
|
expect(results).toHaveLength(1);
|
|
1061
774
|
});
|
|
1062
|
-
it("should use
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
links: [
|
|
1068
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1069
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1070
|
-
]
|
|
1071
|
-
}));
|
|
1072
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
775
|
+
it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
|
|
776
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
777
|
+
instances: [],
|
|
778
|
+
totalCount: 3
|
|
779
|
+
});
|
|
1073
780
|
const count = await Recipe.query(mockPerspective)
|
|
1074
781
|
.where({ rating: { gt: 4 } })
|
|
782
|
+
.engine('sparql')
|
|
1075
783
|
.count();
|
|
1076
|
-
expect(mockPerspective.
|
|
784
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
1077
785
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1078
786
|
expect(count).toBe(3);
|
|
1079
787
|
});
|
|
1080
|
-
it("should use
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1088
|
-
{ predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1089
|
-
]
|
|
1090
|
-
}
|
|
1091
|
-
];
|
|
1092
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
788
|
+
it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
|
|
789
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
790
|
+
instances: [
|
|
791
|
+
{ id: "literal:recipe1", name: "Pasta", rating: 5, ingredients: ["pasta"] }
|
|
792
|
+
],
|
|
793
|
+
totalCount: 1
|
|
794
|
+
});
|
|
1093
795
|
const page = await Recipe.query(mockPerspective)
|
|
1094
796
|
.where({ rating: { gt: 3 } })
|
|
797
|
+
.engine('sparql')
|
|
1095
798
|
.paginate(10, 1);
|
|
1096
|
-
expect(mockPerspective.
|
|
799
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
1097
800
|
expect(mockPerspective.infer).not.toHaveBeenCalled();
|
|
1098
801
|
expect(page.results).toHaveLength(1);
|
|
1099
802
|
expect(page.pageSize).toBe(10);
|
|
@@ -1127,7 +830,8 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1127
830
|
], Recipe);
|
|
1128
831
|
// Mock perspective
|
|
1129
832
|
const mockPerspective = {
|
|
1130
|
-
|
|
833
|
+
querySparql: jest.fn(),
|
|
834
|
+
modelQuery: jest.fn(),
|
|
1131
835
|
infer: jest.fn(),
|
|
1132
836
|
uuid: 'test-perspective-uuid',
|
|
1133
837
|
stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
|
|
@@ -1135,175 +839,1217 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
|
|
|
1135
839
|
beforeEach(() => {
|
|
1136
840
|
jest.clearAllMocks();
|
|
1137
841
|
});
|
|
1138
|
-
it("should apply
|
|
1139
|
-
//
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1145
|
-
{ predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1146
|
-
]
|
|
1147
|
-
}));
|
|
1148
|
-
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
|
+
});
|
|
1149
848
|
// Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
|
|
1150
849
|
const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
|
|
1151
|
-
// Verify count matches the number of instances that would be returned by findAll
|
|
1152
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
|
|
1153
850
|
expect(count).toBe(2);
|
|
1154
|
-
expect(
|
|
1155
|
-
});
|
|
1156
|
-
it("should apply
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
links: [
|
|
1162
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1163
|
-
{ predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1164
|
-
]
|
|
1165
|
-
}));
|
|
1166
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
851
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalled();
|
|
852
|
+
});
|
|
853
|
+
it("should apply filtering for between operator on properties in SPARQL count()", async () => {
|
|
854
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
855
|
+
instances: [],
|
|
856
|
+
totalCount: 3
|
|
857
|
+
});
|
|
1167
858
|
// Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
|
|
1168
859
|
const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
|
|
1169
|
-
// Verify count matches the number of instances that would be returned by findAll
|
|
1170
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
|
|
1171
860
|
expect(count).toBe(3);
|
|
1172
|
-
expect(
|
|
1173
|
-
});
|
|
1174
|
-
it("should apply
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
links: [
|
|
1180
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
|
|
1181
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
|
|
1182
|
-
]
|
|
1183
|
-
}));
|
|
1184
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
1185
|
-
// Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
|
|
861
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalled();
|
|
862
|
+
});
|
|
863
|
+
it("should apply filtering for timestamp gt operator in SPARQL count()", async () => {
|
|
864
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
865
|
+
instances: [],
|
|
866
|
+
totalCount: 2
|
|
867
|
+
});
|
|
1186
868
|
const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
|
|
1187
869
|
const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
|
|
1188
|
-
// Verify count matches the number of instances that would be returned by findAll
|
|
1189
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
|
|
1190
870
|
expect(count).toBe(2);
|
|
1191
|
-
expect(
|
|
1192
|
-
});
|
|
1193
|
-
it("should apply
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
links: [
|
|
1199
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
|
|
1200
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
|
|
1201
|
-
]
|
|
1202
|
-
}));
|
|
1203
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
1204
|
-
// Count recipes with timestamp between 2023-01-02 and 2023-01-04
|
|
871
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalled();
|
|
872
|
+
});
|
|
873
|
+
it("should apply filtering for timestamp between operator in SPARQL count()", async () => {
|
|
874
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
875
|
+
instances: [],
|
|
876
|
+
totalCount: 3
|
|
877
|
+
});
|
|
1205
878
|
const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
|
|
1206
879
|
const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
|
|
1207
880
|
const count = await Recipe.count(mockPerspective, {
|
|
1208
881
|
where: { timestamp: { between: [startTimestamp, endTimestamp] } }
|
|
1209
882
|
});
|
|
1210
|
-
// Verify count matches the number of instances that would be returned by findAll
|
|
1211
|
-
const findAllResults = await Recipe.findAll(mockPerspective, {
|
|
1212
|
-
where: { timestamp: { between: [startTimestamp, endTimestamp] } }
|
|
1213
|
-
});
|
|
1214
883
|
expect(count).toBe(3);
|
|
1215
|
-
expect(
|
|
1216
|
-
});
|
|
1217
|
-
it("should apply
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
source_uri: `literal://recipe${i + 1}`,
|
|
1223
|
-
links: [
|
|
1224
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1225
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1226
|
-
]
|
|
1227
|
-
})),
|
|
1228
|
-
...Array.from({ length: 2 }, (_, i) => ({
|
|
1229
|
-
source: `node:def${i + 4}`,
|
|
1230
|
-
source_uri: `literal://recipe${i + 4}`,
|
|
1231
|
-
links: [
|
|
1232
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
|
|
1233
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
|
|
1234
|
-
]
|
|
1235
|
-
}))
|
|
1236
|
-
];
|
|
1237
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
884
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalled();
|
|
885
|
+
});
|
|
886
|
+
it("should apply filtering for author filtering in SPARQL count()", async () => {
|
|
887
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
888
|
+
instances: [],
|
|
889
|
+
totalCount: 3
|
|
890
|
+
});
|
|
1238
891
|
// Count recipes by Alice (should match 3 recipes)
|
|
1239
892
|
const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
|
|
1240
|
-
// Verify count matches the number of instances that would be returned by findAll
|
|
1241
|
-
const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
|
|
1242
893
|
expect(count).toBe(3);
|
|
1243
|
-
expect(
|
|
1244
|
-
});
|
|
1245
|
-
it("should apply
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
links: [
|
|
1251
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
|
|
1252
|
-
{ predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
|
|
1253
|
-
]
|
|
1254
|
-
}));
|
|
1255
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
894
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalled();
|
|
895
|
+
});
|
|
896
|
+
it("should apply filtering in ModelQueryBuilder.count() with gt operator", async () => {
|
|
897
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
898
|
+
instances: [],
|
|
899
|
+
totalCount: 2
|
|
900
|
+
});
|
|
1256
901
|
// Count recipes with rating > 3 using ModelQueryBuilder
|
|
1257
902
|
const count = await Recipe.query(mockPerspective)
|
|
1258
903
|
.where({ rating: { gt: 3 } })
|
|
904
|
+
.engine('sparql')
|
|
1259
905
|
.count();
|
|
1260
|
-
// Verify count matches the number of instances that would be returned by get()
|
|
1261
|
-
const getResults = await Recipe.query(mockPerspective)
|
|
1262
|
-
.where({ rating: { gt: 3 } })
|
|
1263
|
-
.get();
|
|
1264
906
|
expect(count).toBe(2);
|
|
1265
|
-
expect(
|
|
1266
|
-
});
|
|
1267
|
-
it("should apply
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
links: [
|
|
1273
|
-
{ predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
|
|
1274
|
-
{ predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
|
|
1275
|
-
]
|
|
1276
|
-
}));
|
|
1277
|
-
mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
|
|
907
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalled();
|
|
908
|
+
});
|
|
909
|
+
it("should apply filtering in ModelQueryBuilder.count() with timestamp between", async () => {
|
|
910
|
+
mockPerspective.modelQuery.mockResolvedValue({
|
|
911
|
+
instances: [],
|
|
912
|
+
totalCount: 3
|
|
913
|
+
});
|
|
1278
914
|
const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
|
|
1279
915
|
const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
|
|
1280
916
|
// Count using ModelQueryBuilder
|
|
1281
917
|
const count = await Recipe.query(mockPerspective)
|
|
1282
918
|
.where({ timestamp: { between: [startTimestamp, endTimestamp] } })
|
|
919
|
+
.engine('sparql')
|
|
1283
920
|
.count();
|
|
1284
|
-
// Verify count matches the number of instances that would be returned by get()
|
|
1285
|
-
const getResults = await Recipe.query(mockPerspective)
|
|
1286
|
-
.where({ timestamp: { between: [startTimestamp, endTimestamp] } })
|
|
1287
|
-
.get();
|
|
1288
921
|
expect(count).toBe(3);
|
|
1289
|
-
expect(
|
|
1290
|
-
});
|
|
1291
|
-
it("should handle count() with Prolog for gt operator (legacy)", async () => {
|
|
1292
|
-
const prologResults = [{ TotalCount: 2 }];
|
|
1293
|
-
mockPerspective.infer.mockResolvedValue(prologResults);
|
|
1294
|
-
const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
|
|
1295
|
-
expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
|
|
1296
|
-
expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
|
|
1297
|
-
expect(count).toBe(2);
|
|
922
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalled();
|
|
1298
923
|
});
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
924
|
+
});
|
|
925
|
+
describe("SPARQL comparison filters", () => {
|
|
926
|
+
let Item = class Item extends Ad4mModel {
|
|
927
|
+
};
|
|
928
|
+
__decorate([
|
|
929
|
+
Property({ through: "item://price", required: true }),
|
|
930
|
+
__metadata("design:type", String)
|
|
931
|
+
], Item.prototype, "price", void 0);
|
|
932
|
+
__decorate([
|
|
933
|
+
Property({ through: "item://name", required: true }),
|
|
934
|
+
__metadata("design:type", String)
|
|
935
|
+
], Item.prototype, "name", void 0);
|
|
936
|
+
Item = __decorate([
|
|
937
|
+
Model({ name: "Item" })
|
|
938
|
+
], Item);
|
|
939
|
+
it("should generate gt filter", async () => {
|
|
940
|
+
const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) };
|
|
941
|
+
const query = await Item.queryToSPARQL(mockPersp, { where: { price: { gt: 10 } } });
|
|
942
|
+
// gt is now JS post-filter — SPARQL just joins the property
|
|
943
|
+
expect(query).toContain("item://price");
|
|
944
|
+
});
|
|
945
|
+
it("should generate between filter", async () => {
|
|
946
|
+
const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) };
|
|
947
|
+
const query = await Item.queryToSPARQL(mockPersp, { where: { price: { between: [5, 20] } } });
|
|
948
|
+
// between is now JS post-filter
|
|
949
|
+
expect(query).toContain("item://price");
|
|
950
|
+
});
|
|
951
|
+
it("should generate contains filter", async () => {
|
|
952
|
+
const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) };
|
|
953
|
+
const query = await Item.queryToSPARQL(mockPersp, { where: { name: { contains: "widget" } } });
|
|
954
|
+
// contains is now JS post-filter
|
|
955
|
+
expect(query).toContain("item://name");
|
|
956
|
+
});
|
|
957
|
+
});
|
|
958
|
+
// ──────────────────────────────────────────────────────────
|
|
959
|
+
// SPARQL Direct Triple Pattern & IRI Tests
|
|
960
|
+
// ──────────────────────────────────────────────────────────
|
|
961
|
+
import { buildSPARQLQuery, formatSPARQLValue } from "./query-sparql";
|
|
962
|
+
describe("SPARQL direct triple pattern generation", () => {
|
|
963
|
+
let Channel = class Channel extends Ad4mModel {
|
|
964
|
+
constructor() {
|
|
965
|
+
super(...arguments);
|
|
966
|
+
this.type = "";
|
|
967
|
+
this.name = "";
|
|
968
|
+
this.description = "";
|
|
969
|
+
this.messages = [];
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
__decorate([
|
|
973
|
+
Flag({ through: "flux://entry_type", value: "flux://channel" }),
|
|
974
|
+
__metadata("design:type", String)
|
|
975
|
+
], Channel.prototype, "type", void 0);
|
|
976
|
+
__decorate([
|
|
977
|
+
Property({ through: "flux://name", resolveLanguage: "literal", required: true }),
|
|
978
|
+
__metadata("design:type", String)
|
|
979
|
+
], Channel.prototype, "name", void 0);
|
|
980
|
+
__decorate([
|
|
981
|
+
Optional({ through: "flux://description" }),
|
|
982
|
+
__metadata("design:type", String)
|
|
983
|
+
], Channel.prototype, "description", void 0);
|
|
984
|
+
__decorate([
|
|
985
|
+
HasMany({ through: "flux://has_message" }),
|
|
986
|
+
__metadata("design:type", Array)
|
|
987
|
+
], Channel.prototype, "messages", void 0);
|
|
988
|
+
Channel = __decorate([
|
|
989
|
+
Model({ name: "Channel" })
|
|
990
|
+
], Channel);
|
|
991
|
+
const mockPersp = {};
|
|
992
|
+
it("generates direct triple pattern with ?source ?predicate ?target", async () => {
|
|
993
|
+
const query = await Channel.queryToSPARQL(mockPersp, {});
|
|
994
|
+
// Must use direct triple pattern, not link-node reification
|
|
995
|
+
expect(query).toContain("?source ?predicate ?target");
|
|
996
|
+
expect(query).not.toContain("rdf:type");
|
|
997
|
+
expect(query).not.toContain("ad4m:Link");
|
|
998
|
+
});
|
|
999
|
+
it("generates Flag filter as ?source <predicate> <value>", async () => {
|
|
1000
|
+
const query = await Channel.queryToSPARQL(mockPersp, {});
|
|
1001
|
+
expect(query).toContain("<flux://entry_type>");
|
|
1002
|
+
expect(query).toContain("<flux://channel>");
|
|
1003
|
+
});
|
|
1004
|
+
it("generates Property binding as ?source <predicate> ?varName", async () => {
|
|
1005
|
+
const query = await Channel.queryToSPARQL(mockPersp, {});
|
|
1006
|
+
expect(query).toContain("<flux://name>");
|
|
1007
|
+
expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
|
|
1008
|
+
});
|
|
1009
|
+
it("uses RDF 1.2 reifier pattern for author/timestamp", async () => {
|
|
1010
|
+
const query = await Channel.queryToSPARQL(mockPersp, {});
|
|
1011
|
+
expect(query).toContain("<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>");
|
|
1012
|
+
expect(query).toContain("?source ?predicate ?target .");
|
|
1013
|
+
expect(query).toContain("?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>>");
|
|
1014
|
+
expect(query).toContain("?_reifier <ad4m://ontology/author> ?author");
|
|
1015
|
+
expect(query).toContain("?_reifier <ad4m://ontology/timestamp> ?timestamp");
|
|
1016
|
+
expect(query).not.toContain("GRAPH");
|
|
1017
|
+
});
|
|
1018
|
+
it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
|
|
1019
|
+
const query = await Channel.queryToSPARQL(mockPersp, {});
|
|
1020
|
+
expect(query).toContain("FILTER(isIRI(?source)");
|
|
1021
|
+
});
|
|
1022
|
+
});
|
|
1023
|
+
describe("formatSPARQLValue", () => {
|
|
1024
|
+
it("wraps strings in double quotes", () => {
|
|
1025
|
+
expect(formatSPARQLValue("hello")).toBe('"hello"');
|
|
1026
|
+
});
|
|
1027
|
+
it("escapes special characters", () => {
|
|
1028
|
+
expect(formatSPARQLValue('say "hi"')).toBe('"say \\"hi\\""');
|
|
1029
|
+
});
|
|
1030
|
+
it("converts numbers to quoted strings", () => {
|
|
1031
|
+
expect(formatSPARQLValue(42)).toBe('"42"');
|
|
1032
|
+
});
|
|
1033
|
+
});
|
|
1034
|
+
// ──────────────────────────────────────────────────────────
|
|
1035
|
+
// Comprehensive SPARQL migration unit tests
|
|
1036
|
+
// ──────────────────────────────────────────────────────────
|
|
1037
|
+
import { matchesCondition } from "./hydration";
|
|
1038
|
+
import { Literal } from "../Literal";
|
|
1039
|
+
// Helper: create literal URLs using JSON encoding (which handles all types including booleans)
|
|
1040
|
+
function literalUrl(value) {
|
|
1041
|
+
if (typeof value === 'string')
|
|
1042
|
+
return Literal.from(value).toUrl();
|
|
1043
|
+
// Use JSON encoding for numbers and booleans since Literal.get() doesn't handle boolean: prefix
|
|
1044
|
+
return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
|
|
1045
|
+
}
|
|
1046
|
+
describe("matchesCondition()", () => {
|
|
1047
|
+
// Simple equality
|
|
1048
|
+
it("simple string equality — match", () => {
|
|
1049
|
+
expect(matchesCondition("hello", "hello")).toBe(true);
|
|
1050
|
+
});
|
|
1051
|
+
it("simple string equality — mismatch", () => {
|
|
1052
|
+
expect(matchesCondition("hello", "world")).toBe(false);
|
|
1053
|
+
});
|
|
1054
|
+
it("simple boolean equality — true", () => {
|
|
1055
|
+
expect(matchesCondition(true, true)).toBe(true);
|
|
1056
|
+
});
|
|
1057
|
+
it("simple boolean equality — false", () => {
|
|
1058
|
+
expect(matchesCondition(false, false)).toBe(true);
|
|
1059
|
+
});
|
|
1060
|
+
it("boolean mismatch", () => {
|
|
1061
|
+
expect(matchesCondition(true, false)).toBe(false);
|
|
1062
|
+
});
|
|
1063
|
+
it("simple number equality", () => {
|
|
1064
|
+
expect(matchesCondition(42, 42)).toBe(true);
|
|
1065
|
+
});
|
|
1066
|
+
it("number mismatch", () => {
|
|
1067
|
+
expect(matchesCondition(42, 99)).toBe(false);
|
|
1068
|
+
});
|
|
1069
|
+
// Array IN clause
|
|
1070
|
+
it("array IN clause — value present", () => {
|
|
1071
|
+
expect(matchesCondition("a", ["a", "b", "c"])).toBe(true);
|
|
1072
|
+
});
|
|
1073
|
+
it("array IN clause — value absent", () => {
|
|
1074
|
+
expect(matchesCondition("d", ["a", "b", "c"])).toBe(false);
|
|
1075
|
+
});
|
|
1076
|
+
// NOT operator
|
|
1077
|
+
it("not operator with string", () => {
|
|
1078
|
+
expect(matchesCondition("bob", { not: "alice" })).toBe(true);
|
|
1079
|
+
expect(matchesCondition("alice", { not: "alice" })).toBe(false);
|
|
1080
|
+
});
|
|
1081
|
+
it("not operator with array (NOT IN)", () => {
|
|
1082
|
+
expect(matchesCondition("a", { not: ["b", "c"] })).toBe(true);
|
|
1083
|
+
expect(matchesCondition("b", { not: ["b", "c"] })).toBe(false);
|
|
1084
|
+
});
|
|
1085
|
+
// Comparison operators
|
|
1086
|
+
it("gt", () => {
|
|
1087
|
+
expect(matchesCondition(10, { gt: 5 })).toBe(true);
|
|
1088
|
+
expect(matchesCondition(5, { gt: 5 })).toBe(false);
|
|
1089
|
+
});
|
|
1090
|
+
it("gte", () => {
|
|
1091
|
+
expect(matchesCondition(5, { gte: 5 })).toBe(true);
|
|
1092
|
+
expect(matchesCondition(4, { gte: 5 })).toBe(false);
|
|
1093
|
+
});
|
|
1094
|
+
it("lt", () => {
|
|
1095
|
+
expect(matchesCondition(3, { lt: 5 })).toBe(true);
|
|
1096
|
+
expect(matchesCondition(5, { lt: 5 })).toBe(false);
|
|
1097
|
+
});
|
|
1098
|
+
it("lte", () => {
|
|
1099
|
+
expect(matchesCondition(5, { lte: 5 })).toBe(true);
|
|
1100
|
+
expect(matchesCondition(6, { lte: 5 })).toBe(false);
|
|
1101
|
+
});
|
|
1102
|
+
it("combined gt + lt (range)", () => {
|
|
1103
|
+
expect(matchesCondition(5, { gt: 3, lt: 7 })).toBe(true);
|
|
1104
|
+
expect(matchesCondition(3, { gt: 3, lt: 7 })).toBe(false);
|
|
1105
|
+
expect(matchesCondition(7, { gt: 3, lt: 7 })).toBe(false);
|
|
1106
|
+
});
|
|
1107
|
+
// Between
|
|
1108
|
+
it("between — inclusive range", () => {
|
|
1109
|
+
expect(matchesCondition(5, { between: [3, 7] })).toBe(true);
|
|
1110
|
+
expect(matchesCondition(3, { between: [3, 7] })).toBe(true);
|
|
1111
|
+
expect(matchesCondition(7, { between: [3, 7] })).toBe(true);
|
|
1112
|
+
expect(matchesCondition(2, { between: [3, 7] })).toBe(false);
|
|
1113
|
+
expect(matchesCondition(8, { between: [3, 7] })).toBe(false);
|
|
1114
|
+
});
|
|
1115
|
+
// Contains
|
|
1116
|
+
it("contains with string", () => {
|
|
1117
|
+
expect(matchesCondition("hello world", { contains: "world" })).toBe(true);
|
|
1118
|
+
expect(matchesCondition("hello world", { contains: "xyz" })).toBe(false);
|
|
1119
|
+
});
|
|
1120
|
+
it("contains with array", () => {
|
|
1121
|
+
expect(matchesCondition(["a", "b", "c"], { contains: "b" })).toBe(true);
|
|
1122
|
+
expect(matchesCondition(["a", "b", "c"], { contains: "d" })).toBe(false);
|
|
1123
|
+
});
|
|
1124
|
+
// Edge cases
|
|
1125
|
+
it("returns false for undefined value with equality check", () => {
|
|
1126
|
+
expect(matchesCondition(undefined, "hello")).toBe(false);
|
|
1127
|
+
});
|
|
1128
|
+
it("returns false for empty string when condition is non-empty", () => {
|
|
1129
|
+
expect(matchesCondition("", "Recipe 2")).toBe(false);
|
|
1130
|
+
});
|
|
1131
|
+
it("returns true for undefined with not operator", () => {
|
|
1132
|
+
expect(matchesCondition(undefined, { not: "hello" })).toBe(true);
|
|
1133
|
+
});
|
|
1134
|
+
});
|
|
1135
|
+
describe("buildSPARQLQuery edge cases", () => {
|
|
1136
|
+
let FlagModel = class FlagModel extends Ad4mModel {
|
|
1137
|
+
constructor() {
|
|
1138
|
+
super(...arguments);
|
|
1139
|
+
this.type = "";
|
|
1140
|
+
this.name = "";
|
|
1141
|
+
}
|
|
1142
|
+
};
|
|
1143
|
+
__decorate([
|
|
1144
|
+
Flag({ through: "flag://type", value: "flag://FlagModel" }),
|
|
1145
|
+
__metadata("design:type", String)
|
|
1146
|
+
], FlagModel.prototype, "type", void 0);
|
|
1147
|
+
__decorate([
|
|
1148
|
+
Property({ through: "flag://name", resolveLanguage: "literal", required: true }),
|
|
1149
|
+
__metadata("design:type", String)
|
|
1150
|
+
], FlagModel.prototype, "name", void 0);
|
|
1151
|
+
FlagModel = __decorate([
|
|
1152
|
+
Model({ name: "FlagModel" })
|
|
1153
|
+
], FlagModel);
|
|
1154
|
+
let NoFlagModel = class NoFlagModel extends Ad4mModel {
|
|
1155
|
+
constructor() {
|
|
1156
|
+
super(...arguments);
|
|
1157
|
+
this.title = "";
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
__decorate([
|
|
1161
|
+
Property({ through: "noflag://title", resolveLanguage: "literal" }),
|
|
1162
|
+
__metadata("design:type", String)
|
|
1163
|
+
], NoFlagModel.prototype, "title", void 0);
|
|
1164
|
+
NoFlagModel = __decorate([
|
|
1165
|
+
Model({ name: "NoFlagModel" })
|
|
1166
|
+
], NoFlagModel);
|
|
1167
|
+
it("adds conformance JOIN for flag + required properties", () => {
|
|
1168
|
+
const metadata = FlagModel.getModelMetadata();
|
|
1169
|
+
const allRelsMeta = {};
|
|
1170
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, FlagModel);
|
|
1171
|
+
// Should contain flag triple pattern
|
|
1172
|
+
expect(sparql).toContain("<flag://type>");
|
|
1173
|
+
expect(sparql).toContain("<flag://FlagModel>");
|
|
1174
|
+
// Should contain required property pattern
|
|
1175
|
+
expect(sparql).toContain("<flag://name>");
|
|
1176
|
+
});
|
|
1177
|
+
it("uses structural subquery when no conformance patterns exist", () => {
|
|
1178
|
+
const metadata = NoFlagModel.getModelMetadata();
|
|
1179
|
+
const allRelsMeta = {};
|
|
1180
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, NoFlagModel);
|
|
1181
|
+
// Should contain structural subquery with DISTINCT
|
|
1182
|
+
expect(sparql).toContain("SELECT DISTINCT ?source");
|
|
1183
|
+
expect(sparql).toContain("<noflag://title>");
|
|
1184
|
+
});
|
|
1185
|
+
it("adds JOIN for where-clause on literal-stored fields", () => {
|
|
1186
|
+
const metadata = FlagModel.getModelMetadata();
|
|
1187
|
+
const allRelsMeta = {};
|
|
1188
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { name: "test" } }, FlagModel);
|
|
1189
|
+
// Where clause should add a join pattern for name
|
|
1190
|
+
expect(sparql).toContain("flag://name");
|
|
1191
|
+
});
|
|
1192
|
+
it("handles where: {id: 'specific-id'} with FILTER on ?source", () => {
|
|
1193
|
+
const metadata = FlagModel.getModelMetadata();
|
|
1194
|
+
const allRelsMeta = {};
|
|
1195
|
+
const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { id: "expr:123" } }, FlagModel);
|
|
1196
|
+
// Should filter by source
|
|
1197
|
+
expect(sparql).toContain("expr:123");
|
|
1198
|
+
});
|
|
1199
|
+
});
|
|
1200
|
+
// ── Batch hydration for reverse relations (3.4) ─────────────────────────────
|
|
1201
|
+
describe("Batch hydration for reverse relations", () => {
|
|
1202
|
+
it("batch hydration should correctly group targets by parent instance ID", () => {
|
|
1203
|
+
// Test the grouping logic used in batch SPARQL hydration
|
|
1204
|
+
const sparqlResults = [
|
|
1205
|
+
{ target: "inst:1", source: "child:a" },
|
|
1206
|
+
{ target: "inst:1", source: "child:b" },
|
|
1207
|
+
{ target: "inst:2", source: "child:c" },
|
|
1208
|
+
{ target: "inst:3", source: "child:d" },
|
|
1209
|
+
{ target: "inst:3", source: "child:e" },
|
|
1210
|
+
{ target: "inst:3", source: "child:f" },
|
|
1211
|
+
];
|
|
1212
|
+
const reverseLinksMap = new Map();
|
|
1213
|
+
for (const row of sparqlResults) {
|
|
1214
|
+
if (!reverseLinksMap.has(row.target))
|
|
1215
|
+
reverseLinksMap.set(row.target, []);
|
|
1216
|
+
reverseLinksMap.get(row.target).push(row.source);
|
|
1217
|
+
}
|
|
1218
|
+
expect(reverseLinksMap.get("inst:1")).toEqual(["child:a", "child:b"]);
|
|
1219
|
+
expect(reverseLinksMap.get("inst:2")).toEqual(["child:c"]);
|
|
1220
|
+
expect(reverseLinksMap.get("inst:3")).toEqual(["child:d", "child:e", "child:f"]);
|
|
1221
|
+
});
|
|
1222
|
+
it("batch hydration should handle empty relation sets without error", () => {
|
|
1223
|
+
const sparqlResults = [];
|
|
1224
|
+
const reverseLinksMap = new Map();
|
|
1225
|
+
for (const row of sparqlResults) {
|
|
1226
|
+
if (!reverseLinksMap.has(row.target))
|
|
1227
|
+
reverseLinksMap.set(row.target, []);
|
|
1228
|
+
reverseLinksMap.get(row.target).push(row.source);
|
|
1229
|
+
}
|
|
1230
|
+
expect(reverseLinksMap.size).toBe(0);
|
|
1231
|
+
expect(reverseLinksMap.get("nonexistent") || []).toEqual([]);
|
|
1232
|
+
});
|
|
1233
|
+
it("batch hydration should return identical results to N+1 hydration (grouping equivalence)", () => {
|
|
1234
|
+
// Simulate N+1: each instance queries separately
|
|
1235
|
+
const instances = [{ id: "inst:1" }, { id: "inst:2" }];
|
|
1236
|
+
const allLinks = [
|
|
1237
|
+
{ data: { source: "child:a", predicate: "rel://has", target: "inst:1" } },
|
|
1238
|
+
{ data: { source: "child:b", predicate: "rel://has", target: "inst:1" } },
|
|
1239
|
+
{ data: { source: "child:c", predicate: "rel://has", target: "inst:2" } },
|
|
1240
|
+
];
|
|
1241
|
+
// N+1 approach
|
|
1242
|
+
const n1Results = new Map();
|
|
1243
|
+
for (const inst of instances) {
|
|
1244
|
+
const links = allLinks.filter(l => l.data.target === inst.id);
|
|
1245
|
+
n1Results.set(inst.id, links.map(l => l.data.source));
|
|
1246
|
+
}
|
|
1247
|
+
// Batch approach
|
|
1248
|
+
const batchResults = new Map();
|
|
1249
|
+
const sparqlRows = allLinks.map(l => ({ target: l.data.target, source: l.data.source }));
|
|
1250
|
+
for (const row of sparqlRows) {
|
|
1251
|
+
if (!batchResults.has(row.target))
|
|
1252
|
+
batchResults.set(row.target, []);
|
|
1253
|
+
batchResults.get(row.target).push(row.source);
|
|
1254
|
+
}
|
|
1255
|
+
// Results should be identical
|
|
1256
|
+
for (const inst of instances) {
|
|
1257
|
+
expect(batchResults.get(inst.id)).toEqual(n1Results.get(inst.id));
|
|
1258
|
+
}
|
|
1259
|
+
});
|
|
1260
|
+
it("batch hydration with nested includes should use batched queries at each level", () => {
|
|
1261
|
+
// This test verifies the structure: nested includes result in multiple
|
|
1262
|
+
// batch operations, one per relation depth level
|
|
1263
|
+
const depth0Rows = [
|
|
1264
|
+
{ target: "root:1", source: "mid:a" },
|
|
1265
|
+
{ target: "root:1", source: "mid:b" },
|
|
1266
|
+
];
|
|
1267
|
+
const depth1Rows = [
|
|
1268
|
+
{ target: "mid:a", source: "leaf:x" },
|
|
1269
|
+
{ target: "mid:b", source: "leaf:y" },
|
|
1270
|
+
];
|
|
1271
|
+
// Group each level
|
|
1272
|
+
const level0Map = new Map();
|
|
1273
|
+
for (const r of depth0Rows) {
|
|
1274
|
+
if (!level0Map.has(r.target))
|
|
1275
|
+
level0Map.set(r.target, []);
|
|
1276
|
+
level0Map.get(r.target).push(r.source);
|
|
1277
|
+
}
|
|
1278
|
+
const level1Map = new Map();
|
|
1279
|
+
for (const r of depth1Rows) {
|
|
1280
|
+
if (!level1Map.has(r.target))
|
|
1281
|
+
level1Map.set(r.target, []);
|
|
1282
|
+
level1Map.get(r.target).push(r.source);
|
|
1283
|
+
}
|
|
1284
|
+
expect(level0Map.get("root:1")).toEqual(["mid:a", "mid:b"]);
|
|
1285
|
+
expect(level1Map.get("mid:a")).toEqual(["leaf:x"]);
|
|
1286
|
+
expect(level1Map.get("mid:b")).toEqual(["leaf:y"]);
|
|
1287
|
+
});
|
|
1288
|
+
});
|
|
1289
|
+
// ── Push-down FILTER for literal equality (3.5) ──────────────────────────────
|
|
1290
|
+
describe("Push-down FILTER for literal equality", () => {
|
|
1291
|
+
const mockPerspective = {};
|
|
1292
|
+
let FilterTest = class FilterTest extends Ad4mModel {
|
|
1293
|
+
constructor() {
|
|
1294
|
+
super(...arguments);
|
|
1295
|
+
this.name = "";
|
|
1296
|
+
this.rating = 0;
|
|
1297
|
+
}
|
|
1298
|
+
};
|
|
1299
|
+
__decorate([
|
|
1300
|
+
Property({ through: "ft://name", required: true }),
|
|
1301
|
+
__metadata("design:type", String)
|
|
1302
|
+
], FilterTest.prototype, "name", void 0);
|
|
1303
|
+
__decorate([
|
|
1304
|
+
Property({ through: "ft://rating", required: true }),
|
|
1305
|
+
__metadata("design:type", Number)
|
|
1306
|
+
], FilterTest.prototype, "rating", void 0);
|
|
1307
|
+
FilterTest = __decorate([
|
|
1308
|
+
Model({ name: "FilterTest" })
|
|
1309
|
+
], FilterTest);
|
|
1310
|
+
const normalizeQuery = (q) => q.replace(/\s+/g, " ").trim();
|
|
1311
|
+
it("SPARQL query for where: { name: 'Alice' } should use <ad4m://fn/parse_literal> FILTER", async () => {
|
|
1312
|
+
const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
|
|
1313
|
+
const norm = normalizeQuery(query);
|
|
1314
|
+
// JOIN pattern exists
|
|
1315
|
+
expect(norm).toContain("?wTarget_name");
|
|
1316
|
+
// parse_literal push-down FILTER is present (using correct SPARQL IRI syntax)
|
|
1317
|
+
expect(norm).toContain("ad4m://fn/parse_literal");
|
|
1318
|
+
expect(norm).not.toContain("fn::parse_literal");
|
|
1319
|
+
});
|
|
1320
|
+
it("SPARQL query for where: { name: ['Alice', 'Bob'] } should use <ad4m://fn/parse_literal> IN FILTER", async () => {
|
|
1321
|
+
const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { name: ["Alice", "Bob"] } });
|
|
1322
|
+
const norm = normalizeQuery(query);
|
|
1323
|
+
expect(norm).toContain("?wTarget_name");
|
|
1324
|
+
expect(norm).toContain("ad4m://fn/parse_literal");
|
|
1325
|
+
expect(norm).not.toContain("fn::parse_literal");
|
|
1326
|
+
});
|
|
1327
|
+
it("SPARQL query for where: { rating: { gt: 5 } } should NOT include parse_literal FILTER", async () => {
|
|
1328
|
+
const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { rating: { gt: 5 } } });
|
|
1329
|
+
const norm = normalizeQuery(query);
|
|
1330
|
+
expect(norm).not.toContain("parse_literal");
|
|
1331
|
+
});
|
|
1332
|
+
it("literal property where clause adds JOIN for JS post-filter", async () => {
|
|
1333
|
+
const query = await FilterTest.queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
|
|
1334
|
+
const norm = normalizeQuery(query);
|
|
1335
|
+
expect(norm).toContain("?wTarget_name");
|
|
1336
|
+
});
|
|
1337
|
+
});
|
|
1338
|
+
// ── Lightweight fingerprint (3.7) ────────────────────────────────────────────
|
|
1339
|
+
describe("Lightweight fingerprint optimization", () => {
|
|
1340
|
+
// Replicate the buildFingerprint logic for testing
|
|
1341
|
+
const buildFingerprint = (results) => {
|
|
1342
|
+
if (results.length === 0)
|
|
1343
|
+
return '0:';
|
|
1344
|
+
const ids = results.map((r) => r.id || '').sort().join(',');
|
|
1345
|
+
const ts = results.map((r) => r.updatedAt || r.timestamp || '').join(',');
|
|
1346
|
+
return `${results.length}:${ids}:${ts}`;
|
|
1347
|
+
};
|
|
1348
|
+
const base = [
|
|
1349
|
+
{ id: "a", updatedAt: "100" },
|
|
1350
|
+
{ id: "b", updatedAt: "200" },
|
|
1351
|
+
];
|
|
1352
|
+
it("lightweight fingerprint should detect instance addition", () => {
|
|
1353
|
+
const fp1 = buildFingerprint(base);
|
|
1354
|
+
const fp2 = buildFingerprint([...base, { id: "c", updatedAt: "300" }]);
|
|
1355
|
+
expect(fp1).not.toBe(fp2);
|
|
1356
|
+
});
|
|
1357
|
+
it("lightweight fingerprint should detect instance removal", () => {
|
|
1358
|
+
const fp1 = buildFingerprint(base);
|
|
1359
|
+
const fp2 = buildFingerprint([base[0]]);
|
|
1360
|
+
expect(fp1).not.toBe(fp2);
|
|
1361
|
+
});
|
|
1362
|
+
it("lightweight fingerprint should detect timestamp change", () => {
|
|
1363
|
+
const fp1 = buildFingerprint(base);
|
|
1364
|
+
const fp2 = buildFingerprint([{ id: "a", updatedAt: "999" }, base[1]]);
|
|
1365
|
+
expect(fp1).not.toBe(fp2);
|
|
1366
|
+
});
|
|
1367
|
+
it("lightweight fingerprint should NOT false-positive for identical sets", () => {
|
|
1368
|
+
const fp1 = buildFingerprint(base);
|
|
1369
|
+
const fp2 = buildFingerprint([...base]); // same data, new array
|
|
1370
|
+
expect(fp1).toBe(fp2);
|
|
1371
|
+
});
|
|
1372
|
+
});
|
|
1373
|
+
// ── Native SPARQL getter evaluation ──────────────────────────────────────────
|
|
1374
|
+
describe("Native SPARQL getter evaluation", () => {
|
|
1375
|
+
const { evaluateCustomGettersForInstance } = require("./hydration");
|
|
1376
|
+
const mockPerspective = {
|
|
1377
|
+
getLinks: jest.fn().mockResolvedValue([]),
|
|
1378
|
+
querySparql: jest.fn(),
|
|
1379
|
+
get: jest.fn().mockResolvedValue([]),
|
|
1380
|
+
};
|
|
1381
|
+
beforeEach(() => {
|
|
1382
|
+
jest.clearAllMocks();
|
|
1383
|
+
});
|
|
1384
|
+
it("should execute SELECT getter directly via querySparql", async () => {
|
|
1385
|
+
const metadata = {
|
|
1386
|
+
properties: {
|
|
1387
|
+
replyingTo: {
|
|
1388
|
+
predicate: "flux://has_reply",
|
|
1389
|
+
getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
|
|
1390
|
+
type: "string",
|
|
1391
|
+
}
|
|
1392
|
+
},
|
|
1393
|
+
relations: {},
|
|
1394
|
+
};
|
|
1395
|
+
mockPerspective.querySparql.mockResolvedValue([
|
|
1396
|
+
{ target: { value: "literal:string:msg123" } }
|
|
1397
|
+
]);
|
|
1398
|
+
const instance = { id: "test://msg1", replyingTo: undefined };
|
|
1399
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
1400
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledWith(expect.stringContaining("SELECT ?target WHERE"));
|
|
1401
|
+
expect(instance.replyingTo).toBe("literal:string:msg123");
|
|
1402
|
+
});
|
|
1403
|
+
it("should execute ASK getter and return boolean", async () => {
|
|
1404
|
+
const metadata = {
|
|
1405
|
+
properties: {
|
|
1406
|
+
isPopular: {
|
|
1407
|
+
predicate: "flux://is_popular",
|
|
1408
|
+
getter: 'ASK WHERE { SELECT (COUNT(DISTINCT ?reactor) AS ?count) WHERE { ?reactor <flux://reaction> ?source . } HAVING(?count > 5) }',
|
|
1409
|
+
type: "boolean",
|
|
1410
|
+
readOnly: true,
|
|
1411
|
+
}
|
|
1412
|
+
},
|
|
1413
|
+
relations: {},
|
|
1414
|
+
};
|
|
1415
|
+
mockPerspective.querySparql.mockResolvedValue(true);
|
|
1416
|
+
const instance = { id: "test://msg1", isPopular: false };
|
|
1417
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
1418
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledWith(expect.stringContaining("ASK WHERE"));
|
|
1419
|
+
expect(instance.isPopular).toBe(true);
|
|
1420
|
+
});
|
|
1421
|
+
it("should replace ?source with instance ID in SPARQL getter", async () => {
|
|
1422
|
+
const metadata = {
|
|
1423
|
+
properties: {
|
|
1424
|
+
author: {
|
|
1425
|
+
predicate: "test://author",
|
|
1426
|
+
getter: 'SELECT ?target WHERE { ?source <test://author> ?target . }',
|
|
1427
|
+
type: "string",
|
|
1428
|
+
}
|
|
1429
|
+
},
|
|
1430
|
+
relations: {},
|
|
1431
|
+
};
|
|
1432
|
+
mockPerspective.querySparql.mockResolvedValue([
|
|
1433
|
+
{ target: { value: "did:key:abc123" } }
|
|
1434
|
+
]);
|
|
1435
|
+
const instance = { id: "test://post1", author: undefined };
|
|
1436
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
1437
|
+
expect(mockPerspective.querySparql).toHaveBeenCalledWith(expect.stringContaining("<test://post1>"));
|
|
1438
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalledWith(expect.stringContaining("?source"));
|
|
1439
|
+
});
|
|
1440
|
+
it("should handle empty SPARQL results gracefully", async () => {
|
|
1441
|
+
const metadata = {
|
|
1442
|
+
properties: {
|
|
1443
|
+
replyingTo: {
|
|
1444
|
+
predicate: "flux://has_reply",
|
|
1445
|
+
getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
|
|
1446
|
+
type: "string",
|
|
1447
|
+
}
|
|
1448
|
+
},
|
|
1449
|
+
relations: {},
|
|
1450
|
+
};
|
|
1451
|
+
mockPerspective.querySparql.mockResolvedValue([]);
|
|
1452
|
+
const instance = { id: "test://msg1", replyingTo: "original" };
|
|
1453
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
1454
|
+
// Should not overwrite with undefined
|
|
1455
|
+
expect(instance.replyingTo).toBe("original");
|
|
1456
|
+
});
|
|
1457
|
+
it("should handle SPARQL getter errors without crashing", async () => {
|
|
1458
|
+
const metadata = {
|
|
1459
|
+
properties: {
|
|
1460
|
+
broken: {
|
|
1461
|
+
predicate: "test://broken",
|
|
1462
|
+
getter: 'SELECT ?target WHERE { INVALID SPARQL }',
|
|
1463
|
+
type: "string",
|
|
1464
|
+
}
|
|
1465
|
+
},
|
|
1466
|
+
relations: {},
|
|
1467
|
+
};
|
|
1468
|
+
mockPerspective.querySparql.mockRejectedValue(new Error("SPARQL parse error"));
|
|
1469
|
+
const instance = { id: "test://msg1", broken: undefined };
|
|
1470
|
+
const consoleSpy = jest.spyOn(console, "warn").mockImplementation();
|
|
1471
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
1472
|
+
consoleSpy.mockRestore();
|
|
1473
|
+
// Should not throw, should warn
|
|
1474
|
+
expect(instance.broken).toBeUndefined();
|
|
1475
|
+
});
|
|
1476
|
+
it("should execute SPARQL getter for relations", async () => {
|
|
1477
|
+
const metadata = {
|
|
1478
|
+
properties: {},
|
|
1479
|
+
relations: {
|
|
1480
|
+
tags: {
|
|
1481
|
+
predicate: "test://has_tag",
|
|
1482
|
+
getter: 'SELECT ?target WHERE { ?source <test://has_tag> ?target . }',
|
|
1483
|
+
direction: "forward",
|
|
1484
|
+
}
|
|
1485
|
+
},
|
|
1486
|
+
};
|
|
1487
|
+
mockPerspective.querySparql.mockResolvedValue([
|
|
1488
|
+
{ target: { value: "tag:a" } },
|
|
1489
|
+
{ target: { value: "tag:b" } },
|
|
1490
|
+
]);
|
|
1491
|
+
const instance = { id: "test://post1", tags: [] };
|
|
1492
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
1493
|
+
expect(instance.tags).toEqual(["tag:a", "tag:b"]);
|
|
1494
|
+
});
|
|
1495
|
+
it("should warn for legacy SurrealDB-style getter syntax instead of converting", async () => {
|
|
1496
|
+
const metadata = {
|
|
1497
|
+
properties: {
|
|
1498
|
+
legacy: {
|
|
1499
|
+
predicate: "test://legacy",
|
|
1500
|
+
getter: "(<-link[WHERE predicate = 'test://legacy'].in.uri)[0]",
|
|
1501
|
+
type: "string",
|
|
1502
|
+
}
|
|
1503
|
+
},
|
|
1504
|
+
relations: {},
|
|
1505
|
+
};
|
|
1506
|
+
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => { });
|
|
1507
|
+
const instance = { id: "test://msg1", legacy: undefined };
|
|
1508
|
+
await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
|
|
1509
|
+
// Should NOT call querySparql — legacy getters are no longer converted
|
|
1510
|
+
expect(mockPerspective.querySparql).not.toHaveBeenCalled();
|
|
1511
|
+
// Should warn about unsupported syntax
|
|
1512
|
+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Unsupported legacy getter syntax"));
|
|
1513
|
+
// Value should remain undefined
|
|
1514
|
+
expect(instance.legacy).toBeUndefined();
|
|
1515
|
+
warnSpy.mockRestore();
|
|
1516
|
+
});
|
|
1517
|
+
});
|
|
1518
|
+
// ── Subscribe callback timing ──────────────────────────────────────────
|
|
1519
|
+
describe("ModelQueryBuilder subscribe callback timing", () => {
|
|
1520
|
+
it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
|
|
1521
|
+
// This test verifies that subscribe() uses the Rust model subscription endpoint
|
|
1522
|
+
// and properly handles the subscription lifecycle.
|
|
1523
|
+
const mockSubscriptionId = "test-sub-123";
|
|
1524
|
+
let updateCallback = null;
|
|
1525
|
+
const mockClient = {
|
|
1526
|
+
modelSubscribe: jest.fn().mockResolvedValue({
|
|
1527
|
+
subscriptionId: mockSubscriptionId,
|
|
1528
|
+
result: { instances: [], totalCount: 0 },
|
|
1529
|
+
}),
|
|
1530
|
+
subscribeToQueryUpdates: jest.fn().mockImplementation((_id, cb) => {
|
|
1531
|
+
updateCallback = cb;
|
|
1532
|
+
return () => { }; // unsubscribe function
|
|
1533
|
+
}),
|
|
1534
|
+
keepAliveQuery: jest.fn().mockResolvedValue(true),
|
|
1535
|
+
disposeQuerySubscription: jest.fn().mockResolvedValue(true),
|
|
1536
|
+
};
|
|
1537
|
+
const mockPerspective = {
|
|
1538
|
+
uuid: "test-uuid",
|
|
1539
|
+
client: mockClient,
|
|
1540
|
+
modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
|
|
1541
|
+
return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
|
|
1542
|
+
}),
|
|
1543
|
+
getLinks: jest.fn().mockResolvedValue([]),
|
|
1544
|
+
modelQuery: jest.fn().mockResolvedValue({ instances: [], totalCount: 0 }),
|
|
1545
|
+
};
|
|
1546
|
+
const { Ad4mModel, Model, Property, Flag } = require("./index");
|
|
1547
|
+
let TimingTest = class TimingTest extends Ad4mModel {
|
|
1548
|
+
constructor() {
|
|
1549
|
+
super(...arguments);
|
|
1550
|
+
this.type = "test://timing";
|
|
1551
|
+
this.name = "";
|
|
1552
|
+
}
|
|
1553
|
+
};
|
|
1554
|
+
__decorate([
|
|
1555
|
+
Flag({ through: "test://type", value: "test://timing" }),
|
|
1556
|
+
__metadata("design:type", String)
|
|
1557
|
+
], TimingTest.prototype, "type", void 0);
|
|
1558
|
+
__decorate([
|
|
1559
|
+
Property({ through: "test://name" }),
|
|
1560
|
+
__metadata("design:type", String)
|
|
1561
|
+
], TimingTest.prototype, "name", void 0);
|
|
1562
|
+
TimingTest = __decorate([
|
|
1563
|
+
Model({ name: "TimingTest" })
|
|
1564
|
+
], TimingTest);
|
|
1565
|
+
let callbackInvokedBeforeResolve = false;
|
|
1566
|
+
let promiseResolved = false;
|
|
1567
|
+
const query = TimingTest.query(mockPerspective);
|
|
1568
|
+
const promise = query.subscribe((results) => {
|
|
1569
|
+
if (!promiseResolved) {
|
|
1570
|
+
callbackInvokedBeforeResolve = true;
|
|
1571
|
+
}
|
|
1572
|
+
});
|
|
1573
|
+
// At this point the Promise hasn't resolved yet
|
|
1574
|
+
// The callback should NOT have fired synchronously
|
|
1575
|
+
expect(callbackInvokedBeforeResolve).toBe(false);
|
|
1576
|
+
const initialResults = await promise;
|
|
1577
|
+
promiseResolved = true;
|
|
1578
|
+
expect(initialResults).toEqual([]);
|
|
1579
|
+
expect(mockPerspective.modelSubscribe).toHaveBeenCalled();
|
|
1580
|
+
});
|
|
1581
|
+
});
|
|
1582
|
+
describe("ModelQueryBuilder paginateSubscribe", () => {
|
|
1583
|
+
it("paginateSubscribe should use a single query with count: true", async () => {
|
|
1584
|
+
const mockSubscriptionId = "paginate-sub-123";
|
|
1585
|
+
const mockClient = {
|
|
1586
|
+
modelSubscribe: jest.fn().mockResolvedValue({
|
|
1587
|
+
subscriptionId: mockSubscriptionId,
|
|
1588
|
+
result: { instances: [], totalCount: 0 },
|
|
1589
|
+
}),
|
|
1590
|
+
subscribeToQueryUpdates: jest.fn().mockImplementation((_id, _cb) => {
|
|
1591
|
+
return () => { };
|
|
1592
|
+
}),
|
|
1593
|
+
keepAliveQuery: jest.fn().mockResolvedValue(true),
|
|
1594
|
+
disposeQuerySubscription: jest.fn().mockResolvedValue(true),
|
|
1595
|
+
};
|
|
1596
|
+
const mockPerspective = {
|
|
1597
|
+
uuid: "test-uuid",
|
|
1598
|
+
client: mockClient,
|
|
1599
|
+
modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
|
|
1600
|
+
return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
|
|
1601
|
+
}),
|
|
1602
|
+
modelQuery: jest.fn().mockResolvedValue({ instances: [{ id: "item1", type: "test://paginate" }], totalCount: 42 }),
|
|
1603
|
+
};
|
|
1604
|
+
const { Ad4mModel, Model, Flag, Property } = require("./index");
|
|
1605
|
+
let PaginateTest = class PaginateTest extends Ad4mModel {
|
|
1606
|
+
constructor() {
|
|
1607
|
+
super(...arguments);
|
|
1608
|
+
this.type = "test://paginate";
|
|
1609
|
+
this.name = "";
|
|
1610
|
+
}
|
|
1611
|
+
};
|
|
1612
|
+
__decorate([
|
|
1613
|
+
Flag({ through: "test://type", value: "test://paginate" }),
|
|
1614
|
+
__metadata("design:type", String)
|
|
1615
|
+
], PaginateTest.prototype, "type", void 0);
|
|
1616
|
+
__decorate([
|
|
1617
|
+
Property({ through: "test://name" }),
|
|
1618
|
+
__metadata("design:type", String)
|
|
1619
|
+
], PaginateTest.prototype, "name", void 0);
|
|
1620
|
+
PaginateTest = __decorate([
|
|
1621
|
+
Model({ name: "PaginateTest" })
|
|
1622
|
+
], PaginateTest);
|
|
1623
|
+
const builder = PaginateTest.query(mockPerspective);
|
|
1624
|
+
const result = await builder.paginateSubscribe(10, 1, () => { });
|
|
1625
|
+
// Should return paginated result structure
|
|
1626
|
+
expect(result).toHaveProperty("results");
|
|
1627
|
+
expect(result).toHaveProperty("totalCount");
|
|
1628
|
+
expect(result).toHaveProperty("pageSize", 10);
|
|
1629
|
+
expect(result).toHaveProperty("pageNumber", 1);
|
|
1630
|
+
// modelQuery should be called exactly once (not twice — no separate count query)
|
|
1631
|
+
expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
|
|
1632
|
+
// The query should have count: true
|
|
1633
|
+
const callArgs = mockPerspective.modelQuery.mock.calls[0];
|
|
1634
|
+
const queryJson = JSON.parse(callArgs[1]);
|
|
1635
|
+
expect(queryJson.count).toBe(true);
|
|
1636
|
+
expect(queryJson.limit).toBe(10);
|
|
1637
|
+
expect(queryJson.offset).toBe(0);
|
|
1638
|
+
});
|
|
1639
|
+
it("paginateSubscribe should skip isInit messages from subscription", async () => {
|
|
1640
|
+
const mockSubscriptionId = "paginate-init-sub";
|
|
1641
|
+
let capturedCallback = null;
|
|
1642
|
+
const mockClient = {
|
|
1643
|
+
modelSubscribe: jest.fn().mockResolvedValue({
|
|
1644
|
+
subscriptionId: mockSubscriptionId,
|
|
1645
|
+
result: { instances: [], totalCount: 0 },
|
|
1646
|
+
}),
|
|
1647
|
+
subscribeToQueryUpdates: jest.fn().mockImplementation((_id, cb) => {
|
|
1648
|
+
capturedCallback = cb;
|
|
1649
|
+
return () => { };
|
|
1650
|
+
}),
|
|
1651
|
+
keepAliveQuery: jest.fn().mockResolvedValue(true),
|
|
1652
|
+
disposeQuerySubscription: jest.fn().mockResolvedValue(true),
|
|
1653
|
+
};
|
|
1654
|
+
let modelQueryCallCount = 0;
|
|
1655
|
+
const mockPerspective = {
|
|
1656
|
+
uuid: "test-uuid",
|
|
1657
|
+
client: mockClient,
|
|
1658
|
+
modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
|
|
1659
|
+
return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
|
|
1660
|
+
}),
|
|
1661
|
+
modelQuery: jest.fn().mockImplementation(async () => {
|
|
1662
|
+
modelQueryCallCount++;
|
|
1663
|
+
return { instances: [], totalCount: 0 };
|
|
1664
|
+
}),
|
|
1665
|
+
};
|
|
1666
|
+
const { Ad4mModel, Model, Flag, Property } = require("./index");
|
|
1667
|
+
let InitGuardTest = class InitGuardTest extends Ad4mModel {
|
|
1668
|
+
constructor() {
|
|
1669
|
+
super(...arguments);
|
|
1670
|
+
this.type = "test://init";
|
|
1671
|
+
this.name = "";
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
__decorate([
|
|
1675
|
+
Flag({ through: "test://type", value: "test://init" }),
|
|
1676
|
+
__metadata("design:type", String)
|
|
1677
|
+
], InitGuardTest.prototype, "type", void 0);
|
|
1678
|
+
__decorate([
|
|
1679
|
+
Property({ through: "test://name" }),
|
|
1680
|
+
__metadata("design:type", String)
|
|
1681
|
+
], InitGuardTest.prototype, "name", void 0);
|
|
1682
|
+
InitGuardTest = __decorate([
|
|
1683
|
+
Model({ name: "InitGuardTest" })
|
|
1684
|
+
], InitGuardTest);
|
|
1685
|
+
const userCallback = jest.fn();
|
|
1686
|
+
const builder = InitGuardTest.query(mockPerspective);
|
|
1687
|
+
await builder.paginateSubscribe(10, 1, userCallback);
|
|
1688
|
+
// Reset the count after initial fetch
|
|
1689
|
+
const initialCallCount = modelQueryCallCount;
|
|
1690
|
+
// Simulate an isInit message from subscription
|
|
1691
|
+
expect(capturedCallback).not.toBeNull();
|
|
1692
|
+
capturedCallback({ isInit: true });
|
|
1693
|
+
// Wait for any async processing
|
|
1694
|
+
await new Promise(r => setTimeout(r, 50));
|
|
1695
|
+
// modelQuery should NOT have been called again (isInit was filtered)
|
|
1696
|
+
expect(modelQueryCallCount).toBe(initialCallCount);
|
|
1697
|
+
// User callback should NOT have been invoked by isInit
|
|
1698
|
+
expect(userCallback).not.toHaveBeenCalled();
|
|
1699
|
+
});
|
|
1700
|
+
it("paginateSubscribe should re-fetch on real subscription updates", async () => {
|
|
1701
|
+
const mockSubscriptionId = "paginate-update-sub";
|
|
1702
|
+
let capturedCallback = null;
|
|
1703
|
+
const mockClient = {
|
|
1704
|
+
modelSubscribe: jest.fn().mockResolvedValue({
|
|
1705
|
+
subscriptionId: mockSubscriptionId,
|
|
1706
|
+
result: { instances: [], totalCount: 0 },
|
|
1707
|
+
}),
|
|
1708
|
+
subscribeToQueryUpdates: jest.fn().mockImplementation((_id, cb) => {
|
|
1709
|
+
capturedCallback = cb;
|
|
1710
|
+
return () => { };
|
|
1711
|
+
}),
|
|
1712
|
+
keepAliveQuery: jest.fn().mockResolvedValue(true),
|
|
1713
|
+
disposeQuerySubscription: jest.fn().mockResolvedValue(true),
|
|
1714
|
+
};
|
|
1715
|
+
let modelQueryCallCount = 0;
|
|
1716
|
+
const mockPerspective = {
|
|
1717
|
+
uuid: "test-uuid",
|
|
1718
|
+
client: mockClient,
|
|
1719
|
+
modelSubscribe: jest.fn().mockImplementation(async (className, queryJson, shapeJson) => {
|
|
1720
|
+
return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
|
|
1721
|
+
}),
|
|
1722
|
+
modelQuery: jest.fn().mockImplementation(async () => {
|
|
1723
|
+
modelQueryCallCount++;
|
|
1724
|
+
return { instances: [{ id: "new-item", type: "test://update" }], totalCount: 1 };
|
|
1725
|
+
}),
|
|
1726
|
+
};
|
|
1727
|
+
const { Ad4mModel, Model, Flag, Property } = require("./index");
|
|
1728
|
+
let UpdateTest = class UpdateTest extends Ad4mModel {
|
|
1729
|
+
constructor() {
|
|
1730
|
+
super(...arguments);
|
|
1731
|
+
this.type = "test://update";
|
|
1732
|
+
this.name = "";
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
__decorate([
|
|
1736
|
+
Flag({ through: "test://type", value: "test://update" }),
|
|
1737
|
+
__metadata("design:type", String)
|
|
1738
|
+
], UpdateTest.prototype, "type", void 0);
|
|
1739
|
+
__decorate([
|
|
1740
|
+
Property({ through: "test://name" }),
|
|
1741
|
+
__metadata("design:type", String)
|
|
1742
|
+
], UpdateTest.prototype, "name", void 0);
|
|
1743
|
+
UpdateTest = __decorate([
|
|
1744
|
+
Model({ name: "UpdateTest" })
|
|
1745
|
+
], UpdateTest);
|
|
1746
|
+
const userCallback = jest.fn();
|
|
1747
|
+
const builder = UpdateTest.query(mockPerspective);
|
|
1748
|
+
await builder.paginateSubscribe(10, 1, userCallback);
|
|
1749
|
+
const initialCallCount = modelQueryCallCount;
|
|
1750
|
+
// Simulate a real subscription update (not isInit)
|
|
1751
|
+
capturedCallback({ instances: [{ id: "new-item" }], totalCount: 1 });
|
|
1752
|
+
// Wait for async processing
|
|
1753
|
+
await new Promise(r => setTimeout(r, 100));
|
|
1754
|
+
// modelQuery should have been called again for the re-fetch
|
|
1755
|
+
expect(modelQueryCallCount).toBeGreaterThan(initialCallCount);
|
|
1756
|
+
// User callback should have been invoked with paginated results
|
|
1757
|
+
expect(userCallback).toHaveBeenCalled();
|
|
1758
|
+
const callArg = userCallback.mock.calls[0][0];
|
|
1759
|
+
expect(callArg).toHaveProperty("totalCount");
|
|
1760
|
+
expect(callArg).toHaveProperty("pageSize", 10);
|
|
1761
|
+
expect(callArg).toHaveProperty("pageNumber", 1);
|
|
1762
|
+
});
|
|
1763
|
+
});
|
|
1764
|
+
// ============================================================================
|
|
1765
|
+
// Performance Optimisation Tests
|
|
1766
|
+
// ============================================================================
|
|
1767
|
+
import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
|
|
1768
|
+
import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
|
|
1769
|
+
describe("QueryCache", () => {
|
|
1770
|
+
beforeEach(() => clearQueryCache());
|
|
1771
|
+
it("should return undefined for cache miss", () => {
|
|
1772
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
|
|
1773
|
+
});
|
|
1774
|
+
it("should return cached result within TTL", () => {
|
|
1775
|
+
const result = [{ s: "test" }];
|
|
1776
|
+
setCachedResult("uuid1", "SELECT ?s WHERE {}", result);
|
|
1777
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe(result);
|
|
1778
|
+
});
|
|
1779
|
+
it("should expire after TTL", async () => {
|
|
1780
|
+
setCachedResult("uuid1", "SELECT ?s WHERE {}", [{ s: "test" }], 50);
|
|
1781
|
+
await new Promise(r => setTimeout(r, 60));
|
|
1782
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
|
|
1783
|
+
});
|
|
1784
|
+
it("should cache independently per perspective", () => {
|
|
1785
|
+
setCachedResult("uuid1", "SELECT ?s WHERE {}", "result1");
|
|
1786
|
+
setCachedResult("uuid2", "SELECT ?s WHERE {}", "result2");
|
|
1787
|
+
expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe("result1");
|
|
1788
|
+
expect(getCachedResult("uuid2", "SELECT ?s WHERE {}")).toBe("result2");
|
|
1789
|
+
});
|
|
1790
|
+
it("should cache independently per query", () => {
|
|
1791
|
+
setCachedResult("uuid1", "query1", "r1");
|
|
1792
|
+
setCachedResult("uuid1", "query2", "r2");
|
|
1793
|
+
expect(getCachedResult("uuid1", "query1")).toBe("r1");
|
|
1794
|
+
expect(getCachedResult("uuid1", "query2")).toBe("r2");
|
|
1795
|
+
});
|
|
1796
|
+
it("should clear all entries", () => {
|
|
1797
|
+
setCachedResult("uuid1", "q1", "r1");
|
|
1798
|
+
setCachedResult("uuid2", "q2", "r2");
|
|
1799
|
+
expect(queryCacheSize()).toBe(2);
|
|
1800
|
+
clearQueryCache();
|
|
1801
|
+
expect(queryCacheSize()).toBe(0);
|
|
1802
|
+
});
|
|
1803
|
+
});
|
|
1804
|
+
describe("SHACL Memoisation", () => {
|
|
1805
|
+
it("should memoise generateSHACL() per class", () => {
|
|
1806
|
+
let MemoTest1 = class MemoTest1 extends Ad4mModel {
|
|
1807
|
+
constructor() {
|
|
1808
|
+
super(...arguments);
|
|
1809
|
+
this.name = "";
|
|
1810
|
+
}
|
|
1811
|
+
};
|
|
1812
|
+
__decorate([
|
|
1813
|
+
Property({ through: "test://name" }),
|
|
1814
|
+
__metadata("design:type", String)
|
|
1815
|
+
], MemoTest1.prototype, "name", void 0);
|
|
1816
|
+
MemoTest1 = __decorate([
|
|
1817
|
+
Model({ name: "MemoTest1" })
|
|
1818
|
+
], MemoTest1);
|
|
1819
|
+
const result1 = MemoTest1.generateSHACL();
|
|
1820
|
+
const result2 = MemoTest1.generateSHACL();
|
|
1821
|
+
expect(result1).toBe(result2); // Same reference = memoised
|
|
1822
|
+
});
|
|
1823
|
+
it("should memoise getPropertiesMetadata per class", () => {
|
|
1824
|
+
let PropMemoTest = class PropMemoTest extends Ad4mModel {
|
|
1825
|
+
constructor() {
|
|
1826
|
+
super(...arguments);
|
|
1827
|
+
this.x = "";
|
|
1828
|
+
}
|
|
1829
|
+
};
|
|
1830
|
+
__decorate([
|
|
1831
|
+
Property({ through: "test://x" }),
|
|
1832
|
+
__metadata("design:type", String)
|
|
1833
|
+
], PropMemoTest.prototype, "x", void 0);
|
|
1834
|
+
PropMemoTest = __decorate([
|
|
1835
|
+
Model({ name: "PropMemoTest" })
|
|
1836
|
+
], PropMemoTest);
|
|
1837
|
+
const r1 = getPropertiesMetadata(PropMemoTest);
|
|
1838
|
+
const r2 = getPropertiesMetadata(PropMemoTest);
|
|
1839
|
+
expect(r1).toBe(r2); // Same reference
|
|
1840
|
+
});
|
|
1841
|
+
it("should memoise getRelationsMetadata per class", () => {
|
|
1842
|
+
let RelMemoTest = class RelMemoTest extends Ad4mModel {
|
|
1843
|
+
constructor() {
|
|
1844
|
+
super(...arguments);
|
|
1845
|
+
this.items = [];
|
|
1846
|
+
}
|
|
1847
|
+
};
|
|
1848
|
+
__decorate([
|
|
1849
|
+
HasMany({ through: "test://items" }),
|
|
1850
|
+
__metadata("design:type", Array)
|
|
1851
|
+
], RelMemoTest.prototype, "items", void 0);
|
|
1852
|
+
RelMemoTest = __decorate([
|
|
1853
|
+
Model({ name: "RelMemoTest" })
|
|
1854
|
+
], RelMemoTest);
|
|
1855
|
+
const r1 = getRelationsMetadata(RelMemoTest);
|
|
1856
|
+
const r2 = getRelationsMetadata(RelMemoTest);
|
|
1857
|
+
expect(r1).toBe(r2); // Same reference
|
|
1858
|
+
});
|
|
1859
|
+
it("should return different results for different classes", () => {
|
|
1860
|
+
let ClassA = class ClassA extends Ad4mModel {
|
|
1861
|
+
constructor() {
|
|
1862
|
+
super(...arguments);
|
|
1863
|
+
this.a = "";
|
|
1864
|
+
}
|
|
1865
|
+
};
|
|
1866
|
+
__decorate([
|
|
1867
|
+
Property({ through: "test://a" }),
|
|
1868
|
+
__metadata("design:type", String)
|
|
1869
|
+
], ClassA.prototype, "a", void 0);
|
|
1870
|
+
ClassA = __decorate([
|
|
1871
|
+
Model({ name: "ClassA" })
|
|
1872
|
+
], ClassA);
|
|
1873
|
+
let ClassB = class ClassB extends Ad4mModel {
|
|
1874
|
+
constructor() {
|
|
1875
|
+
super(...arguments);
|
|
1876
|
+
this.b = "";
|
|
1877
|
+
}
|
|
1878
|
+
};
|
|
1879
|
+
__decorate([
|
|
1880
|
+
Property({ through: "test://b" }),
|
|
1881
|
+
__metadata("design:type", String)
|
|
1882
|
+
], ClassB.prototype, "b", void 0);
|
|
1883
|
+
ClassB = __decorate([
|
|
1884
|
+
Model({ name: "ClassB" })
|
|
1885
|
+
], ClassB);
|
|
1886
|
+
const propsA = getPropertiesMetadata(ClassA);
|
|
1887
|
+
const propsB = getPropertiesMetadata(ClassB);
|
|
1888
|
+
expect(propsA).not.toBe(propsB);
|
|
1889
|
+
expect(propsA).toHaveProperty("a");
|
|
1890
|
+
expect(propsB).toHaveProperty("b");
|
|
1891
|
+
});
|
|
1892
|
+
});
|
|
1893
|
+
describe("Lazy Conformance Filters", () => {
|
|
1894
|
+
it("should defer conformance filter resolution until property access", () => {
|
|
1895
|
+
let LazyTarget2 = class LazyTarget2 extends Ad4mModel {
|
|
1896
|
+
constructor() {
|
|
1897
|
+
super(...arguments);
|
|
1898
|
+
this.type = "test://lazy";
|
|
1899
|
+
this.name = "";
|
|
1900
|
+
}
|
|
1901
|
+
};
|
|
1902
|
+
__decorate([
|
|
1903
|
+
Flag({ through: "test://type", value: "test://lazy" }),
|
|
1904
|
+
__metadata("design:type", String)
|
|
1905
|
+
], LazyTarget2.prototype, "type", void 0);
|
|
1906
|
+
__decorate([
|
|
1907
|
+
Property({ through: "test://name", required: true }),
|
|
1908
|
+
__metadata("design:type", String)
|
|
1909
|
+
], LazyTarget2.prototype, "name", void 0);
|
|
1910
|
+
LazyTarget2 = __decorate([
|
|
1911
|
+
Model({ name: "LazyTarget2" })
|
|
1912
|
+
], LazyTarget2);
|
|
1913
|
+
let LazyParent2 = class LazyParent2 extends Ad4mModel {
|
|
1914
|
+
constructor() {
|
|
1915
|
+
super(...arguments);
|
|
1916
|
+
this.children = [];
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
__decorate([
|
|
1920
|
+
HasMany(() => LazyTarget2, { through: "test://children" }),
|
|
1921
|
+
__metadata("design:type", Array)
|
|
1922
|
+
], LazyParent2.prototype, "children", void 0);
|
|
1923
|
+
LazyParent2 = __decorate([
|
|
1924
|
+
Model({ name: "LazyParent2" })
|
|
1925
|
+
], LazyParent2);
|
|
1926
|
+
// generateSHACL was called during @Model — the shape exists
|
|
1927
|
+
const shacl = LazyParent2.generateSHACL();
|
|
1928
|
+
expect(shacl).toBeDefined();
|
|
1929
|
+
expect(shacl.shape).toBeDefined();
|
|
1930
|
+
expect(shacl.name).toBe("LazyParent2");
|
|
1931
|
+
});
|
|
1932
|
+
});
|
|
1933
|
+
// ──────────────────────────────────────────────────────────
|
|
1934
|
+
// deepQuery opt-in — getter evaluation on collection queries
|
|
1935
|
+
// ──────────────────────────────────────────────────────────
|
|
1936
|
+
describe("deepQuery opt-in — getter evaluation", () => {
|
|
1937
|
+
let DeepQueryTestMessage = class DeepQueryTestMessage extends Ad4mModel {
|
|
1938
|
+
constructor() {
|
|
1939
|
+
super(...arguments);
|
|
1940
|
+
this.type = "";
|
|
1941
|
+
this.body = "";
|
|
1942
|
+
this.isPopular = false;
|
|
1943
|
+
this.reactions = [];
|
|
1944
|
+
}
|
|
1945
|
+
};
|
|
1946
|
+
__decorate([
|
|
1947
|
+
Flag({ through: "flux://entry_type", value: "flux://message" }),
|
|
1948
|
+
__metadata("design:type", String)
|
|
1949
|
+
], DeepQueryTestMessage.prototype, "type", void 0);
|
|
1950
|
+
__decorate([
|
|
1951
|
+
Property({ through: "flux://body", resolveLanguage: "literal" }),
|
|
1952
|
+
__metadata("design:type", String)
|
|
1953
|
+
], DeepQueryTestMessage.prototype, "body", void 0);
|
|
1954
|
+
__decorate([
|
|
1955
|
+
Property({
|
|
1956
|
+
through: "flux://has_reply",
|
|
1957
|
+
getter: `SELECT ?target WHERE { ?source <flux://has_reply> ?target . } LIMIT 1`,
|
|
1958
|
+
}),
|
|
1959
|
+
__metadata("design:type", String)
|
|
1960
|
+
], DeepQueryTestMessage.prototype, "replyingTo", void 0);
|
|
1961
|
+
__decorate([
|
|
1962
|
+
ReadOnly({
|
|
1963
|
+
through: "flux://is_popular",
|
|
1964
|
+
getter: `ASK WHERE { ?source <flux://is_popular> "true" . }`,
|
|
1965
|
+
}),
|
|
1966
|
+
__metadata("design:type", Boolean)
|
|
1967
|
+
], DeepQueryTestMessage.prototype, "isPopular", void 0);
|
|
1968
|
+
__decorate([
|
|
1969
|
+
HasMany({ through: "flux://reaction" }),
|
|
1970
|
+
__metadata("design:type", Array)
|
|
1971
|
+
], DeepQueryTestMessage.prototype, "reactions", void 0);
|
|
1972
|
+
DeepQueryTestMessage = __decorate([
|
|
1973
|
+
Model({ name: "DeepQueryTestMessage" })
|
|
1974
|
+
], DeepQueryTestMessage);
|
|
1975
|
+
let sparqlCalls;
|
|
1976
|
+
const mockPerspective = {
|
|
1977
|
+
uuid: "test-uuid",
|
|
1978
|
+
modelQuery: jest.fn(async (className, queryJson, shapeJson) => {
|
|
1979
|
+
// Return a basic result for the single-instance getData() path
|
|
1980
|
+
const query = JSON.parse(queryJson);
|
|
1981
|
+
const id = query?.where?.id;
|
|
1982
|
+
if (id) {
|
|
1983
|
+
return {
|
|
1984
|
+
instances: [{ id, body: "Hello" }],
|
|
1985
|
+
totalCount: 1,
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
return { instances: [], totalCount: 0 };
|
|
1989
|
+
}),
|
|
1990
|
+
querySparql: jest.fn(async (q) => {
|
|
1991
|
+
sparqlCalls.push(q);
|
|
1992
|
+
return [];
|
|
1993
|
+
}),
|
|
1994
|
+
get: jest.fn().mockResolvedValue([]),
|
|
1995
|
+
getExpression: jest.fn().mockResolvedValue(null),
|
|
1996
|
+
stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("DeepQueryTestMessage"),
|
|
1997
|
+
};
|
|
1998
|
+
beforeEach(() => {
|
|
1999
|
+
sparqlCalls = [];
|
|
2000
|
+
mockPerspective.querySparql.mockClear();
|
|
2001
|
+
mockPerspective.get.mockClear();
|
|
2002
|
+
});
|
|
2003
|
+
function makeInstances(count) {
|
|
2004
|
+
return Array.from({ length: count }, (_, i) => new DeepQueryTestMessage(mockPerspective, `flux://msg-${i}`));
|
|
2005
|
+
}
|
|
2006
|
+
it("single-instance get() delegates getter evaluation to Rust (no JS-side SPARQL)", async () => {
|
|
2007
|
+
const instance = new DeepQueryTestMessage(mockPerspective, "flux://msg-single");
|
|
2008
|
+
mockPerspective.querySparql.mockImplementation(async (q) => {
|
|
2009
|
+
sparqlCalls.push(q);
|
|
2010
|
+
if (q.includes("flux://msg-single") && !q.includes("flux://has_reply") && !q.includes("flux://is_popular")) {
|
|
2011
|
+
return [
|
|
2012
|
+
{ source: "flux://msg-single", predicate: "flux://entry_type", target: "flux://message", author: "did:key:a", timestamp: "3000" },
|
|
2013
|
+
{ source: "flux://msg-single", predicate: "flux://body", target: "literal:string:Hello", author: "did:key:a", timestamp: "3000" },
|
|
2014
|
+
];
|
|
2015
|
+
}
|
|
2016
|
+
return [];
|
|
2017
|
+
});
|
|
2018
|
+
await instance.get();
|
|
2019
|
+
// Getter evaluation now happens Rust-side via evaluate_getters() — no JS SPARQL calls
|
|
2020
|
+
const getterCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply") || q.includes("flux://is_popular"));
|
|
2021
|
+
expect(getterCalls.length).toBe(0);
|
|
2022
|
+
});
|
|
2023
|
+
describe("Ad4mModel.evaluateGetters()", () => {
|
|
2024
|
+
it("resolves getters for a batch of instances", async () => {
|
|
2025
|
+
const instances = makeInstances(4);
|
|
2026
|
+
sparqlCalls = [];
|
|
2027
|
+
await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
|
|
2028
|
+
const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
|
|
2029
|
+
expect(replyCalls.length).toBe(2);
|
|
2030
|
+
const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
|
|
2031
|
+
expect(popularCalls.length).toBe(0);
|
|
2032
|
+
});
|
|
2033
|
+
it("evaluates all getters when propertyNames is omitted", async () => {
|
|
2034
|
+
const instances = makeInstances(2);
|
|
2035
|
+
sparqlCalls = [];
|
|
2036
|
+
await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
|
|
2037
|
+
const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
|
|
2038
|
+
const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
|
|
2039
|
+
expect(replyCalls.length).toBe(2);
|
|
2040
|
+
expect(popularCalls.length).toBe(2);
|
|
2041
|
+
});
|
|
2042
|
+
it("handles empty array gracefully", async () => {
|
|
2043
|
+
sparqlCalls = [];
|
|
2044
|
+
await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
|
|
2045
|
+
expect(sparqlCalls.length).toBe(0);
|
|
2046
|
+
});
|
|
2047
|
+
});
|
|
2048
|
+
describe("deepQuery via ModelQueryBuilder", () => {
|
|
2049
|
+
it("deepQuery() method sets deepQuery flag on queryParams", () => {
|
|
2050
|
+
const builder = DeepQueryTestMessage.query(mockPerspective);
|
|
2051
|
+
builder.deepQuery();
|
|
2052
|
+
expect(builder.queryParams.deepQuery).toBe(true);
|
|
2053
|
+
});
|
|
1308
2054
|
});
|
|
1309
2055
|
});
|