@coasys/ad4m 0.13.0-test-3 → 0.13.0-test-5
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 +6717 -15519
- package/lib/index.js +4811 -13662
- package/lib/src/Ad4mClient.d.ts +7 -3
- package/lib/src/Ad4mClient.js +39 -13
- package/lib/src/agent/Agent.js +26 -272
- package/lib/src/agent/AgentClient.d.ts +10 -21
- package/lib/src/agent/AgentClient.js +75 -427
- 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 +52 -0
- package/lib/src/apiClient.js +231 -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 +3 -3
- package/lib/src/expression/ExpressionClient.js +13 -76
- package/lib/src/expression/ExpressionRef.js +2 -25
- 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 +6 -1
- package/lib/src/index.js +6 -1
- 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 +1 -1
- package/lib/src/language/Language.js +10 -76
- 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 +76 -44
- package/lib/src/model/Ad4mModel.js +635 -479
- package/lib/src/model/Ad4mModel.test.js +371 -815
- package/lib/src/model/ModelQueryBuilder.d.ts +15 -27
- package/lib/src/model/ModelQueryBuilder.js +163 -224
- package/lib/src/model/decorators.d.ts +22 -0
- package/lib/src/model/decorators.js +7 -0
- package/lib/src/model/hydration.d.ts +3 -93
- package/lib/src/model/hydration.js +3 -970
- package/lib/src/model/index.d.ts +0 -4
- package/lib/src/model/index.js +0 -4
- package/lib/src/model/model-manifest.d.ts +41 -0
- package/lib/src/model/model-manifest.js +11 -0
- package/lib/src/model/query-sparql.d.ts +4 -67
- package/lib/src/model/query-sparql.js +26 -322
- package/lib/src/model/query-sparql.test.js +35 -218
- package/lib/src/model/query-utils.d.ts +1 -0
- package/lib/src/model/query-utils.js +46 -1
- package/lib/src/model/shacl-gen.js +4 -0
- package/lib/src/model/types.d.ts +51 -43
- package/lib/src/model/types.js +4 -1
- 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 +13 -17
- package/lib/src/perspectives/PerspectiveClient.js +179 -429
- package/lib/src/perspectives/PerspectiveClient.test.js +55 -0
- package/lib/src/perspectives/PerspectiveDiff.js +4 -31
- package/lib/src/perspectives/PerspectiveHandle.js +3 -43
- package/lib/src/perspectives/PerspectiveProxy.d.ts +106 -71
- package/lib/src/perspectives/PerspectiveProxy.js +289 -310
- package/lib/src/runtime/RuntimeClient.d.ts +6 -6
- package/lib/src/runtime/RuntimeClient.js +93 -467
- package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
- package/lib/src/runtime/RuntimeTypes.js +45 -0
- package/lib/src/shacl/SHACLShape.d.ts +7 -0
- package/lib/src/shacl/SHACLShape.js +19 -0
- package/lib/src/shacl/SHACLShape.test.js +82 -0
- package/lib/src/typeDefs.js +3 -628
- package/package.json +6 -18
- package/rollup.config.js +0 -7
- package/src/Ad4mClient.test.ts +1179 -1340
- package/src/Ad4mClient.ts +40 -15
- package/src/agent/Agent.ts +0 -99
- package/src/agent/AgentClient.ts +112 -526
- 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 +283 -0
- package/src/expression/Expression.ts +3 -43
- package/src/expression/ExpressionClient.ts +14 -77
- package/src/expression/ExpressionRef.ts +0 -6
- 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 +6 -1
- package/src/jestSetup.ts +1 -1
- package/src/language/Icon.ts +0 -4
- package/src/language/Language.ts +2 -23
- 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 +766 -1173
- package/src/model/Ad4mModel.ts +664 -529
- package/src/model/ModelQueryBuilder.ts +203 -251
- package/src/model/decorators.ts +29 -0
- package/src/model/hydration.ts +3 -1037
- package/src/model/index.ts +0 -4
- package/src/model/query-sparql.test.ts +34 -242
- package/src/model/query-sparql.ts +27 -337
- package/src/model/query-utils.ts +47 -2
- package/src/model/shacl-gen.ts +5 -0
- package/src/model/types.ts +55 -44
- 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 +206 -148
- package/src/perspectives/PerspectiveClient.ts +247 -442
- package/src/perspectives/PerspectiveDiff.ts +0 -8
- package/src/perspectives/PerspectiveHandle.ts +1 -12
- package/src/perspectives/PerspectiveProxy.test.ts +41 -0
- package/src/perspectives/PerspectiveProxy.ts +331 -348
- package/src/runtime/RuntimeClient.ts +112 -474
- package/src/runtime/RuntimeTypes.ts +144 -0
- package/src/shacl/SHACLShape.test.ts +94 -0
- package/src/shacl/SHACLShape.ts +27 -0
- package/src/typeDefs.ts +3 -5
- package/tsconfig.json +3 -7
- 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/LanguageResolver.ts +0 -98
- package/src/model/Subject.ts +0 -159
- package/src/model/hydration-batch.ts +0 -205
- package/src/model/hydration-batching.test.ts +0 -563
- package/src/model/prolog-facts.ts +0 -145
- package/src/model/query-prolog.ts +0 -148
- package/src/model/query-sparql-batch.ts +0 -301
- package/src/model/subscription-delta.test.ts +0 -207
- package/src/model/subscription-pool.ts +0 -211
- package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
- package/src/perspectives/PerspectiveResolver.ts +0 -364
- package/src/runtime/RuntimeResolver.ts +0 -749
- package/src/unwrapApolloResult.ts +0 -16
|
@@ -2,13 +2,148 @@ import { Literal } from "../Literal";
|
|
|
2
2
|
import { Link } from "../links/Links";
|
|
3
3
|
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
4
4
|
import { makeRandomId } from "./util";
|
|
5
|
-
import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
|
|
5
|
+
import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
|
|
6
|
+
import { compileWhereClause } from "./query-utils";
|
|
6
7
|
import { resolveParentPredicate } from "./query-common";
|
|
7
|
-
import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
|
|
8
8
|
import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
|
|
9
|
-
import { buildSPARQLQuery
|
|
9
|
+
import { buildSPARQLQuery } from "./query-sparql";
|
|
10
10
|
import { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
11
|
-
import { normalizeValue,
|
|
11
|
+
import { normalizeValue, } from "./hydration";
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// Helpers for Rust-side include resolution
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
/**
|
|
16
|
+
* Recursively enrich relation metadata in the shape with target class shapes
|
|
17
|
+
* so the Rust endpoint can resolve includes in-process (no extra GraphQL
|
|
18
|
+
* round-trips per relation).
|
|
19
|
+
*/
|
|
20
|
+
function enrichShapeForIncludes(metadata, include, allRelMeta) {
|
|
21
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
22
|
+
if (!includeVal)
|
|
23
|
+
continue;
|
|
24
|
+
const meta = allRelMeta[relName];
|
|
25
|
+
if (!meta?.target)
|
|
26
|
+
continue;
|
|
27
|
+
const TargetClass = meta.target();
|
|
28
|
+
// Deep-copy so we don't mutate the cached metadata
|
|
29
|
+
const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
|
|
30
|
+
// Ensure the relation is in metadata.relations (fallback for edge cases)
|
|
31
|
+
if (!metadata.relations[relName]) {
|
|
32
|
+
metadata.relations[relName] = {
|
|
33
|
+
name: relName,
|
|
34
|
+
predicate: meta.predicate,
|
|
35
|
+
direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
|
|
36
|
+
? 'reverse'
|
|
37
|
+
: 'forward',
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const rel = metadata.relations[relName];
|
|
41
|
+
rel.kind = meta.kind;
|
|
42
|
+
rel.maxCount = meta.maxCount;
|
|
43
|
+
rel.targetShape = targetMeta;
|
|
44
|
+
rel.targetClassName = targetMeta.className;
|
|
45
|
+
// Recurse for nested includes
|
|
46
|
+
const nested = typeof includeVal === 'object' && includeVal !== null
|
|
47
|
+
? includeVal.include
|
|
48
|
+
: undefined;
|
|
49
|
+
if (nested) {
|
|
50
|
+
const targetRelMeta = getRelationsMetadata(TargetClass);
|
|
51
|
+
enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
57
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
58
|
+
* back as plain JSON objects) into proper model class instances.
|
|
59
|
+
*/
|
|
60
|
+
function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
|
|
61
|
+
const instance = new ModelClass(perspective, json.id || json.baseExpression);
|
|
62
|
+
// When a properties projection is active, remove own properties set by the
|
|
63
|
+
// constructor that are not in the projected JSON. This ensures assertions
|
|
64
|
+
// like `expect(r).to.not.have.own.property("body")` pass.
|
|
65
|
+
if (properties) {
|
|
66
|
+
const jsonKeys = new Set(Object.keys(json));
|
|
67
|
+
for (const key of Object.getOwnPropertyNames(instance)) {
|
|
68
|
+
// Keep internal fields (backing store for getters), id, baseExpression, perspective
|
|
69
|
+
if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_'))
|
|
70
|
+
continue;
|
|
71
|
+
if (!jsonKeys.has(key)) {
|
|
72
|
+
delete instance[key];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const [key, value] of Object.entries(json)) {
|
|
77
|
+
if (key === 'baseExpression' || key === 'id')
|
|
78
|
+
continue;
|
|
79
|
+
// Skip getter-only properties anywhere in the prototype chain
|
|
80
|
+
let isReadonly = false;
|
|
81
|
+
let proto = Object.getPrototypeOf(instance);
|
|
82
|
+
while (proto) {
|
|
83
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
84
|
+
if (desc) {
|
|
85
|
+
isReadonly = !!(desc.get && !desc.set);
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
proto = Object.getPrototypeOf(proto);
|
|
89
|
+
}
|
|
90
|
+
if (isReadonly)
|
|
91
|
+
continue;
|
|
92
|
+
// Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
|
|
93
|
+
if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
|
|
94
|
+
instance[key] = new Date(value).getTime();
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
instance[key] = value;
|
|
98
|
+
}
|
|
99
|
+
// Apply property transform functions from decorators (only for literal-resolved
|
|
100
|
+
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
101
|
+
// asynchronously in executeModelQuery).
|
|
102
|
+
try {
|
|
103
|
+
const propsMeta = getPropertiesMetadata(ModelClass);
|
|
104
|
+
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
105
|
+
const o = opts;
|
|
106
|
+
if (typeof o.transform !== 'function' || !(propName in json))
|
|
107
|
+
continue;
|
|
108
|
+
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
109
|
+
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
|
|
110
|
+
continue;
|
|
111
|
+
instance[propName] = o.transform(instance[propName]);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch (_) { /* no metadata available */ }
|
|
115
|
+
// Recursively convert included relation values to class instances
|
|
116
|
+
if (include) {
|
|
117
|
+
const relMeta = getRelationsMetadata(ModelClass);
|
|
118
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
119
|
+
if (!includeVal)
|
|
120
|
+
continue;
|
|
121
|
+
const meta = relMeta[relName];
|
|
122
|
+
if (!meta?.target)
|
|
123
|
+
continue;
|
|
124
|
+
const TargetClass = meta.target();
|
|
125
|
+
const nestedInclude = typeof includeVal === 'object' && includeVal !== null
|
|
126
|
+
? includeVal.include
|
|
127
|
+
: undefined;
|
|
128
|
+
const nestedProperties = typeof includeVal === 'object' && includeVal !== null
|
|
129
|
+
? includeVal.properties
|
|
130
|
+
: undefined;
|
|
131
|
+
const raw = instance[relName];
|
|
132
|
+
if (Array.isArray(raw)) {
|
|
133
|
+
instance[relName] = raw.map((item) => {
|
|
134
|
+
if (typeof item === 'object' && item !== null && item.id) {
|
|
135
|
+
return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
|
|
136
|
+
}
|
|
137
|
+
return item;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
else if (typeof raw === 'object' && raw !== null && raw.id) {
|
|
141
|
+
instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return instance;
|
|
146
|
+
}
|
|
12
147
|
/**
|
|
13
148
|
* Base class for defining data models in AD4M.
|
|
14
149
|
*
|
|
@@ -106,6 +241,13 @@ import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInsta
|
|
|
106
241
|
* ```
|
|
107
242
|
*/
|
|
108
243
|
export class Ad4mModel {
|
|
244
|
+
/**
|
|
245
|
+
* Backwards compatibility alias for createdAt.
|
|
246
|
+
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
247
|
+
*/
|
|
248
|
+
get timestamp() {
|
|
249
|
+
return this.createdAt;
|
|
250
|
+
}
|
|
109
251
|
/**
|
|
110
252
|
* Generates the SDNA (Subject DNA) Prolog rules for this model class.
|
|
111
253
|
* Injected at class-definition time by the `@Model` decorator.
|
|
@@ -143,13 +285,6 @@ export class Ad4mModel {
|
|
|
143
285
|
}
|
|
144
286
|
return classCache[perspectiveID];
|
|
145
287
|
}
|
|
146
|
-
/**
|
|
147
|
-
* Backwards compatibility alias for createdAt.
|
|
148
|
-
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
149
|
-
*/
|
|
150
|
-
get timestamp() {
|
|
151
|
-
return this.createdAt;
|
|
152
|
-
}
|
|
153
288
|
/**
|
|
154
289
|
* Extracts metadata from decorators for query building.
|
|
155
290
|
*
|
|
@@ -221,7 +356,7 @@ export class Ad4mModel {
|
|
|
221
356
|
// Extract relations (relations) from WeakMap registry
|
|
222
357
|
const relationsMetadata = {};
|
|
223
358
|
const allRelationsMeta = getRelationsMetadata(this);
|
|
224
|
-
const prototypeRelations =
|
|
359
|
+
const prototypeRelations = allRelationsMeta;
|
|
225
360
|
for (const [relationName, opts] of Object.entries(prototypeRelations)) {
|
|
226
361
|
const options = opts;
|
|
227
362
|
relationsMetadata[relationName] = {
|
|
@@ -230,6 +365,8 @@ export class Ad4mModel {
|
|
|
230
365
|
...(options.local !== undefined && { local: options.local }),
|
|
231
366
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
232
367
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
368
|
+
...(options.kind !== undefined && { kind: options.kind }),
|
|
369
|
+
...(options.maxCount !== undefined && { maxCount: options.maxCount }),
|
|
233
370
|
...(options.target !== undefined && { target: options.target }),
|
|
234
371
|
...(options.filter !== undefined && { filter: options.filter }),
|
|
235
372
|
...(options.where !== undefined && { where: options.where }),
|
|
@@ -304,12 +441,6 @@ export class Ad4mModel {
|
|
|
304
441
|
get id() {
|
|
305
442
|
return this._baseExpression;
|
|
306
443
|
}
|
|
307
|
-
/**
|
|
308
|
-
* @deprecated Use `.id` instead. Will be removed in a future version.
|
|
309
|
-
*/
|
|
310
|
-
get baseExpression() {
|
|
311
|
-
return this._baseExpression;
|
|
312
|
-
}
|
|
313
444
|
/**
|
|
314
445
|
* Protected getter for the perspective.
|
|
315
446
|
* Allows subclasses to access the perspective while keeping it private from external code.
|
|
@@ -390,13 +521,6 @@ export class Ad4mModel {
|
|
|
390
521
|
...(metadata.local && { local: true })
|
|
391
522
|
}];
|
|
392
523
|
}
|
|
393
|
-
/**
|
|
394
|
-
* Assigns decoded Prolog property values to an instance.
|
|
395
|
-
* Delegates to the standalone function in hydration.ts.
|
|
396
|
-
*/
|
|
397
|
-
static async assignValuesToInstance(perspective, instance, values) {
|
|
398
|
-
return _assignValuesToInstance(perspective, instance, values);
|
|
399
|
-
}
|
|
400
524
|
// ──────────────────────────────────────────────────────────
|
|
401
525
|
// Snapshot / dirty tracking
|
|
402
526
|
// ──────────────────────────────────────────────────────────
|
|
@@ -516,78 +640,53 @@ export class Ad4mModel {
|
|
|
516
640
|
return changed;
|
|
517
641
|
}
|
|
518
642
|
async getData(opts) {
|
|
519
|
-
//
|
|
520
|
-
//
|
|
643
|
+
// Route through the Rust model query endpoint — same pipeline as executeModelQuery
|
|
644
|
+
// but for a single instance by ID.
|
|
521
645
|
try {
|
|
522
646
|
const ctor = this.constructor;
|
|
523
|
-
const
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
647
|
+
const query = {
|
|
648
|
+
where: { id: this._baseExpression },
|
|
649
|
+
limit: 1,
|
|
650
|
+
deepQuery: true, // Single-instance get() always evaluates property getters
|
|
651
|
+
};
|
|
652
|
+
if (opts?.properties)
|
|
653
|
+
query.properties = opts.properties;
|
|
654
|
+
if (opts?.include)
|
|
655
|
+
query.include = opts.include;
|
|
656
|
+
const { results } = await ctor.executeModelQuery(this._perspective, query, null);
|
|
657
|
+
if (results.length > 0) {
|
|
658
|
+
const hydrated = results[0];
|
|
659
|
+
// Copy all hydrated values from the Rust-side result onto this instance
|
|
660
|
+
for (const [key, value] of Object.entries(hydrated)) {
|
|
661
|
+
if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot')
|
|
662
|
+
continue;
|
|
663
|
+
if (key.startsWith('_'))
|
|
664
|
+
continue;
|
|
665
|
+
// Check for readonly getters
|
|
666
|
+
let isReadonly = false;
|
|
667
|
+
let proto = Object.getPrototypeOf(this);
|
|
668
|
+
while (proto) {
|
|
669
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
670
|
+
if (desc) {
|
|
671
|
+
isReadonly = !!(desc.get && !desc.set);
|
|
672
|
+
break;
|
|
673
|
+
}
|
|
674
|
+
proto = Object.getPrototypeOf(proto);
|
|
675
|
+
}
|
|
676
|
+
if (isReadonly)
|
|
677
|
+
continue;
|
|
678
|
+
this[key] = value;
|
|
549
679
|
}
|
|
550
680
|
}
|
|
551
|
-
//
|
|
552
|
-
|
|
553
|
-
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
554
|
-
: undefined;
|
|
555
|
-
await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
|
|
556
|
-
// Eager-load relations if requested
|
|
557
|
-
if (opts?.include) {
|
|
558
|
-
await hydrateRelations(ctor, [this], this._perspective, opts.include);
|
|
559
|
-
}
|
|
681
|
+
// Property getters and relation conformance getters are now evaluated
|
|
682
|
+
// Rust-side via evaluate_getters() in model_query.rs.
|
|
560
683
|
}
|
|
561
684
|
catch (e) {
|
|
562
|
-
console.error(`
|
|
685
|
+
console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
|
|
563
686
|
}
|
|
564
|
-
this.takeSnapshot();
|
|
687
|
+
this.takeSnapshot(opts?.include);
|
|
565
688
|
return this;
|
|
566
689
|
}
|
|
567
|
-
static async queryToProlog(perspective, query, modelClassName) {
|
|
568
|
-
const { properties, where, order, offset, limit, count } = query;
|
|
569
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
570
|
-
// Resolve parent predicate from model metadata if needed
|
|
571
|
-
const resolvedParentPredicate = query.parent
|
|
572
|
-
? resolveParentPredicate(query.parent, this)
|
|
573
|
-
: undefined;
|
|
574
|
-
const instanceQueries = [
|
|
575
|
-
buildAuthorAndTimestampQuery(),
|
|
576
|
-
buildParentQuery(query.parent, resolvedParentPredicate),
|
|
577
|
-
buildPropertiesQuery(properties),
|
|
578
|
-
buildWhereQuery(where),
|
|
579
|
-
];
|
|
580
|
-
const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
|
|
581
|
-
const fullQuery = `
|
|
582
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
583
|
-
subject_class("${className}", SubjectClass),
|
|
584
|
-
instance(SubjectClass, Base),
|
|
585
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
586
|
-
), UnsortedInstances),
|
|
587
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
588
|
-
`;
|
|
589
|
-
return fullQuery;
|
|
590
|
-
}
|
|
591
690
|
/**
|
|
592
691
|
* Generates a SPARQL query from a Query object.
|
|
593
692
|
*
|
|
@@ -629,301 +728,322 @@ export class Ad4mModel {
|
|
|
629
728
|
const allRelMeta = getRelationsMetadata(this);
|
|
630
729
|
return buildSPARQLQuery(metadata, allRelMeta, query, this);
|
|
631
730
|
}
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
731
|
+
/**
|
|
732
|
+
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
733
|
+
* Returns the className, queryJson, and shapeJson that the Rust executor expects.
|
|
734
|
+
* @internal
|
|
735
|
+
*/
|
|
736
|
+
static prepareModelQueryParams(query = {}, classNameOverride) {
|
|
737
|
+
const metadata = this.getModelMetadata();
|
|
738
|
+
const className = classNameOverride || metadata.className;
|
|
739
|
+
const queryInput = {};
|
|
740
|
+
if (query.parent) {
|
|
741
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
742
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
743
|
+
}
|
|
744
|
+
if (query.properties)
|
|
745
|
+
queryInput.properties = query.properties;
|
|
746
|
+
if (query.include)
|
|
747
|
+
queryInput.include = query.include;
|
|
748
|
+
if (query.where)
|
|
749
|
+
queryInput.where = query.where;
|
|
750
|
+
if (query.order) {
|
|
751
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
752
|
+
}
|
|
753
|
+
if (query.offset !== undefined)
|
|
754
|
+
queryInput.offset = query.offset;
|
|
755
|
+
if (query.limit !== undefined)
|
|
756
|
+
queryInput.limit = query.limit;
|
|
757
|
+
if (query.count !== undefined)
|
|
758
|
+
queryInput.count = query.count;
|
|
759
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
760
|
+
if (query.include) {
|
|
761
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
762
|
+
enrichShapeForIncludes(metadata, query.include, allRelMeta);
|
|
763
|
+
}
|
|
764
|
+
// Pre-compute conformance getters (with where-clause support)
|
|
765
|
+
{
|
|
766
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
767
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
768
|
+
const rel = relMeta;
|
|
769
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
|
|
770
|
+
continue;
|
|
771
|
+
const meta = allRelMeta[relName];
|
|
772
|
+
if (!meta?.target)
|
|
773
|
+
continue;
|
|
774
|
+
try {
|
|
775
|
+
const TargetClass = meta.target();
|
|
776
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
777
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
778
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
779
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
780
|
+
// that can't be matched by value in SPARQL.
|
|
781
|
+
let whereConditions = [];
|
|
782
|
+
if (rel.where) {
|
|
783
|
+
try {
|
|
784
|
+
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
785
|
+
let allSparqlFilterable = true;
|
|
786
|
+
if (targetMetadata) {
|
|
787
|
+
for (const propName of Object.keys(rel.where)) {
|
|
788
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
789
|
+
continue;
|
|
790
|
+
const propMeta = targetMetadata.properties[propName];
|
|
791
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
792
|
+
allSparqlFilterable = false;
|
|
793
|
+
break;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
if (allSparqlFilterable) {
|
|
798
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
catch (_) { }
|
|
802
|
+
}
|
|
803
|
+
if (filter) {
|
|
804
|
+
let getter = filter.getter;
|
|
805
|
+
if (whereConditions.length > 0) {
|
|
806
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
807
|
+
}
|
|
808
|
+
rel.getter = getter;
|
|
809
|
+
}
|
|
810
|
+
else if (whereConditions.length > 0) {
|
|
811
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
812
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
813
|
+
}
|
|
646
814
|
}
|
|
647
|
-
|
|
648
|
-
const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
|
|
649
|
-
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
650
|
-
return instance;
|
|
651
|
-
}
|
|
652
|
-
catch (error) {
|
|
653
|
-
console.error(`Failed to process instance ${Base}:`, error);
|
|
654
|
-
// Return null for failed instances - we'll filter these out below
|
|
655
|
-
return null;
|
|
815
|
+
catch (_) { }
|
|
656
816
|
}
|
|
657
|
-
}));
|
|
658
|
-
const instances = allInstances.filter((instance) => instance !== null);
|
|
659
|
-
// Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
|
|
660
|
-
if (query.include && instances.length > 0) {
|
|
661
|
-
await hydrateRelations(this, instances, perspective, query.include);
|
|
662
|
-
}
|
|
663
|
-
// Take snapshots for dirty tracking after ALL hydration is complete
|
|
664
|
-
// (including eager-loaded relations).
|
|
665
|
-
// When `include` is specified, only snapshot those relations.
|
|
666
|
-
// Otherwise snapshot ALL fields (properties + relations) since
|
|
667
|
-
// hydrateFromLinks populates relations with stable raw IDs.
|
|
668
|
-
const snapshotRelations = query.include;
|
|
669
|
-
for (const inst of instances) {
|
|
670
|
-
inst.takeSnapshot(snapshotRelations);
|
|
671
817
|
}
|
|
672
|
-
return {
|
|
818
|
+
return {
|
|
819
|
+
className,
|
|
820
|
+
queryJson: JSON.stringify(queryInput),
|
|
821
|
+
shapeJson: JSON.stringify(metadata),
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Parse raw model query/subscription result JSON into typed model instances.
|
|
826
|
+
* Used by ModelQueryBuilder to convert subscription updates without circular imports.
|
|
827
|
+
* @internal
|
|
828
|
+
*/
|
|
829
|
+
static parseModelResult(perspective, raw, include, properties) {
|
|
830
|
+
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
831
|
+
const arr = data.instances || data;
|
|
832
|
+
if (!Array.isArray(arr))
|
|
833
|
+
return [];
|
|
834
|
+
return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
673
835
|
}
|
|
836
|
+
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
674
837
|
/**
|
|
675
|
-
*
|
|
838
|
+
* Execute a model query via the executor-side endpoint.
|
|
676
839
|
*
|
|
677
|
-
*
|
|
678
|
-
*
|
|
679
|
-
* @param result - Array of result objects from SPARQL
|
|
680
|
-
* @returns Promise resolving to results with total count
|
|
840
|
+
* This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
|
|
841
|
+
* with a single RPC to the executor that handles everything in Rust.
|
|
681
842
|
*
|
|
682
843
|
* @internal
|
|
683
844
|
*/
|
|
684
|
-
static async
|
|
685
|
-
if (!result || result.length === 0)
|
|
686
|
-
return { results: [], totalCount: 0 };
|
|
845
|
+
static async executeModelQuery(perspective, query = {}, classNameOverride) {
|
|
687
846
|
const metadata = this.getModelMetadata();
|
|
688
|
-
const
|
|
689
|
-
//
|
|
690
|
-
//
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
// Use source_uri as the base (the actual URI), not the node ID
|
|
698
|
-
base = row.source_uri;
|
|
699
|
-
// Skip rows without a source_uri field
|
|
700
|
-
if (!base) {
|
|
701
|
-
continue;
|
|
702
|
-
}
|
|
703
|
-
const links = row.links || [];
|
|
704
|
-
const instance = new this(perspective, base);
|
|
705
|
-
// Core hydration via unified helper (pass requestedProperties for sparse fieldset).
|
|
706
|
-
// Also hydrate any properties referenced in `where` so the JS post-filter can match them,
|
|
707
|
-
// even if they're not in the user's `properties` projection.
|
|
708
|
-
let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
|
|
709
|
-
if (hydrationProps && query.where) {
|
|
710
|
-
for (const key of Object.keys(query.where)) {
|
|
711
|
-
if (!hydrationProps.includes(key)) {
|
|
712
|
-
hydrationProps.push(key);
|
|
713
|
-
}
|
|
714
|
-
}
|
|
847
|
+
const className = classNameOverride || metadata.className;
|
|
848
|
+
// Expand includeAll: true to a full IncludeMap covering every forward relation.
|
|
849
|
+
// Done before queryInput is built so all downstream uses of query.include see the expansion.
|
|
850
|
+
if (query.includeAll) {
|
|
851
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
852
|
+
const expanded = {};
|
|
853
|
+
for (const [relName, relMeta] of Object.entries(allRelMeta)) {
|
|
854
|
+
if (relMeta.direction !== 'reverse') {
|
|
855
|
+
expanded[relName] = true;
|
|
715
856
|
}
|
|
716
|
-
await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
|
|
717
|
-
// NOTE: Property deletion for sparse fieldsets is deferred until AFTER
|
|
718
|
-
// where-filtering so that where conditions can reference any property,
|
|
719
|
-
// even ones not in the `properties` projection.
|
|
720
|
-
instances.push(instance);
|
|
721
857
|
}
|
|
722
|
-
|
|
723
|
-
|
|
858
|
+
// Explicit include entries take precedence over the expansion
|
|
859
|
+
query = { ...query, include: { ...expanded, ...query.include } };
|
|
860
|
+
}
|
|
861
|
+
// Build the query input that the Rust endpoint expects.
|
|
862
|
+
// Convert the TS Query type to the executor's ModelQueryInput format.
|
|
863
|
+
const queryInput = {};
|
|
864
|
+
if (query.parent) {
|
|
865
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
866
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
867
|
+
}
|
|
868
|
+
if (query.properties)
|
|
869
|
+
queryInput.properties = query.properties;
|
|
870
|
+
if (query.include) {
|
|
871
|
+
// Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
|
|
872
|
+
// All other keys (boolean | RelationSubQuery) → queryInput.include
|
|
873
|
+
const normalIncludes = {};
|
|
874
|
+
const projections = {};
|
|
875
|
+
for (const [key, val] of Object.entries(query.include)) {
|
|
876
|
+
if (key.startsWith('$')) {
|
|
877
|
+
projections[key] = val;
|
|
878
|
+
}
|
|
879
|
+
else {
|
|
880
|
+
normalIncludes[key] = val;
|
|
881
|
+
}
|
|
724
882
|
}
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
inst[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
|
|
742
|
-
}
|
|
743
|
-
else {
|
|
744
|
-
inst[relName] = sourceIds;
|
|
883
|
+
if (Object.keys(normalIncludes).length > 0)
|
|
884
|
+
queryInput.include = normalIncludes;
|
|
885
|
+
if (Object.keys(projections).length > 0) {
|
|
886
|
+
// Enrich projections with target shapes so Rust can apply where clause filtering
|
|
887
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
888
|
+
for (const [, proj] of Object.entries(projections)) {
|
|
889
|
+
const relMeta = allRelMeta[proj.from];
|
|
890
|
+
if (!proj.targetShape && relMeta?.target) {
|
|
891
|
+
try {
|
|
892
|
+
const TargetClass = relMeta.target();
|
|
893
|
+
const targetMeta = TargetClass.getModelMetadata?.();
|
|
894
|
+
if (targetMeta) {
|
|
895
|
+
proj.targetShape = targetMeta;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
catch (_) { /* target class may not be available */ }
|
|
745
899
|
}
|
|
746
900
|
}
|
|
747
|
-
|
|
748
|
-
}
|
|
749
|
-
// Evaluate custom getters for all instances.
|
|
750
|
-
// Relation getters (type-conformance filtering) always run — they ensure
|
|
751
|
-
// correctness of @HasMany/@HasOne targets. Property getters only run when
|
|
752
|
-
// deepQuery is true or when where conditions reference getter-backed properties.
|
|
753
|
-
const whereGetterProperties = query.where
|
|
754
|
-
? Object.keys(query.where).filter((propName) => metadata.properties[propName]?.getter)
|
|
755
|
-
: [];
|
|
756
|
-
const shouldEvaluatePropertyGetters = query.deepQuery === true || whereGetterProperties.length > 0;
|
|
757
|
-
{
|
|
758
|
-
const skipPropertyGetters = !shouldEvaluatePropertyGetters;
|
|
759
|
-
const getterRequestedProperties = shouldEvaluatePropertyGetters
|
|
760
|
-
? (requestedProperties.length > 0
|
|
761
|
-
? Array.from(new Set([...requestedProperties, ...whereGetterProperties]))
|
|
762
|
-
: query.deepQuery === true
|
|
763
|
-
? [] // deepQuery: evaluate all getters
|
|
764
|
-
: whereGetterProperties) // only evaluate where-referenced getters
|
|
765
|
-
: [];
|
|
766
|
-
const getterOpts = {
|
|
767
|
-
...(getterRequestedProperties.length > 0 && { requestedProperties: getterRequestedProperties }),
|
|
768
|
-
...(query.include && { include: query.include }),
|
|
769
|
-
skipPropertyGetters,
|
|
770
|
-
};
|
|
771
|
-
for (const instance of instances) {
|
|
772
|
-
await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
|
|
901
|
+
queryInput.projections = projections;
|
|
773
902
|
}
|
|
774
903
|
}
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
904
|
+
if (query.where)
|
|
905
|
+
queryInput.where = query.where;
|
|
906
|
+
if (query.order) {
|
|
907
|
+
// Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
|
|
908
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
909
|
+
}
|
|
910
|
+
if (query.offset !== undefined)
|
|
911
|
+
queryInput.offset = query.offset;
|
|
912
|
+
if (query.limit !== undefined)
|
|
913
|
+
queryInput.limit = query.limit;
|
|
914
|
+
if (query.count !== undefined)
|
|
915
|
+
queryInput.count = query.count;
|
|
916
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
917
|
+
// Enrich relation metadata with target class shapes for Rust-side
|
|
918
|
+
// include resolution. This eliminates per-relation GraphQL round-trips
|
|
919
|
+
// by letting the Rust endpoint resolve includes in-process.
|
|
920
|
+
if (queryInput.include) {
|
|
921
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
922
|
+
enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
|
|
923
|
+
}
|
|
924
|
+
// ── Pre-compute conformance getters for Rust-side evaluation ──────
|
|
925
|
+
// For each relation with a target class and filter !== false, compute
|
|
926
|
+
// the conformance getter SPARQL so Rust can evaluate it in-process
|
|
927
|
+
// (eliminating N × querySparql round-trips per instance).
|
|
928
|
+
// When a relation has a `where` clause, compile the where conditions
|
|
929
|
+
// into the getter SPARQL so Rust applies them during evaluation.
|
|
930
|
+
{
|
|
931
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
932
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
933
|
+
const rel = relMeta;
|
|
934
|
+
if (rel.getter)
|
|
935
|
+
continue; // explicit getter already set
|
|
936
|
+
if (rel.direction === 'reverse')
|
|
937
|
+
continue; // reverse relations use reverse link lookup
|
|
938
|
+
if (rel.filter === false)
|
|
939
|
+
continue; // opt-out of conformance filtering
|
|
940
|
+
const meta = allRelMeta[relName];
|
|
941
|
+
if (!meta?.target)
|
|
942
|
+
continue;
|
|
943
|
+
try {
|
|
944
|
+
const TargetClass = meta.target();
|
|
945
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
946
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
947
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
948
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
949
|
+
// that can't be matched by value in SPARQL.
|
|
950
|
+
let whereConditions = [];
|
|
951
|
+
if (rel.where) {
|
|
952
|
+
try {
|
|
953
|
+
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
954
|
+
let allSparqlFilterable = true;
|
|
955
|
+
if (targetMetadata) {
|
|
956
|
+
for (const propName of Object.keys(rel.where)) {
|
|
957
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
958
|
+
continue;
|
|
959
|
+
const propMeta = targetMetadata.properties[propName];
|
|
960
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
961
|
+
allSparqlFilterable = false;
|
|
962
|
+
break;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
if (allSparqlFilterable) {
|
|
967
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
968
|
+
}
|
|
794
969
|
}
|
|
795
|
-
|
|
970
|
+
catch (_) { /* target metadata unavailable */ }
|
|
796
971
|
}
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
return false;
|
|
972
|
+
if (filter) {
|
|
973
|
+
let getter = filter.getter;
|
|
974
|
+
if (whereConditions.length > 0) {
|
|
975
|
+
// Append where conditions before the closing }
|
|
976
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
803
977
|
}
|
|
804
|
-
|
|
978
|
+
rel.getter = getter;
|
|
805
979
|
}
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
return false;
|
|
980
|
+
else if (whereConditions.length > 0) {
|
|
981
|
+
// No conformance filter but where clause exists — build getter from where alone
|
|
982
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
983
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
811
984
|
}
|
|
812
985
|
}
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
}
|
|
816
|
-
// Apply ordering in JavaScript
|
|
817
|
-
// If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
|
|
818
|
-
// This ensures consistent pagination behavior
|
|
819
|
-
const effectiveOrder = query.order ||
|
|
820
|
-
(query.limit !== undefined || query.offset !== undefined ? { createdAt: 'ASC' } : null);
|
|
821
|
-
if (effectiveOrder) {
|
|
822
|
-
const orderEntries = Object.entries(effectiveOrder);
|
|
823
|
-
filteredInstances.sort((a, b) => {
|
|
824
|
-
for (const [orderPropName, orderDirection] of orderEntries) {
|
|
825
|
-
let aVal = a[orderPropName];
|
|
826
|
-
let bVal = b[orderPropName];
|
|
827
|
-
// Handle undefined values - push them to the end
|
|
828
|
-
if (aVal === undefined && bVal === undefined)
|
|
829
|
-
continue;
|
|
830
|
-
if (aVal === undefined)
|
|
831
|
-
return orderDirection === 'ASC' ? 1 : -1;
|
|
832
|
-
if (bVal === undefined)
|
|
833
|
-
return orderDirection === 'ASC' ? -1 : 1;
|
|
834
|
-
// Compare values
|
|
835
|
-
let comparison = 0;
|
|
836
|
-
if (typeof aVal === 'number' && typeof bVal === 'number') {
|
|
837
|
-
comparison = aVal - bVal;
|
|
838
|
-
}
|
|
839
|
-
else if (typeof aVal === 'string' && typeof bVal === 'string') {
|
|
840
|
-
comparison = aVal.localeCompare(bVal);
|
|
841
|
-
}
|
|
842
|
-
else {
|
|
843
|
-
comparison = String(aVal).localeCompare(String(bVal));
|
|
844
|
-
}
|
|
845
|
-
if (comparison !== 0) {
|
|
846
|
-
return orderDirection === 'DESC' ? -comparison : comparison;
|
|
847
|
-
}
|
|
848
|
-
// comparison === 0: continue to next sort field
|
|
986
|
+
catch (e) {
|
|
987
|
+
// Target class may not be available; skip silently
|
|
849
988
|
}
|
|
850
|
-
return 0;
|
|
851
|
-
});
|
|
852
|
-
}
|
|
853
|
-
// Determine if SPARQL already applied LIMIT/OFFSET (i.e., the pagination
|
|
854
|
-
// subquery was used). When it was, skip JS-level slicing — instances are
|
|
855
|
-
// already the correct page.
|
|
856
|
-
const allRelsMeta2 = getRelationsMetadata(this);
|
|
857
|
-
const sparqlPaginated = !hasJsOnlyWhereFilters(metadata, allRelsMeta2, query.where)
|
|
858
|
-
&& (query.limit !== undefined || query.offset !== undefined)
|
|
859
|
-
&& query.order !== undefined && Object.keys(query.order).length > 0;
|
|
860
|
-
// Calculate totalCount BEFORE applying limit/offset.
|
|
861
|
-
// When SPARQL already paginated, filteredInstances.length is the page size,
|
|
862
|
-
// not the total — use a separate COUNT query for the real total.
|
|
863
|
-
// Only run the COUNT query when the caller actually needs it (computeTotalCount=true).
|
|
864
|
-
let totalCount;
|
|
865
|
-
if (sparqlPaginated && computeTotalCount) {
|
|
866
|
-
try {
|
|
867
|
-
const countSparql = buildSPARQLCountQuery(metadata, allRelsMeta2, query, this);
|
|
868
|
-
const countResult = await perspective.querySparql(countSparql);
|
|
869
|
-
totalCount = parseSparqlCount(countResult) ?? filteredInstances.length;
|
|
870
989
|
}
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
990
|
+
}
|
|
991
|
+
// Send shape metadata to the executor so it knows the model structure.
|
|
992
|
+
// This is more reliable than reading SHACL from the store because
|
|
993
|
+
// the TS decorators are the definitive source of truth.
|
|
994
|
+
const shapeJson = JSON.stringify(metadata);
|
|
995
|
+
const queryJson = JSON.stringify(queryInput);
|
|
996
|
+
// TEMP DEBUG: Log getters with where-clause filters to diagnose CI failure
|
|
997
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
998
|
+
const rel = relMeta;
|
|
999
|
+
if (rel.where) {
|
|
1000
|
+
console.log(`[MODEL_QUERY_DEBUG] relation="${relName}" getter=${rel.getter ?? 'NONE'} where=${JSON.stringify(rel.where)}`);
|
|
874
1001
|
}
|
|
875
1002
|
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
1003
|
+
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
1004
|
+
// Convert JSON instances to model class instances, recursively constructing
|
|
1005
|
+
// class instances for any included relations resolved by Rust.
|
|
1006
|
+
const instances = result.instances.map((json) => {
|
|
1007
|
+
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
1008
|
+
});
|
|
1009
|
+
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1010
|
+
// value is a content-addressed hash that must be fetched from the language
|
|
1011
|
+
// runtime). The Rust endpoint returns raw target URIs; we resolve them here.
|
|
1012
|
+
const propsMeta = getPropertiesMetadata(this);
|
|
1013
|
+
const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
|
|
1014
|
+
opts.resolveLanguage !== 'literal');
|
|
1015
|
+
if (resolveProps.length > 0) {
|
|
1016
|
+
await Promise.all(instances.map(async (inst) => {
|
|
1017
|
+
for (const [propName, opts] of resolveProps) {
|
|
1018
|
+
const val = inst[propName];
|
|
1019
|
+
if (typeof val !== 'string' || !val || val.startsWith('literal:'))
|
|
1020
|
+
continue;
|
|
1021
|
+
try {
|
|
1022
|
+
const expression = await perspective.getExpression(val);
|
|
1023
|
+
if (expression) {
|
|
1024
|
+
let resolved;
|
|
1025
|
+
try {
|
|
1026
|
+
resolved = JSON.parse(expression.data);
|
|
1027
|
+
}
|
|
1028
|
+
catch {
|
|
1029
|
+
resolved = expression.data;
|
|
1030
|
+
}
|
|
1031
|
+
const transform = opts.transform;
|
|
1032
|
+
inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
|
|
1033
|
+
}
|
|
906
1034
|
}
|
|
1035
|
+
catch (_) { /* resolution failed — keep raw value */ }
|
|
907
1036
|
}
|
|
908
|
-
}
|
|
1037
|
+
}));
|
|
909
1038
|
}
|
|
910
|
-
//
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
}
|
|
914
|
-
// Take snapshots for dirty tracking after ALL hydration is complete
|
|
915
|
-
// (including eager-loaded relations).
|
|
916
|
-
// When `include` is specified, only snapshot those relations.
|
|
917
|
-
// Otherwise snapshot ALL fields (properties + relations) since
|
|
918
|
-
// hydrateFromLinks populates relations with stable raw IDs —
|
|
919
|
-
// this ensures push-to-array + save() correctly detects dirty relations.
|
|
920
|
-
const snapshotRelations = query.include;
|
|
921
|
-
for (const inst of paginatedInstances) {
|
|
1039
|
+
// Take snapshots for dirty tracking
|
|
1040
|
+
const snapshotRelations = queryInput.include;
|
|
1041
|
+
for (const inst of instances) {
|
|
922
1042
|
inst.takeSnapshot(snapshotRelations);
|
|
923
1043
|
}
|
|
924
1044
|
return {
|
|
925
|
-
results:
|
|
926
|
-
totalCount
|
|
1045
|
+
results: instances,
|
|
1046
|
+
totalCount: result.totalCount,
|
|
927
1047
|
};
|
|
928
1048
|
}
|
|
929
1049
|
/**
|
|
@@ -953,31 +1073,12 @@ export class Ad4mModel {
|
|
|
953
1073
|
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
954
1074
|
* ```
|
|
955
1075
|
*/
|
|
956
|
-
static async findAll(perspective, query = {},
|
|
1076
|
+
static async findAll(perspective, query = {}, _engine) {
|
|
957
1077
|
if (query.properties && query.properties.length === 0) {
|
|
958
1078
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
959
1079
|
}
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
? (engine ? 'sparql' : 'prolog')
|
|
963
|
-
: engine;
|
|
964
|
-
if (resolvedEngine === 'sparql') {
|
|
965
|
-
// Always use the regular SPARQL path + JS-level hydrateRelations for includes.
|
|
966
|
-
// The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
|
|
967
|
-
// non-conforming node filtering, and parse_literal compatibility.
|
|
968
|
-
// hydrateRelations handles all of these correctly via per-relation findAll calls.
|
|
969
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
970
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
971
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
972
|
-
const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
|
|
973
|
-
return results;
|
|
974
|
-
}
|
|
975
|
-
else {
|
|
976
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
977
|
-
const result = await perspective.infer(prologQuery);
|
|
978
|
-
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
979
|
-
return results;
|
|
980
|
-
}
|
|
1080
|
+
const { results } = await this.executeModelQuery(perspective, query);
|
|
1081
|
+
return results;
|
|
981
1082
|
}
|
|
982
1083
|
/**
|
|
983
1084
|
* Finds the first instance matching the query, or `null` if none exists.
|
|
@@ -999,9 +1100,9 @@ export class Ad4mModel {
|
|
|
999
1100
|
* }
|
|
1000
1101
|
* ```
|
|
1001
1102
|
*/
|
|
1002
|
-
static async findOne(perspective, query = {},
|
|
1103
|
+
static async findOne(perspective, query = {}, _engine) {
|
|
1003
1104
|
const limitedQuery = { ...query, limit: 1 };
|
|
1004
|
-
const results = await this.findAll(perspective, limitedQuery
|
|
1105
|
+
const results = await this.findAll(perspective, limitedQuery);
|
|
1005
1106
|
return results[0] ?? null;
|
|
1006
1107
|
}
|
|
1007
1108
|
/**
|
|
@@ -1024,21 +1125,8 @@ export class Ad4mModel {
|
|
|
1024
1125
|
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
1025
1126
|
* ```
|
|
1026
1127
|
*/
|
|
1027
|
-
static async findAllAndCount(perspective, query = {},
|
|
1028
|
-
|
|
1029
|
-
? (engine ? 'sparql' : 'prolog')
|
|
1030
|
-
: engine;
|
|
1031
|
-
if (resolvedEngine === 'sparql') {
|
|
1032
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1033
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1034
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1035
|
-
return await this.instancesFromQueryResult(perspective, query, grouped, true);
|
|
1036
|
-
}
|
|
1037
|
-
else {
|
|
1038
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1039
|
-
const result = await perspective.infer(prologQuery);
|
|
1040
|
-
return await this.instancesFromPrologResult(perspective, query, result);
|
|
1041
|
-
}
|
|
1128
|
+
static async findAllAndCount(perspective, query = {}, _engine) {
|
|
1129
|
+
return await this.executeModelQuery(perspective, query);
|
|
1042
1130
|
}
|
|
1043
1131
|
/**
|
|
1044
1132
|
* Helper function for pagination with explicit page size and number.
|
|
@@ -1047,7 +1135,6 @@ export class Ad4mModel {
|
|
|
1047
1135
|
* @param pageSize - Number of items per page
|
|
1048
1136
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
1049
1137
|
* @param query - Optional additional query parameters
|
|
1050
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1051
1138
|
* @returns Paginated results with metadata
|
|
1052
1139
|
*
|
|
1053
1140
|
* @example
|
|
@@ -1056,47 +1143,12 @@ export class Ad4mModel {
|
|
|
1056
1143
|
* where: { category: "Main Course" }
|
|
1057
1144
|
* });
|
|
1058
1145
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1059
|
-
*
|
|
1060
|
-
* // Use Prolog explicitly (legacy)
|
|
1061
|
-
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
1062
1146
|
* ```
|
|
1063
1147
|
*/
|
|
1064
|
-
static async paginate(perspective, pageSize, pageNumber, query,
|
|
1148
|
+
static async paginate(perspective, pageSize, pageNumber, query, _engine) {
|
|
1065
1149
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1066
|
-
const
|
|
1067
|
-
|
|
1068
|
-
: engine;
|
|
1069
|
-
if (resolvedEngine === 'sparql') {
|
|
1070
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
|
|
1071
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1072
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1073
|
-
const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped, true);
|
|
1074
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1075
|
-
}
|
|
1076
|
-
else {
|
|
1077
|
-
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
1078
|
-
const result = await perspective.infer(prologQuery);
|
|
1079
|
-
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
1080
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
static async countQueryToProlog(perspective, query = {}, modelClassName) {
|
|
1084
|
-
const { where } = query;
|
|
1085
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
1086
|
-
const resolvedParentPredicate = query.parent
|
|
1087
|
-
? resolveParentPredicate(query.parent, this)
|
|
1088
|
-
: undefined;
|
|
1089
|
-
const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
|
|
1090
|
-
const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
|
|
1091
|
-
const fullQuery = `
|
|
1092
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
1093
|
-
subject_class("${className}", SubjectClass),
|
|
1094
|
-
instance(SubjectClass, Base),
|
|
1095
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
1096
|
-
), UnsortedInstances),
|
|
1097
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
1098
|
-
`;
|
|
1099
|
-
return fullQuery;
|
|
1150
|
+
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
1151
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1100
1152
|
}
|
|
1101
1153
|
/**
|
|
1102
1154
|
* Generates a SPARQL COUNT query for the model.
|
|
@@ -1107,17 +1159,12 @@ export class Ad4mModel {
|
|
|
1107
1159
|
*
|
|
1108
1160
|
* @private
|
|
1109
1161
|
*/
|
|
1110
|
-
|
|
1111
|
-
const metadata = this.getModelMetadata();
|
|
1112
|
-
const allRelMeta = getRelationsMetadata(this);
|
|
1113
|
-
return buildSPARQLCountQuery(metadata, allRelMeta, query, this);
|
|
1114
|
-
}
|
|
1162
|
+
// countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
|
|
1115
1163
|
/**
|
|
1116
1164
|
* Gets a count of all matching instances.
|
|
1117
1165
|
*
|
|
1118
1166
|
* @param perspective - The perspective to search in
|
|
1119
1167
|
* @param query - Optional query parameters to filter results
|
|
1120
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1121
1168
|
* @returns Total count of matching entities
|
|
1122
1169
|
*
|
|
1123
1170
|
* @example
|
|
@@ -1126,37 +1173,11 @@ export class Ad4mModel {
|
|
|
1126
1173
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
1127
1174
|
* where: { status: "active" }
|
|
1128
1175
|
* });
|
|
1129
|
-
*
|
|
1130
|
-
* // Use Prolog explicitly (legacy)
|
|
1131
|
-
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
1132
1176
|
* ```
|
|
1133
1177
|
*/
|
|
1134
|
-
static async count(perspective, query = {}
|
|
1135
|
-
const
|
|
1136
|
-
|
|
1137
|
-
: engine;
|
|
1138
|
-
if (resolvedEngine === 'sparql') {
|
|
1139
|
-
// When query has JS-only where filters (gt, between, author, timestamp, etc.),
|
|
1140
|
-
// we must fall back to full hydration + JS filtering to get accurate count.
|
|
1141
|
-
const metadata = this.getModelMetadata();
|
|
1142
|
-
const allRelMeta = getRelationsMetadata(this);
|
|
1143
|
-
if (hasJsOnlyWhereFilters(metadata, allRelMeta, query.where)) {
|
|
1144
|
-
// Fall back to full query + JS filter path for accurate count
|
|
1145
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1146
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1147
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1148
|
-
const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped, true);
|
|
1149
|
-
return totalCount;
|
|
1150
|
-
}
|
|
1151
|
-
// No JS-only filters — use efficient COUNT query
|
|
1152
|
-
const countSparql = await this.countQueryToSPARQL(perspective, query);
|
|
1153
|
-
const countResult = await perspective.querySparql(countSparql);
|
|
1154
|
-
return parseSparqlCount(countResult) ?? 0;
|
|
1155
|
-
}
|
|
1156
|
-
else {
|
|
1157
|
-
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
1158
|
-
return result?.[0]?.TotalCount || 0;
|
|
1159
|
-
}
|
|
1178
|
+
static async count(perspective, query = {}) {
|
|
1179
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
1180
|
+
return totalCount;
|
|
1160
1181
|
}
|
|
1161
1182
|
async setProperty(key, value, batchId) {
|
|
1162
1183
|
const metadata = this.getPropertyMetadata(key);
|
|
@@ -1442,10 +1463,10 @@ export class Ad4mModel {
|
|
|
1442
1463
|
/**
|
|
1443
1464
|
* Evaluate SPARQL getters for a batch of instances on demand.
|
|
1444
1465
|
*
|
|
1445
|
-
*
|
|
1446
|
-
*
|
|
1447
|
-
*
|
|
1448
|
-
* a
|
|
1466
|
+
* Since deepQuery defaults to true, property getters are evaluated
|
|
1467
|
+
* automatically during collection queries. Use this method when
|
|
1468
|
+
* deepQuery was explicitly set to false and you want to lazily
|
|
1469
|
+
* resolve getter-backed properties for a subset of instances.
|
|
1449
1470
|
*
|
|
1450
1471
|
* @param instances - Array of model instances to evaluate getters on
|
|
1451
1472
|
* @param perspective - The perspective to query against
|
|
@@ -1454,8 +1475,8 @@ export class Ad4mModel {
|
|
|
1454
1475
|
*
|
|
1455
1476
|
* @example
|
|
1456
1477
|
* ```typescript
|
|
1457
|
-
* const messages = await Message.
|
|
1458
|
-
* // messages[i].replyingTo is undefined (getter skipped
|
|
1478
|
+
* const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
|
|
1479
|
+
* // messages[i].replyingTo is undefined (getter skipped)
|
|
1459
1480
|
*
|
|
1460
1481
|
* // Evaluate getters for the visible subset
|
|
1461
1482
|
* await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
|
|
@@ -1466,10 +1487,28 @@ export class Ad4mModel {
|
|
|
1466
1487
|
if (instances.length === 0)
|
|
1467
1488
|
return;
|
|
1468
1489
|
const metadata = this.getModelMetadata();
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1490
|
+
// Pre-compute conformance getters so the shape sent to Rust includes them
|
|
1491
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
1492
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1493
|
+
const rel = relMeta;
|
|
1494
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
|
|
1495
|
+
continue;
|
|
1496
|
+
const meta = allRelMeta[relName];
|
|
1497
|
+
if (!meta?.target)
|
|
1498
|
+
continue;
|
|
1499
|
+
try {
|
|
1500
|
+
const TargetClass = meta.target();
|
|
1501
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1502
|
+
if (filter)
|
|
1503
|
+
rel.getter = filter.getter;
|
|
1504
|
+
}
|
|
1505
|
+
catch (_) { /* target class may not be available */ }
|
|
1506
|
+
}
|
|
1507
|
+
const shapeJson = JSON.stringify(metadata);
|
|
1508
|
+
const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
|
|
1509
|
+
// Single RPC call evaluates all getters in-process on the executor
|
|
1510
|
+
const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
|
|
1511
|
+
// Determine which property names were evaluated for snapshot sync
|
|
1473
1512
|
const evaluatedPropertyNames = [];
|
|
1474
1513
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1475
1514
|
if (propMeta.getter) {
|
|
@@ -1478,13 +1517,24 @@ export class Ad4mModel {
|
|
|
1478
1517
|
}
|
|
1479
1518
|
}
|
|
1480
1519
|
}
|
|
1520
|
+
// Also include relation getters
|
|
1521
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1522
|
+
if (relMeta.getter) {
|
|
1523
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
|
|
1524
|
+
evaluatedPropertyNames.push(relName);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
// Apply results to instances and sync snapshots
|
|
1481
1529
|
for (const instance of instances) {
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1530
|
+
const id = instance.id || instance._baseExpression;
|
|
1531
|
+
const props = result[id];
|
|
1532
|
+
if (props) {
|
|
1533
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1534
|
+
instance[key] = value;
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
// Sync snapshot so isDirty() doesn't flag getter-only changes
|
|
1488
1538
|
const modelInstance = instance;
|
|
1489
1539
|
if (modelInstance._snapshot) {
|
|
1490
1540
|
for (const propName of evaluatedPropertyNames) {
|
|
@@ -1861,5 +1911,111 @@ export class Ad4mModel {
|
|
|
1861
1911
|
static fromJSONSchema(schema, options) {
|
|
1862
1912
|
return buildModelFromJSONSchema(this, schema, options);
|
|
1863
1913
|
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Creates a fully functional Ad4mModel subclass from a SHACL shape.
|
|
1916
|
+
*
|
|
1917
|
+
* Unlike `fromJSONSchema()`, no predicate inference is required —
|
|
1918
|
+
* `SHACLShape` already contains the exact predicate URI in `path` for
|
|
1919
|
+
* every property. The method reads each property's `path`, `maxCount`,
|
|
1920
|
+
* `writable`, and `resolveLanguage` directly and writes them to the
|
|
1921
|
+
* WeakMap metadata registries.
|
|
1922
|
+
*
|
|
1923
|
+
* Properties with `hasValue` (flag / type-discrimination markers) are
|
|
1924
|
+
* registered as hidden flag entries so that the SPARQL query builder emits
|
|
1925
|
+
* the fixed triple `?source <predicate> <value>` needed for type discrimination.
|
|
1926
|
+
* Properties without a `name` field are skipped.
|
|
1927
|
+
*
|
|
1928
|
+
* **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
|
|
1929
|
+
* was persisted on property shapes) carry the flag value only in
|
|
1930
|
+
* `shape.constructor_actions` as the `target` of an `addLink` action.
|
|
1931
|
+
* This method recovers those values so that old perspectives are queried
|
|
1932
|
+
* with the correct type-discriminator triple.
|
|
1933
|
+
*
|
|
1934
|
+
* @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
|
|
1935
|
+
* @param name - Class name to assign (e.g. "Channel")
|
|
1936
|
+
* @returns Generated Ad4mModel subclass, ready for querying
|
|
1937
|
+
*/
|
|
1938
|
+
/**
|
|
1939
|
+
* Synthesise an `Ad4mModel` subclass from a SHACL shape.
|
|
1940
|
+
*
|
|
1941
|
+
* @param shape - The SHACL shape to synthesise from.
|
|
1942
|
+
* @param name - The model name (e.g. "Channel").
|
|
1943
|
+
* @param classResolver - Optional thunk factory. When provided, any collection
|
|
1944
|
+
* property that carries a `sh:class` URI will have its `target` wired up lazily:
|
|
1945
|
+
* `target: () => classResolver(localName)`. Because `target` is only called at
|
|
1946
|
+
* query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
|
|
1947
|
+
* resolver just needs to return the correct class by the time a query runs —
|
|
1948
|
+
* making it safe to pass a closure over a registry object that is still being
|
|
1949
|
+
* populated (e.g. the `result` record inside `getModelClasses`).
|
|
1950
|
+
*/
|
|
1951
|
+
static fromSHACL(shape, name, classResolver) {
|
|
1952
|
+
const DynamicModelClass = class extends this {
|
|
1953
|
+
};
|
|
1954
|
+
DynamicModelClass.className = name;
|
|
1955
|
+
DynamicModelClass.prototype.className = name;
|
|
1956
|
+
// Build a backward-compat fallback map: predicate → fixed-IRI-value from
|
|
1957
|
+
// constructor actions. Old SHACL stores (created before sh:hasValue was
|
|
1958
|
+
// persisted on the property shape) don't carry sh:hasValue on properties,
|
|
1959
|
+
// but the shape-level constructor_actions always contain an addLink action
|
|
1960
|
+
// with the fixed flag value as the target.
|
|
1961
|
+
const flagValueFromConstructor = new Map();
|
|
1962
|
+
for (const action of shape.constructor_actions ?? []) {
|
|
1963
|
+
if (action.action === 'addLink' &&
|
|
1964
|
+
typeof action.predicate === 'string' &&
|
|
1965
|
+
typeof action.target === 'string' &&
|
|
1966
|
+
action.target !== 'value' &&
|
|
1967
|
+
!action.target.startsWith('literal:')) {
|
|
1968
|
+
flagValueFromConstructor.set(action.predicate, action.target);
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
for (const prop of shape.properties) {
|
|
1972
|
+
const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
|
|
1973
|
+
if (resolvedHasValue !== undefined) {
|
|
1974
|
+
const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
|
|
1975
|
+
setPropertyRegistryEntry(DynamicModelClass, flagKey, {
|
|
1976
|
+
through: prop.path,
|
|
1977
|
+
required: true,
|
|
1978
|
+
initial: resolvedHasValue,
|
|
1979
|
+
flag: true,
|
|
1980
|
+
writable: false,
|
|
1981
|
+
readOnly: true,
|
|
1982
|
+
});
|
|
1983
|
+
continue;
|
|
1984
|
+
}
|
|
1985
|
+
// Skip properties without a declared name
|
|
1986
|
+
if (!prop.name)
|
|
1987
|
+
continue;
|
|
1988
|
+
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
1989
|
+
if (isCollection) {
|
|
1990
|
+
// Derive a lazy `target` thunk when a sh:class URI is present and a
|
|
1991
|
+
// classResolver was supplied. The thunk is evaluated at query time so
|
|
1992
|
+
// it is safe even if the target class hasn't been registered yet.
|
|
1993
|
+
let targetThunk;
|
|
1994
|
+
if (prop.class && classResolver) {
|
|
1995
|
+
const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
|
|
1996
|
+
const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
|
|
1997
|
+
targetThunk = () => classResolver(localName);
|
|
1998
|
+
}
|
|
1999
|
+
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
2000
|
+
predicate: prop.path,
|
|
2001
|
+
kind: 'hasMany',
|
|
2002
|
+
...(targetThunk !== undefined && { target: targetThunk }),
|
|
2003
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2004
|
+
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
2005
|
+
});
|
|
2006
|
+
}
|
|
2007
|
+
else {
|
|
2008
|
+
setPropertyRegistryEntry(DynamicModelClass, prop.name, {
|
|
2009
|
+
through: prop.path,
|
|
2010
|
+
writable: prop.writable ?? true,
|
|
2011
|
+
...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
|
|
2012
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
const ModelDecorator = Model({ name });
|
|
2017
|
+
ModelDecorator(DynamicModelClass);
|
|
2018
|
+
return DynamicModelClass;
|
|
2019
|
+
}
|
|
1864
2020
|
}
|
|
1865
2021
|
Ad4mModel.classNamesByClass = new WeakMap();
|