@coasys/ad4m 0.13.0-test-3 → 0.13.0-test-4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -25
- package/jest-setup.ts +1 -1
- package/lib/index.cjs +2406 -11070
- package/lib/index.js +2209 -10925
- package/lib/src/Ad4mClient.d.ts +7 -3
- package/lib/src/Ad4mClient.js +29 -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 +57 -38
- package/lib/src/model/Ad4mModel.js +594 -460
- package/lib/src/model/Ad4mModel.test.js +371 -815
- package/lib/src/model/ModelQueryBuilder.d.ts +9 -21
- package/lib/src/model/ModelQueryBuilder.js +138 -217
- package/lib/src/model/decorators.d.ts +22 -0
- package/lib/src/model/decorators.js +7 -0
- package/lib/src/model/hydration.d.ts +7 -60
- package/lib/src/model/hydration.js +7 -716
- 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/shacl-gen.js +4 -0
- package/lib/src/model/types.d.ts +47 -38
- 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 +12 -17
- package/lib/src/perspectives/PerspectiveClient.js +169 -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 +92 -71
- package/lib/src/perspectives/PerspectiveProxy.js +273 -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 +9 -24
- package/rollup.config.js +0 -7
- package/src/Ad4mClient.test.ts +1179 -1340
- package/src/Ad4mClient.ts +30 -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 +708 -876
- package/src/model/Ad4mModel.ts +613 -508
- package/src/model/ModelQueryBuilder.ts +178 -244
- package/src/model/decorators.ts +29 -0
- package/src/model/hydration.ts +9 -766
- 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/shacl-gen.ts +5 -0
- package/src/model/types.ts +51 -39
- 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 +228 -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 +307 -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
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -3,30 +3,180 @@ 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 { formatQueryValue } from "./query-utils";
|
|
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
|
|
15
|
-
import { buildBatchSPARQLQuery } from "./query-sparql-batch";
|
|
16
|
-
import { hydrateBatchResult } from "./hydration-batch";
|
|
14
|
+
import { buildSPARQLQuery } from "./query-sparql";
|
|
17
15
|
import { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
18
16
|
import {
|
|
19
|
-
normalizeValue,
|
|
20
|
-
assignValuesToInstance as _assignValuesToInstance,
|
|
17
|
+
normalizeValue,
|
|
21
18
|
evaluateCustomGettersForInstance,
|
|
22
|
-
hydrateRelations,
|
|
23
19
|
} from "./hydration";
|
|
24
20
|
import type {
|
|
25
21
|
ParentScope, IncludeMap, Query,
|
|
26
22
|
GetOptions, AllInstancesResult, ResultsWithTotalCount,
|
|
27
|
-
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
23
|
+
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
24
|
+
IncludeProjection,
|
|
28
25
|
} from "./types";
|
|
29
26
|
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Helpers for Rust-side include resolution
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Recursively enrich relation metadata in the shape with target class shapes
|
|
34
|
+
* so the Rust endpoint can resolve includes in-process (no extra GraphQL
|
|
35
|
+
* round-trips per relation).
|
|
36
|
+
*/
|
|
37
|
+
function enrichShapeForIncludes(
|
|
38
|
+
metadata: ModelMetadata,
|
|
39
|
+
include: IncludeMap,
|
|
40
|
+
allRelMeta: Record<string, RelationMetadataEntry>,
|
|
41
|
+
): void {
|
|
42
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
43
|
+
if (!includeVal) continue;
|
|
44
|
+
const meta = allRelMeta[relName];
|
|
45
|
+
if (!meta?.target) continue;
|
|
46
|
+
|
|
47
|
+
const TargetClass = meta.target() as typeof Ad4mModel;
|
|
48
|
+
// Deep-copy so we don't mutate the cached metadata
|
|
49
|
+
const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
|
|
50
|
+
|
|
51
|
+
// Ensure the relation is in metadata.relations (fallback for edge cases)
|
|
52
|
+
if (!metadata.relations[relName]) {
|
|
53
|
+
metadata.relations[relName] = {
|
|
54
|
+
name: relName,
|
|
55
|
+
predicate: meta.predicate,
|
|
56
|
+
direction:
|
|
57
|
+
meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
|
|
58
|
+
? 'reverse'
|
|
59
|
+
: 'forward',
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const rel = metadata.relations[relName] as any;
|
|
63
|
+
rel.kind = meta.kind;
|
|
64
|
+
rel.maxCount = meta.maxCount;
|
|
65
|
+
rel.targetShape = targetMeta;
|
|
66
|
+
rel.targetClassName = targetMeta.className;
|
|
67
|
+
|
|
68
|
+
// Recurse for nested includes
|
|
69
|
+
const nested =
|
|
70
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
71
|
+
? (includeVal as any).include
|
|
72
|
+
: undefined;
|
|
73
|
+
if (nested) {
|
|
74
|
+
const targetRelMeta = getRelationsMetadata(TargetClass as any);
|
|
75
|
+
enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
82
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
83
|
+
* back as plain JSON objects) into proper model class instances.
|
|
84
|
+
*/
|
|
85
|
+
function jsonToModelInstance<T extends Ad4mModel>(
|
|
86
|
+
ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
87
|
+
perspective: PerspectiveProxy,
|
|
88
|
+
json: any,
|
|
89
|
+
include?: IncludeMap,
|
|
90
|
+
properties?: string[],
|
|
91
|
+
): T {
|
|
92
|
+
const instance = new ModelClass(perspective, json.id || json.baseExpression) as any;
|
|
93
|
+
|
|
94
|
+
// When a properties projection is active, remove own properties set by the
|
|
95
|
+
// constructor that are not in the projected JSON. This ensures assertions
|
|
96
|
+
// like `expect(r).to.not.have.own.property("body")` pass.
|
|
97
|
+
if (properties) {
|
|
98
|
+
const jsonKeys = new Set(Object.keys(json));
|
|
99
|
+
for (const key of Object.getOwnPropertyNames(instance)) {
|
|
100
|
+
// Keep internal fields (backing store for getters), id, baseExpression, perspective
|
|
101
|
+
if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_')) continue;
|
|
102
|
+
if (!jsonKeys.has(key)) {
|
|
103
|
+
delete instance[key];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
for (const [key, value] of Object.entries(json)) {
|
|
109
|
+
if (key === 'baseExpression' || key === 'id') continue;
|
|
110
|
+
|
|
111
|
+
// Skip getter-only properties anywhere in the prototype chain
|
|
112
|
+
let isReadonly = false;
|
|
113
|
+
let proto = Object.getPrototypeOf(instance);
|
|
114
|
+
while (proto) {
|
|
115
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
116
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
117
|
+
proto = Object.getPrototypeOf(proto);
|
|
118
|
+
}
|
|
119
|
+
if (isReadonly) continue;
|
|
120
|
+
|
|
121
|
+
// Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
|
|
122
|
+
if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
|
|
123
|
+
instance[key] = new Date(value).getTime();
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
instance[key] = value;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Apply property transform functions from decorators (only for literal-resolved
|
|
131
|
+
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
132
|
+
// asynchronously in executeModelQuery).
|
|
133
|
+
try {
|
|
134
|
+
const propsMeta = getPropertiesMetadata(ModelClass as any);
|
|
135
|
+
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
136
|
+
const o = opts as any;
|
|
137
|
+
if (typeof o.transform !== 'function' || !(propName in json)) continue;
|
|
138
|
+
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
139
|
+
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
|
|
140
|
+
instance[propName] = o.transform(instance[propName]);
|
|
141
|
+
}
|
|
142
|
+
} catch (_) { /* no metadata available */ }
|
|
143
|
+
|
|
144
|
+
// Recursively convert included relation values to class instances
|
|
145
|
+
if (include) {
|
|
146
|
+
const relMeta = getRelationsMetadata(ModelClass as any);
|
|
147
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
148
|
+
if (!includeVal) continue;
|
|
149
|
+
const meta = relMeta[relName];
|
|
150
|
+
if (!meta?.target) continue;
|
|
151
|
+
const TargetClass = meta.target() as any;
|
|
152
|
+
const nestedInclude =
|
|
153
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
154
|
+
? (includeVal as any).include
|
|
155
|
+
: undefined;
|
|
156
|
+
const nestedProperties =
|
|
157
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
158
|
+
? (includeVal as any).properties
|
|
159
|
+
: undefined;
|
|
160
|
+
|
|
161
|
+
const raw = instance[relName];
|
|
162
|
+
if (Array.isArray(raw)) {
|
|
163
|
+
instance[relName] = raw.map((item: any) => {
|
|
164
|
+
if (typeof item === 'object' && item !== null && item.id) {
|
|
165
|
+
return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
|
|
166
|
+
}
|
|
167
|
+
return item;
|
|
168
|
+
});
|
|
169
|
+
} else if (typeof raw === 'object' && raw !== null && raw.id) {
|
|
170
|
+
instance[relName] = jsonToModelInstance(
|
|
171
|
+
TargetClass, perspective, raw, nestedInclude, nestedProperties,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return instance;
|
|
178
|
+
}
|
|
179
|
+
|
|
30
180
|
/**
|
|
31
181
|
* Base class for defining data models in AD4M.
|
|
32
182
|
*
|
|
@@ -131,6 +281,14 @@ export class Ad4mModel {
|
|
|
131
281
|
createdAt: any;
|
|
132
282
|
updatedAt: any;
|
|
133
283
|
|
|
284
|
+
/**
|
|
285
|
+
* Backwards compatibility alias for createdAt.
|
|
286
|
+
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
287
|
+
*/
|
|
288
|
+
get timestamp(): any {
|
|
289
|
+
return (this as any).createdAt;
|
|
290
|
+
}
|
|
291
|
+
|
|
134
292
|
private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
|
|
135
293
|
|
|
136
294
|
/**
|
|
@@ -177,14 +335,6 @@ export class Ad4mModel {
|
|
|
177
335
|
return classCache[perspectiveID];
|
|
178
336
|
}
|
|
179
337
|
|
|
180
|
-
/**
|
|
181
|
-
* Backwards compatibility alias for createdAt.
|
|
182
|
-
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
183
|
-
*/
|
|
184
|
-
get timestamp(): any {
|
|
185
|
-
return (this as any).createdAt;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
338
|
/**
|
|
189
339
|
* Extracts metadata from decorators for query building.
|
|
190
340
|
*
|
|
@@ -261,9 +411,7 @@ export class Ad4mModel {
|
|
|
261
411
|
// Extract relations (relations) from WeakMap registry
|
|
262
412
|
const relationsMetadata: Record<string, RelationMetadata> = {};
|
|
263
413
|
const allRelationsMeta = getRelationsMetadata(this as any);
|
|
264
|
-
const prototypeRelations =
|
|
265
|
-
Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
|
|
266
|
-
);
|
|
414
|
+
const prototypeRelations = allRelationsMeta;
|
|
267
415
|
|
|
268
416
|
for (const [relationName, opts] of Object.entries(prototypeRelations)) {
|
|
269
417
|
const options = opts as RelationMetadataEntry;
|
|
@@ -273,6 +421,8 @@ export class Ad4mModel {
|
|
|
273
421
|
...(options.local !== undefined && { local: options.local }),
|
|
274
422
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
275
423
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
424
|
+
...(options.kind !== undefined && { kind: options.kind }),
|
|
425
|
+
...(options.maxCount !== undefined && { maxCount: options.maxCount }),
|
|
276
426
|
...(options.target !== undefined && { target: options.target }),
|
|
277
427
|
...(options.filter !== undefined && { filter: options.filter }),
|
|
278
428
|
...(options.where !== undefined && { where: options.where }),
|
|
@@ -359,13 +509,6 @@ export class Ad4mModel {
|
|
|
359
509
|
return this._baseExpression;
|
|
360
510
|
}
|
|
361
511
|
|
|
362
|
-
/**
|
|
363
|
-
* @deprecated Use `.id` instead. Will be removed in a future version.
|
|
364
|
-
*/
|
|
365
|
-
get baseExpression(): string {
|
|
366
|
-
return this._baseExpression;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
512
|
/**
|
|
370
513
|
* Protected getter for the perspective.
|
|
371
514
|
* Allows subclasses to access the perspective while keeping it private from external code.
|
|
@@ -462,14 +605,6 @@ export class Ad4mModel {
|
|
|
462
605
|
}];
|
|
463
606
|
}
|
|
464
607
|
|
|
465
|
-
/**
|
|
466
|
-
* Assigns decoded Prolog property values to an instance.
|
|
467
|
-
* Delegates to the standalone function in hydration.ts.
|
|
468
|
-
*/
|
|
469
|
-
public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
|
|
470
|
-
return _assignValuesToInstance(perspective, instance, values);
|
|
471
|
-
}
|
|
472
|
-
|
|
473
608
|
// ──────────────────────────────────────────────────────────
|
|
474
609
|
// Snapshot / dirty tracking
|
|
475
610
|
// ──────────────────────────────────────────────────────────
|
|
@@ -603,89 +738,50 @@ export class Ad4mModel {
|
|
|
603
738
|
}
|
|
604
739
|
|
|
605
740
|
private async getData(opts?: GetOptions) {
|
|
606
|
-
//
|
|
607
|
-
//
|
|
741
|
+
// Route through the Rust model query endpoint — same pipeline as executeModelQuery
|
|
742
|
+
// but for a single instance by ID.
|
|
608
743
|
try {
|
|
609
744
|
const ctor = this.constructor as typeof Ad4mModel;
|
|
610
|
-
const
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
745
|
+
const query: Query = {
|
|
746
|
+
where: { id: this._baseExpression },
|
|
747
|
+
limit: 1,
|
|
748
|
+
};
|
|
749
|
+
if (opts?.properties) query.properties = opts.properties;
|
|
750
|
+
if (opts?.include) query.include = opts.include;
|
|
615
751
|
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
|
|
620
|
-
}
|
|
752
|
+
const { results } = await (ctor as any).executeModelQuery(
|
|
753
|
+
this._perspective, query, null
|
|
754
|
+
);
|
|
621
755
|
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
(this as any)[
|
|
756
|
+
if (results.length > 0) {
|
|
757
|
+
const hydrated = results[0];
|
|
758
|
+
// Copy all hydrated values from the Rust-side result onto this instance
|
|
759
|
+
for (const [key, value] of Object.entries(hydrated as any)) {
|
|
760
|
+
if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot') continue;
|
|
761
|
+
if (key.startsWith('_')) continue;
|
|
762
|
+
// Check for readonly getters
|
|
763
|
+
let isReadonly = false;
|
|
764
|
+
let proto = Object.getPrototypeOf(this);
|
|
765
|
+
while (proto) {
|
|
766
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
767
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
768
|
+
proto = Object.getPrototypeOf(proto);
|
|
769
|
+
}
|
|
770
|
+
if (isReadonly) continue;
|
|
771
|
+
(this as any)[key] = value;
|
|
638
772
|
}
|
|
639
773
|
}
|
|
640
774
|
|
|
641
|
-
//
|
|
642
|
-
|
|
643
|
-
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
644
|
-
: undefined;
|
|
645
|
-
await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
|
|
646
|
-
|
|
647
|
-
// Eager-load relations if requested
|
|
648
|
-
if (opts?.include) {
|
|
649
|
-
await hydrateRelations(ctor, [this], this._perspective, opts.include);
|
|
650
|
-
}
|
|
775
|
+
// Property getters and relation conformance getters are now evaluated
|
|
776
|
+
// Rust-side via evaluate_getters() in model_query.rs.
|
|
651
777
|
} catch (e) {
|
|
652
|
-
console.error(`
|
|
778
|
+
console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
|
|
653
779
|
}
|
|
654
780
|
|
|
655
|
-
this.takeSnapshot();
|
|
781
|
+
this.takeSnapshot(opts?.include);
|
|
656
782
|
return this;
|
|
657
783
|
}
|
|
658
784
|
|
|
659
|
-
public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
|
|
660
|
-
const { properties, where, order, offset, limit, count } = query;
|
|
661
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
662
|
-
|
|
663
|
-
// Resolve parent predicate from model metadata if needed
|
|
664
|
-
const resolvedParentPredicate = query.parent
|
|
665
|
-
? resolveParentPredicate(query.parent, this)
|
|
666
|
-
: undefined;
|
|
667
|
-
|
|
668
|
-
const instanceQueries = [
|
|
669
|
-
buildAuthorAndTimestampQuery(),
|
|
670
|
-
buildParentQuery(query.parent, resolvedParentPredicate),
|
|
671
|
-
buildPropertiesQuery(properties),
|
|
672
|
-
buildWhereQuery(where),
|
|
673
|
-
];
|
|
674
|
-
|
|
675
|
-
const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
|
|
676
|
-
|
|
677
|
-
const fullQuery = `
|
|
678
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
679
|
-
subject_class("${className}", SubjectClass),
|
|
680
|
-
instance(SubjectClass, Base),
|
|
681
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
682
|
-
), UnsortedInstances),
|
|
683
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
684
|
-
`;
|
|
685
|
-
|
|
686
|
-
return fullQuery;
|
|
687
|
-
}
|
|
688
|
-
|
|
689
785
|
/**
|
|
690
786
|
* Generates a SPARQL query from a Query object.
|
|
691
787
|
*
|
|
@@ -728,341 +824,360 @@ export class Ad4mModel {
|
|
|
728
824
|
return buildSPARQLQuery(metadata, allRelMeta, query, this);
|
|
729
825
|
}
|
|
730
826
|
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
const
|
|
741
|
-
|
|
827
|
+
/**
|
|
828
|
+
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
829
|
+
* Returns the className, queryJson, and shapeJson that the Rust executor expects.
|
|
830
|
+
* @internal
|
|
831
|
+
*/
|
|
832
|
+
static prepareModelQueryParams(
|
|
833
|
+
query: Query = {},
|
|
834
|
+
classNameOverride?: string | null,
|
|
835
|
+
): { className: string; queryJson: string; shapeJson: string } {
|
|
836
|
+
const metadata = this.getModelMetadata();
|
|
837
|
+
const className = classNameOverride || metadata.className;
|
|
838
|
+
|
|
839
|
+
const queryInput: any = {};
|
|
840
|
+
if (query.parent) {
|
|
841
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
842
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
843
|
+
}
|
|
844
|
+
if (query.properties) queryInput.properties = query.properties;
|
|
845
|
+
if (query.include) queryInput.include = query.include;
|
|
846
|
+
if (query.where) queryInput.where = query.where;
|
|
847
|
+
if (query.order) {
|
|
848
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
849
|
+
}
|
|
850
|
+
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
851
|
+
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
852
|
+
if (query.count !== undefined) queryInput.count = query.count;
|
|
853
|
+
|
|
854
|
+
if (query.include) {
|
|
855
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
856
|
+
enrichShapeForIncludes(metadata, query.include, allRelMeta);
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// Pre-compute conformance getters (with where-clause support)
|
|
860
|
+
{
|
|
861
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
862
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
863
|
+
const rel = relMeta as any;
|
|
864
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
865
|
+
const meta = allRelMeta[relName];
|
|
866
|
+
if (!meta?.target) continue;
|
|
742
867
|
try {
|
|
743
|
-
const
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
868
|
+
const TargetClass = meta.target();
|
|
869
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
870
|
+
|
|
871
|
+
// Only compile where clauses to SPARQL when the target properties
|
|
872
|
+
// are stored as plain IRIs (not signed expressions). Properties
|
|
873
|
+
// without resolveLanguage or with resolveLanguage='literal' store
|
|
874
|
+
// values as signed JSON envelopes, so SPARQL exact-match fails.
|
|
875
|
+
let whereConditions: string[] = [];
|
|
876
|
+
if (rel.where) {
|
|
877
|
+
try {
|
|
878
|
+
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
879
|
+
let allSparqlFilterable = true;
|
|
880
|
+
if (targetMetadata) {
|
|
881
|
+
for (const propName of Object.keys(rel.where)) {
|
|
882
|
+
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
883
|
+
const propMeta = targetMetadata.properties[propName];
|
|
884
|
+
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
885
|
+
allSparqlFilterable = false;
|
|
886
|
+
break;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
} else {
|
|
890
|
+
allSparqlFilterable = false;
|
|
891
|
+
}
|
|
892
|
+
if (allSparqlFilterable) {
|
|
893
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
894
|
+
}
|
|
895
|
+
} catch (_) {}
|
|
749
896
|
}
|
|
750
|
-
// Collect values to assign to instance
|
|
751
|
-
const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
|
|
752
|
-
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
753
|
-
|
|
754
|
-
return instance;
|
|
755
|
-
} catch (error) {
|
|
756
|
-
console.error(`Failed to process instance ${Base}:`, error);
|
|
757
|
-
// Return null for failed instances - we'll filter these out below
|
|
758
|
-
return null;
|
|
759
|
-
}
|
|
760
|
-
})
|
|
761
|
-
);
|
|
762
|
-
const instances = allInstances.filter((instance) => instance !== null) as T[];
|
|
763
897
|
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
898
|
+
if (filter) {
|
|
899
|
+
let getter = filter.getter;
|
|
900
|
+
if (whereConditions.length > 0) {
|
|
901
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
902
|
+
}
|
|
903
|
+
rel.getter = getter;
|
|
904
|
+
} else if (whereConditions.length > 0) {
|
|
905
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
906
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
907
|
+
}
|
|
908
|
+
} catch (_) {}
|
|
909
|
+
}
|
|
767
910
|
}
|
|
768
911
|
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
for (const inst of instances) {
|
|
776
|
-
(inst as Ad4mModel).takeSnapshot(snapshotRelations);
|
|
777
|
-
}
|
|
912
|
+
return {
|
|
913
|
+
className,
|
|
914
|
+
queryJson: JSON.stringify(queryInput),
|
|
915
|
+
shapeJson: JSON.stringify(metadata),
|
|
916
|
+
};
|
|
917
|
+
}
|
|
778
918
|
|
|
779
|
-
|
|
919
|
+
/**
|
|
920
|
+
* Parse raw model query/subscription result JSON into typed model instances.
|
|
921
|
+
* Used by ModelQueryBuilder to convert subscription updates without circular imports.
|
|
922
|
+
* @internal
|
|
923
|
+
*/
|
|
924
|
+
static parseModelResult<T extends Ad4mModel>(
|
|
925
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
926
|
+
perspective: PerspectiveProxy,
|
|
927
|
+
raw: any,
|
|
928
|
+
include?: IncludeMap,
|
|
929
|
+
properties?: string[],
|
|
930
|
+
): T[] {
|
|
931
|
+
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
932
|
+
const arr = data.instances || data;
|
|
933
|
+
if (!Array.isArray(arr)) return [];
|
|
934
|
+
return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
780
935
|
}
|
|
781
936
|
|
|
937
|
+
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
938
|
+
|
|
782
939
|
/**
|
|
783
|
-
*
|
|
940
|
+
* Execute a model query via the executor-side endpoint.
|
|
784
941
|
*
|
|
785
|
-
*
|
|
786
|
-
*
|
|
787
|
-
* @param result - Array of result objects from SPARQL
|
|
788
|
-
* @returns Promise resolving to results with total count
|
|
942
|
+
* This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
|
|
943
|
+
* with a single RPC to the executor that handles everything in Rust.
|
|
789
944
|
*
|
|
790
945
|
* @internal
|
|
791
946
|
*/
|
|
792
|
-
|
|
793
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
947
|
+
private static async executeModelQuery<T extends Ad4mModel>(
|
|
948
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
794
949
|
perspective: PerspectiveProxy,
|
|
795
|
-
query: Query,
|
|
796
|
-
|
|
797
|
-
computeTotalCount: boolean = false
|
|
950
|
+
query: Query = {},
|
|
951
|
+
classNameOverride?: string | null,
|
|
798
952
|
): Promise<ResultsWithTotalCount<T>> {
|
|
799
|
-
if (!result || result.length === 0) return { results: [], totalCount: 0 };
|
|
800
|
-
|
|
801
953
|
const metadata = this.getModelMetadata();
|
|
802
|
-
const
|
|
803
|
-
|
|
804
|
-
// The query used GROUP BY with graph traversal, so each row has:
|
|
805
|
-
// - source: the node ID (e.g., "node:abc123")
|
|
806
|
-
// - source_uri: the actual URI (the base expression)
|
|
807
|
-
// - links: array of link objects with {predicate, target, author, timestamp}
|
|
808
|
-
|
|
809
|
-
const instances: T[] = [];
|
|
810
|
-
for (const row of result) {
|
|
811
|
-
let base;
|
|
812
|
-
try {
|
|
813
|
-
// Use source_uri as the base (the actual URI), not the node ID
|
|
814
|
-
base = row.source_uri;
|
|
954
|
+
const className = classNameOverride || metadata.className;
|
|
815
955
|
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
// Core hydration via unified helper (pass requestedProperties for sparse fieldset).
|
|
826
|
-
// Also hydrate any properties referenced in `where` so the JS post-filter can match them,
|
|
827
|
-
// even if they're not in the user's `properties` projection.
|
|
828
|
-
let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
|
|
829
|
-
if (hydrationProps && query.where) {
|
|
830
|
-
for (const key of Object.keys(query.where)) {
|
|
831
|
-
if (!hydrationProps.includes(key)) {
|
|
832
|
-
hydrationProps.push(key);
|
|
833
|
-
}
|
|
834
|
-
}
|
|
956
|
+
// Expand includeAll: true to a full IncludeMap covering every forward relation.
|
|
957
|
+
// Done before queryInput is built so all downstream uses of query.include see the expansion.
|
|
958
|
+
if (query.includeAll) {
|
|
959
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
960
|
+
const expanded: IncludeMap = {};
|
|
961
|
+
for (const [relName, relMeta] of Object.entries(allRelMeta)) {
|
|
962
|
+
if ((relMeta as any).direction !== 'reverse') {
|
|
963
|
+
expanded[relName] = true;
|
|
835
964
|
}
|
|
836
|
-
await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
|
|
837
|
-
|
|
838
|
-
// NOTE: Property deletion for sparse fieldsets is deferred until AFTER
|
|
839
|
-
// where-filtering so that where conditions can reference any property,
|
|
840
|
-
// even ones not in the `properties` projection.
|
|
841
|
-
|
|
842
|
-
instances.push(instance);
|
|
843
|
-
} catch (error) {
|
|
844
|
-
console.error(`Failed to process SPARQL instance ${base}:`, error);
|
|
845
965
|
}
|
|
966
|
+
// Explicit include entries take precedence over the expansion
|
|
967
|
+
query = { ...query, include: { ...expanded, ...query.include } };
|
|
846
968
|
}
|
|
847
969
|
|
|
848
|
-
//
|
|
849
|
-
//
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
970
|
+
// Build the query input that the Rust endpoint expects.
|
|
971
|
+
// Convert the TS Query type to the executor's ModelQueryInput format.
|
|
972
|
+
const queryInput: any = {};
|
|
973
|
+
if (query.parent) {
|
|
974
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
975
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
976
|
+
}
|
|
977
|
+
if (query.properties) queryInput.properties = query.properties;
|
|
978
|
+
if (query.include) {
|
|
979
|
+
// Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
|
|
980
|
+
// All other keys (boolean | RelationSubQuery) → queryInput.include
|
|
981
|
+
const normalIncludes: IncludeMap = {};
|
|
982
|
+
const projections: Record<string, IncludeProjection> = {};
|
|
983
|
+
for (const [key, val] of Object.entries(query.include)) {
|
|
984
|
+
if (key.startsWith('$')) {
|
|
985
|
+
projections[key] = val as IncludeProjection;
|
|
986
|
+
} else {
|
|
987
|
+
normalIncludes[key] = val;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
|
|
991
|
+
if (Object.keys(projections).length > 0) {
|
|
992
|
+
// Enrich projections with target shapes so Rust can apply where clause filtering
|
|
993
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
994
|
+
for (const [, proj] of Object.entries(projections)) {
|
|
995
|
+
const relMeta = allRelMeta[proj.from];
|
|
996
|
+
if (!proj.targetShape && relMeta?.target) {
|
|
997
|
+
try {
|
|
998
|
+
const TargetClass = relMeta.target();
|
|
999
|
+
const targetMeta = (TargetClass as any).getModelMetadata?.();
|
|
1000
|
+
if (targetMeta) {
|
|
1001
|
+
proj.targetShape = targetMeta;
|
|
1002
|
+
}
|
|
1003
|
+
} catch (_) { /* target class may not be available */ }
|
|
873
1004
|
}
|
|
874
|
-
}
|
|
875
|
-
|
|
1005
|
+
}
|
|
1006
|
+
queryInput.projections = projections;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
if (query.where) queryInput.where = query.where;
|
|
1010
|
+
if (query.order) {
|
|
1011
|
+
// Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
|
|
1012
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
1013
|
+
}
|
|
1014
|
+
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
1015
|
+
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
1016
|
+
if (query.count !== undefined) queryInput.count = query.count;
|
|
1017
|
+
|
|
1018
|
+
// Enrich relation metadata with target class shapes for Rust-side
|
|
1019
|
+
// include resolution. This eliminates per-relation GraphQL round-trips
|
|
1020
|
+
// by letting the Rust endpoint resolve includes in-process.
|
|
1021
|
+
if (queryInput.include) {
|
|
1022
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
1023
|
+
enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
|
|
876
1024
|
}
|
|
877
1025
|
|
|
878
|
-
//
|
|
879
|
-
//
|
|
880
|
-
//
|
|
881
|
-
//
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
: [];
|
|
885
|
-
const shouldEvaluatePropertyGetters = query.deepQuery === true || whereGetterProperties.length > 0;
|
|
1026
|
+
// ── Pre-compute conformance getters for Rust-side evaluation ──────
|
|
1027
|
+
// For each relation with a target class and filter !== false, compute
|
|
1028
|
+
// the conformance getter SPARQL so Rust can evaluate it in-process
|
|
1029
|
+
// (eliminating N × querySparql round-trips per instance).
|
|
1030
|
+
// When a relation has a `where` clause, compile the where conditions
|
|
1031
|
+
// into the getter SPARQL so Rust applies them during evaluation.
|
|
886
1032
|
{
|
|
887
|
-
const
|
|
888
|
-
const
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
: whereGetterProperties) // only evaluate where-referenced getters
|
|
894
|
-
: [];
|
|
895
|
-
const getterOpts = {
|
|
896
|
-
...(getterRequestedProperties.length > 0 && { requestedProperties: getterRequestedProperties }),
|
|
897
|
-
...(query.include && { include: query.include }),
|
|
898
|
-
skipPropertyGetters,
|
|
899
|
-
};
|
|
900
|
-
for (const instance of instances) {
|
|
901
|
-
await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
// Filter by where conditions that couldn't be filtered in SPARQL
|
|
906
|
-
// This includes:
|
|
907
|
-
// - author/timestamp (computed from grouped links)
|
|
908
|
-
// - Properties with comparison operators (gt, gte, lt, lte, between, contains)
|
|
909
|
-
// because <ad4m://fn/parse_literal>() returns strings, making numeric/date
|
|
910
|
-
// comparisons unreliable. Equality, IN, and NOT are pushed to SPARQL.
|
|
911
|
-
// - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
|
|
912
|
-
// which require reverse-link resolution before filtering
|
|
913
|
-
let filteredInstances = instances;
|
|
914
|
-
if (query.where) {
|
|
915
|
-
filteredInstances = instances.filter(instance => {
|
|
916
|
-
for (const [propertyName, condition] of Object.entries(query.where!)) {
|
|
917
|
-
// Skip 'base'/'id' as it's filtered in SPARQL
|
|
918
|
-
if (propertyName === 'base' || propertyName === 'id') continue;
|
|
919
|
-
|
|
920
|
-
// For author and timestamp, always filter in JS
|
|
921
|
-
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
922
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
923
|
-
return false;
|
|
924
|
-
}
|
|
925
|
-
continue;
|
|
926
|
-
}
|
|
1033
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
1034
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1035
|
+
const rel = relMeta as any;
|
|
1036
|
+
if (rel.getter) continue; // explicit getter already set
|
|
1037
|
+
if (rel.direction === 'reverse') continue; // reverse relations use reverse link lookup
|
|
1038
|
+
if (rel.filter === false) continue; // opt-out of conformance filtering
|
|
927
1039
|
|
|
928
|
-
|
|
929
|
-
|
|
1040
|
+
const meta = allRelMeta[relName];
|
|
1041
|
+
if (!meta?.target) continue;
|
|
930
1042
|
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
1043
|
+
try {
|
|
1044
|
+
const TargetClass = meta.target();
|
|
1045
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1046
|
+
|
|
1047
|
+
// Only compile where clauses to SPARQL when the target properties
|
|
1048
|
+
// are stored as plain IRIs (not signed expressions). Properties
|
|
1049
|
+
// without resolveLanguage or with resolveLanguage='literal' store
|
|
1050
|
+
// values as signed JSON envelopes, so SPARQL exact-match fails.
|
|
1051
|
+
let whereConditions: string[] = [];
|
|
1052
|
+
if (rel.where) {
|
|
1053
|
+
try {
|
|
1054
|
+
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
1055
|
+
let allSparqlFilterable = true;
|
|
1056
|
+
if (targetMetadata) {
|
|
1057
|
+
for (const propName of Object.keys(rel.where)) {
|
|
1058
|
+
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
1059
|
+
const propMeta = targetMetadata.properties[propName];
|
|
1060
|
+
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
1061
|
+
allSparqlFilterable = false;
|
|
1062
|
+
break;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
} else {
|
|
1066
|
+
allSparqlFilterable = false;
|
|
1067
|
+
}
|
|
1068
|
+
if (allSparqlFilterable) {
|
|
1069
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
1070
|
+
}
|
|
1071
|
+
} catch (_) { /* target metadata unavailable */ }
|
|
937
1072
|
}
|
|
938
1073
|
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
1074
|
+
if (filter) {
|
|
1075
|
+
let getter = filter.getter;
|
|
1076
|
+
if (whereConditions.length > 0) {
|
|
1077
|
+
// Append where conditions before the closing }
|
|
1078
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
1079
|
+
}
|
|
1080
|
+
rel.getter = getter;
|
|
1081
|
+
} else if (whereConditions.length > 0) {
|
|
1082
|
+
// No conformance filter but where clause exists — build getter from where alone
|
|
1083
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
1084
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
944
1085
|
}
|
|
1086
|
+
} catch (e) {
|
|
1087
|
+
// Target class may not be available; skip silently
|
|
945
1088
|
}
|
|
946
|
-
|
|
947
|
-
});
|
|
1089
|
+
}
|
|
948
1090
|
}
|
|
949
1091
|
|
|
950
|
-
//
|
|
951
|
-
//
|
|
952
|
-
//
|
|
953
|
-
const
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
1092
|
+
// Send shape metadata to the executor so it knows the model structure.
|
|
1093
|
+
// This is more reliable than reading SHACL from the store because
|
|
1094
|
+
// the TS decorators are the definitive source of truth.
|
|
1095
|
+
const shapeJson = JSON.stringify(metadata);
|
|
1096
|
+
const queryJson = JSON.stringify(queryInput);
|
|
1097
|
+
|
|
1098
|
+
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
1099
|
+
|
|
1100
|
+
// Convert JSON instances to model class instances, recursively constructing
|
|
1101
|
+
// class instances for any included relations resolved by Rust.
|
|
1102
|
+
const instances: T[] = result.instances.map((json: any) => {
|
|
1103
|
+
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
1104
|
+
});
|
|
1105
|
+
|
|
1106
|
+
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1107
|
+
// value is a content-addressed hash that must be fetched from the language
|
|
1108
|
+
// runtime). The Rust endpoint returns raw target URIs; we resolve them here.
|
|
1109
|
+
const propsMeta = getPropertiesMetadata(this as any);
|
|
1110
|
+
const resolveProps = Object.entries(propsMeta).filter(
|
|
1111
|
+
([, opts]: [string, any]) =>
|
|
1112
|
+
opts.resolveLanguage != null &&
|
|
1113
|
+
opts.resolveLanguage !== 'literal',
|
|
1114
|
+
);
|
|
1115
|
+
if (resolveProps.length > 0) {
|
|
1116
|
+
await Promise.all(
|
|
1117
|
+
instances.map(async (inst: any) => {
|
|
1118
|
+
for (const [propName, opts] of resolveProps) {
|
|
1119
|
+
const val = inst[propName];
|
|
1120
|
+
if (typeof val !== 'string' || !val || val.startsWith('literal:')) continue;
|
|
1121
|
+
try {
|
|
1122
|
+
const expression = await perspective.getExpression(val);
|
|
1123
|
+
if (expression) {
|
|
1124
|
+
let resolved: any;
|
|
1125
|
+
try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
|
|
1126
|
+
const transform = (opts as any).transform;
|
|
1127
|
+
inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
|
|
1128
|
+
}
|
|
1129
|
+
} catch (_) { /* resolution failed — keep raw value */ }
|
|
977
1130
|
}
|
|
1131
|
+
}),
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
978
1134
|
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
1135
|
+
// Relation conformance getters are evaluated Rust-side via evaluate_getters()
|
|
1136
|
+
// in model_query.rs. However, for relations with non-SPARQL-filterable where
|
|
1137
|
+
// clauses (e.g. properties stored as signed expressions), we still need
|
|
1138
|
+
// TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
|
|
1139
|
+
// with skipPropertyGetters ensures conformance + JS post-filtering for
|
|
1140
|
+
// where clauses that couldn't be compiled to SPARQL.
|
|
1141
|
+
const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set<string>();
|
|
1142
|
+
for (const inst of instances) {
|
|
1143
|
+
// Save included relation values that came from Rust hydration
|
|
1144
|
+
const savedIncluded: Record<string, any> = {};
|
|
1145
|
+
for (const relName of includedRelNames) {
|
|
1146
|
+
if ((inst as any)[relName] !== undefined) {
|
|
1147
|
+
savedIncluded[relName] = (inst as any)[relName];
|
|
983
1148
|
}
|
|
984
|
-
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
await evaluateCustomGettersForInstance(inst, perspective, metadata, {
|
|
1152
|
+
skipPropertyGetters: true,
|
|
985
1153
|
});
|
|
986
|
-
}
|
|
987
1154
|
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
const allRelsMeta2 = getRelationsMetadata(this as any);
|
|
992
|
-
const sparqlPaginated = !hasJsOnlyWhereFilters(metadata, allRelsMeta2, query.where)
|
|
993
|
-
&& (query.limit !== undefined || query.offset !== undefined)
|
|
994
|
-
&& query.order !== undefined && Object.keys(query.order).length > 0;
|
|
995
|
-
|
|
996
|
-
// Calculate totalCount BEFORE applying limit/offset.
|
|
997
|
-
// When SPARQL already paginated, filteredInstances.length is the page size,
|
|
998
|
-
// not the total — use a separate COUNT query for the real total.
|
|
999
|
-
// Only run the COUNT query when the caller actually needs it (computeTotalCount=true).
|
|
1000
|
-
let totalCount: number;
|
|
1001
|
-
if (sparqlPaginated && computeTotalCount) {
|
|
1002
|
-
try {
|
|
1003
|
-
const countSparql = buildSPARQLCountQuery(metadata, allRelsMeta2, query, this);
|
|
1004
|
-
const countResult = await perspective.querySparql(countSparql);
|
|
1005
|
-
totalCount = parseSparqlCount(countResult) ?? filteredInstances.length;
|
|
1006
|
-
} catch {
|
|
1007
|
-
// Fallback: if count query fails, use what we have
|
|
1008
|
-
totalCount = filteredInstances.length;
|
|
1155
|
+
// Restore hydrated include objects that were overwritten by conformance getters
|
|
1156
|
+
for (const [relName, value] of Object.entries(savedIncluded)) {
|
|
1157
|
+
(inst as any)[relName] = value;
|
|
1009
1158
|
}
|
|
1010
|
-
} else {
|
|
1011
|
-
totalCount = filteredInstances.length;
|
|
1012
|
-
}
|
|
1013
|
-
|
|
1014
|
-
// Apply offset and limit in JavaScript only when SPARQL didn't already paginate.
|
|
1015
|
-
// Subscription queries use unpaginated SPARQL, so JS must apply pagination.
|
|
1016
|
-
// Direct queries use SPARQL-level pagination, so JS slicing would double-apply.
|
|
1017
|
-
let paginatedInstances = filteredInstances;
|
|
1018
|
-
if (!sparqlPaginated && (query.offset !== undefined || query.limit !== undefined)) {
|
|
1019
|
-
const start = query.offset || 0;
|
|
1020
|
-
const end = query.limit ? start + query.limit : undefined;
|
|
1021
|
-
paginatedInstances = filteredInstances.slice(start, end);
|
|
1022
|
-
}
|
|
1023
1159
|
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
for (const relName of Object.keys(metadata.relations)) {
|
|
1035
|
-
if (!requested.has(relName) && !(query.include && relName in query.include)) {
|
|
1036
|
-
delete (inst as any)[relName];
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
for (const metaField of ['author', 'createdAt', 'updatedAt'] as const) {
|
|
1040
|
-
if (!requested.has(metaField)) {
|
|
1041
|
-
delete (inst as any)[metaField];
|
|
1042
|
-
}
|
|
1160
|
+
// Fix cardinality for non-included HasOne/BelongsToOne relations:
|
|
1161
|
+
// The conformance getter always produces arrays; unwrap to scalar.
|
|
1162
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1163
|
+
if (includedRelNames.has(relName)) continue;
|
|
1164
|
+
const kind = (relMeta as any).kind;
|
|
1165
|
+
if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray((inst as any)[relName])) {
|
|
1166
|
+
const arr = (inst as any)[relName] as any[];
|
|
1167
|
+
(inst as any)[relName] = arr.length > 0 ? arr[0] : null;
|
|
1043
1168
|
}
|
|
1044
1169
|
}
|
|
1045
1170
|
}
|
|
1046
1171
|
|
|
1047
|
-
//
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
// Take snapshots for dirty tracking after ALL hydration is complete
|
|
1053
|
-
// (including eager-loaded relations).
|
|
1054
|
-
// When `include` is specified, only snapshot those relations.
|
|
1055
|
-
// Otherwise snapshot ALL fields (properties + relations) since
|
|
1056
|
-
// hydrateFromLinks populates relations with stable raw IDs —
|
|
1057
|
-
// this ensures push-to-array + save() correctly detects dirty relations.
|
|
1058
|
-
const snapshotRelations = query.include;
|
|
1059
|
-
for (const inst of paginatedInstances) {
|
|
1172
|
+
// Take snapshots for dirty tracking
|
|
1173
|
+
const snapshotRelations = queryInput.include;
|
|
1174
|
+
for (const inst of instances) {
|
|
1060
1175
|
(inst as Ad4mModel).takeSnapshot(snapshotRelations);
|
|
1061
1176
|
}
|
|
1062
1177
|
|
|
1063
1178
|
return {
|
|
1064
|
-
results:
|
|
1065
|
-
totalCount
|
|
1179
|
+
results: instances,
|
|
1180
|
+
totalCount: result.totalCount,
|
|
1066
1181
|
};
|
|
1067
1182
|
}
|
|
1068
1183
|
|
|
@@ -1097,33 +1212,14 @@ export class Ad4mModel {
|
|
|
1097
1212
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1098
1213
|
perspective: PerspectiveProxy,
|
|
1099
1214
|
query: Query = {},
|
|
1100
|
-
|
|
1215
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1101
1216
|
): Promise<T[]> {
|
|
1102
1217
|
if (query.properties && query.properties.length === 0) {
|
|
1103
1218
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
1104
1219
|
}
|
|
1105
1220
|
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
? (engine ? 'sparql' : 'prolog')
|
|
1109
|
-
: engine;
|
|
1110
|
-
|
|
1111
|
-
if (resolvedEngine === 'sparql') {
|
|
1112
|
-
// Always use the regular SPARQL path + JS-level hydrateRelations for includes.
|
|
1113
|
-
// The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
|
|
1114
|
-
// non-conforming node filtering, and parse_literal compatibility.
|
|
1115
|
-
// hydrateRelations handles all of these correctly via per-relation findAll calls.
|
|
1116
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1117
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1118
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1119
|
-
const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
|
|
1120
|
-
return results;
|
|
1121
|
-
} else {
|
|
1122
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1123
|
-
const result = await perspective.infer(prologQuery);
|
|
1124
|
-
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
1125
|
-
return results;
|
|
1126
|
-
}
|
|
1221
|
+
const { results } = await this.executeModelQuery(perspective, query);
|
|
1222
|
+
return results;
|
|
1127
1223
|
}
|
|
1128
1224
|
|
|
1129
1225
|
/**
|
|
@@ -1150,10 +1246,10 @@ export class Ad4mModel {
|
|
|
1150
1246
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1151
1247
|
perspective: PerspectiveProxy,
|
|
1152
1248
|
query: Query = {},
|
|
1153
|
-
|
|
1249
|
+
_engine?: 'sparql' | 'prolog' | boolean,
|
|
1154
1250
|
): Promise<T | null> {
|
|
1155
1251
|
const limitedQuery = { ...query, limit: 1 };
|
|
1156
|
-
const results = await this.findAll(perspective, limitedQuery
|
|
1252
|
+
const results = await this.findAll(perspective, limitedQuery);
|
|
1157
1253
|
return results[0] ?? null;
|
|
1158
1254
|
}
|
|
1159
1255
|
|
|
@@ -1181,22 +1277,9 @@ export class Ad4mModel {
|
|
|
1181
1277
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1182
1278
|
perspective: PerspectiveProxy,
|
|
1183
1279
|
query: Query = {},
|
|
1184
|
-
|
|
1280
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1185
1281
|
): Promise<ResultsWithTotalCount<T>> {
|
|
1186
|
-
|
|
1187
|
-
? (engine ? 'sparql' : 'prolog')
|
|
1188
|
-
: engine;
|
|
1189
|
-
|
|
1190
|
-
if (resolvedEngine === 'sparql') {
|
|
1191
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1192
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1193
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1194
|
-
return await this.instancesFromQueryResult(perspective, query, grouped, true);
|
|
1195
|
-
} else {
|
|
1196
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1197
|
-
const result = await perspective.infer(prologQuery);
|
|
1198
|
-
return await this.instancesFromPrologResult(perspective, query, result);
|
|
1199
|
-
}
|
|
1282
|
+
return await this.executeModelQuery(perspective, query);
|
|
1200
1283
|
}
|
|
1201
1284
|
|
|
1202
1285
|
/**
|
|
@@ -1206,7 +1289,6 @@ export class Ad4mModel {
|
|
|
1206
1289
|
* @param pageSize - Number of items per page
|
|
1207
1290
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
1208
1291
|
* @param query - Optional additional query parameters
|
|
1209
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1210
1292
|
* @returns Paginated results with metadata
|
|
1211
1293
|
*
|
|
1212
1294
|
* @example
|
|
@@ -1215,9 +1297,6 @@ export class Ad4mModel {
|
|
|
1215
1297
|
* where: { category: "Main Course" }
|
|
1216
1298
|
* });
|
|
1217
1299
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1218
|
-
*
|
|
1219
|
-
* // Use Prolog explicitly (legacy)
|
|
1220
|
-
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
1221
1300
|
* ```
|
|
1222
1301
|
*/
|
|
1223
1302
|
static async paginate<T extends Ad4mModel>(
|
|
@@ -1226,46 +1305,11 @@ export class Ad4mModel {
|
|
|
1226
1305
|
pageSize: number,
|
|
1227
1306
|
pageNumber: number,
|
|
1228
1307
|
query?: Query,
|
|
1229
|
-
|
|
1308
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1230
1309
|
): Promise<PaginationResult<T>> {
|
|
1231
1310
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1232
|
-
const
|
|
1233
|
-
|
|
1234
|
-
: engine;
|
|
1235
|
-
|
|
1236
|
-
if (resolvedEngine === 'sparql') {
|
|
1237
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
|
|
1238
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1239
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1240
|
-
const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped, true);
|
|
1241
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1242
|
-
} else {
|
|
1243
|
-
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
1244
|
-
const result = await perspective.infer(prologQuery);
|
|
1245
|
-
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
1246
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
|
|
1251
|
-
const { where } = query;
|
|
1252
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
1253
|
-
const resolvedParentPredicate = query.parent
|
|
1254
|
-
? resolveParentPredicate(query.parent, this)
|
|
1255
|
-
: undefined;
|
|
1256
|
-
const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
|
|
1257
|
-
const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
|
|
1258
|
-
|
|
1259
|
-
const fullQuery = `
|
|
1260
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
1261
|
-
subject_class("${className}", SubjectClass),
|
|
1262
|
-
instance(SubjectClass, Base),
|
|
1263
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
1264
|
-
), UnsortedInstances),
|
|
1265
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
1266
|
-
`;
|
|
1267
|
-
|
|
1268
|
-
return fullQuery;
|
|
1311
|
+
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
1312
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1269
1313
|
}
|
|
1270
1314
|
|
|
1271
1315
|
/**
|
|
@@ -1277,18 +1321,13 @@ export class Ad4mModel {
|
|
|
1277
1321
|
*
|
|
1278
1322
|
* @private
|
|
1279
1323
|
*/
|
|
1280
|
-
|
|
1281
|
-
const metadata = this.getModelMetadata();
|
|
1282
|
-
const allRelMeta = getRelationsMetadata(this as any);
|
|
1283
|
-
return buildSPARQLCountQuery(metadata, allRelMeta, query, this);
|
|
1284
|
-
}
|
|
1324
|
+
// countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
|
|
1285
1325
|
|
|
1286
1326
|
/**
|
|
1287
1327
|
* Gets a count of all matching instances.
|
|
1288
1328
|
*
|
|
1289
1329
|
* @param perspective - The perspective to search in
|
|
1290
1330
|
* @param query - Optional query parameters to filter results
|
|
1291
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1292
1331
|
* @returns Total count of matching entities
|
|
1293
1332
|
*
|
|
1294
1333
|
* @example
|
|
@@ -1297,36 +1336,11 @@ export class Ad4mModel {
|
|
|
1297
1336
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
1298
1337
|
* where: { status: "active" }
|
|
1299
1338
|
* });
|
|
1300
|
-
*
|
|
1301
|
-
* // Use Prolog explicitly (legacy)
|
|
1302
|
-
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
1303
1339
|
* ```
|
|
1304
1340
|
*/
|
|
1305
|
-
static async count(perspective: PerspectiveProxy, query: Query = {}
|
|
1306
|
-
const
|
|
1307
|
-
|
|
1308
|
-
: engine;
|
|
1309
|
-
|
|
1310
|
-
if (resolvedEngine === 'sparql') {
|
|
1311
|
-
// When query has JS-only where filters (gt, between, author, timestamp, etc.),
|
|
1312
|
-
// we must fall back to full hydration + JS filtering to get accurate count.
|
|
1313
|
-
const metadata = this.getModelMetadata();
|
|
1314
|
-
const allRelMeta = getRelationsMetadata(this as any);
|
|
1315
|
-
if (hasJsOnlyWhereFilters(metadata, allRelMeta, query.where)) {
|
|
1316
|
-
// Fall back to full query + JS filter path for accurate count
|
|
1317
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1318
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1319
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1320
|
-
const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped, true); return totalCount;
|
|
1321
|
-
}
|
|
1322
|
-
// No JS-only filters — use efficient COUNT query
|
|
1323
|
-
const countSparql = await this.countQueryToSPARQL(perspective, query);
|
|
1324
|
-
const countResult = await perspective.querySparql(countSparql);
|
|
1325
|
-
return parseSparqlCount(countResult) ?? 0;
|
|
1326
|
-
} else {
|
|
1327
|
-
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
1328
|
-
return result?.[0]?.TotalCount || 0;
|
|
1329
|
-
}
|
|
1341
|
+
static async count(perspective: PerspectiveProxy, query: Query = {}): Promise<number> {
|
|
1342
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
1343
|
+
return totalCount;
|
|
1330
1344
|
}
|
|
1331
1345
|
|
|
1332
1346
|
private async setProperty(key: string, value: any, batchId?: string) {
|
|
@@ -2132,5 +2146,96 @@ export class Ad4mModel {
|
|
|
2132
2146
|
): typeof Ad4mModel {
|
|
2133
2147
|
return buildModelFromJSONSchema(this, schema, options);
|
|
2134
2148
|
}
|
|
2149
|
+
|
|
2150
|
+
/**
|
|
2151
|
+
* Creates a fully functional Ad4mModel subclass from a SHACL shape.
|
|
2152
|
+
*
|
|
2153
|
+
* Unlike `fromJSONSchema()`, no predicate inference is required —
|
|
2154
|
+
* `SHACLShape` already contains the exact predicate URI in `path` for
|
|
2155
|
+
* every property. The method reads each property's `path`, `maxCount`,
|
|
2156
|
+
* `writable`, and `resolveLanguage` directly and writes them to the
|
|
2157
|
+
* WeakMap metadata registries.
|
|
2158
|
+
*
|
|
2159
|
+
* Properties with `hasValue` (flag / type-discrimination markers) are
|
|
2160
|
+
* registered as hidden flag entries so that the SPARQL query builder emits
|
|
2161
|
+
* the fixed triple `?source <predicate> <value>` needed for type discrimination.
|
|
2162
|
+
* Properties without a `name` field are skipped.
|
|
2163
|
+
*
|
|
2164
|
+
* **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
|
|
2165
|
+
* was persisted on property shapes) carry the flag value only in
|
|
2166
|
+
* `shape.constructor_actions` as the `target` of an `addLink` action.
|
|
2167
|
+
* This method recovers those values so that old perspectives are queried
|
|
2168
|
+
* with the correct type-discriminator triple.
|
|
2169
|
+
*
|
|
2170
|
+
* @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
|
|
2171
|
+
* @param name - Class name to assign (e.g. "Channel")
|
|
2172
|
+
* @returns Generated Ad4mModel subclass, ready for querying
|
|
2173
|
+
*/
|
|
2174
|
+
static fromSHACL(shape: SHACLShape, name: string): typeof Ad4mModel {
|
|
2175
|
+
const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
|
|
2176
|
+
(DynamicModelClass as any).className = name;
|
|
2177
|
+
(DynamicModelClass.prototype as any).className = name;
|
|
2178
|
+
|
|
2179
|
+
// Build a backward-compat fallback map: predicate → fixed-IRI-value from
|
|
2180
|
+
// constructor actions. Old SHACL stores (created before sh:hasValue was
|
|
2181
|
+
// persisted on the property shape) don't carry sh:hasValue on properties,
|
|
2182
|
+
// but the shape-level constructor_actions always contain an addLink action
|
|
2183
|
+
// with the fixed flag value as the target.
|
|
2184
|
+
const flagValueFromConstructor = new Map<string, string>();
|
|
2185
|
+
for (const action of shape.constructor_actions ?? []) {
|
|
2186
|
+
if (
|
|
2187
|
+
action.action === 'addLink' &&
|
|
2188
|
+
typeof action.predicate === 'string' &&
|
|
2189
|
+
typeof action.target === 'string' &&
|
|
2190
|
+
action.target !== 'value' &&
|
|
2191
|
+
!action.target.startsWith('literal:')
|
|
2192
|
+
) {
|
|
2193
|
+
flagValueFromConstructor.set(action.predicate, action.target);
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
for (const prop of shape.properties) {
|
|
2198
|
+
const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
|
|
2199
|
+
|
|
2200
|
+
if (resolvedHasValue !== undefined) {
|
|
2201
|
+
const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
|
|
2202
|
+
setPropertyRegistryEntry(DynamicModelClass, flagKey, {
|
|
2203
|
+
through: prop.path,
|
|
2204
|
+
required: true,
|
|
2205
|
+
initial: resolvedHasValue,
|
|
2206
|
+
flag: true,
|
|
2207
|
+
writable: false,
|
|
2208
|
+
readOnly: true,
|
|
2209
|
+
});
|
|
2210
|
+
continue;
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
// Skip properties without a declared name
|
|
2214
|
+
if (!prop.name) continue;
|
|
2215
|
+
|
|
2216
|
+
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
2217
|
+
|
|
2218
|
+
if (isCollection) {
|
|
2219
|
+
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
2220
|
+
predicate: prop.path,
|
|
2221
|
+
kind: 'hasMany',
|
|
2222
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2223
|
+
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
2224
|
+
});
|
|
2225
|
+
} else {
|
|
2226
|
+
setPropertyRegistryEntry(DynamicModelClass, prop.name, {
|
|
2227
|
+
through: prop.path,
|
|
2228
|
+
writable: prop.writable ?? true,
|
|
2229
|
+
...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
|
|
2230
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2231
|
+
});
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
const ModelDecorator = Model({ name });
|
|
2236
|
+
ModelDecorator(DynamicModelClass);
|
|
2237
|
+
|
|
2238
|
+
return DynamicModelClass as typeof Ad4mModel;
|
|
2239
|
+
}
|
|
2135
2240
|
}
|
|
2136
2241
|
|