@coasys/ad4m 0.12.0 → 0.13.0-postmessage-ws-proxy.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -25
- package/jest-setup.ts +1 -1
- package/lib/index.cjs +7444 -13939
- package/lib/index.js +5322 -11888
- 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 -373
- 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 +7 -2
- package/lib/src/index.js +7 -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 +150 -62
- package/lib/src/model/Ad4mModel.js +689 -417
- package/lib/src/model/Ad4mModel.test.js +1434 -688
- package/lib/src/model/ModelQueryBuilder.d.ts +59 -38
- package/lib/src/model/ModelQueryBuilder.js +317 -153
- 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 +46 -18
- 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 +60 -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 +189 -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 +156 -78
- package/lib/src/perspectives/PerspectiveProxy.js +474 -389
- package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveResolver.js +0 -11
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
- package/lib/src/perspectives/WakerSubscriptionManager.js +12 -12
- package/lib/src/runtime/RuntimeClient.d.ts +34 -6
- package/lib/src/runtime/RuntimeClient.js +131 -362
- package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
- package/lib/src/runtime/RuntimeResolver.js +197 -4
- package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
- package/lib/src/runtime/RuntimeTypes.js +45 -0
- package/lib/src/schema.gql +27 -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 +8 -1
- package/lib/src/shacl/SHACLShape.js +57 -38
- package/lib/src/shacl/SHACLShape.test.js +82 -0
- package/lib/src/typeDefs.js +3 -602
- package/lib/src/utils.d.ts +6 -6
- package/lib/src/utils.js +6 -6
- package/package.json +6 -18
- 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 -465
- 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 +7 -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 +1690 -777
- package/src/model/Ad4mModel.ts +749 -477
- package/src/model/ModelQueryBuilder.ts +356 -171
- 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 +15 -15
- package/src/model/sdna.ts +1 -1
- package/src/model/shacl-gen.ts +47 -17
- package/src/model/types.ts +65 -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 +254 -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/WakerSubscriptionManager.ts +13 -13
- package/src/runtime/RuntimeClient.ts +166 -369
- package/src/runtime/RuntimeTypes.ts +144 -0
- package/src/shacl/SHACLFlow.ts +9 -9
- package/src/shacl/SHACLShape.test.ts +94 -0
- package/src/shacl/SHACLShape.ts +66 -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 -617
- package/src/unwrapApolloResult.ts +0 -16
- package/tsconfig-browser.json +0 -82
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -3,27 +3,219 @@ 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, buildConformanceFilter, 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,
|
|
25
24
|
} from "./types";
|
|
26
25
|
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Default decoder for file-storage (non-literal resolveLanguage) properties
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* When the Rust executor resolves a non-literal expression it may return a
|
|
33
|
+
* `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
|
|
34
|
+
* raw URI string. If the model class has no custom `transform` registered
|
|
35
|
+
* (e.g. it was synthesised from a SHACL shape at runtime) we still want to
|
|
36
|
+
* decode the content rather than passing raw `FileData` to callers.
|
|
37
|
+
*
|
|
38
|
+
* Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
|
|
39
|
+
* - `application/json` (default when `file_type` is absent) → JSON.parse
|
|
40
|
+
* - anything else → raw decoded string
|
|
41
|
+
*
|
|
42
|
+
* If `resolved` is not a `FileData` object the value is returned unchanged so
|
|
43
|
+
* that callers can use this as a safe unconditional fallback.
|
|
44
|
+
*/
|
|
45
|
+
function defaultFileDecode(resolved: unknown): unknown {
|
|
46
|
+
if (
|
|
47
|
+
resolved !== null &&
|
|
48
|
+
typeof resolved === 'object' &&
|
|
49
|
+
'data_base64' in (resolved as object)
|
|
50
|
+
) {
|
|
51
|
+
const fd = resolved as { data_base64: string; file_type?: string };
|
|
52
|
+
let raw: string;
|
|
53
|
+
try {
|
|
54
|
+
raw = atob(fd.data_base64);
|
|
55
|
+
} catch {
|
|
56
|
+
return resolved; // malformed base64 — keep as-is
|
|
57
|
+
}
|
|
58
|
+
const isJson = !fd.file_type || fd.file_type === 'application/json';
|
|
59
|
+
if (isJson) {
|
|
60
|
+
try { return JSON.parse(raw); } catch { return raw; }
|
|
61
|
+
}
|
|
62
|
+
return raw;
|
|
63
|
+
}
|
|
64
|
+
return resolved;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// Helpers for Rust-side include resolution
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Recursively enrich relation metadata in the shape with target class shapes
|
|
73
|
+
* so the Rust endpoint can resolve includes in-process (no extra GraphQL
|
|
74
|
+
* round-trips per relation).
|
|
75
|
+
*/
|
|
76
|
+
function enrichShapeForIncludes(
|
|
77
|
+
metadata: ModelMetadata,
|
|
78
|
+
include: IncludeMap,
|
|
79
|
+
allRelMeta: Record<string, RelationMetadataEntry>,
|
|
80
|
+
): void {
|
|
81
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
82
|
+
if (!includeVal) continue;
|
|
83
|
+
const meta = allRelMeta[relName];
|
|
84
|
+
if (!meta?.target) continue;
|
|
85
|
+
|
|
86
|
+
const TargetClass = meta.target() as typeof Ad4mModel;
|
|
87
|
+
// Deep-copy so we don't mutate the cached metadata
|
|
88
|
+
const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
|
|
89
|
+
|
|
90
|
+
// Ensure the relation is in metadata.relations (fallback for edge cases)
|
|
91
|
+
if (!metadata.relations[relName]) {
|
|
92
|
+
metadata.relations[relName] = {
|
|
93
|
+
name: relName,
|
|
94
|
+
predicate: meta.predicate,
|
|
95
|
+
direction:
|
|
96
|
+
meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
|
|
97
|
+
? 'reverse'
|
|
98
|
+
: 'forward',
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const rel = metadata.relations[relName] as any;
|
|
102
|
+
rel.kind = meta.kind;
|
|
103
|
+
rel.maxCount = meta.maxCount;
|
|
104
|
+
rel.targetShape = targetMeta;
|
|
105
|
+
rel.targetClassName = targetMeta.className;
|
|
106
|
+
|
|
107
|
+
// Recurse for nested includes
|
|
108
|
+
const nested =
|
|
109
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
110
|
+
? (includeVal as any).include
|
|
111
|
+
: undefined;
|
|
112
|
+
if (nested) {
|
|
113
|
+
const targetRelMeta = getRelationsMetadata(TargetClass as any);
|
|
114
|
+
enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
121
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
122
|
+
* back as plain JSON objects) into proper model class instances.
|
|
123
|
+
*/
|
|
124
|
+
function jsonToModelInstance<T extends Ad4mModel>(
|
|
125
|
+
ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
126
|
+
perspective: PerspectiveProxy,
|
|
127
|
+
json: any,
|
|
128
|
+
include?: IncludeMap,
|
|
129
|
+
properties?: string[],
|
|
130
|
+
): T {
|
|
131
|
+
const instance = new ModelClass(perspective, json.id || json.baseExpression) as any;
|
|
132
|
+
|
|
133
|
+
// When a properties projection is active, remove own properties set by the
|
|
134
|
+
// constructor that are not in the projected JSON. This ensures assertions
|
|
135
|
+
// like `expect(r).to.not.have.own.property("body")` pass.
|
|
136
|
+
if (properties) {
|
|
137
|
+
const jsonKeys = new Set(Object.keys(json));
|
|
138
|
+
for (const key of Object.getOwnPropertyNames(instance)) {
|
|
139
|
+
// Keep internal fields (backing store for getters), id, baseExpression, perspective
|
|
140
|
+
if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_')) continue;
|
|
141
|
+
if (!jsonKeys.has(key)) {
|
|
142
|
+
delete instance[key];
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
for (const [key, value] of Object.entries(json)) {
|
|
148
|
+
if (key === 'baseExpression' || key === 'id') continue;
|
|
149
|
+
|
|
150
|
+
// Skip getter-only properties anywhere in the prototype chain
|
|
151
|
+
let isReadonly = false;
|
|
152
|
+
let proto = Object.getPrototypeOf(instance);
|
|
153
|
+
while (proto) {
|
|
154
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
155
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
156
|
+
proto = Object.getPrototypeOf(proto);
|
|
157
|
+
}
|
|
158
|
+
if (isReadonly) continue;
|
|
159
|
+
|
|
160
|
+
// Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
|
|
161
|
+
if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
|
|
162
|
+
instance[key] = new Date(value).getTime();
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
instance[key] = value;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Apply property transform functions from decorators (only for literal-resolved
|
|
170
|
+
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
171
|
+
// asynchronously in executeModelQuery).
|
|
172
|
+
try {
|
|
173
|
+
const propsMeta = getPropertiesMetadata(ModelClass as any);
|
|
174
|
+
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
175
|
+
const o = opts as any;
|
|
176
|
+
if (typeof o.transform !== 'function' || !(propName in json)) continue;
|
|
177
|
+
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
178
|
+
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
|
|
179
|
+
instance[propName] = o.transform(instance[propName]);
|
|
180
|
+
}
|
|
181
|
+
} catch (e) { console.debug('jsonToModelInstance: transform metadata unavailable:', e); }
|
|
182
|
+
|
|
183
|
+
// Recursively convert included relation values to class instances
|
|
184
|
+
if (include) {
|
|
185
|
+
const relMeta = getRelationsMetadata(ModelClass as any);
|
|
186
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
187
|
+
if (!includeVal) continue;
|
|
188
|
+
const meta = relMeta[relName];
|
|
189
|
+
if (!meta?.target) continue;
|
|
190
|
+
const TargetClass = meta.target() as any;
|
|
191
|
+
const nestedInclude =
|
|
192
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
193
|
+
? (includeVal as any).include
|
|
194
|
+
: undefined;
|
|
195
|
+
const nestedProperties =
|
|
196
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
197
|
+
? (includeVal as any).properties
|
|
198
|
+
: undefined;
|
|
199
|
+
|
|
200
|
+
const raw = instance[relName];
|
|
201
|
+
if (Array.isArray(raw)) {
|
|
202
|
+
instance[relName] = raw.map((item: any) => {
|
|
203
|
+
if (typeof item === 'object' && item !== null && item.id) {
|
|
204
|
+
return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
|
|
205
|
+
}
|
|
206
|
+
return item;
|
|
207
|
+
});
|
|
208
|
+
} else if (typeof raw === 'object' && raw !== null && raw.id) {
|
|
209
|
+
instance[relName] = jsonToModelInstance(
|
|
210
|
+
TargetClass, perspective, raw, nestedInclude, nestedProperties,
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return instance;
|
|
217
|
+
}
|
|
218
|
+
|
|
27
219
|
/**
|
|
28
220
|
* Base class for defining data models in AD4M.
|
|
29
221
|
*
|
|
@@ -128,6 +320,14 @@ export class Ad4mModel {
|
|
|
128
320
|
createdAt: any;
|
|
129
321
|
updatedAt: any;
|
|
130
322
|
|
|
323
|
+
/**
|
|
324
|
+
* Backwards compatibility alias for createdAt.
|
|
325
|
+
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
326
|
+
*/
|
|
327
|
+
get timestamp(): any {
|
|
328
|
+
return (this as any).createdAt;
|
|
329
|
+
}
|
|
330
|
+
|
|
131
331
|
private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
|
|
132
332
|
|
|
133
333
|
/**
|
|
@@ -174,14 +374,6 @@ export class Ad4mModel {
|
|
|
174
374
|
return classCache[perspectiveID];
|
|
175
375
|
}
|
|
176
376
|
|
|
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
377
|
/**
|
|
186
378
|
* Extracts metadata from decorators for query building.
|
|
187
379
|
*
|
|
@@ -258,9 +450,7 @@ export class Ad4mModel {
|
|
|
258
450
|
// Extract relations (relations) from WeakMap registry
|
|
259
451
|
const relationsMetadata: Record<string, RelationMetadata> = {};
|
|
260
452
|
const allRelationsMeta = getRelationsMetadata(this as any);
|
|
261
|
-
const prototypeRelations =
|
|
262
|
-
Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
|
|
263
|
-
);
|
|
453
|
+
const prototypeRelations = allRelationsMeta;
|
|
264
454
|
|
|
265
455
|
for (const [relationName, opts] of Object.entries(prototypeRelations)) {
|
|
266
456
|
const options = opts as RelationMetadataEntry;
|
|
@@ -270,6 +460,8 @@ export class Ad4mModel {
|
|
|
270
460
|
...(options.local !== undefined && { local: options.local }),
|
|
271
461
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
272
462
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
463
|
+
...(options.kind !== undefined && { kind: options.kind }),
|
|
464
|
+
...(options.maxCount !== undefined && { maxCount: options.maxCount }),
|
|
273
465
|
...(options.target !== undefined && { target: options.target }),
|
|
274
466
|
...(options.filter !== undefined && { filter: options.filter }),
|
|
275
467
|
...(options.where !== undefined && { where: options.where }),
|
|
@@ -341,7 +533,7 @@ export class Ad4mModel {
|
|
|
341
533
|
* const recipe = new Recipe(perspective);
|
|
342
534
|
*
|
|
343
535
|
* // Create with specific base expression
|
|
344
|
-
* const recipe = new Recipe(perspective, "literal
|
|
536
|
+
* const recipe = new Recipe(perspective, "literal:...");
|
|
345
537
|
* ```
|
|
346
538
|
*/
|
|
347
539
|
constructor(perspective: PerspectiveProxy, baseExpression?: string) {
|
|
@@ -356,13 +548,6 @@ export class Ad4mModel {
|
|
|
356
548
|
return this._baseExpression;
|
|
357
549
|
}
|
|
358
550
|
|
|
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
551
|
/**
|
|
367
552
|
* Protected getter for the perspective.
|
|
368
553
|
* Allows subclasses to access the perspective while keeping it private from external code.
|
|
@@ -459,14 +644,6 @@ export class Ad4mModel {
|
|
|
459
644
|
}];
|
|
460
645
|
}
|
|
461
646
|
|
|
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
647
|
// ──────────────────────────────────────────────────────────
|
|
471
648
|
// Snapshot / dirty tracking
|
|
472
649
|
// ──────────────────────────────────────────────────────────
|
|
@@ -482,7 +659,8 @@ export class Ad4mModel {
|
|
|
482
659
|
* • `null` / empty object — skip ALL relations (used by bare
|
|
483
660
|
* subscriptions that don't eagerly load relations).
|
|
484
661
|
*/
|
|
485
|
-
|
|
662
|
+
/** @internal */
|
|
663
|
+
protected takeSnapshot(includedRelations?: Record<string, any> | null): void {
|
|
486
664
|
const ctor = this.constructor as typeof Ad4mModel;
|
|
487
665
|
const metadata = ctor.getModelMetadata();
|
|
488
666
|
const snap: Record<string, any> = {};
|
|
@@ -600,103 +778,59 @@ export class Ad4mModel {
|
|
|
600
778
|
}
|
|
601
779
|
|
|
602
780
|
private async getData(opts?: GetOptions) {
|
|
603
|
-
//
|
|
604
|
-
//
|
|
781
|
+
// Route through the Rust model query endpoint — same pipeline as executeModelQuery
|
|
782
|
+
// but for a single instance by ID.
|
|
605
783
|
try {
|
|
606
784
|
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
|
-
}
|
|
785
|
+
const query: Query = {
|
|
786
|
+
where: { id: this._baseExpression },
|
|
787
|
+
limit: 1,
|
|
788
|
+
deepQuery: true, // Single-instance get() always evaluates property getters
|
|
789
|
+
};
|
|
790
|
+
if (opts?.properties) query.properties = opts.properties;
|
|
791
|
+
if (opts?.include) query.include = opts.include;
|
|
624
792
|
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
(
|
|
639
|
-
|
|
640
|
-
|
|
793
|
+
const { results } = await (ctor as any).executeModelQuery(
|
|
794
|
+
this._perspective, query, null
|
|
795
|
+
);
|
|
796
|
+
|
|
797
|
+
if (results.length > 0) {
|
|
798
|
+
const hydrated = results[0];
|
|
799
|
+
// Copy all hydrated values from the Rust-side result onto this instance
|
|
800
|
+
for (const [key, value] of Object.entries(hydrated as any)) {
|
|
801
|
+
if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot') continue;
|
|
802
|
+
if (key.startsWith('_')) continue;
|
|
803
|
+
// Check for readonly getters
|
|
804
|
+
let isReadonly = false;
|
|
805
|
+
let proto = Object.getPrototypeOf(this);
|
|
806
|
+
while (proto) {
|
|
807
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
808
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
809
|
+
proto = Object.getPrototypeOf(proto);
|
|
810
|
+
}
|
|
811
|
+
if (isReadonly) continue;
|
|
812
|
+
(this as any)[key] = value;
|
|
641
813
|
}
|
|
642
814
|
}
|
|
643
815
|
|
|
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
|
-
}
|
|
816
|
+
// Property getters and relation conformance getters are now evaluated
|
|
817
|
+
// Rust-side via evaluate_getters() in model_query.rs.
|
|
654
818
|
} catch (e) {
|
|
655
|
-
console.error(`
|
|
819
|
+
console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
|
|
656
820
|
}
|
|
657
821
|
|
|
658
|
-
this.takeSnapshot();
|
|
822
|
+
this.takeSnapshot(opts?.include);
|
|
659
823
|
return this;
|
|
660
824
|
}
|
|
661
825
|
|
|
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
826
|
/**
|
|
693
|
-
* Generates a
|
|
827
|
+
* Generates a SPARQL query from a Query object.
|
|
694
828
|
*
|
|
695
829
|
* @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
|
|
830
|
+
* This method translates high-level query parameters into a SPARQL query string
|
|
831
|
+
* that can be executed against the SPARQL backend. Unlike Prolog queries which
|
|
832
|
+
* operate on SDNA-aware predicates, SPARQL queries operate directly on raw links
|
|
833
|
+
* stored in SPARQL.
|
|
700
834
|
*
|
|
701
835
|
* The generated query uses a CTE (Common Table Expression) pattern:
|
|
702
836
|
* 1. First, identify candidate base expressions by filtering links based on where conditions
|
|
@@ -704,7 +838,7 @@ export class Ad4mModel {
|
|
|
704
838
|
* 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
|
|
705
839
|
*
|
|
706
840
|
* Key architectural notes:
|
|
707
|
-
* -
|
|
841
|
+
* - SPARQL stores only raw links (source, predicate, target, author, timestamp)
|
|
708
842
|
* - No SDNA knowledge at the database level
|
|
709
843
|
* - Properties are resolved via subqueries that look for links with specific predicates
|
|
710
844
|
* - Relations are similar but return multiple values instead of one
|
|
@@ -712,11 +846,11 @@ export class Ad4mModel {
|
|
|
712
846
|
*
|
|
713
847
|
* @param perspective - The perspective to query (used for metadata extraction)
|
|
714
848
|
* @param query - Query parameters (where, order, limit, offset, properties, relations)
|
|
715
|
-
* @returns Complete
|
|
849
|
+
* @returns Complete SPARQL query string ready for execution
|
|
716
850
|
*
|
|
717
851
|
* @example
|
|
718
852
|
* ```typescript
|
|
719
|
-
* const query = Recipe.
|
|
853
|
+
* const query = Recipe.queryToSPARQL(perspective, {
|
|
720
854
|
* where: { name: "Pasta", rating: { gt: 4 } },
|
|
721
855
|
* order: { timestamp: "DESC" },
|
|
722
856
|
* limit: 10
|
|
@@ -725,281 +859,260 @@ export class Ad4mModel {
|
|
|
725
859
|
* // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
|
|
726
860
|
* ```
|
|
727
861
|
*/
|
|
728
|
-
public static async
|
|
862
|
+
public static async queryToSPARQL(perspective: PerspectiveProxy, query: Query): Promise<string> {
|
|
729
863
|
const metadata = this.getModelMetadata();
|
|
730
864
|
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 };
|
|
865
|
+
return buildSPARQLQuery(metadata, allRelMeta, query, this);
|
|
783
866
|
}
|
|
784
867
|
|
|
785
868
|
/**
|
|
786
|
-
*
|
|
787
|
-
*
|
|
788
|
-
* @param perspective - The perspective context
|
|
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
|
-
*
|
|
869
|
+
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
870
|
+
* Returns the className, queryJson, and shapeJson that the Rust executor expects.
|
|
793
871
|
* @internal
|
|
794
872
|
*/
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
result: any[]
|
|
800
|
-
): Promise<ResultsWithTotalCount<T>> {
|
|
801
|
-
if (!result || result.length === 0) return { results: [], totalCount: 0 };
|
|
802
|
-
|
|
873
|
+
static prepareModelQueryParams(
|
|
874
|
+
query: Query = {},
|
|
875
|
+
classNameOverride?: string | null,
|
|
876
|
+
): { className: string; queryJson: string; shapeJson: string; metadata: ModelMetadata } {
|
|
803
877
|
const metadata = this.getModelMetadata();
|
|
804
|
-
const
|
|
805
|
-
|
|
806
|
-
//
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
878
|
+
const className = classNameOverride || metadata.className;
|
|
879
|
+
|
|
880
|
+
// Expand includeAll: true to a full IncludeMap covering every forward relation.
|
|
881
|
+
if (query.includeAll) {
|
|
882
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
883
|
+
const expanded: IncludeMap = {};
|
|
884
|
+
for (const [relName, relMeta] of Object.entries(allRelMeta)) {
|
|
885
|
+
if ((relMeta as any).direction !== 'reverse') {
|
|
886
|
+
expanded[relName] = true;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
query = { ...query, include: { ...expanded, ...query.include } };
|
|
890
|
+
}
|
|
817
891
|
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
892
|
+
const queryInput: any = {};
|
|
893
|
+
if (query.parent) {
|
|
894
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
895
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
896
|
+
}
|
|
897
|
+
if (query.properties) queryInput.properties = query.properties;
|
|
898
|
+
if (query.include) {
|
|
899
|
+
// Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
|
|
900
|
+
// All other keys (boolean | RelationSubQuery) → queryInput.include
|
|
901
|
+
const normalIncludes: IncludeMap = {};
|
|
902
|
+
const projections: Record<string, IncludeProjection> = {};
|
|
903
|
+
for (const [key, val] of Object.entries(query.include)) {
|
|
904
|
+
if (key.startsWith('$')) {
|
|
905
|
+
projections[key] = val as IncludeProjection;
|
|
906
|
+
} else {
|
|
907
|
+
normalIncludes[key] = val;
|
|
821
908
|
}
|
|
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
|
-
}
|
|
909
|
+
}
|
|
910
|
+
if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
|
|
911
|
+
if (Object.keys(projections).length > 0) {
|
|
912
|
+
// Enrich projections with target shapes so Rust can apply where clause filtering
|
|
913
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
914
|
+
for (const [, proj] of Object.entries(projections)) {
|
|
915
|
+
const relMeta = allRelMeta[proj.from];
|
|
916
|
+
if (!proj.targetShape && relMeta?.target) {
|
|
917
|
+
try {
|
|
918
|
+
const TargetClass = relMeta.target();
|
|
919
|
+
const targetMeta = (TargetClass as any).getModelMetadata?.();
|
|
920
|
+
if (targetMeta) {
|
|
921
|
+
proj.targetShape = targetMeta;
|
|
922
|
+
}
|
|
923
|
+
} catch (e) { console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e); }
|
|
849
924
|
}
|
|
850
925
|
}
|
|
851
|
-
|
|
852
|
-
instances.push(instance);
|
|
853
|
-
} catch (error) {
|
|
854
|
-
console.error(`Failed to process SurrealDB instance ${base}:`, error);
|
|
926
|
+
queryInput.projections = projections;
|
|
855
927
|
}
|
|
856
928
|
}
|
|
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
|
-
);
|
|
929
|
+
if (query.where) queryInput.where = query.where;
|
|
930
|
+
if (query.order) {
|
|
931
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
886
932
|
}
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
933
|
+
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
934
|
+
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
935
|
+
if (query.count !== undefined) queryInput.count = query.count;
|
|
936
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
937
|
+
|
|
938
|
+
if (queryInput.include) {
|
|
939
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
940
|
+
enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
|
|
894
941
|
}
|
|
895
|
-
|
|
896
|
-
//
|
|
897
|
-
//
|
|
898
|
-
//
|
|
899
|
-
//
|
|
900
|
-
//
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
942
|
+
|
|
943
|
+
// Pre-compute conformance getters for Rust-side evaluation.
|
|
944
|
+
// Where clauses are NOT compiled into getter SPARQL because stored
|
|
945
|
+
// property values are signed expression envelopes (literal:json:...),
|
|
946
|
+
// not simple literal:string:X values. Instead, where clauses are
|
|
947
|
+
// attached as metadata for Rust-side post-evaluation filtering.
|
|
948
|
+
{
|
|
949
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
950
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
951
|
+
const rel = relMeta as any;
|
|
952
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
953
|
+
const meta = allRelMeta[relName];
|
|
954
|
+
if (!meta?.target) continue;
|
|
955
|
+
try {
|
|
956
|
+
const TargetClass = meta.target();
|
|
957
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
958
|
+
|
|
959
|
+
if (filter) {
|
|
960
|
+
rel.getter = filter.getter;
|
|
914
961
|
}
|
|
915
962
|
|
|
916
|
-
//
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
963
|
+
// Attach where-clause metadata for Rust-side post-getter filtering
|
|
964
|
+
if (rel.where) {
|
|
965
|
+
try {
|
|
966
|
+
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
967
|
+
if (targetMetadata) {
|
|
968
|
+
const predicates: Record<string, string> = {};
|
|
969
|
+
for (const propName of Object.keys(rel.where)) {
|
|
970
|
+
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
971
|
+
const propMeta = targetMetadata.properties[propName];
|
|
972
|
+
if (propMeta?.predicate) {
|
|
973
|
+
predicates[propName] = propMeta.predicate;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
if (Object.keys(predicates).length > 0) {
|
|
977
|
+
rel.whereFilter = rel.where;
|
|
978
|
+
rel.wherePredicates = predicates;
|
|
979
|
+
}
|
|
927
980
|
}
|
|
928
|
-
}
|
|
981
|
+
} catch (e) { console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e); }
|
|
929
982
|
}
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
});
|
|
983
|
+
} catch (e) { console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e); }
|
|
984
|
+
}
|
|
933
985
|
}
|
|
934
986
|
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
} else {
|
|
961
|
-
comparison = String(aVal).localeCompare(String(bVal));
|
|
962
|
-
}
|
|
987
|
+
return {
|
|
988
|
+
className,
|
|
989
|
+
queryJson: JSON.stringify(queryInput),
|
|
990
|
+
shapeJson: JSON.stringify(metadata),
|
|
991
|
+
metadata,
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* Parse raw model query/subscription result JSON into typed model instances.
|
|
997
|
+
* Used by ModelQueryBuilder to convert subscription updates without circular imports.
|
|
998
|
+
* @internal
|
|
999
|
+
*/
|
|
1000
|
+
static parseModelResult<T extends Ad4mModel>(
|
|
1001
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1002
|
+
perspective: PerspectiveProxy,
|
|
1003
|
+
raw: any,
|
|
1004
|
+
include?: IncludeMap,
|
|
1005
|
+
properties?: string[],
|
|
1006
|
+
): T[] {
|
|
1007
|
+
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
1008
|
+
const arr = data.instances || data;
|
|
1009
|
+
if (!Array.isArray(arr)) return [];
|
|
1010
|
+
return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
1011
|
+
}
|
|
963
1012
|
|
|
964
|
-
|
|
965
|
-
|
|
1013
|
+
/**
|
|
1014
|
+
* Resolve non-literal (file-language) properties on an array of already-constructed
|
|
1015
|
+
* model instances. Handles two cases:
|
|
1016
|
+
*
|
|
1017
|
+
* 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
|
|
1018
|
+
* 2. The Rust executor already resolved the expression and returned a `FileData` object
|
|
1019
|
+
* (happens when the perspective backend eagerly fetches file content) → apply transform
|
|
1020
|
+
* (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
|
|
1021
|
+
* synthesised model classes).
|
|
1022
|
+
*
|
|
1023
|
+
* Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
|
|
1024
|
+
* duplicating logic or introducing a circular dependency.
|
|
1025
|
+
* @internal
|
|
1026
|
+
*/
|
|
1027
|
+
static async resolveNonLiteralProps<T extends Ad4mModel>(
|
|
1028
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1029
|
+
perspective: PerspectiveProxy,
|
|
1030
|
+
instances: T[],
|
|
1031
|
+
): Promise<void> {
|
|
1032
|
+
const propsMeta = getPropertiesMetadata(this as any);
|
|
1033
|
+
const resolveProps = Object.entries(propsMeta).filter(
|
|
1034
|
+
([, opts]: [string, any]) =>
|
|
1035
|
+
opts.resolveLanguage != null &&
|
|
1036
|
+
opts.resolveLanguage !== 'literal',
|
|
1037
|
+
);
|
|
1038
|
+
if (resolveProps.length === 0) return;
|
|
1039
|
+
|
|
1040
|
+
await Promise.all(
|
|
1041
|
+
instances.map(async (inst: any) => {
|
|
1042
|
+
for (const [propName, opts] of resolveProps) {
|
|
1043
|
+
const val = inst[propName];
|
|
1044
|
+
const transform = (opts as any).transform;
|
|
1045
|
+
const applyTransform = (resolved: unknown) =>
|
|
1046
|
+
typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
|
|
1047
|
+
|
|
1048
|
+
if (typeof val === 'string' && val && !val.startsWith('literal:')) {
|
|
1049
|
+
// Case 1: raw URI — fetch from language runtime
|
|
1050
|
+
try {
|
|
1051
|
+
const expression = await perspective.getExpression(val);
|
|
1052
|
+
if (expression) {
|
|
1053
|
+
let resolved: any;
|
|
1054
|
+
try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
|
|
1055
|
+
inst[propName] = applyTransform(resolved);
|
|
1056
|
+
}
|
|
1057
|
+
} catch (e) { console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e); }
|
|
1058
|
+
} else if (val !== null && val !== undefined && typeof val === 'object') {
|
|
1059
|
+
// Case 2: already resolved by Rust — apply transform / default decode
|
|
1060
|
+
inst[propName] = applyTransform(val);
|
|
966
1061
|
}
|
|
967
|
-
// comparison === 0: continue to next sort field
|
|
968
1062
|
}
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
1063
|
+
}),
|
|
1064
|
+
);
|
|
1065
|
+
}
|
|
972
1066
|
|
|
973
|
-
|
|
974
|
-
const totalCount = filteredInstances.length;
|
|
1067
|
+
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
975
1068
|
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
1069
|
+
/**
|
|
1070
|
+
* Execute a model query via the executor-side endpoint.
|
|
1071
|
+
*
|
|
1072
|
+
* This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
|
|
1073
|
+
* with a single RPC to the executor that handles everything in Rust.
|
|
1074
|
+
*
|
|
1075
|
+
* @internal
|
|
1076
|
+
*/
|
|
1077
|
+
private static async executeModelQuery<T extends Ad4mModel>(
|
|
1078
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1079
|
+
perspective: PerspectiveProxy,
|
|
1080
|
+
query: Query = {},
|
|
1081
|
+
classNameOverride?: string | null,
|
|
1082
|
+
): Promise<ResultsWithTotalCount<T>> {
|
|
1083
|
+
// Delegate all query input building, shape enrichment, and getter
|
|
1084
|
+
// pre-computation to the shared prepareModelQueryParams helper.
|
|
1085
|
+
const { className, queryJson, shapeJson } = this.prepareModelQueryParams(
|
|
1086
|
+
query, classNameOverride,
|
|
1087
|
+
);
|
|
983
1088
|
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1089
|
+
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
1090
|
+
|
|
1091
|
+
// Convert JSON instances to model class instances, recursively constructing
|
|
1092
|
+
// class instances for any included relations resolved by Rust.
|
|
1093
|
+
const instances: T[] = result.instances.map((json: any) => {
|
|
1094
|
+
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
1095
|
+
});
|
|
1096
|
+
|
|
1097
|
+
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1098
|
+
// value is a content-addressed hash that must be fetched from the language
|
|
1099
|
+
// runtime). The Rust endpoint may return either a raw target URI (string)
|
|
1100
|
+
// or an already-resolved FileData object — both cases are handled here.
|
|
1101
|
+
await (this as any).resolveNonLiteralProps(perspective, instances);
|
|
988
1102
|
|
|
989
|
-
// Take snapshots for dirty tracking
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
(inst as Ad4mModel).takeSnapshot(snapshotRelations);
|
|
1103
|
+
// Take snapshots for dirty tracking (exclude $-prefixed projection keys)
|
|
1104
|
+
const snapshotRelations = query.include
|
|
1105
|
+
? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
|
|
1106
|
+
: undefined;
|
|
1107
|
+
for (const inst of instances) {
|
|
1108
|
+
(inst as Ad4mModel).takeSnapshot(
|
|
1109
|
+
snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined,
|
|
1110
|
+
);
|
|
998
1111
|
}
|
|
999
1112
|
|
|
1000
1113
|
return {
|
|
1001
|
-
results:
|
|
1002
|
-
totalCount
|
|
1114
|
+
results: instances,
|
|
1115
|
+
totalCount: result.totalCount,
|
|
1003
1116
|
};
|
|
1004
1117
|
}
|
|
1005
1118
|
|
|
@@ -1008,48 +1121,37 @@ export class Ad4mModel {
|
|
|
1008
1121
|
*
|
|
1009
1122
|
* @param perspective - The perspective to search in
|
|
1010
1123
|
* @param query - Optional query parameters to filter results
|
|
1011
|
-
* @param
|
|
1124
|
+
* @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
|
|
1125
|
+
* All queries now use the Rust SPARQL pipeline.
|
|
1012
1126
|
* @returns Array of matching models
|
|
1013
|
-
*
|
|
1127
|
+
*
|
|
1014
1128
|
* @example
|
|
1015
1129
|
* ```typescript
|
|
1016
|
-
* // Get all recipes (uses SurrealDB by default)
|
|
1017
1130
|
* const allRecipes = await Recipe.findAll(perspective);
|
|
1018
|
-
*
|
|
1019
|
-
* // Get recipes with specific criteria (uses SurrealDB)
|
|
1131
|
+
*
|
|
1020
1132
|
* const recipes = await Recipe.findAll(perspective, {
|
|
1021
|
-
* where: {
|
|
1133
|
+
* where: {
|
|
1022
1134
|
* name: "Pasta",
|
|
1023
1135
|
* rating: { gt: 4 }
|
|
1024
1136
|
* },
|
|
1025
1137
|
* order: { createdAt: "DESC" },
|
|
1026
1138
|
* limit: 10
|
|
1027
1139
|
* });
|
|
1028
|
-
*
|
|
1029
|
-
* // Explicitly use Prolog (legacy, for backward compatibility)
|
|
1030
|
-
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
1031
1140
|
* ```
|
|
1032
1141
|
*/
|
|
1033
1142
|
static async findAll<T extends Ad4mModel>(
|
|
1034
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1035
|
-
perspective: PerspectiveProxy,
|
|
1143
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1144
|
+
perspective: PerspectiveProxy,
|
|
1036
1145
|
query: Query = {},
|
|
1037
|
-
|
|
1146
|
+
/** @deprecated Ignored — Prolog engine has been removed. */
|
|
1147
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1038
1148
|
): Promise<T[]> {
|
|
1039
1149
|
if (query.properties && query.properties.length === 0) {
|
|
1040
1150
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
1041
1151
|
}
|
|
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
|
-
}
|
|
1152
|
+
|
|
1153
|
+
const { results } = await this.executeModelQuery(perspective, query);
|
|
1154
|
+
return results;
|
|
1053
1155
|
}
|
|
1054
1156
|
|
|
1055
1157
|
/**
|
|
@@ -1059,7 +1161,7 @@ export class Ad4mModel {
|
|
|
1059
1161
|
*
|
|
1060
1162
|
* @param perspective - The perspective to search in
|
|
1061
1163
|
* @param query - Optional query parameters to filter results
|
|
1062
|
-
* @param
|
|
1164
|
+
* @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
|
|
1063
1165
|
* @returns The first matching instance, or `null`
|
|
1064
1166
|
*
|
|
1065
1167
|
* @example
|
|
@@ -1076,10 +1178,11 @@ export class Ad4mModel {
|
|
|
1076
1178
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1077
1179
|
perspective: PerspectiveProxy,
|
|
1078
1180
|
query: Query = {},
|
|
1079
|
-
|
|
1181
|
+
/** @deprecated Ignored — Prolog engine has been removed. */
|
|
1182
|
+
_engine?: 'sparql' | 'prolog' | boolean,
|
|
1080
1183
|
): Promise<T | null> {
|
|
1081
1184
|
const limitedQuery = { ...query, limit: 1 };
|
|
1082
|
-
const results = await this.findAll(perspective, limitedQuery
|
|
1185
|
+
const results = await this.findAll(perspective, limitedQuery);
|
|
1083
1186
|
return results[0] ?? null;
|
|
1084
1187
|
}
|
|
1085
1188
|
|
|
@@ -1088,9 +1191,9 @@ export class Ad4mModel {
|
|
|
1088
1191
|
*
|
|
1089
1192
|
* @param perspective - The perspective to search in
|
|
1090
1193
|
* @param query - Optional query parameters to filter results
|
|
1091
|
-
* @param
|
|
1194
|
+
* @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
|
|
1092
1195
|
* @returns Object containing results array and total count
|
|
1093
|
-
*
|
|
1196
|
+
*
|
|
1094
1197
|
* @example
|
|
1095
1198
|
* ```typescript
|
|
1096
1199
|
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
|
|
@@ -1098,26 +1201,16 @@ export class Ad4mModel {
|
|
|
1098
1201
|
* limit: 10
|
|
1099
1202
|
* });
|
|
1100
1203
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
1101
|
-
*
|
|
1102
|
-
* // Use Prolog explicitly (legacy)
|
|
1103
|
-
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
1104
1204
|
* ```
|
|
1105
1205
|
*/
|
|
1106
1206
|
static async findAllAndCount<T extends Ad4mModel>(
|
|
1107
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1108
|
-
perspective: PerspectiveProxy,
|
|
1207
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1208
|
+
perspective: PerspectiveProxy,
|
|
1109
1209
|
query: Query = {},
|
|
1110
|
-
|
|
1210
|
+
/** @deprecated Ignored — Prolog engine has been removed. */
|
|
1211
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1111
1212
|
): Promise<ResultsWithTotalCount<T>> {
|
|
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
|
-
}
|
|
1213
|
+
return await this.executeModelQuery(perspective, query);
|
|
1121
1214
|
}
|
|
1122
1215
|
|
|
1123
1216
|
/**
|
|
@@ -1127,7 +1220,6 @@ export class Ad4mModel {
|
|
|
1127
1220
|
* @param pageSize - Number of items per page
|
|
1128
1221
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
1129
1222
|
* @param query - Optional additional query parameters
|
|
1130
|
-
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
1131
1223
|
* @returns Paginated results with metadata
|
|
1132
1224
|
*
|
|
1133
1225
|
* @example
|
|
@@ -1136,78 +1228,38 @@ export class Ad4mModel {
|
|
|
1136
1228
|
* where: { category: "Main Course" }
|
|
1137
1229
|
* });
|
|
1138
1230
|
* 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
1231
|
* ```
|
|
1143
1232
|
*/
|
|
1144
1233
|
static async paginate<T extends Ad4mModel>(
|
|
1145
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1146
|
-
perspective: PerspectiveProxy,
|
|
1147
|
-
pageSize: number,
|
|
1148
|
-
pageNumber: number,
|
|
1234
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1235
|
+
perspective: PerspectiveProxy,
|
|
1236
|
+
pageSize: number,
|
|
1237
|
+
pageNumber: number,
|
|
1149
1238
|
query?: Query,
|
|
1150
|
-
|
|
1239
|
+
/** @deprecated Ignored — Prolog engine has been removed. */
|
|
1240
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1151
1241
|
): Promise<PaginationResult<T>> {
|
|
1152
1242
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1153
|
-
|
|
1154
|
-
|
|
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;
|
|
1243
|
+
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
1244
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1185
1245
|
}
|
|
1186
1246
|
|
|
1187
1247
|
/**
|
|
1188
|
-
* Generates a
|
|
1248
|
+
* Generates a SPARQL COUNT query for the model.
|
|
1189
1249
|
*
|
|
1190
1250
|
* @param perspective - The perspective context
|
|
1191
1251
|
* @param query - Query parameters to filter the count
|
|
1192
|
-
* @returns
|
|
1252
|
+
* @returns SPARQL COUNT query string
|
|
1193
1253
|
*
|
|
1194
1254
|
* @private
|
|
1195
1255
|
*/
|
|
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
|
-
}
|
|
1256
|
+
// countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
|
|
1204
1257
|
|
|
1205
1258
|
/**
|
|
1206
1259
|
* Gets a count of all matching instances.
|
|
1207
1260
|
*
|
|
1208
1261
|
* @param perspective - The perspective to search in
|
|
1209
1262
|
* @param query - Optional query parameters to filter results
|
|
1210
|
-
* @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
1211
1263
|
* @returns Total count of matching entities
|
|
1212
1264
|
*
|
|
1213
1265
|
* @example
|
|
@@ -1216,24 +1268,11 @@ export class Ad4mModel {
|
|
|
1216
1268
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
1217
1269
|
* where: { status: "active" }
|
|
1218
1270
|
* });
|
|
1219
|
-
*
|
|
1220
|
-
* // Use Prolog explicitly (legacy)
|
|
1221
|
-
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
1222
1271
|
* ```
|
|
1223
1272
|
*/
|
|
1224
|
-
static async count(perspective: PerspectiveProxy, query: Query = {}
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
const result = await perspective.querySurrealDB(surrealQuery);
|
|
1228
|
-
// Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
|
|
1229
|
-
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
1230
|
-
// This ensures count() returns the same number as findAll().length
|
|
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
|
-
}
|
|
1273
|
+
static async count(perspective: PerspectiveProxy, query: Query = {}): Promise<number> {
|
|
1274
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
1275
|
+
return totalCount;
|
|
1237
1276
|
}
|
|
1238
1277
|
|
|
1239
1278
|
private async setProperty(key: string, value: any, batchId?: string) {
|
|
@@ -1249,7 +1288,7 @@ export class Ad4mModel {
|
|
|
1249
1288
|
// Get resolve language from metadata (replaces Prolog query)
|
|
1250
1289
|
let resolveLanguage = metadata.resolveLanguage;
|
|
1251
1290
|
|
|
1252
|
-
// Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal
|
|
1291
|
+
// Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
|
|
1253
1292
|
if (value === undefined || value === null || value === "") {
|
|
1254
1293
|
return;
|
|
1255
1294
|
}
|
|
@@ -1565,6 +1604,100 @@ export class Ad4mModel {
|
|
|
1565
1604
|
}
|
|
1566
1605
|
}
|
|
1567
1606
|
|
|
1607
|
+
/**
|
|
1608
|
+
* Evaluate SPARQL getters for a batch of instances on demand.
|
|
1609
|
+
*
|
|
1610
|
+
* Since deepQuery defaults to true, property getters are evaluated
|
|
1611
|
+
* automatically during collection queries. Use this method when
|
|
1612
|
+
* deepQuery was explicitly set to false and you want to lazily
|
|
1613
|
+
* resolve getter-backed properties for a subset of instances.
|
|
1614
|
+
*
|
|
1615
|
+
* @param instances - Array of model instances to evaluate getters on
|
|
1616
|
+
* @param perspective - The perspective to query against
|
|
1617
|
+
* @param propertyNames - Optional list of getter-backed property names to evaluate.
|
|
1618
|
+
* If omitted, all getters are evaluated.
|
|
1619
|
+
*
|
|
1620
|
+
* @example
|
|
1621
|
+
* ```typescript
|
|
1622
|
+
* const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
|
|
1623
|
+
* // messages[i].replyingTo is undefined (getter skipped)
|
|
1624
|
+
*
|
|
1625
|
+
* // Evaluate getters for the visible subset
|
|
1626
|
+
* await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
|
|
1627
|
+
* // messages[0..9].replyingTo is now populated
|
|
1628
|
+
* ```
|
|
1629
|
+
*/
|
|
1630
|
+
static async evaluateGetters<T extends Ad4mModel>(
|
|
1631
|
+
instances: T[],
|
|
1632
|
+
perspective: PerspectiveProxy,
|
|
1633
|
+
propertyNames?: string[],
|
|
1634
|
+
): Promise<void> {
|
|
1635
|
+
if (instances.length === 0) return;
|
|
1636
|
+
const metadata = this.getModelMetadata();
|
|
1637
|
+
|
|
1638
|
+
// Pre-compute conformance getters so the shape sent to Rust includes them
|
|
1639
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
1640
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1641
|
+
const rel = relMeta as any;
|
|
1642
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
1643
|
+
const meta = allRelMeta[relName];
|
|
1644
|
+
if (!meta?.target) continue;
|
|
1645
|
+
try {
|
|
1646
|
+
const TargetClass = meta.target();
|
|
1647
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1648
|
+
if (filter) rel.getter = filter.getter;
|
|
1649
|
+
} catch (e) { console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e); }
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
const shapeJson = JSON.stringify(metadata);
|
|
1653
|
+
const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
|
|
1654
|
+
|
|
1655
|
+
// Single RPC call evaluates all getters in-process on the executor
|
|
1656
|
+
const result = await perspective.evaluateGetters(
|
|
1657
|
+
metadata.className,
|
|
1658
|
+
instanceIds,
|
|
1659
|
+
shapeJson,
|
|
1660
|
+
propertyNames,
|
|
1661
|
+
);
|
|
1662
|
+
|
|
1663
|
+
// Determine which property names were evaluated for snapshot sync
|
|
1664
|
+
const evaluatedPropertyNames: string[] = [];
|
|
1665
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1666
|
+
if ((propMeta as any).getter) {
|
|
1667
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {
|
|
1668
|
+
evaluatedPropertyNames.push(propName);
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
// Also include relation getters
|
|
1673
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1674
|
+
if ((relMeta as any).getter) {
|
|
1675
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
|
|
1676
|
+
evaluatedPropertyNames.push(relName);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// Apply results to instances and sync snapshots
|
|
1682
|
+
for (const instance of instances) {
|
|
1683
|
+
const id = (instance as any).id || (instance as any)._baseExpression;
|
|
1684
|
+
const props = result[id];
|
|
1685
|
+
if (props) {
|
|
1686
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1687
|
+
(instance as any)[key] = value;
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
// Sync snapshot so isDirty() doesn't flag getter-only changes
|
|
1691
|
+
const modelInstance = instance as Ad4mModel;
|
|
1692
|
+
if (modelInstance._snapshot) {
|
|
1693
|
+
for (const propName of evaluatedPropertyNames) {
|
|
1694
|
+
const val = (instance as any)[propName];
|
|
1695
|
+
modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1568
1701
|
/**
|
|
1569
1702
|
* Gets the model instance with all properties and relations populated.
|
|
1570
1703
|
*
|
|
@@ -1853,6 +1986,26 @@ export class Ad4mModel {
|
|
|
1853
1986
|
await perspective.ensureSDNASubjectClass(this);
|
|
1854
1987
|
}
|
|
1855
1988
|
|
|
1989
|
+
/**
|
|
1990
|
+
* Batch-registers multiple model classes on a perspective in a single RPC call.
|
|
1991
|
+
* This is significantly faster than calling `register()` on each model individually
|
|
1992
|
+
* because it eliminates N-1 round-trips and mutex acquisitions.
|
|
1993
|
+
*
|
|
1994
|
+
* @param perspective - The perspective to register the models on
|
|
1995
|
+
* @param models - Array of Ad4mModel subclasses to register
|
|
1996
|
+
*
|
|
1997
|
+
* @example
|
|
1998
|
+
* ```typescript
|
|
1999
|
+
* await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);
|
|
2000
|
+
* ```
|
|
2001
|
+
*/
|
|
2002
|
+
static async registerAll(
|
|
2003
|
+
perspective: PerspectiveProxy,
|
|
2004
|
+
models: (typeof Ad4mModel)[],
|
|
2005
|
+
): Promise<void> {
|
|
2006
|
+
await perspective.ensureSubjectClasses(models);
|
|
2007
|
+
}
|
|
2008
|
+
|
|
1856
2009
|
/**
|
|
1857
2010
|
* Executes a set of model operations inside a single batch (transaction).
|
|
1858
2011
|
*
|
|
@@ -1978,5 +2131,124 @@ export class Ad4mModel {
|
|
|
1978
2131
|
): typeof Ad4mModel {
|
|
1979
2132
|
return buildModelFromJSONSchema(this, schema, options);
|
|
1980
2133
|
}
|
|
2134
|
+
|
|
2135
|
+
/**
|
|
2136
|
+
* Creates a fully functional Ad4mModel subclass from a SHACL shape.
|
|
2137
|
+
*
|
|
2138
|
+
* Unlike `fromJSONSchema()`, no predicate inference is required —
|
|
2139
|
+
* `SHACLShape` already contains the exact predicate URI in `path` for
|
|
2140
|
+
* every property. The method reads each property's `path`, `maxCount`,
|
|
2141
|
+
* `writable`, and `resolveLanguage` directly and writes them to the
|
|
2142
|
+
* WeakMap metadata registries.
|
|
2143
|
+
*
|
|
2144
|
+
* Properties with `hasValue` (flag / type-discrimination markers) are
|
|
2145
|
+
* registered as hidden flag entries so that the SPARQL query builder emits
|
|
2146
|
+
* the fixed triple `?source <predicate> <value>` needed for type discrimination.
|
|
2147
|
+
* Properties without a `name` field are skipped.
|
|
2148
|
+
*
|
|
2149
|
+
* **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
|
|
2150
|
+
* was persisted on property shapes) carry the flag value only in
|
|
2151
|
+
* `shape.constructor_actions` as the `target` of an `addLink` action.
|
|
2152
|
+
* This method recovers those values so that old perspectives are queried
|
|
2153
|
+
* with the correct type-discriminator triple.
|
|
2154
|
+
*
|
|
2155
|
+
* @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
|
|
2156
|
+
* @param name - Class name to assign (e.g. "Channel")
|
|
2157
|
+
* @returns Generated Ad4mModel subclass, ready for querying
|
|
2158
|
+
*/
|
|
2159
|
+
/**
|
|
2160
|
+
* Synthesise an `Ad4mModel` subclass from a SHACL shape.
|
|
2161
|
+
*
|
|
2162
|
+
* @param shape - The SHACL shape to synthesise from.
|
|
2163
|
+
* @param name - The model name (e.g. "Channel").
|
|
2164
|
+
* @param classResolver - Optional thunk factory. When provided, any collection
|
|
2165
|
+
* property that carries a `sh:class` URI will have its `target` wired up lazily:
|
|
2166
|
+
* `target: () => classResolver(localName)`. Because `target` is only called at
|
|
2167
|
+
* query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
|
|
2168
|
+
* resolver just needs to return the correct class by the time a query runs —
|
|
2169
|
+
* making it safe to pass a closure over a registry object that is still being
|
|
2170
|
+
* populated (e.g. the `result` record inside `getModelClasses`).
|
|
2171
|
+
*/
|
|
2172
|
+
static fromSHACL(
|
|
2173
|
+
shape: SHACLShape,
|
|
2174
|
+
name: string,
|
|
2175
|
+
classResolver?: (localName: string) => typeof Ad4mModel | undefined,
|
|
2176
|
+
): typeof Ad4mModel {
|
|
2177
|
+
const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
|
|
2178
|
+
(DynamicModelClass as any).className = name;
|
|
2179
|
+
(DynamicModelClass.prototype as any).className = name;
|
|
2180
|
+
|
|
2181
|
+
// Build a backward-compat fallback map: predicate → fixed-IRI-value from
|
|
2182
|
+
// constructor actions. Old SHACL stores (created before sh:hasValue was
|
|
2183
|
+
// persisted on the property shape) don't carry sh:hasValue on properties,
|
|
2184
|
+
// but the shape-level constructor_actions always contain an addLink action
|
|
2185
|
+
// with the fixed flag value as the target.
|
|
2186
|
+
const flagValueFromConstructor = new Map<string, string>();
|
|
2187
|
+
for (const action of shape.constructor_actions ?? []) {
|
|
2188
|
+
if (
|
|
2189
|
+
action.action === 'addLink' &&
|
|
2190
|
+
typeof action.predicate === 'string' &&
|
|
2191
|
+
typeof action.target === 'string' &&
|
|
2192
|
+
action.target !== 'value' &&
|
|
2193
|
+
!action.target.startsWith('literal:')
|
|
2194
|
+
) {
|
|
2195
|
+
flagValueFromConstructor.set(action.predicate, action.target);
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
for (const prop of shape.properties) {
|
|
2200
|
+
const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
|
|
2201
|
+
|
|
2202
|
+
if (resolvedHasValue !== undefined) {
|
|
2203
|
+
const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
|
|
2204
|
+
setPropertyRegistryEntry(DynamicModelClass, flagKey, {
|
|
2205
|
+
through: prop.path,
|
|
2206
|
+
required: true,
|
|
2207
|
+
initial: resolvedHasValue,
|
|
2208
|
+
flag: true,
|
|
2209
|
+
writable: false,
|
|
2210
|
+
readOnly: true,
|
|
2211
|
+
});
|
|
2212
|
+
continue;
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
// Skip properties without a declared name
|
|
2216
|
+
if (!prop.name) continue;
|
|
2217
|
+
|
|
2218
|
+
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
2219
|
+
|
|
2220
|
+
if (isCollection) {
|
|
2221
|
+
// Derive a lazy `target` thunk when a sh:class URI is present and a
|
|
2222
|
+
// classResolver was supplied. The thunk is evaluated at query time so
|
|
2223
|
+
// it is safe even if the target class hasn't been registered yet.
|
|
2224
|
+
let targetThunk: (() => typeof Ad4mModel) | undefined;
|
|
2225
|
+
if (prop.class && classResolver) {
|
|
2226
|
+
const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
|
|
2227
|
+
const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
|
|
2228
|
+
targetThunk = () => classResolver(localName) as typeof Ad4mModel;
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
2232
|
+
predicate: prop.path,
|
|
2233
|
+
kind: 'hasMany',
|
|
2234
|
+
...(targetThunk !== undefined && { target: targetThunk }),
|
|
2235
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2236
|
+
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
2237
|
+
});
|
|
2238
|
+
} else {
|
|
2239
|
+
setPropertyRegistryEntry(DynamicModelClass, prop.name, {
|
|
2240
|
+
through: prop.path,
|
|
2241
|
+
writable: prop.writable ?? true,
|
|
2242
|
+
...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
|
|
2243
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2244
|
+
});
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
const ModelDecorator = Model({ name });
|
|
2249
|
+
ModelDecorator(DynamicModelClass);
|
|
2250
|
+
|
|
2251
|
+
return DynamicModelClass as typeof Ad4mModel;
|
|
2252
|
+
}
|
|
1981
2253
|
}
|
|
1982
2254
|
|