@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
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -3,27 +3,172 @@ import { Link } from "../links/Links";
|
|
|
3
3
|
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
4
4
|
import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
5
5
|
import { makeRandomId } from "./util";
|
|
6
|
-
import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
|
|
6
|
+
import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
|
|
7
7
|
import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
|
|
8
|
-
import {
|
|
8
|
+
import { formatQueryValue, compileWhereClause } from "./query-utils";
|
|
9
9
|
import { resolveParentPredicate } from "./query-common";
|
|
10
|
-
import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
|
|
11
10
|
import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
|
|
11
|
+
import type { SHACLShape } from "../shacl/SHACLShape";
|
|
12
12
|
import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
|
|
13
|
-
|
|
13
|
+
|
|
14
|
+
import { buildSPARQLQuery } from "./query-sparql";
|
|
14
15
|
import { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
15
16
|
import {
|
|
16
|
-
normalizeValue,
|
|
17
|
-
assignValuesToInstance as _assignValuesToInstance,
|
|
18
|
-
evaluateCustomGettersForInstance,
|
|
19
|
-
hydrateRelations,
|
|
17
|
+
normalizeValue,
|
|
20
18
|
} from "./hydration";
|
|
21
19
|
import type {
|
|
22
20
|
ParentScope, IncludeMap, Query,
|
|
23
21
|
GetOptions, AllInstancesResult, ResultsWithTotalCount,
|
|
24
|
-
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
22
|
+
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
23
|
+
IncludeProjection,
|
|
24
|
+
TypedQuery, IncludeExtras, IncludeOf,
|
|
25
25
|
} from "./types";
|
|
26
26
|
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Default decoder for file-storage (non-literal resolveLanguage) properties
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* When the Rust executor resolves a non-literal expression it may return a
|
|
34
|
+
* `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
|
|
35
|
+
* raw URI string. If the model class has no custom `transform` registered
|
|
36
|
+
* (e.g. it was synthesised from a SHACL shape at runtime) we still want to
|
|
37
|
+
* decode the content rather than passing raw `FileData` to callers.
|
|
38
|
+
*
|
|
39
|
+
* Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
|
|
40
|
+
* - `application/json` (default when `file_type` is absent) → JSON.parse
|
|
41
|
+
* - anything else → raw decoded string
|
|
42
|
+
*
|
|
43
|
+
* If `resolved` is not a `FileData` object the value is returned unchanged so
|
|
44
|
+
* that callers can use this as a safe unconditional fallback.
|
|
45
|
+
*/
|
|
46
|
+
function defaultFileDecode(resolved: unknown): unknown {
|
|
47
|
+
if (
|
|
48
|
+
resolved !== null &&
|
|
49
|
+
typeof resolved === 'object' &&
|
|
50
|
+
'data_base64' in (resolved as object)
|
|
51
|
+
) {
|
|
52
|
+
const fd = resolved as { data_base64: string; file_type?: string };
|
|
53
|
+
let raw: string;
|
|
54
|
+
try {
|
|
55
|
+
raw = atob(fd.data_base64);
|
|
56
|
+
} catch {
|
|
57
|
+
return resolved; // malformed base64 — keep as-is
|
|
58
|
+
}
|
|
59
|
+
const isJson = !fd.file_type || fd.file_type === 'application/json';
|
|
60
|
+
if (isJson) {
|
|
61
|
+
try { return JSON.parse(raw); } catch { return raw; }
|
|
62
|
+
}
|
|
63
|
+
return raw;
|
|
64
|
+
}
|
|
65
|
+
return resolved;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
// Helpers for Rust-side include resolution
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
74
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
75
|
+
* back as plain JSON objects) into proper model class instances.
|
|
76
|
+
*/
|
|
77
|
+
function jsonToModelInstance<T extends Ad4mModel>(
|
|
78
|
+
ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
79
|
+
perspective: PerspectiveProxy,
|
|
80
|
+
json: any,
|
|
81
|
+
include?: IncludeMap,
|
|
82
|
+
properties?: string[],
|
|
83
|
+
): T {
|
|
84
|
+
const instance = new ModelClass(perspective, json.id || json.baseExpression) as any;
|
|
85
|
+
|
|
86
|
+
// When a properties projection is active, remove own properties set by the
|
|
87
|
+
// constructor that are not in the projected JSON. This ensures assertions
|
|
88
|
+
// like `expect(r).to.not.have.own.property("body")` pass.
|
|
89
|
+
if (properties) {
|
|
90
|
+
const jsonKeys = new Set(Object.keys(json));
|
|
91
|
+
for (const key of Object.getOwnPropertyNames(instance)) {
|
|
92
|
+
// Keep internal fields (backing store for getters), id, baseExpression, perspective
|
|
93
|
+
if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_')) continue;
|
|
94
|
+
if (!jsonKeys.has(key)) {
|
|
95
|
+
delete instance[key];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
for (const [key, value] of Object.entries(json)) {
|
|
101
|
+
if (key === 'baseExpression' || key === 'id') continue;
|
|
102
|
+
|
|
103
|
+
// Skip getter-only properties anywhere in the prototype chain
|
|
104
|
+
let isReadonly = false;
|
|
105
|
+
let proto = Object.getPrototypeOf(instance);
|
|
106
|
+
while (proto) {
|
|
107
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
108
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
109
|
+
proto = Object.getPrototypeOf(proto);
|
|
110
|
+
}
|
|
111
|
+
if (isReadonly) continue;
|
|
112
|
+
|
|
113
|
+
// Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
|
|
114
|
+
if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
|
|
115
|
+
instance[key] = new Date(value).getTime();
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
instance[key] = value;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Apply property transform functions from decorators (only for literal-resolved
|
|
123
|
+
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
124
|
+
// asynchronously in executeModelQuery).
|
|
125
|
+
try {
|
|
126
|
+
const propsMeta = getPropertiesMetadata(ModelClass as any);
|
|
127
|
+
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
128
|
+
const o = opts as any;
|
|
129
|
+
if (typeof o.transform !== 'function' || !(propName in json)) continue;
|
|
130
|
+
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
131
|
+
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
|
|
132
|
+
instance[propName] = o.transform(instance[propName]);
|
|
133
|
+
}
|
|
134
|
+
} catch (e) { console.debug('jsonToModelInstance: transform metadata unavailable:', e); }
|
|
135
|
+
|
|
136
|
+
// Recursively convert included relation values to class instances
|
|
137
|
+
if (include) {
|
|
138
|
+
const relMeta = getRelationsMetadata(ModelClass as any);
|
|
139
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
140
|
+
if (!includeVal) continue;
|
|
141
|
+
const meta = relMeta[relName];
|
|
142
|
+
if (!meta?.target) continue;
|
|
143
|
+
const TargetClass = meta.target() as any;
|
|
144
|
+
const nestedInclude =
|
|
145
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
146
|
+
? (includeVal as any).include
|
|
147
|
+
: undefined;
|
|
148
|
+
const nestedProperties =
|
|
149
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
150
|
+
? (includeVal as any).properties
|
|
151
|
+
: undefined;
|
|
152
|
+
|
|
153
|
+
const raw = instance[relName];
|
|
154
|
+
if (Array.isArray(raw)) {
|
|
155
|
+
instance[relName] = raw.map((item: any) => {
|
|
156
|
+
if (typeof item === 'object' && item !== null && item.id) {
|
|
157
|
+
return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
|
|
158
|
+
}
|
|
159
|
+
return item;
|
|
160
|
+
});
|
|
161
|
+
} else if (typeof raw === 'object' && raw !== null && raw.id) {
|
|
162
|
+
instance[relName] = jsonToModelInstance(
|
|
163
|
+
TargetClass, perspective, raw, nestedInclude, nestedProperties,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return instance;
|
|
170
|
+
}
|
|
171
|
+
|
|
27
172
|
/**
|
|
28
173
|
* Base class for defining data models in AD4M.
|
|
29
174
|
*
|
|
@@ -128,6 +273,14 @@ export class Ad4mModel {
|
|
|
128
273
|
createdAt: any;
|
|
129
274
|
updatedAt: any;
|
|
130
275
|
|
|
276
|
+
/**
|
|
277
|
+
* Backwards compatibility alias for createdAt.
|
|
278
|
+
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
279
|
+
*/
|
|
280
|
+
get timestamp(): any {
|
|
281
|
+
return (this as any).createdAt;
|
|
282
|
+
}
|
|
283
|
+
|
|
131
284
|
private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
|
|
132
285
|
|
|
133
286
|
/**
|
|
@@ -174,14 +327,6 @@ export class Ad4mModel {
|
|
|
174
327
|
return classCache[perspectiveID];
|
|
175
328
|
}
|
|
176
329
|
|
|
177
|
-
/**
|
|
178
|
-
* Backwards compatibility alias for createdAt.
|
|
179
|
-
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
180
|
-
*/
|
|
181
|
-
get timestamp(): any {
|
|
182
|
-
return (this as any).createdAt;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
330
|
/**
|
|
186
331
|
* Extracts metadata from decorators for query building.
|
|
187
332
|
*
|
|
@@ -258,9 +403,7 @@ export class Ad4mModel {
|
|
|
258
403
|
// Extract relations (relations) from WeakMap registry
|
|
259
404
|
const relationsMetadata: Record<string, RelationMetadata> = {};
|
|
260
405
|
const allRelationsMeta = getRelationsMetadata(this as any);
|
|
261
|
-
const prototypeRelations =
|
|
262
|
-
Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
|
|
263
|
-
);
|
|
406
|
+
const prototypeRelations = allRelationsMeta;
|
|
264
407
|
|
|
265
408
|
for (const [relationName, opts] of Object.entries(prototypeRelations)) {
|
|
266
409
|
const options = opts as RelationMetadataEntry;
|
|
@@ -270,6 +413,8 @@ export class Ad4mModel {
|
|
|
270
413
|
...(options.local !== undefined && { local: options.local }),
|
|
271
414
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
272
415
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
416
|
+
...(options.kind !== undefined && { kind: options.kind }),
|
|
417
|
+
...(options.maxCount !== undefined && { maxCount: options.maxCount }),
|
|
273
418
|
...(options.target !== undefined && { target: options.target }),
|
|
274
419
|
...(options.filter !== undefined && { filter: options.filter }),
|
|
275
420
|
...(options.where !== undefined && { where: options.where }),
|
|
@@ -341,7 +486,7 @@ export class Ad4mModel {
|
|
|
341
486
|
* const recipe = new Recipe(perspective);
|
|
342
487
|
*
|
|
343
488
|
* // Create with specific base expression
|
|
344
|
-
* const recipe = new Recipe(perspective, "literal
|
|
489
|
+
* const recipe = new Recipe(perspective, "literal:...");
|
|
345
490
|
* ```
|
|
346
491
|
*/
|
|
347
492
|
constructor(perspective: PerspectiveProxy, baseExpression?: string) {
|
|
@@ -356,13 +501,6 @@ export class Ad4mModel {
|
|
|
356
501
|
return this._baseExpression;
|
|
357
502
|
}
|
|
358
503
|
|
|
359
|
-
/**
|
|
360
|
-
* @deprecated Use `.id` instead. Will be removed in a future version.
|
|
361
|
-
*/
|
|
362
|
-
get baseExpression(): string {
|
|
363
|
-
return this._baseExpression;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
504
|
/**
|
|
367
505
|
* Protected getter for the perspective.
|
|
368
506
|
* Allows subclasses to access the perspective while keeping it private from external code.
|
|
@@ -459,14 +597,6 @@ export class Ad4mModel {
|
|
|
459
597
|
}];
|
|
460
598
|
}
|
|
461
599
|
|
|
462
|
-
/**
|
|
463
|
-
* Assigns decoded Prolog property values to an instance.
|
|
464
|
-
* Delegates to the standalone function in hydration.ts.
|
|
465
|
-
*/
|
|
466
|
-
public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
|
|
467
|
-
return _assignValuesToInstance(perspective, instance, values);
|
|
468
|
-
}
|
|
469
|
-
|
|
470
600
|
// ──────────────────────────────────────────────────────────
|
|
471
601
|
// Snapshot / dirty tracking
|
|
472
602
|
// ──────────────────────────────────────────────────────────
|
|
@@ -482,7 +612,8 @@ export class Ad4mModel {
|
|
|
482
612
|
* • `null` / empty object — skip ALL relations (used by bare
|
|
483
613
|
* subscriptions that don't eagerly load relations).
|
|
484
614
|
*/
|
|
485
|
-
|
|
615
|
+
/** @internal */
|
|
616
|
+
protected takeSnapshot(includedRelations?: Record<string, any> | null): void {
|
|
486
617
|
const ctor = this.constructor as typeof Ad4mModel;
|
|
487
618
|
const metadata = ctor.getModelMetadata();
|
|
488
619
|
const snap: Record<string, any> = {};
|
|
@@ -600,103 +731,59 @@ export class Ad4mModel {
|
|
|
600
731
|
}
|
|
601
732
|
|
|
602
733
|
private async getData(opts?: GetOptions) {
|
|
603
|
-
//
|
|
604
|
-
//
|
|
734
|
+
// Route through the Rust model query endpoint — same pipeline as executeModelQuery
|
|
735
|
+
// but for a single instance by ID.
|
|
605
736
|
try {
|
|
606
737
|
const ctor = this.constructor as typeof Ad4mModel;
|
|
607
|
-
const
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
WHERE in.uri = ${safeBaseExpression}
|
|
615
|
-
ORDER BY timestamp ASC
|
|
616
|
-
`;
|
|
617
|
-
const links = await this._perspective.querySurrealDB(linksQuery);
|
|
618
|
-
|
|
619
|
-
if (links && links.length > 0) {
|
|
620
|
-
// Core hydration: properties (latest-wins), relations, timestamps/author
|
|
621
|
-
const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
|
|
622
|
-
await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
|
|
623
|
-
}
|
|
738
|
+
const query: Query = {
|
|
739
|
+
where: { id: this._baseExpression },
|
|
740
|
+
limit: 1,
|
|
741
|
+
deepQuery: true, // Single-instance get() always evaluates property getters
|
|
742
|
+
};
|
|
743
|
+
if (opts?.properties) query.properties = opts.properties;
|
|
744
|
+
if (opts?.include) query.include = opts.include;
|
|
624
745
|
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
(
|
|
639
|
-
|
|
640
|
-
|
|
746
|
+
const { results } = await (ctor as any).executeModelQuery(
|
|
747
|
+
this._perspective, query, null
|
|
748
|
+
);
|
|
749
|
+
|
|
750
|
+
if (results.length > 0) {
|
|
751
|
+
const hydrated = results[0];
|
|
752
|
+
// Copy all hydrated values from the Rust-side result onto this instance
|
|
753
|
+
for (const [key, value] of Object.entries(hydrated as any)) {
|
|
754
|
+
if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot') continue;
|
|
755
|
+
if (key.startsWith('_')) continue;
|
|
756
|
+
// Check for readonly getters
|
|
757
|
+
let isReadonly = false;
|
|
758
|
+
let proto = Object.getPrototypeOf(this);
|
|
759
|
+
while (proto) {
|
|
760
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
761
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
762
|
+
proto = Object.getPrototypeOf(proto);
|
|
763
|
+
}
|
|
764
|
+
if (isReadonly) continue;
|
|
765
|
+
(this as any)[key] = value;
|
|
641
766
|
}
|
|
642
767
|
}
|
|
643
768
|
|
|
644
|
-
//
|
|
645
|
-
|
|
646
|
-
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
647
|
-
: undefined;
|
|
648
|
-
await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
|
|
649
|
-
|
|
650
|
-
// Eager-load relations if requested
|
|
651
|
-
if (opts?.include) {
|
|
652
|
-
await hydrateRelations(ctor, [this], this._perspective, opts.include);
|
|
653
|
-
}
|
|
769
|
+
// Property getters and relation conformance getters are now evaluated
|
|
770
|
+
// Rust-side via evaluate_getters() in model_query.rs.
|
|
654
771
|
} catch (e) {
|
|
655
|
-
console.error(`
|
|
772
|
+
console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
|
|
656
773
|
}
|
|
657
774
|
|
|
658
|
-
this.takeSnapshot();
|
|
775
|
+
this.takeSnapshot(opts?.include);
|
|
659
776
|
return this;
|
|
660
777
|
}
|
|
661
778
|
|
|
662
|
-
public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
|
|
663
|
-
const { properties, where, order, offset, limit, count } = query;
|
|
664
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
665
|
-
|
|
666
|
-
// Resolve parent predicate from model metadata if needed
|
|
667
|
-
const resolvedParentPredicate = query.parent
|
|
668
|
-
? resolveParentPredicate(query.parent, this)
|
|
669
|
-
: undefined;
|
|
670
|
-
|
|
671
|
-
const instanceQueries = [
|
|
672
|
-
buildAuthorAndTimestampQuery(),
|
|
673
|
-
buildParentQuery(query.parent, resolvedParentPredicate),
|
|
674
|
-
buildPropertiesQuery(properties),
|
|
675
|
-
buildWhereQuery(where),
|
|
676
|
-
];
|
|
677
|
-
|
|
678
|
-
const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
|
|
679
|
-
|
|
680
|
-
const fullQuery = `
|
|
681
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
682
|
-
subject_class("${className}", SubjectClass),
|
|
683
|
-
instance(SubjectClass, Base),
|
|
684
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
685
|
-
), UnsortedInstances),
|
|
686
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
687
|
-
`;
|
|
688
|
-
|
|
689
|
-
return fullQuery;
|
|
690
|
-
}
|
|
691
|
-
|
|
692
779
|
/**
|
|
693
|
-
* Generates a
|
|
780
|
+
* Generates a SPARQL query from a Query object.
|
|
694
781
|
*
|
|
695
782
|
* @description
|
|
696
|
-
* This method translates high-level query parameters into a
|
|
697
|
-
* that can be executed against the
|
|
698
|
-
* operate on SDNA-aware predicates,
|
|
699
|
-
* stored in
|
|
783
|
+
* This method translates high-level query parameters into a SPARQL query string
|
|
784
|
+
* that can be executed against the SPARQL backend. Unlike Prolog queries which
|
|
785
|
+
* operate on SDNA-aware predicates, SPARQL queries operate directly on raw links
|
|
786
|
+
* stored in SPARQL.
|
|
700
787
|
*
|
|
701
788
|
* The generated query uses a CTE (Common Table Expression) pattern:
|
|
702
789
|
* 1. First, identify candidate base expressions by filtering links based on where conditions
|
|
@@ -704,7 +791,7 @@ export class Ad4mModel {
|
|
|
704
791
|
* 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
|
|
705
792
|
*
|
|
706
793
|
* Key architectural notes:
|
|
707
|
-
* -
|
|
794
|
+
* - SPARQL stores only raw links (source, predicate, target, author, timestamp)
|
|
708
795
|
* - No SDNA knowledge at the database level
|
|
709
796
|
* - Properties are resolved via subqueries that look for links with specific predicates
|
|
710
797
|
* - Relations are similar but return multiple values instead of one
|
|
@@ -712,11 +799,11 @@ export class Ad4mModel {
|
|
|
712
799
|
*
|
|
713
800
|
* @param perspective - The perspective to query (used for metadata extraction)
|
|
714
801
|
* @param query - Query parameters (where, order, limit, offset, properties, relations)
|
|
715
|
-
* @returns Complete
|
|
802
|
+
* @returns Complete SPARQL query string ready for execution
|
|
716
803
|
*
|
|
717
804
|
* @example
|
|
718
805
|
* ```typescript
|
|
719
|
-
* const query = Recipe.
|
|
806
|
+
* const query = Recipe.queryToSPARQL(perspective, {
|
|
720
807
|
* where: { name: "Pasta", rating: { gt: 4 } },
|
|
721
808
|
* order: { timestamp: "DESC" },
|
|
722
809
|
* limit: 10
|
|
@@ -725,281 +812,217 @@ export class Ad4mModel {
|
|
|
725
812
|
* // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
|
|
726
813
|
* ```
|
|
727
814
|
*/
|
|
728
|
-
public static async
|
|
815
|
+
public static async queryToSPARQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
|
|
729
816
|
const metadata = this.getModelMetadata();
|
|
730
817
|
const allRelMeta = getRelationsMetadata(this as any);
|
|
731
|
-
return
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
public static async instancesFromPrologResult<T extends Ad4mModel>(
|
|
735
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
736
|
-
perspective: PerspectiveProxy,
|
|
737
|
-
query: Query,
|
|
738
|
-
result: AllInstancesResult
|
|
739
|
-
): Promise<ResultsWithTotalCount<T>> {
|
|
740
|
-
if (!result?.[0]?.AllInstances) return { results: [], totalCount: 0 };
|
|
741
|
-
// Map results to instances
|
|
742
|
-
const requestedProperties = query?.properties || [];
|
|
743
|
-
const allInstances = await Promise.all(
|
|
744
|
-
result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
|
|
745
|
-
try {
|
|
746
|
-
const instance = new this(perspective, Base) as any;
|
|
747
|
-
// Remove unrequested attributes from instance
|
|
748
|
-
if (requestedProperties.length) {
|
|
749
|
-
Object.keys(instance).forEach((key) => {
|
|
750
|
-
if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression') delete instance[key];
|
|
751
|
-
});
|
|
752
|
-
}
|
|
753
|
-
// Collect values to assign to instance
|
|
754
|
-
const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
|
|
755
|
-
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
756
|
-
|
|
757
|
-
return instance;
|
|
758
|
-
} catch (error) {
|
|
759
|
-
console.error(`Failed to process instance ${Base}:`, error);
|
|
760
|
-
// Return null for failed instances - we'll filter these out below
|
|
761
|
-
return null;
|
|
762
|
-
}
|
|
763
|
-
})
|
|
764
|
-
);
|
|
765
|
-
const instances = allInstances.filter((instance) => instance !== null) as T[];
|
|
766
|
-
|
|
767
|
-
// Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
|
|
768
|
-
if (query.include && instances.length > 0) {
|
|
769
|
-
await hydrateRelations(this, instances, perspective, query.include);
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
// Take snapshots for dirty tracking after ALL hydration is complete
|
|
773
|
-
// (including eager-loaded relations).
|
|
774
|
-
// When `include` is specified, only snapshot those relations.
|
|
775
|
-
// Otherwise snapshot ALL fields (properties + relations) since
|
|
776
|
-
// hydrateFromLinks populates relations with stable raw IDs.
|
|
777
|
-
const snapshotRelations = query.include;
|
|
778
|
-
for (const inst of instances) {
|
|
779
|
-
(inst as Ad4mModel).takeSnapshot(snapshotRelations);
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
return { results: instances, totalCount: result[0].TotalCount };
|
|
818
|
+
return buildSPARQLQuery(metadata, allRelMeta, query, this);
|
|
783
819
|
}
|
|
784
820
|
|
|
785
821
|
/**
|
|
786
|
-
*
|
|
787
|
-
*
|
|
788
|
-
*
|
|
789
|
-
* @param query - The query parameters used
|
|
790
|
-
* @param result - Array of result objects from SurrealDB
|
|
791
|
-
* @returns Promise resolving to results with total count
|
|
792
|
-
*
|
|
822
|
+
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
823
|
+
* Returns the className and queryJson that the Rust executor expects.
|
|
824
|
+
* Shape resolution happens server-side from the perspective's SHACL triples.
|
|
793
825
|
* @internal
|
|
794
826
|
*/
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
result: any[]
|
|
800
|
-
): Promise<ResultsWithTotalCount<T>> {
|
|
801
|
-
if (!result || result.length === 0) return { results: [], totalCount: 0 };
|
|
802
|
-
|
|
827
|
+
static prepareModelQueryParams(
|
|
828
|
+
query: Query = {},
|
|
829
|
+
classNameOverride?: string | null,
|
|
830
|
+
): { className: string; queryJson: string; metadata: ModelMetadata } {
|
|
803
831
|
const metadata = this.getModelMetadata();
|
|
804
|
-
const
|
|
805
|
-
|
|
806
|
-
//
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
832
|
+
const className = classNameOverride || metadata.className;
|
|
833
|
+
|
|
834
|
+
// Expand includeAll: true to a full IncludeMap covering every forward relation.
|
|
835
|
+
if (query.includeAll) {
|
|
836
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
837
|
+
const expanded: IncludeMap = {};
|
|
838
|
+
for (const [relName, relMeta] of Object.entries(allRelMeta)) {
|
|
839
|
+
if ((relMeta as any).direction !== 'reverse') {
|
|
840
|
+
expanded[relName] = true;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
query = { ...query, include: { ...expanded, ...query.include } };
|
|
844
|
+
}
|
|
817
845
|
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
846
|
+
const queryInput: any = {};
|
|
847
|
+
if (query.parent) {
|
|
848
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
849
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
850
|
+
}
|
|
851
|
+
if (query.properties) queryInput.properties = query.properties;
|
|
852
|
+
if (query.include) {
|
|
853
|
+
// Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
|
|
854
|
+
// All other keys (boolean | RelationSubQuery) → queryInput.include
|
|
855
|
+
const normalIncludes: IncludeMap = {};
|
|
856
|
+
const projections: Record<string, IncludeProjection> = {};
|
|
857
|
+
for (const [key, val] of Object.entries(query.include)) {
|
|
858
|
+
if (key.startsWith('$')) {
|
|
859
|
+
projections[key] = val as IncludeProjection;
|
|
860
|
+
} else {
|
|
861
|
+
normalIncludes[key] = val;
|
|
821
862
|
}
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
//
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
for (const relName of Object.keys(metadata.relations)) {
|
|
840
|
-
if (!requested.has(relName) && !(query.include && relName in query.include)) {
|
|
841
|
-
delete instance[relName];
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
// Also strip metadata fields unless explicitly requested
|
|
845
|
-
for (const metaField of ['author', 'createdAt', 'updatedAt'] as const) {
|
|
846
|
-
if (!requested.has(metaField)) {
|
|
847
|
-
delete instance[metaField];
|
|
848
|
-
}
|
|
863
|
+
}
|
|
864
|
+
if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
|
|
865
|
+
if (Object.keys(projections).length > 0) {
|
|
866
|
+
// Tag each projection with its target class name so the executor can
|
|
867
|
+
// resolve the target shape through its in-memory cache when applying
|
|
868
|
+
// projection where-clause filters.
|
|
869
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
870
|
+
for (const [, proj] of Object.entries(projections)) {
|
|
871
|
+
const relMeta = allRelMeta[proj.from];
|
|
872
|
+
if (!proj.targetClassName && relMeta?.target) {
|
|
873
|
+
try {
|
|
874
|
+
const TargetClass = relMeta.target();
|
|
875
|
+
const targetMeta = (TargetClass as any).getModelMetadata?.();
|
|
876
|
+
if (targetMeta?.className) {
|
|
877
|
+
proj.targetClassName = targetMeta.className;
|
|
878
|
+
}
|
|
879
|
+
} catch (e) { console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e); }
|
|
849
880
|
}
|
|
850
881
|
}
|
|
851
|
-
|
|
852
|
-
instances.push(instance);
|
|
853
|
-
} catch (error) {
|
|
854
|
-
console.error(`Failed to process SurrealDB instance ${base}:`, error);
|
|
882
|
+
queryInput.projections = projections;
|
|
855
883
|
}
|
|
856
884
|
}
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
// from the node's own outgoing links fetched above. We do a reverse-link lookup here
|
|
861
|
-
// so that these fields are populated as IDs even without an explicit include.
|
|
862
|
-
const allRelsMeta = getRelationsMetadata(this as any);
|
|
863
|
-
const reverseRelEntries = Object.entries(allRelsMeta).filter(
|
|
864
|
-
([relName, meta]) =>
|
|
865
|
-
(meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
|
|
866
|
-
(requestedProperties.length === 0 || requestedProperties.includes(relName))
|
|
867
|
-
);
|
|
868
|
-
if (reverseRelEntries.length > 0 && instances.length > 0) {
|
|
869
|
-
await Promise.all(
|
|
870
|
-
instances.map(async (inst) => {
|
|
871
|
-
for (const [relName, relMeta] of reverseRelEntries) {
|
|
872
|
-
const reverseLinks = await perspective.get(
|
|
873
|
-
new LinkQuery({ predicate: relMeta.predicate, target: inst.id })
|
|
874
|
-
);
|
|
875
|
-
const sourceIds = reverseLinks
|
|
876
|
-
.filter((l) => l.data.target === inst.id)
|
|
877
|
-
.map((l) => l.data.source);
|
|
878
|
-
if (relMeta.kind === 'belongsToOne') {
|
|
879
|
-
(inst as any)[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
|
|
880
|
-
} else {
|
|
881
|
-
(inst as any)[relName] = sourceIds;
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
})
|
|
885
|
-
);
|
|
885
|
+
if (query.where) queryInput.where = query.where;
|
|
886
|
+
if (query.order) {
|
|
887
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
886
888
|
}
|
|
889
|
+
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
890
|
+
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
891
|
+
if (query.count !== undefined) queryInput.count = query.count;
|
|
892
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
887
893
|
|
|
888
|
-
//
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
: undefined;
|
|
892
|
-
for (const instance of instances) {
|
|
893
|
-
await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
// Filter by where conditions that couldn't be filtered in SQL
|
|
897
|
-
// This includes:
|
|
898
|
-
// - author/timestamp (computed from grouped links)
|
|
899
|
-
// - Properties with comparison operators (gt, gte, lt, lte, between, contains)
|
|
900
|
-
// because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
|
|
901
|
-
let filteredInstances = instances;
|
|
902
|
-
if (query.where) {
|
|
903
|
-
filteredInstances = instances.filter(instance => {
|
|
904
|
-
for (const [propertyName, condition] of Object.entries(query.where!)) {
|
|
905
|
-
// Skip 'base' as it's filtered in SQL
|
|
906
|
-
if (propertyName === 'base') continue;
|
|
907
|
-
|
|
908
|
-
// For author and timestamp, always filter in JS
|
|
909
|
-
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
910
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
911
|
-
return false;
|
|
912
|
-
}
|
|
913
|
-
continue;
|
|
914
|
-
}
|
|
894
|
+
// Conformance getters, where filters, and target shapes for includes
|
|
895
|
+
// are all resolved by the executor from the perspective's SHACL triples
|
|
896
|
+
// — no client-side pre-computation is needed any more.
|
|
915
897
|
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
898
|
+
return {
|
|
899
|
+
className,
|
|
900
|
+
queryJson: JSON.stringify(queryInput),
|
|
901
|
+
metadata,
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* Parse raw model query/subscription result JSON into typed model instances.
|
|
907
|
+
* Used by ModelQueryBuilder to convert subscription updates without circular imports.
|
|
908
|
+
* @internal
|
|
909
|
+
*/
|
|
910
|
+
static parseModelResult<T extends Ad4mModel>(
|
|
911
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
912
|
+
perspective: PerspectiveProxy,
|
|
913
|
+
raw: any,
|
|
914
|
+
include?: IncludeMap,
|
|
915
|
+
properties?: string[],
|
|
916
|
+
): T[] {
|
|
917
|
+
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
918
|
+
const arr = data.instances || data;
|
|
919
|
+
if (!Array.isArray(arr)) return [];
|
|
920
|
+
return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* Resolve non-literal (file-language) properties on an array of already-constructed
|
|
925
|
+
* model instances. Handles two cases:
|
|
926
|
+
*
|
|
927
|
+
* 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
|
|
928
|
+
* 2. The Rust executor already resolved the expression and returned a `FileData` object
|
|
929
|
+
* (happens when the perspective backend eagerly fetches file content) → apply transform
|
|
930
|
+
* (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
|
|
931
|
+
* synthesised model classes).
|
|
932
|
+
*
|
|
933
|
+
* Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
|
|
934
|
+
* duplicating logic or introducing a circular dependency.
|
|
935
|
+
* @internal
|
|
936
|
+
*/
|
|
937
|
+
static async resolveNonLiteralProps<T extends Ad4mModel>(
|
|
938
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
939
|
+
perspective: PerspectiveProxy,
|
|
940
|
+
instances: T[],
|
|
941
|
+
): Promise<void> {
|
|
942
|
+
const propsMeta = getPropertiesMetadata(this as any);
|
|
943
|
+
const resolveProps = Object.entries(propsMeta).filter(
|
|
944
|
+
([, opts]: [string, any]) =>
|
|
945
|
+
opts.resolveLanguage != null &&
|
|
946
|
+
opts.resolveLanguage !== 'literal',
|
|
947
|
+
);
|
|
948
|
+
if (resolveProps.length === 0) return;
|
|
949
|
+
|
|
950
|
+
await Promise.all(
|
|
951
|
+
instances.map(async (inst: any) => {
|
|
952
|
+
for (const [propName, opts] of resolveProps) {
|
|
953
|
+
const val = inst[propName];
|
|
954
|
+
const transform = (opts as any).transform;
|
|
955
|
+
const applyTransform = (resolved: unknown) =>
|
|
956
|
+
typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
|
|
957
|
+
|
|
958
|
+
if (typeof val === 'string' && val && !val.startsWith('literal:')) {
|
|
959
|
+
// Case 1: raw URI — fetch from language runtime
|
|
960
|
+
try {
|
|
961
|
+
const expression = await perspective.getExpression(val);
|
|
962
|
+
if (expression) {
|
|
963
|
+
let resolved: any;
|
|
964
|
+
try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
|
|
965
|
+
inst[propName] = applyTransform(resolved);
|
|
927
966
|
}
|
|
928
|
-
}
|
|
967
|
+
} catch (e) { console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e); }
|
|
968
|
+
} else if (val !== null && val !== undefined && typeof val === 'object') {
|
|
969
|
+
// Case 2: already resolved by Rust — apply transform / default decode
|
|
970
|
+
inst[propName] = applyTransform(val);
|
|
929
971
|
}
|
|
930
972
|
}
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
973
|
+
}),
|
|
974
|
+
);
|
|
975
|
+
}
|
|
934
976
|
|
|
935
|
-
|
|
936
|
-
// If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
|
|
937
|
-
// This ensures consistent pagination behavior
|
|
938
|
-
const effectiveOrder = query.order ||
|
|
939
|
-
(query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' as 'ASC' } : null);
|
|
940
|
-
|
|
941
|
-
if (effectiveOrder) {
|
|
942
|
-
const orderEntries = Object.entries(effectiveOrder);
|
|
943
|
-
|
|
944
|
-
filteredInstances.sort((a: any, b: any) => {
|
|
945
|
-
for (const [orderPropName, orderDirection] of orderEntries) {
|
|
946
|
-
let aVal = a[orderPropName];
|
|
947
|
-
let bVal = b[orderPropName];
|
|
948
|
-
|
|
949
|
-
// Handle undefined values - push them to the end
|
|
950
|
-
if (aVal === undefined && bVal === undefined) continue;
|
|
951
|
-
if (aVal === undefined) return orderDirection === 'ASC' ? 1 : -1;
|
|
952
|
-
if (bVal === undefined) return orderDirection === 'ASC' ? -1 : 1;
|
|
953
|
-
|
|
954
|
-
// Compare values
|
|
955
|
-
let comparison = 0;
|
|
956
|
-
if (typeof aVal === 'number' && typeof bVal === 'number') {
|
|
957
|
-
comparison = aVal - bVal;
|
|
958
|
-
} else if (typeof aVal === 'string' && typeof bVal === 'string') {
|
|
959
|
-
comparison = aVal.localeCompare(bVal);
|
|
960
|
-
} else {
|
|
961
|
-
comparison = String(aVal).localeCompare(String(bVal));
|
|
962
|
-
}
|
|
977
|
+
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
963
978
|
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
979
|
+
/**
|
|
980
|
+
* Execute a model query via the executor-side endpoint.
|
|
981
|
+
*
|
|
982
|
+
* This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
|
|
983
|
+
* with a single RPC to the executor that handles everything in Rust.
|
|
984
|
+
*
|
|
985
|
+
* @internal
|
|
986
|
+
*/
|
|
987
|
+
private static async executeModelQuery<T extends Ad4mModel>(
|
|
988
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
989
|
+
perspective: PerspectiveProxy,
|
|
990
|
+
query: Query = {},
|
|
991
|
+
classNameOverride?: string | null,
|
|
992
|
+
): Promise<ResultsWithTotalCount<T>> {
|
|
993
|
+
// Delegate query input building to the shared prepareModelQueryParams
|
|
994
|
+
// helper. The executor resolves the shape from SHACL server-side.
|
|
995
|
+
const { className, queryJson } = this.prepareModelQueryParams(
|
|
996
|
+
query, classNameOverride,
|
|
997
|
+
);
|
|
972
998
|
|
|
973
|
-
|
|
974
|
-
const totalCount = filteredInstances.length;
|
|
999
|
+
const result = await perspective.modelQuery(className, queryJson);
|
|
975
1000
|
|
|
976
|
-
//
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
paginatedInstances = filteredInstances.slice(start, end);
|
|
982
|
-
}
|
|
1001
|
+
// Convert JSON instances to model class instances, recursively constructing
|
|
1002
|
+
// class instances for any included relations resolved by Rust.
|
|
1003
|
+
const instances: T[] = result.instances.map((json: any) => {
|
|
1004
|
+
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
1005
|
+
});
|
|
983
1006
|
|
|
984
|
-
//
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1007
|
+
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1008
|
+
// value is a content-addressed hash that must be fetched from the language
|
|
1009
|
+
// runtime). The Rust endpoint may return either a raw target URI (string)
|
|
1010
|
+
// or an already-resolved FileData object — both cases are handled here.
|
|
1011
|
+
await (this as any).resolveNonLiteralProps(perspective, instances);
|
|
988
1012
|
|
|
989
|
-
// Take snapshots for dirty tracking
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
(inst as Ad4mModel).takeSnapshot(snapshotRelations);
|
|
1013
|
+
// Take snapshots for dirty tracking (exclude $-prefixed projection keys)
|
|
1014
|
+
const snapshotRelations = query.include
|
|
1015
|
+
? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
|
|
1016
|
+
: undefined;
|
|
1017
|
+
for (const inst of instances) {
|
|
1018
|
+
(inst as Ad4mModel).takeSnapshot(
|
|
1019
|
+
snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined,
|
|
1020
|
+
);
|
|
998
1021
|
}
|
|
999
1022
|
|
|
1000
1023
|
return {
|
|
1001
|
-
results:
|
|
1002
|
-
totalCount
|
|
1024
|
+
results: instances,
|
|
1025
|
+
totalCount: result.totalCount,
|
|
1003
1026
|
};
|
|
1004
1027
|
}
|
|
1005
1028
|
|
|
@@ -1008,48 +1031,36 @@ export class Ad4mModel {
|
|
|
1008
1031
|
*
|
|
1009
1032
|
* @param perspective - The perspective to search in
|
|
1010
1033
|
* @param query - Optional query parameters to filter results
|
|
1011
|
-
* @param
|
|
1034
|
+
* @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
|
|
1035
|
+
* All queries now use the Rust SPARQL pipeline.
|
|
1012
1036
|
* @returns Array of matching models
|
|
1013
|
-
*
|
|
1037
|
+
*
|
|
1014
1038
|
* @example
|
|
1015
1039
|
* ```typescript
|
|
1016
|
-
* // Get all recipes (uses SurrealDB by default)
|
|
1017
1040
|
* const allRecipes = await Recipe.findAll(perspective);
|
|
1018
|
-
*
|
|
1019
|
-
* // Get recipes with specific criteria (uses SurrealDB)
|
|
1041
|
+
*
|
|
1020
1042
|
* const recipes = await Recipe.findAll(perspective, {
|
|
1021
|
-
* where: {
|
|
1043
|
+
* where: {
|
|
1022
1044
|
* name: "Pasta",
|
|
1023
1045
|
* rating: { gt: 4 }
|
|
1024
1046
|
* },
|
|
1025
1047
|
* order: { createdAt: "DESC" },
|
|
1026
1048
|
* limit: 10
|
|
1027
1049
|
* });
|
|
1028
|
-
*
|
|
1029
|
-
* // Explicitly use Prolog (legacy, for backward compatibility)
|
|
1030
|
-
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
1031
1050
|
* ```
|
|
1032
1051
|
*/
|
|
1033
|
-
static async findAll<T extends Ad4mModel>(
|
|
1034
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1035
|
-
perspective: PerspectiveProxy,
|
|
1036
|
-
query
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
if (
|
|
1052
|
+
static async findAll<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1053
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1054
|
+
perspective: PerspectiveProxy,
|
|
1055
|
+
query?: Q,
|
|
1056
|
+
): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]> {
|
|
1057
|
+
const q = (query ?? {}) as Query;
|
|
1058
|
+
if (q.properties && q.properties.length === 0) {
|
|
1040
1059
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
1041
1060
|
}
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
const { results } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
1046
|
-
return results;
|
|
1047
|
-
} else {
|
|
1048
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1049
|
-
const result = await perspective.infer(prologQuery);
|
|
1050
|
-
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
1051
|
-
return results;
|
|
1052
|
-
}
|
|
1061
|
+
|
|
1062
|
+
const { results } = await this.executeModelQuery(perspective, q);
|
|
1063
|
+
return results as (T & IncludeExtras<T, IncludeOf<Q>>)[];
|
|
1053
1064
|
}
|
|
1054
1065
|
|
|
1055
1066
|
/**
|
|
@@ -1059,7 +1070,7 @@ export class Ad4mModel {
|
|
|
1059
1070
|
*
|
|
1060
1071
|
* @param perspective - The perspective to search in
|
|
1061
1072
|
* @param query - Optional query parameters to filter results
|
|
1062
|
-
* @param
|
|
1073
|
+
* @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
|
|
1063
1074
|
* @returns The first matching instance, or `null`
|
|
1064
1075
|
*
|
|
1065
1076
|
* @example
|
|
@@ -1072,14 +1083,13 @@ export class Ad4mModel {
|
|
|
1072
1083
|
* }
|
|
1073
1084
|
* ```
|
|
1074
1085
|
*/
|
|
1075
|
-
static async findOne<T extends Ad4mModel>(
|
|
1086
|
+
static async findOne<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1076
1087
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1077
1088
|
perspective: PerspectiveProxy,
|
|
1078
|
-
query
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
const
|
|
1082
|
-
const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
|
|
1089
|
+
query?: Q,
|
|
1090
|
+
): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null> {
|
|
1091
|
+
const limitedQuery = { ...((query ?? {}) as Query), limit: 1 } as Q;
|
|
1092
|
+
const results = await this.findAll<T, Q>(perspective, limitedQuery);
|
|
1083
1093
|
return results[0] ?? null;
|
|
1084
1094
|
}
|
|
1085
1095
|
|
|
@@ -1088,9 +1098,9 @@ export class Ad4mModel {
|
|
|
1088
1098
|
*
|
|
1089
1099
|
* @param perspective - The perspective to search in
|
|
1090
1100
|
* @param query - Optional query parameters to filter results
|
|
1091
|
-
* @param
|
|
1101
|
+
* @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
|
|
1092
1102
|
* @returns Object containing results array and total count
|
|
1093
|
-
*
|
|
1103
|
+
*
|
|
1094
1104
|
* @example
|
|
1095
1105
|
* ```typescript
|
|
1096
1106
|
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
|
|
@@ -1098,26 +1108,15 @@ export class Ad4mModel {
|
|
|
1098
1108
|
* limit: 10
|
|
1099
1109
|
* });
|
|
1100
1110
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
1101
|
-
*
|
|
1102
|
-
* // Use Prolog explicitly (legacy)
|
|
1103
|
-
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
1104
1111
|
* ```
|
|
1105
1112
|
*/
|
|
1106
|
-
static async findAllAndCount<T extends Ad4mModel>(
|
|
1107
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1108
|
-
perspective: PerspectiveProxy,
|
|
1109
|
-
query
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
const surrealQuery = await this.queryToSurrealQL(perspective, query);
|
|
1114
|
-
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1115
|
-
return await this.instancesFromSurrealResult(perspective, query, result);
|
|
1116
|
-
} else {
|
|
1117
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1118
|
-
const result = await perspective.infer(prologQuery);
|
|
1119
|
-
return await this.instancesFromPrologResult(perspective, query, result);
|
|
1120
|
-
}
|
|
1113
|
+
static async findAllAndCount<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1114
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1115
|
+
perspective: PerspectiveProxy,
|
|
1116
|
+
query?: Q,
|
|
1117
|
+
): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>> {
|
|
1118
|
+
const out = await this.executeModelQuery(perspective, (query ?? {}) as Query);
|
|
1119
|
+
return out as ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>;
|
|
1121
1120
|
}
|
|
1122
1121
|
|
|
1123
1122
|
/**
|
|
@@ -1127,7 +1126,6 @@ export class Ad4mModel {
|
|
|
1127
1126
|
* @param pageSize - Number of items per page
|
|
1128
1127
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
1129
1128
|
* @param query - Optional additional query parameters
|
|
1130
|
-
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
1131
1129
|
* @returns Paginated results with metadata
|
|
1132
1130
|
*
|
|
1133
1131
|
* @example
|
|
@@ -1136,78 +1134,36 @@ export class Ad4mModel {
|
|
|
1136
1134
|
* where: { category: "Main Course" }
|
|
1137
1135
|
* });
|
|
1138
1136
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1139
|
-
*
|
|
1140
|
-
* // Use Prolog explicitly (legacy)
|
|
1141
|
-
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
1142
1137
|
* ```
|
|
1143
1138
|
*/
|
|
1144
|
-
static async paginate<T extends Ad4mModel>(
|
|
1145
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1146
|
-
perspective: PerspectiveProxy,
|
|
1147
|
-
pageSize: number,
|
|
1148
|
-
pageNumber: number,
|
|
1149
|
-
query?:
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
const
|
|
1153
|
-
|
|
1154
|
-
const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
|
|
1155
|
-
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1156
|
-
const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
|
|
1157
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1158
|
-
} else {
|
|
1159
|
-
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
1160
|
-
const result = await perspective.infer(prologQuery);
|
|
1161
|
-
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
1162
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1163
|
-
}
|
|
1164
|
-
}
|
|
1165
|
-
|
|
1166
|
-
static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
|
|
1167
|
-
const { where } = query;
|
|
1168
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
1169
|
-
const resolvedParentPredicate = query.parent
|
|
1170
|
-
? resolveParentPredicate(query.parent, this)
|
|
1171
|
-
: undefined;
|
|
1172
|
-
const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
|
|
1173
|
-
const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
|
|
1174
|
-
|
|
1175
|
-
const fullQuery = `
|
|
1176
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
1177
|
-
subject_class("${className}", SubjectClass),
|
|
1178
|
-
instance(SubjectClass, Base),
|
|
1179
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
1180
|
-
), UnsortedInstances),
|
|
1181
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
1182
|
-
`;
|
|
1183
|
-
|
|
1184
|
-
return fullQuery;
|
|
1139
|
+
static async paginate<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1140
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1141
|
+
perspective: PerspectiveProxy,
|
|
1142
|
+
pageSize: number,
|
|
1143
|
+
pageNumber: number,
|
|
1144
|
+
query?: Q,
|
|
1145
|
+
): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>> {
|
|
1146
|
+
const paginationQuery = { ...((query ?? {}) as Query), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1147
|
+
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
1148
|
+
return { results: results as (T & IncludeExtras<T, IncludeOf<Q>>)[], totalCount, pageSize, pageNumber };
|
|
1185
1149
|
}
|
|
1186
1150
|
|
|
1187
1151
|
/**
|
|
1188
|
-
* Generates a
|
|
1152
|
+
* Generates a SPARQL COUNT query for the model.
|
|
1189
1153
|
*
|
|
1190
1154
|
* @param perspective - The perspective context
|
|
1191
1155
|
* @param query - Query parameters to filter the count
|
|
1192
|
-
* @returns
|
|
1156
|
+
* @returns SPARQL COUNT query string
|
|
1193
1157
|
*
|
|
1194
1158
|
* @private
|
|
1195
1159
|
*/
|
|
1196
|
-
|
|
1197
|
-
// Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
|
|
1198
|
-
// We'll count the number of rows returned (one row per source)
|
|
1199
|
-
const countQuery = { ...query };
|
|
1200
|
-
delete countQuery.limit;
|
|
1201
|
-
delete countQuery.offset;
|
|
1202
|
-
return await this.queryToSurrealQL(perspective, countQuery);
|
|
1203
|
-
}
|
|
1160
|
+
// countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
|
|
1204
1161
|
|
|
1205
1162
|
/**
|
|
1206
1163
|
* Gets a count of all matching instances.
|
|
1207
1164
|
*
|
|
1208
1165
|
* @param perspective - The perspective to search in
|
|
1209
1166
|
* @param query - Optional query parameters to filter results
|
|
1210
|
-
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
1211
1167
|
* @returns Total count of matching entities
|
|
1212
1168
|
*
|
|
1213
1169
|
* @example
|
|
@@ -1216,24 +1172,15 @@ export class Ad4mModel {
|
|
|
1216
1172
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
1217
1173
|
* where: { status: "active" }
|
|
1218
1174
|
* });
|
|
1219
|
-
*
|
|
1220
|
-
* // Use Prolog explicitly (legacy)
|
|
1221
|
-
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
1222
1175
|
* ```
|
|
1223
1176
|
*/
|
|
1224
|
-
static async count
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
|
|
1232
|
-
return totalCount;
|
|
1233
|
-
} else {
|
|
1234
|
-
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
1235
|
-
return result?.[0]?.TotalCount || 0;
|
|
1236
|
-
}
|
|
1177
|
+
static async count<T extends Ad4mModel>(
|
|
1178
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1179
|
+
perspective: PerspectiveProxy,
|
|
1180
|
+
query?: TypedQuery<T>,
|
|
1181
|
+
): Promise<number> {
|
|
1182
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...((query ?? {}) as Query), limit: 0 });
|
|
1183
|
+
return totalCount;
|
|
1237
1184
|
}
|
|
1238
1185
|
|
|
1239
1186
|
private async setProperty(key: string, value: any, batchId?: string) {
|
|
@@ -1249,7 +1196,7 @@ export class Ad4mModel {
|
|
|
1249
1196
|
// Get resolve language from metadata (replaces Prolog query)
|
|
1250
1197
|
let resolveLanguage = metadata.resolveLanguage;
|
|
1251
1198
|
|
|
1252
|
-
// Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal
|
|
1199
|
+
// Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
|
|
1253
1200
|
if (value === undefined || value === null || value === "") {
|
|
1254
1201
|
return;
|
|
1255
1202
|
}
|
|
@@ -1565,6 +1512,85 @@ export class Ad4mModel {
|
|
|
1565
1512
|
}
|
|
1566
1513
|
}
|
|
1567
1514
|
|
|
1515
|
+
/**
|
|
1516
|
+
* Evaluate SPARQL getters for a batch of instances on demand.
|
|
1517
|
+
*
|
|
1518
|
+
* Since deepQuery defaults to true, property getters are evaluated
|
|
1519
|
+
* automatically during collection queries. Use this method when
|
|
1520
|
+
* deepQuery was explicitly set to false and you want to lazily
|
|
1521
|
+
* resolve getter-backed properties for a subset of instances.
|
|
1522
|
+
*
|
|
1523
|
+
* @param instances - Array of model instances to evaluate getters on
|
|
1524
|
+
* @param perspective - The perspective to query against
|
|
1525
|
+
* @param propertyNames - Optional list of getter-backed property names to evaluate.
|
|
1526
|
+
* If omitted, all getters are evaluated.
|
|
1527
|
+
*
|
|
1528
|
+
* @example
|
|
1529
|
+
* ```typescript
|
|
1530
|
+
* const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
|
|
1531
|
+
* // messages[i].replyingTo is undefined (getter skipped)
|
|
1532
|
+
*
|
|
1533
|
+
* // Evaluate getters for the visible subset
|
|
1534
|
+
* await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
|
|
1535
|
+
* // messages[0..9].replyingTo is now populated
|
|
1536
|
+
* ```
|
|
1537
|
+
*/
|
|
1538
|
+
static async evaluateGetters<T extends Ad4mModel>(
|
|
1539
|
+
instances: T[],
|
|
1540
|
+
perspective: PerspectiveProxy,
|
|
1541
|
+
propertyNames?: string[],
|
|
1542
|
+
): Promise<void> {
|
|
1543
|
+
if (instances.length === 0) return;
|
|
1544
|
+
const metadata = this.getModelMetadata();
|
|
1545
|
+
|
|
1546
|
+
const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
|
|
1547
|
+
|
|
1548
|
+
// The executor reads getter SPARQL from the perspective's SHACL triples
|
|
1549
|
+
// (written by `addSdna`), so no shape JSON is shipped with the call.
|
|
1550
|
+
const result = await perspective.evaluateGetters(
|
|
1551
|
+
metadata.className,
|
|
1552
|
+
instanceIds,
|
|
1553
|
+
propertyNames,
|
|
1554
|
+
);
|
|
1555
|
+
|
|
1556
|
+
// Determine which property names were evaluated for snapshot sync
|
|
1557
|
+
const evaluatedPropertyNames: string[] = [];
|
|
1558
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1559
|
+
if ((propMeta as any).getter) {
|
|
1560
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {
|
|
1561
|
+
evaluatedPropertyNames.push(propName);
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
// Also include relation getters
|
|
1566
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1567
|
+
if ((relMeta as any).getter) {
|
|
1568
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
|
|
1569
|
+
evaluatedPropertyNames.push(relName);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
// Apply results to instances and sync snapshots
|
|
1575
|
+
for (const instance of instances) {
|
|
1576
|
+
const id = (instance as any).id || (instance as any)._baseExpression;
|
|
1577
|
+
const props = result[id];
|
|
1578
|
+
if (props) {
|
|
1579
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1580
|
+
(instance as any)[key] = value;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
// Sync snapshot so isDirty() doesn't flag getter-only changes
|
|
1584
|
+
const modelInstance = instance as Ad4mModel;
|
|
1585
|
+
if (modelInstance._snapshot) {
|
|
1586
|
+
for (const propName of evaluatedPropertyNames) {
|
|
1587
|
+
const val = (instance as any)[propName];
|
|
1588
|
+
modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1568
1594
|
/**
|
|
1569
1595
|
* Gets the model instance with all properties and relations populated.
|
|
1570
1596
|
*
|
|
@@ -1853,6 +1879,26 @@ export class Ad4mModel {
|
|
|
1853
1879
|
await perspective.ensureSDNASubjectClass(this);
|
|
1854
1880
|
}
|
|
1855
1881
|
|
|
1882
|
+
/**
|
|
1883
|
+
* Batch-registers multiple model classes on a perspective in a single RPC call.
|
|
1884
|
+
* This is significantly faster than calling `register()` on each model individually
|
|
1885
|
+
* because it eliminates N-1 round-trips and mutex acquisitions.
|
|
1886
|
+
*
|
|
1887
|
+
* @param perspective - The perspective to register the models on
|
|
1888
|
+
* @param models - Array of Ad4mModel subclasses to register
|
|
1889
|
+
*
|
|
1890
|
+
* @example
|
|
1891
|
+
* ```typescript
|
|
1892
|
+
* await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);
|
|
1893
|
+
* ```
|
|
1894
|
+
*/
|
|
1895
|
+
static async registerAll(
|
|
1896
|
+
perspective: PerspectiveProxy,
|
|
1897
|
+
models: (typeof Ad4mModel)[],
|
|
1898
|
+
): Promise<void> {
|
|
1899
|
+
await perspective.ensureSubjectClasses(models);
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1856
1902
|
/**
|
|
1857
1903
|
* Executes a set of model operations inside a single batch (transaction).
|
|
1858
1904
|
*
|
|
@@ -1914,11 +1960,11 @@ export class Ad4mModel {
|
|
|
1914
1960
|
* ```
|
|
1915
1961
|
*/
|
|
1916
1962
|
static query<T extends Ad4mModel>(
|
|
1917
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1918
|
-
perspective: PerspectiveProxy,
|
|
1919
|
-
query?:
|
|
1963
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1964
|
+
perspective: PerspectiveProxy,
|
|
1965
|
+
query?: TypedQuery<T>,
|
|
1920
1966
|
): ModelQueryBuilder<T> {
|
|
1921
|
-
return new ModelQueryBuilder<T>(perspective, this as any, query);
|
|
1967
|
+
return new ModelQueryBuilder<T>(perspective, this as any, (query ?? {}) as Query);
|
|
1922
1968
|
}
|
|
1923
1969
|
|
|
1924
1970
|
/**
|
|
@@ -1978,5 +2024,124 @@ export class Ad4mModel {
|
|
|
1978
2024
|
): typeof Ad4mModel {
|
|
1979
2025
|
return buildModelFromJSONSchema(this, schema, options);
|
|
1980
2026
|
}
|
|
2027
|
+
|
|
2028
|
+
/**
|
|
2029
|
+
* Creates a fully functional Ad4mModel subclass from a SHACL shape.
|
|
2030
|
+
*
|
|
2031
|
+
* Unlike `fromJSONSchema()`, no predicate inference is required —
|
|
2032
|
+
* `SHACLShape` already contains the exact predicate URI in `path` for
|
|
2033
|
+
* every property. The method reads each property's `path`, `maxCount`,
|
|
2034
|
+
* `writable`, and `resolveLanguage` directly and writes them to the
|
|
2035
|
+
* WeakMap metadata registries.
|
|
2036
|
+
*
|
|
2037
|
+
* Properties with `hasValue` (flag / type-discrimination markers) are
|
|
2038
|
+
* registered as hidden flag entries so that the SPARQL query builder emits
|
|
2039
|
+
* the fixed triple `?source <predicate> <value>` needed for type discrimination.
|
|
2040
|
+
* Properties without a `name` field are skipped.
|
|
2041
|
+
*
|
|
2042
|
+
* **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
|
|
2043
|
+
* was persisted on property shapes) carry the flag value only in
|
|
2044
|
+
* `shape.constructor_actions` as the `target` of an `addLink` action.
|
|
2045
|
+
* This method recovers those values so that old perspectives are queried
|
|
2046
|
+
* with the correct type-discriminator triple.
|
|
2047
|
+
*
|
|
2048
|
+
* @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
|
|
2049
|
+
* @param name - Class name to assign (e.g. "Channel")
|
|
2050
|
+
* @returns Generated Ad4mModel subclass, ready for querying
|
|
2051
|
+
*/
|
|
2052
|
+
/**
|
|
2053
|
+
* Synthesise an `Ad4mModel` subclass from a SHACL shape.
|
|
2054
|
+
*
|
|
2055
|
+
* @param shape - The SHACL shape to synthesise from.
|
|
2056
|
+
* @param name - The model name (e.g. "Channel").
|
|
2057
|
+
* @param classResolver - Optional thunk factory. When provided, any collection
|
|
2058
|
+
* property that carries a `sh:class` URI will have its `target` wired up lazily:
|
|
2059
|
+
* `target: () => classResolver(localName)`. Because `target` is only called at
|
|
2060
|
+
* query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
|
|
2061
|
+
* resolver just needs to return the correct class by the time a query runs —
|
|
2062
|
+
* making it safe to pass a closure over a registry object that is still being
|
|
2063
|
+
* populated (e.g. the `result` record inside `getModelClasses`).
|
|
2064
|
+
*/
|
|
2065
|
+
static fromSHACL(
|
|
2066
|
+
shape: SHACLShape,
|
|
2067
|
+
name: string,
|
|
2068
|
+
classResolver?: (localName: string) => typeof Ad4mModel | undefined,
|
|
2069
|
+
): typeof Ad4mModel {
|
|
2070
|
+
const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
|
|
2071
|
+
(DynamicModelClass as any).className = name;
|
|
2072
|
+
(DynamicModelClass.prototype as any).className = name;
|
|
2073
|
+
|
|
2074
|
+
// Build a backward-compat fallback map: predicate → fixed-IRI-value from
|
|
2075
|
+
// constructor actions. Old SHACL stores (created before sh:hasValue was
|
|
2076
|
+
// persisted on the property shape) don't carry sh:hasValue on properties,
|
|
2077
|
+
// but the shape-level constructor_actions always contain an addLink action
|
|
2078
|
+
// with the fixed flag value as the target.
|
|
2079
|
+
const flagValueFromConstructor = new Map<string, string>();
|
|
2080
|
+
for (const action of shape.constructor_actions ?? []) {
|
|
2081
|
+
if (
|
|
2082
|
+
action.action === 'addLink' &&
|
|
2083
|
+
typeof action.predicate === 'string' &&
|
|
2084
|
+
typeof action.target === 'string' &&
|
|
2085
|
+
action.target !== 'value' &&
|
|
2086
|
+
!action.target.startsWith('literal:')
|
|
2087
|
+
) {
|
|
2088
|
+
flagValueFromConstructor.set(action.predicate, action.target);
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
for (const prop of shape.properties) {
|
|
2093
|
+
const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
|
|
2094
|
+
|
|
2095
|
+
if (resolvedHasValue !== undefined) {
|
|
2096
|
+
const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
|
|
2097
|
+
setPropertyRegistryEntry(DynamicModelClass, flagKey, {
|
|
2098
|
+
through: prop.path,
|
|
2099
|
+
required: true,
|
|
2100
|
+
initial: resolvedHasValue,
|
|
2101
|
+
flag: true,
|
|
2102
|
+
writable: false,
|
|
2103
|
+
readOnly: true,
|
|
2104
|
+
});
|
|
2105
|
+
continue;
|
|
2106
|
+
}
|
|
2107
|
+
|
|
2108
|
+
// Skip properties without a declared name
|
|
2109
|
+
if (!prop.name) continue;
|
|
2110
|
+
|
|
2111
|
+
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
2112
|
+
|
|
2113
|
+
if (isCollection) {
|
|
2114
|
+
// Derive a lazy `target` thunk when a sh:class URI is present and a
|
|
2115
|
+
// classResolver was supplied. The thunk is evaluated at query time so
|
|
2116
|
+
// it is safe even if the target class hasn't been registered yet.
|
|
2117
|
+
let targetThunk: (() => typeof Ad4mModel) | undefined;
|
|
2118
|
+
if (prop.class && classResolver) {
|
|
2119
|
+
const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
|
|
2120
|
+
const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
|
|
2121
|
+
targetThunk = () => classResolver(localName) as typeof Ad4mModel;
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
2125
|
+
predicate: prop.path,
|
|
2126
|
+
kind: 'hasMany',
|
|
2127
|
+
...(targetThunk !== undefined && { target: targetThunk }),
|
|
2128
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2129
|
+
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
2130
|
+
});
|
|
2131
|
+
} else {
|
|
2132
|
+
setPropertyRegistryEntry(DynamicModelClass, prop.name, {
|
|
2133
|
+
through: prop.path,
|
|
2134
|
+
writable: prop.writable ?? true,
|
|
2135
|
+
...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
|
|
2136
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2137
|
+
});
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
const ModelDecorator = Model({ name });
|
|
2142
|
+
ModelDecorator(DynamicModelClass);
|
|
2143
|
+
|
|
2144
|
+
return DynamicModelClass as typeof Ad4mModel;
|
|
2145
|
+
}
|
|
1981
2146
|
}
|
|
1982
2147
|
|