@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
|
@@ -1,17 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* hydration.ts — Instance hydration helpers extracted from Ad4mModel.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* the instance, metadata, or perspective as explicit parameters.
|
|
4
|
+
* After the Rust model_query pipeline migration, most hydration logic moved
|
|
5
|
+
* to Rust. This file retains:
|
|
6
|
+
* - normalizeValue() — snapshot dirty-tracking
|
|
8
7
|
*/
|
|
9
|
-
import { Literal } from "../Literal";
|
|
10
|
-
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
11
|
-
import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter } from "./decorators";
|
|
12
|
-
import { compileWhereClause } from "./query-utils";
|
|
13
|
-
import { escapeQueryString } from "../utils";
|
|
14
|
-
import { buildSPARQLGroupedCountQuery, parseSparqlGroupedCount } from "./query-sparql";
|
|
15
8
|
// ──────────────────────────────────────────────────────────
|
|
16
9
|
// Pure helpers
|
|
17
10
|
// ──────────────────────────────────────────────────────────
|
|
@@ -26,963 +19,3 @@ export function normalizeValue(value) {
|
|
|
26
19
|
}
|
|
27
20
|
return value;
|
|
28
21
|
}
|
|
29
|
-
/**
|
|
30
|
-
* Checks if a value matches a where-condition (for post-query filtering).
|
|
31
|
-
*/
|
|
32
|
-
export function matchesCondition(value, condition) {
|
|
33
|
-
// Handle array values (IN clause)
|
|
34
|
-
if (Array.isArray(condition)) {
|
|
35
|
-
return condition.includes(value);
|
|
36
|
-
}
|
|
37
|
-
// Handle operator object
|
|
38
|
-
if (typeof condition === 'object' && condition !== null) {
|
|
39
|
-
const ops = condition;
|
|
40
|
-
// Special case: 'not' operator (exclusive with other operators)
|
|
41
|
-
if (ops.not !== undefined) {
|
|
42
|
-
if (Array.isArray(ops.not)) {
|
|
43
|
-
return !ops.not.includes(value);
|
|
44
|
-
}
|
|
45
|
-
else {
|
|
46
|
-
return value !== ops.not;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
// Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
|
|
50
|
-
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
51
|
-
return value >= ops.between[0] && value <= ops.between[1];
|
|
52
|
-
}
|
|
53
|
-
// For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
|
|
54
|
-
// and return true only if ALL conditions are satisfied
|
|
55
|
-
let allConditionsMet = true;
|
|
56
|
-
if (ops.gt !== undefined) {
|
|
57
|
-
allConditionsMet = allConditionsMet && (value > ops.gt);
|
|
58
|
-
}
|
|
59
|
-
if (ops.gte !== undefined) {
|
|
60
|
-
allConditionsMet = allConditionsMet && (value >= ops.gte);
|
|
61
|
-
}
|
|
62
|
-
if (ops.lt !== undefined) {
|
|
63
|
-
allConditionsMet = allConditionsMet && (value < ops.lt);
|
|
64
|
-
}
|
|
65
|
-
if (ops.lte !== undefined) {
|
|
66
|
-
allConditionsMet = allConditionsMet && (value <= ops.lte);
|
|
67
|
-
}
|
|
68
|
-
if (ops.contains !== undefined) {
|
|
69
|
-
if (typeof value === 'string') {
|
|
70
|
-
allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
|
|
71
|
-
}
|
|
72
|
-
else if (Array.isArray(value)) {
|
|
73
|
-
allConditionsMet = allConditionsMet && value.includes(ops.contains);
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
allConditionsMet = false;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return allConditionsMet;
|
|
80
|
-
}
|
|
81
|
-
// Simple equality
|
|
82
|
-
return value === condition;
|
|
83
|
-
}
|
|
84
|
-
// ──────────────────────────────────────────────────────────
|
|
85
|
-
// Property / link hydration
|
|
86
|
-
// ──────────────────────────────────────────────────────────
|
|
87
|
-
/**
|
|
88
|
-
* Resolves a single property value from a raw link target string.
|
|
89
|
-
*
|
|
90
|
-
* Handles expression resolution, literal URI parsing, primitive
|
|
91
|
-
* type coercion, and optional transform functions.
|
|
92
|
-
*
|
|
93
|
-
* @param target - The raw target string from the link
|
|
94
|
-
* @param propMeta - Property metadata from the decorator registry
|
|
95
|
-
* @param perspective - The perspective for expression resolution
|
|
96
|
-
* @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
|
|
97
|
-
* @returns The resolved value
|
|
98
|
-
*/
|
|
99
|
-
export async function hydratePropertyValue(target, propMeta, perspective, expectedType) {
|
|
100
|
-
let value = target;
|
|
101
|
-
if (target !== undefined && target !== null && target !== '') {
|
|
102
|
-
// Non-literal expression resolution
|
|
103
|
-
if (propMeta.resolveLanguage != null &&
|
|
104
|
-
propMeta.resolveLanguage !== 'literal' &&
|
|
105
|
-
typeof target === 'string' &&
|
|
106
|
-
!target.startsWith('literal:')) {
|
|
107
|
-
try {
|
|
108
|
-
const expression = await perspective.getExpression(target);
|
|
109
|
-
if (expression) {
|
|
110
|
-
try {
|
|
111
|
-
value = JSON.parse(expression.data);
|
|
112
|
-
}
|
|
113
|
-
catch {
|
|
114
|
-
value = expression.data;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
catch (e) {
|
|
119
|
-
console.warn(`hydratePropertyValue: failed to resolve expression for "${propMeta.name}":`, e);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
// Literal URI parsing
|
|
123
|
-
else if (propMeta.resolveLanguage === 'literal' &&
|
|
124
|
-
typeof target === 'string' &&
|
|
125
|
-
target.startsWith('literal:')) {
|
|
126
|
-
try {
|
|
127
|
-
const parsed = Literal.fromUrl(target).get();
|
|
128
|
-
value = parsed.data !== undefined ? parsed.data : parsed;
|
|
129
|
-
}
|
|
130
|
-
catch {
|
|
131
|
-
// Keep raw value
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
// Primitive type coercion
|
|
135
|
-
else if (typeof target === 'string' && expectedType) {
|
|
136
|
-
if (expectedType === 'number')
|
|
137
|
-
value = Number(target);
|
|
138
|
-
else if (expectedType === 'boolean')
|
|
139
|
-
value = target === 'true' || target === '1';
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
// Transform function
|
|
143
|
-
if (propMeta.transform && typeof propMeta.transform === 'function') {
|
|
144
|
-
value = propMeta.transform(value);
|
|
145
|
-
}
|
|
146
|
-
return value;
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* Hydrates an instance from an array of raw links.
|
|
150
|
-
*
|
|
151
|
-
* Processes properties (latest-wins semantics), relations
|
|
152
|
-
* (chronological accumulation), and timestamps/author in a single
|
|
153
|
-
* pass over the links array.
|
|
154
|
-
*
|
|
155
|
-
* @param instance - The blank model instance to populate
|
|
156
|
-
* @param links - Array of link objects (predicate, target, author?, timestamp?)
|
|
157
|
-
* @param metadata - Model metadata from `getModelMetadata()`
|
|
158
|
-
* @param perspective - The perspective for expression resolution
|
|
159
|
-
* @param requestedProperties - Optional sparse fieldset; when provided, only these
|
|
160
|
-
* property names are hydrated (relations are unaffected).
|
|
161
|
-
* Omit or pass `undefined` to hydrate all properties.
|
|
162
|
-
*/
|
|
163
|
-
export async function hydrateFromLinks(instance, links, metadata, perspective, requestedProperties) {
|
|
164
|
-
if (!links || links.length === 0)
|
|
165
|
-
return;
|
|
166
|
-
let minTimestamp = null;
|
|
167
|
-
let maxTimestamp = null;
|
|
168
|
-
let originalAuthor = null;
|
|
169
|
-
let latestAuthor = null;
|
|
170
|
-
// Build predicate→propName and predicate→relName lookup maps for O(1) matching
|
|
171
|
-
// When requestedProperties is provided, only include those properties in the map
|
|
172
|
-
const propFilter = requestedProperties && requestedProperties.length > 0
|
|
173
|
-
? new Set(requestedProperties)
|
|
174
|
-
: null;
|
|
175
|
-
const predToProperty = new Map();
|
|
176
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
177
|
-
if (propMeta.getter)
|
|
178
|
-
continue; // Handled via custom getter evaluation
|
|
179
|
-
if (propFilter && !propFilter.has(propName))
|
|
180
|
-
continue; // Skip unrequested properties
|
|
181
|
-
predToProperty.set(propMeta.predicate, [propName, propMeta]);
|
|
182
|
-
}
|
|
183
|
-
const predToRelation = new Map();
|
|
184
|
-
// Two-pass approach: first add all non-getter, non-target-filtered relations,
|
|
185
|
-
// then try to add target+filter relations only if their predicate isn't
|
|
186
|
-
// already claimed. This prevents predicate collisions (e.g. entries +
|
|
187
|
-
// messages sharing the same predicate) while still populating unique-
|
|
188
|
-
// predicate relations normally via link hydration.
|
|
189
|
-
const deferredTargetRelations = [];
|
|
190
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
191
|
-
if (relMeta.getter)
|
|
192
|
-
continue; // Handled via explicit custom getter evaluation
|
|
193
|
-
if (relMeta.target && relMeta.filter !== false) {
|
|
194
|
-
deferredTargetRelations.push([relName, relMeta]);
|
|
195
|
-
continue;
|
|
196
|
-
}
|
|
197
|
-
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
198
|
-
}
|
|
199
|
-
// Second pass: add deferred target+filter relations only if their predicate
|
|
200
|
-
// is not already claimed by a base relation. When a collision exists, the
|
|
201
|
-
// conformance getter will handle the filtered view instead.
|
|
202
|
-
for (const [relName, relMeta] of deferredTargetRelations) {
|
|
203
|
-
if (!predToRelation.has(relMeta.predicate)) {
|
|
204
|
-
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
// Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
|
|
208
|
-
const propertyLatest = new Map();
|
|
209
|
-
// Per-relation accumulator: ordered targets with metadata for sorting
|
|
210
|
-
const relationAccum = new Map();
|
|
211
|
-
// Single pass over all links
|
|
212
|
-
for (let i = 0; i < links.length; i++) {
|
|
213
|
-
const link = links[i];
|
|
214
|
-
const { predicate, target, author, timestamp } = link;
|
|
215
|
-
if (target === 'None' || target === undefined || target === null)
|
|
216
|
-
continue;
|
|
217
|
-
// Track timestamps/authors
|
|
218
|
-
if (timestamp != null) {
|
|
219
|
-
if (minTimestamp == null || timestamp < minTimestamp) {
|
|
220
|
-
minTimestamp = timestamp;
|
|
221
|
-
originalAuthor = author ?? null;
|
|
222
|
-
}
|
|
223
|
-
if (maxTimestamp == null || timestamp > maxTimestamp) {
|
|
224
|
-
maxTimestamp = timestamp;
|
|
225
|
-
latestAuthor = author ?? null;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
// Property match — accumulate for latest-wins
|
|
229
|
-
const propEntry = predToProperty.get(predicate);
|
|
230
|
-
if (propEntry) {
|
|
231
|
-
const existing = propertyLatest.get(propEntry[0]);
|
|
232
|
-
// Latest-wins: always overwrite (links are ordered ASC so last = latest)
|
|
233
|
-
propertyLatest.set(propEntry[0], { target, timestamp });
|
|
234
|
-
continue;
|
|
235
|
-
}
|
|
236
|
-
// Relation match — accumulate all
|
|
237
|
-
const relEntry = predToRelation.get(predicate);
|
|
238
|
-
if (relEntry) {
|
|
239
|
-
const [relName] = relEntry;
|
|
240
|
-
let arr = relationAccum.get(relName);
|
|
241
|
-
if (!arr) {
|
|
242
|
-
arr = [];
|
|
243
|
-
relationAccum.set(relName, arr);
|
|
244
|
-
}
|
|
245
|
-
arr.push({ target, timestamp: timestamp ?? '', index: i });
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
// Resolve properties
|
|
249
|
-
for (const [propName, { target }] of propertyLatest) {
|
|
250
|
-
const [, propMeta] = predToProperty.get(metadata.properties[propName].predicate);
|
|
251
|
-
const expectedType = typeof instance[propName];
|
|
252
|
-
instance[propName] = await hydratePropertyValue(target, propMeta, perspective, expectedType !== 'undefined' ? expectedType : undefined);
|
|
253
|
-
}
|
|
254
|
-
// Resolve relations: sort by timestamp (stable via index tiebreaker), filter empties
|
|
255
|
-
for (const [relName, items] of relationAccum) {
|
|
256
|
-
items.sort((a, b) => {
|
|
257
|
-
const cmp = String(a.timestamp).localeCompare(String(b.timestamp));
|
|
258
|
-
return cmp !== 0 ? cmp : a.index - b.index;
|
|
259
|
-
});
|
|
260
|
-
instance[relName] = items
|
|
261
|
-
.map(i => i.target)
|
|
262
|
-
.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
263
|
-
}
|
|
264
|
-
// Assign author / timestamps
|
|
265
|
-
if (originalAuthor)
|
|
266
|
-
instance.author = originalAuthor;
|
|
267
|
-
if (minTimestamp != null) {
|
|
268
|
-
instance.createdAt = typeof minTimestamp === 'string' && minTimestamp.includes('T')
|
|
269
|
-
? new Date(minTimestamp).getTime()
|
|
270
|
-
: typeof minTimestamp === 'string'
|
|
271
|
-
? (isNaN(parseInt(minTimestamp, 10)) ? minTimestamp : parseInt(minTimestamp, 10))
|
|
272
|
-
: minTimestamp;
|
|
273
|
-
}
|
|
274
|
-
if (maxTimestamp != null) {
|
|
275
|
-
instance.updatedAt = typeof maxTimestamp === 'string' && maxTimestamp.includes('T')
|
|
276
|
-
? new Date(maxTimestamp).getTime()
|
|
277
|
-
: typeof maxTimestamp === 'string'
|
|
278
|
-
? (isNaN(parseInt(maxTimestamp, 10)) ? maxTimestamp : parseInt(maxTimestamp, 10))
|
|
279
|
-
: maxTimestamp;
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
// ──────────────────────────────────────────────────────────
|
|
283
|
-
// Prolog result hydration (assignValuesToInstance)
|
|
284
|
-
// ──────────────────────────────────────────────────────────
|
|
285
|
-
/**
|
|
286
|
-
* Assigns decoded Prolog property values to an instance.
|
|
287
|
-
*
|
|
288
|
-
* Handles UTF-8 byte sequence reconstruction, expression resolution,
|
|
289
|
-
* transform functions, and read-only property filtering.
|
|
290
|
-
*/
|
|
291
|
-
export async function assignValuesToInstance(perspective, instance, values) {
|
|
292
|
-
// Map properties to object
|
|
293
|
-
const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
|
|
294
|
-
let finalValue = value;
|
|
295
|
-
// Handle UTF-8 byte sequences from Prolog URL decoding
|
|
296
|
-
if (!resolve && typeof value === 'string') {
|
|
297
|
-
// Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
|
|
298
|
-
// and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
|
|
299
|
-
const codePoints = Array.from(value, ch => ch.codePointAt(0));
|
|
300
|
-
const looksByteString = codePoints.every(cp => cp <= 0xFF);
|
|
301
|
-
const hasHighByte = codePoints.some(cp => cp >= 0x80);
|
|
302
|
-
if (looksByteString && hasHighByte) {
|
|
303
|
-
try {
|
|
304
|
-
const bytes = Uint8Array.from(codePoints);
|
|
305
|
-
const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
306
|
-
if (decoded !== value)
|
|
307
|
-
finalValue = decoded;
|
|
308
|
-
}
|
|
309
|
-
catch (error) {
|
|
310
|
-
// If UTF-8 conversion fails, keep the original value
|
|
311
|
-
console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
// Resolve the value if necessary
|
|
316
|
-
if (resolve) {
|
|
317
|
-
let resolvedExpression = await perspective.getExpression(value);
|
|
318
|
-
if (resolvedExpression) {
|
|
319
|
-
try {
|
|
320
|
-
// Attempt to parse the data as JSON
|
|
321
|
-
finalValue = JSON.parse(resolvedExpression.data);
|
|
322
|
-
}
|
|
323
|
-
catch (error) {
|
|
324
|
-
// If parsing fails, keep the original data
|
|
325
|
-
finalValue = resolvedExpression.data;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
// Apply transform function if it exists
|
|
330
|
-
const propsMeta = getPropertiesMetadata(instance.constructor);
|
|
331
|
-
const transform = propsMeta[name]?.transform;
|
|
332
|
-
if (transform && typeof transform === "function") {
|
|
333
|
-
finalValue = transform(finalValue);
|
|
334
|
-
}
|
|
335
|
-
return [name, finalValue];
|
|
336
|
-
})));
|
|
337
|
-
// Filter out properties that are read-only (getters without setters)
|
|
338
|
-
const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
|
|
339
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
|
|
340
|
-
if (!descriptor) {
|
|
341
|
-
// No descriptor means it's a regular property on the instance, allow it
|
|
342
|
-
return true;
|
|
343
|
-
}
|
|
344
|
-
// Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
|
|
345
|
-
const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
|
|
346
|
-
if (isAccessor) {
|
|
347
|
-
// Accessor descriptor: only allow if it has a setter
|
|
348
|
-
return descriptor.set !== undefined;
|
|
349
|
-
}
|
|
350
|
-
else {
|
|
351
|
-
// Data descriptor: only allow if writable is not explicitly false
|
|
352
|
-
return descriptor.writable !== false;
|
|
353
|
-
}
|
|
354
|
-
}));
|
|
355
|
-
// Assign properties to instance
|
|
356
|
-
Object.assign(instance, writableProps);
|
|
357
|
-
}
|
|
358
|
-
// ──────────────────────────────────────────────────────────
|
|
359
|
-
// SPARQL custom getter evaluation
|
|
360
|
-
// ──────────────────────────────────────────────────────────
|
|
361
|
-
/**
|
|
362
|
-
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
363
|
-
* is known but no explicit `getter` string was supplied.
|
|
364
|
-
*
|
|
365
|
-
* The generated getter traverses outgoing links matching the relation's
|
|
366
|
-
* predicate and then filters the target nodes to only those that conform to
|
|
367
|
-
* the target model's shape (required properties / flags).
|
|
368
|
-
*
|
|
369
|
-
* Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
|
|
370
|
-
* so the same logic is used at shape-definition time and at query time.
|
|
371
|
-
*
|
|
372
|
-
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
373
|
-
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
374
|
-
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
375
|
-
* conditions could be derived from the target model.
|
|
376
|
-
*/
|
|
377
|
-
export function buildConformanceGetter(relationPredicate, targetClass) {
|
|
378
|
-
const filter = buildConformanceFilter(relationPredicate, targetClass);
|
|
379
|
-
if (!filter) {
|
|
380
|
-
const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
|
|
381
|
-
console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
|
|
382
|
-
return undefined;
|
|
383
|
-
}
|
|
384
|
-
return filter.getter;
|
|
385
|
-
}
|
|
386
|
-
/**
|
|
387
|
-
* Evaluates custom SurrealQL getters for properties and relations on a specific instance.
|
|
388
|
-
*
|
|
389
|
-
* For relations that declare a `target` but no explicit `getter`, a conformance
|
|
390
|
-
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
391
|
-
*/
|
|
392
|
-
export async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
|
|
393
|
-
const safeBaseExpression = `<${instance.id}>`;
|
|
394
|
-
// Build projection filter — when requestedProperties is active, only
|
|
395
|
-
// evaluate getters for fields that are requested (or included).
|
|
396
|
-
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
397
|
-
const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
|
|
398
|
-
// Evaluate property getters (skip when caller only wants relation type-filtering)
|
|
399
|
-
if (!options?.skipPropertyGetters) {
|
|
400
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
401
|
-
if (projectionSet && !projectionSet.has(propName))
|
|
402
|
-
continue;
|
|
403
|
-
if (propMeta.getter) {
|
|
404
|
-
try {
|
|
405
|
-
const rawGetter = propMeta.getter;
|
|
406
|
-
const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
|
|
407
|
-
// If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
|
|
408
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
409
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
410
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
411
|
-
if (trimmed.startsWith('ASK')) {
|
|
412
|
-
instance[propName] = result === true || result === 'true';
|
|
413
|
-
}
|
|
414
|
-
else if (result && result.length > 0) {
|
|
415
|
-
// Get first binding's first value
|
|
416
|
-
const firstRow = result[0];
|
|
417
|
-
const firstKey = Object.keys(firstRow)[0];
|
|
418
|
-
const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
|
|
419
|
-
if (val !== undefined && val !== null && val !== 'None' && val !== '') {
|
|
420
|
-
instance[propName] = val;
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
else {
|
|
425
|
-
// Legacy SurrealDB-style getter — safety guard for getters that don't match
|
|
426
|
-
// SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
427
|
-
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
catch (error) {
|
|
431
|
-
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
} // end skipPropertyGetters guard
|
|
436
|
-
// Evaluate relation getters (explicit or auto-generated from target)
|
|
437
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
438
|
-
// Skip relations excluded by property projection (unless in include map)
|
|
439
|
-
if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
|
|
440
|
-
continue;
|
|
441
|
-
const meta = relMeta;
|
|
442
|
-
// Determine the getter to execute:
|
|
443
|
-
// 1. Explicit `getter` always wins
|
|
444
|
-
// 2. If `target` is set and `filter !== false`, auto-generate conformance getter
|
|
445
|
-
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
446
|
-
// because buildConformanceGetter traverses outgoing links which is wrong for
|
|
447
|
-
// reverse relations. Their values are already populated by the reverse link
|
|
448
|
-
// lookup in instancesFromQueryResult / getData.
|
|
449
|
-
let getter = meta.getter;
|
|
450
|
-
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
451
|
-
try {
|
|
452
|
-
const TargetClass = meta.target?.();
|
|
453
|
-
const targetMetadata = TargetClass
|
|
454
|
-
? TargetClass.getModelMetadata?.() ?? null
|
|
455
|
-
: null;
|
|
456
|
-
// Check if all where conditions can be SPARQL-filtered.
|
|
457
|
-
// literal-resolved properties store signed expressions (literal:json:{…}),
|
|
458
|
-
// not raw literal:string: IRIs, so SPARQL exact-match fails for them.
|
|
459
|
-
let allSparqlFilterable = true;
|
|
460
|
-
if (targetMetadata) {
|
|
461
|
-
for (const propName of Object.keys(meta.where)) {
|
|
462
|
-
if (['id', 'author', 'timestamp'].includes(propName))
|
|
463
|
-
continue;
|
|
464
|
-
const propMeta = targetMetadata.properties[propName];
|
|
465
|
-
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
466
|
-
allSparqlFilterable = false;
|
|
467
|
-
break;
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
else {
|
|
472
|
-
allSparqlFilterable = false;
|
|
473
|
-
}
|
|
474
|
-
if (allSparqlFilterable) {
|
|
475
|
-
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
476
|
-
if (conditions.length > 0) {
|
|
477
|
-
const escapedPredicate = escapeQueryString(meta.predicate);
|
|
478
|
-
getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
// If not filterable, fall through to buildConformanceGetter + JS post-filter below
|
|
482
|
-
}
|
|
483
|
-
catch (e) {
|
|
484
|
-
console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
488
|
-
try {
|
|
489
|
-
const TargetClass = meta.target();
|
|
490
|
-
getter = buildConformanceGetter(meta.predicate, TargetClass);
|
|
491
|
-
if (!getter) {
|
|
492
|
-
console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
catch (e) {
|
|
496
|
-
console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
if (getter) {
|
|
500
|
-
try {
|
|
501
|
-
const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
|
|
502
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
503
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
504
|
-
// Native SPARQL getter — execute directly
|
|
505
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
506
|
-
if (result && result.length > 0) {
|
|
507
|
-
const values = result.map((r) => {
|
|
508
|
-
const firstKey = Object.keys(r)[0];
|
|
509
|
-
return r[firstKey]?.value ?? r[firstKey];
|
|
510
|
-
}).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
511
|
-
instance[relName] = values;
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
else {
|
|
515
|
-
// Legacy SurrealDB-style getter — safety guard for relation getters that don't
|
|
516
|
-
// match SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
517
|
-
console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
catch (error) {
|
|
521
|
-
console.warn(`Failed to evaluate getter for ${relName}:`, error);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
// JS post-filter for where conditions that couldn't be SPARQL-filtered
|
|
525
|
-
// (e.g. literal-resolved properties storing signed expressions)
|
|
526
|
-
const currentValues = instance[relName];
|
|
527
|
-
if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
|
|
528
|
-
const TargetClass = meta.target?.();
|
|
529
|
-
if (TargetClass) {
|
|
530
|
-
const filtered = [];
|
|
531
|
-
for (const targetId of currentValues) {
|
|
532
|
-
try {
|
|
533
|
-
const inst = new TargetClass(perspective, targetId);
|
|
534
|
-
await inst.get();
|
|
535
|
-
let matches = true;
|
|
536
|
-
for (const [prop, expected] of Object.entries(meta.where)) {
|
|
537
|
-
if (inst[prop] !== expected) {
|
|
538
|
-
matches = false;
|
|
539
|
-
break;
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
if (matches)
|
|
543
|
-
filtered.push(targetId);
|
|
544
|
-
}
|
|
545
|
-
catch {
|
|
546
|
-
// If we can't hydrate, keep the value (conservative)
|
|
547
|
-
filtered.push(targetId);
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
instance[relName] = filtered;
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
/**
|
|
556
|
-
* Hydrates relation fields on instances according to the provided IncludeMap.
|
|
557
|
-
*
|
|
558
|
-
* For each relation listed in `includeMap`, the raw expression-URI strings
|
|
559
|
-
* stored on the instance are replaced with fully-hydrated model instances
|
|
560
|
-
* (fetched via the relation's `target()` class). Nested IncludeMaps are
|
|
561
|
-
* supported for multi-level eager loading.
|
|
562
|
-
*
|
|
563
|
-
* @param modelClass - The model class whose relation metadata to read
|
|
564
|
-
* @param instances - The instances whose relations should be hydrated
|
|
565
|
-
* @param perspective - The perspective to fetch related instances from
|
|
566
|
-
* @param includeMap - Describes which relations to hydrate
|
|
567
|
-
*/
|
|
568
|
-
export async function hydrateRelations(modelClass, instances, perspective, includeMap) {
|
|
569
|
-
if (!includeMap || Object.keys(includeMap).length === 0)
|
|
570
|
-
return;
|
|
571
|
-
const relMeta = getRelationsMetadata(modelClass);
|
|
572
|
-
// ── Projections ($-prefixed keys) ────────────────────────────────────────
|
|
573
|
-
// Collect all projection entries up-front so we can batch the count queries
|
|
574
|
-
// together per-projection before processing. Each projection key starts
|
|
575
|
-
// with '$' and has a descriptor with a `from` field.
|
|
576
|
-
const projectionEntries = [];
|
|
577
|
-
for (const [key, val] of Object.entries(includeMap)) {
|
|
578
|
-
if (key.startsWith('$') && val !== null && typeof val === 'object' && 'from' in val) {
|
|
579
|
-
projectionEntries.push([key, val]);
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
for (const [projKey, proj] of projectionEntries) {
|
|
583
|
-
const sourceMeta = relMeta[proj.from];
|
|
584
|
-
if (!sourceMeta) {
|
|
585
|
-
console.warn(`include projection "${projKey}": relation "${proj.from}" not found in metadata, skipping`);
|
|
586
|
-
for (const inst of instances)
|
|
587
|
-
inst[projKey] = proj.count ? 0 : [];
|
|
588
|
-
continue;
|
|
589
|
-
}
|
|
590
|
-
const TargetClass = sourceMeta.target();
|
|
591
|
-
const allParentIds = instances.map(inst => inst.id).filter(Boolean);
|
|
592
|
-
if (proj.count) {
|
|
593
|
-
// ── Path A: grouped SPARQL COUNT ─────────────────────────────────────
|
|
594
|
-
// One round-trip, zero instance hydration. Returns one row per parent.
|
|
595
|
-
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
596
|
-
const targetRelMeta = TargetClass.getAllRelationsMetadata?.() ?? {};
|
|
597
|
-
let countMap = new Map();
|
|
598
|
-
if (targetMetadata && allParentIds.length > 0) {
|
|
599
|
-
try {
|
|
600
|
-
const sparql = buildSPARQLGroupedCountQuery(targetMetadata, targetRelMeta, sourceMeta.predicate, allParentIds, proj.where);
|
|
601
|
-
const raw = await perspective.querySparql(sparql);
|
|
602
|
-
const rows = Array.isArray(raw) ? raw
|
|
603
|
-
: raw?.results?.bindings ?? raw?.bindings ?? [];
|
|
604
|
-
countMap = parseSparqlGroupedCount(rows);
|
|
605
|
-
}
|
|
606
|
-
catch (e) {
|
|
607
|
-
console.warn(`include projection "${projKey}" count query failed, falling back to 0:`, e);
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
for (const inst of instances) {
|
|
611
|
-
inst[projKey] = countMap.get(inst.id) ?? 0;
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
else {
|
|
615
|
-
// ── Path B: findAll + Map distribution ───────────────────────────────
|
|
616
|
-
// For reverse relations we don't have the child IDs on the instance,
|
|
617
|
-
// so fall back to a parent-scoped findAll per instance (uncommon path).
|
|
618
|
-
const isReverse = sourceMeta.kind === 'belongsToOne' || sourceMeta.kind === 'belongsToMany';
|
|
619
|
-
if (isReverse) {
|
|
620
|
-
// Reverse: the link goes child→parent, reuse the batched SPARQL pattern
|
|
621
|
-
// from the existing belongsTo path to collect source IDs per parent.
|
|
622
|
-
if (allParentIds.length > 0) {
|
|
623
|
-
const sparqlQuery = `SELECT ?source ?target WHERE {
|
|
624
|
-
GRAPH ?g { ?source <${sourceMeta.predicate}> ?target }
|
|
625
|
-
FILTER(?target IN (${allParentIds.map(id => `<${id}>`).join(', ')}))
|
|
626
|
-
}`;
|
|
627
|
-
const sourcesByTarget = new Map();
|
|
628
|
-
try {
|
|
629
|
-
const raw = await perspective.querySparql(sparqlQuery);
|
|
630
|
-
const bindings = Array.isArray(raw) ? raw : raw?.results?.bindings ?? raw?.bindings ?? [];
|
|
631
|
-
for (const row of bindings) {
|
|
632
|
-
const source = row.source?.value ?? row.source;
|
|
633
|
-
const target = row.target?.value ?? row.target;
|
|
634
|
-
if (!source || !target)
|
|
635
|
-
continue;
|
|
636
|
-
if (!sourcesByTarget.has(target))
|
|
637
|
-
sourcesByTarget.set(target, []);
|
|
638
|
-
sourcesByTarget.get(target).push(source);
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
catch (e) {
|
|
642
|
-
console.warn(`include projection "${projKey}" reverse SPARQL failed:`, e);
|
|
643
|
-
}
|
|
644
|
-
const allSourceIds = new Set();
|
|
645
|
-
for (const ids of sourcesByTarget.values())
|
|
646
|
-
for (const id of ids)
|
|
647
|
-
allSourceIds.add(id);
|
|
648
|
-
const hydratedMap = new Map();
|
|
649
|
-
if (allSourceIds.size > 0) {
|
|
650
|
-
const results = await TargetClass.findAll(perspective, {
|
|
651
|
-
where: { id: Array.from(allSourceIds), ...(proj.where ?? {}) },
|
|
652
|
-
});
|
|
653
|
-
for (const r of results)
|
|
654
|
-
hydratedMap.set(r.id, r);
|
|
655
|
-
}
|
|
656
|
-
for (const inst of instances) {
|
|
657
|
-
const sourceIds = sourcesByTarget.get(inst.id) ?? [];
|
|
658
|
-
let resolved = sourceIds.map(id => hydratedMap.get(id)).filter((v) => v != null);
|
|
659
|
-
if (proj.limit != null) {
|
|
660
|
-
if (proj.limit === 1) {
|
|
661
|
-
inst[projKey] = resolved[0] ?? null;
|
|
662
|
-
}
|
|
663
|
-
else {
|
|
664
|
-
inst[projKey] = resolved.slice(0, proj.limit);
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
else {
|
|
668
|
-
inst[projKey] = resolved;
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
else {
|
|
673
|
-
for (const inst of instances)
|
|
674
|
-
inst[projKey] = proj.limit === 1 ? null : [];
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
else {
|
|
678
|
-
// Forward: instance[from] holds raw child URIs — collect across all parents
|
|
679
|
-
const uriSet = new Set();
|
|
680
|
-
const rawCache = new Map();
|
|
681
|
-
for (const inst of instances) {
|
|
682
|
-
const raw = inst[proj.from];
|
|
683
|
-
const uris = [];
|
|
684
|
-
if (Array.isArray(raw)) {
|
|
685
|
-
for (const v of raw) {
|
|
686
|
-
const id = typeof v === 'string' ? v : v?.id;
|
|
687
|
-
if (id) {
|
|
688
|
-
uriSet.add(id);
|
|
689
|
-
uris.push(id);
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
else if (typeof raw === 'string') {
|
|
694
|
-
uriSet.add(raw);
|
|
695
|
-
uris.push(raw);
|
|
696
|
-
}
|
|
697
|
-
else if (raw?.id) {
|
|
698
|
-
uriSet.add(raw.id);
|
|
699
|
-
uris.push(raw.id);
|
|
700
|
-
}
|
|
701
|
-
rawCache.set(inst, uris);
|
|
702
|
-
}
|
|
703
|
-
const hydratedMap = new Map();
|
|
704
|
-
if (uriSet.size > 0) {
|
|
705
|
-
const results = await TargetClass.findAll(perspective, {
|
|
706
|
-
where: { id: Array.from(uriSet), ...(proj.where ?? {}) },
|
|
707
|
-
});
|
|
708
|
-
for (const r of results)
|
|
709
|
-
hydratedMap.set(r.id, r);
|
|
710
|
-
}
|
|
711
|
-
for (const inst of instances) {
|
|
712
|
-
const uris = rawCache.get(inst) ?? [];
|
|
713
|
-
const resolved = uris.map(id => hydratedMap.get(id)).filter((v) => v != null);
|
|
714
|
-
if (proj.limit === 1) {
|
|
715
|
-
inst[projKey] = resolved[0] ?? null;
|
|
716
|
-
}
|
|
717
|
-
else if (proj.limit != null) {
|
|
718
|
-
inst[projKey] = resolved.slice(0, proj.limit);
|
|
719
|
-
}
|
|
720
|
-
else {
|
|
721
|
-
inst[projKey] = resolved;
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
// ── Standard relations (non-projected) ───────────────────────────────────
|
|
728
|
-
for (const [relName, includeValue] of Object.entries(includeMap)) {
|
|
729
|
-
// Skip projection keys — already handled above
|
|
730
|
-
if (relName.startsWith('$') && typeof includeValue === 'object' && includeValue !== null && 'from' in includeValue)
|
|
731
|
-
continue;
|
|
732
|
-
const meta = relMeta[relName];
|
|
733
|
-
if (!meta) {
|
|
734
|
-
console.warn(`include: relation "${relName}" not found in metadata, skipping`);
|
|
735
|
-
continue;
|
|
736
|
-
}
|
|
737
|
-
const TargetClass = meta.target();
|
|
738
|
-
// Determine if a RelationSubQuery was supplied (object) vs a plain `true`
|
|
739
|
-
const subQuery = typeof includeValue === 'object' && includeValue !== null
|
|
740
|
-
? includeValue
|
|
741
|
-
: undefined;
|
|
742
|
-
const nestedInclude = subQuery?.include;
|
|
743
|
-
// ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
|
|
744
|
-
// The link goes target→instance, so we query backwards:
|
|
745
|
-
// predicate = meta.predicate, target = inst.id → source is the related id
|
|
746
|
-
//
|
|
747
|
-
// PERF: Batch all reverse lookups into a single SPARQL query instead of
|
|
748
|
-
// N sequential perspective.get() calls (N+1 → 1 optimisation).
|
|
749
|
-
if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
|
|
750
|
-
const allIds = instances.map(inst => inst.id).filter(Boolean);
|
|
751
|
-
// Batch query: find all (source, target) pairs for this predicate
|
|
752
|
-
// where target is one of our instance IDs
|
|
753
|
-
const sourcesByTarget = new Map();
|
|
754
|
-
if (allIds.length > 0) {
|
|
755
|
-
const sparqlQuery = `SELECT ?source ?target WHERE {
|
|
756
|
-
GRAPH ?g { ?source <${meta.predicate}> ?target }
|
|
757
|
-
FILTER(?target IN (${allIds.map(id => `<${id}>`).join(', ')}))
|
|
758
|
-
}`;
|
|
759
|
-
try {
|
|
760
|
-
const sparqlResult = await perspective.querySparql(sparqlQuery);
|
|
761
|
-
// Parse SPARQL results — querySparql returns a flat array of row objects
|
|
762
|
-
// e.g. [{ source: "uri1", target: "uri2" }, ...]
|
|
763
|
-
const bindings = Array.isArray(sparqlResult) ? sparqlResult
|
|
764
|
-
: sparqlResult?.results?.bindings ?? sparqlResult?.bindings ?? [];
|
|
765
|
-
for (const row of bindings) {
|
|
766
|
-
const source = row.source?.value ?? row.source;
|
|
767
|
-
const target = row.target?.value ?? row.target;
|
|
768
|
-
if (!source || !target)
|
|
769
|
-
continue;
|
|
770
|
-
if (!sourcesByTarget.has(target))
|
|
771
|
-
sourcesByTarget.set(target, []);
|
|
772
|
-
sourcesByTarget.get(target).push(source);
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
catch (e) {
|
|
776
|
-
// Fallback: sequential queries if SPARQL fails
|
|
777
|
-
console.warn('Batched reverse relation SPARQL failed, falling back to sequential:', e);
|
|
778
|
-
for (const inst of instances) {
|
|
779
|
-
const reverseLinks = await perspective.get(new LinkQuery({ predicate: meta.predicate, target: inst.id }));
|
|
780
|
-
const sourceIds = reverseLinks
|
|
781
|
-
.filter(l => l.data.target === inst.id)
|
|
782
|
-
.map(l => l.data.source);
|
|
783
|
-
if (sourceIds.length > 0) {
|
|
784
|
-
sourcesByTarget.set(inst.id, sourceIds);
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
// Collect ALL source IDs across all instances for batch hydration
|
|
790
|
-
const allSourceIds = new Set();
|
|
791
|
-
for (const ids of sourcesByTarget.values()) {
|
|
792
|
-
for (const id of ids)
|
|
793
|
-
allSourceIds.add(id);
|
|
794
|
-
}
|
|
795
|
-
// Batch-hydrate all related instances at once (1 findAll instead of N)
|
|
796
|
-
const hydratedMap = new Map();
|
|
797
|
-
if (allSourceIds.size > 0) {
|
|
798
|
-
const fetchQuery = {
|
|
799
|
-
where: {
|
|
800
|
-
id: Array.from(allSourceIds),
|
|
801
|
-
...(subQuery?.where ?? {}),
|
|
802
|
-
},
|
|
803
|
-
...(subQuery?.order && { order: subQuery.order }),
|
|
804
|
-
...(subQuery?.properties && { properties: subQuery.properties }),
|
|
805
|
-
};
|
|
806
|
-
try {
|
|
807
|
-
const allResults = await TargetClass.findAll(perspective, fetchQuery);
|
|
808
|
-
for (const r of allResults)
|
|
809
|
-
hydratedMap.set(r.id, r);
|
|
810
|
-
}
|
|
811
|
-
catch {
|
|
812
|
-
// Fallback: hydrate individually
|
|
813
|
-
await Promise.all(Array.from(allSourceIds).map(async (sid) => {
|
|
814
|
-
try {
|
|
815
|
-
const related = new TargetClass(perspective, sid);
|
|
816
|
-
await related.get(subQuery?.properties ? { properties: subQuery.properties } : undefined);
|
|
817
|
-
hydratedMap.set(sid, related);
|
|
818
|
-
}
|
|
819
|
-
catch { /* skip */ }
|
|
820
|
-
}));
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
// Assign hydrated instances to each parent
|
|
824
|
-
for (const inst of instances) {
|
|
825
|
-
const instId = inst.id;
|
|
826
|
-
const sourceIds = sourcesByTarget.get(instId) ?? [];
|
|
827
|
-
if (meta.kind === 'belongsToOne') {
|
|
828
|
-
if (sourceIds.length === 0) {
|
|
829
|
-
inst[relName] = null;
|
|
830
|
-
continue;
|
|
831
|
-
}
|
|
832
|
-
const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
|
|
833
|
-
inst[relName] = hydratedMap.get(sourceId) ?? null;
|
|
834
|
-
}
|
|
835
|
-
else {
|
|
836
|
-
// belongsToMany — return array of hydrated instances
|
|
837
|
-
let hydrated = sourceIds
|
|
838
|
-
.map(sid => hydratedMap.get(sid))
|
|
839
|
-
.filter((v) => v != null);
|
|
840
|
-
// Apply order (client-side)
|
|
841
|
-
if (subQuery?.order) {
|
|
842
|
-
const orderEntries = Object.entries(subQuery.order);
|
|
843
|
-
hydrated = hydrated.sort((a, b) => {
|
|
844
|
-
for (const [field, dir] of orderEntries) {
|
|
845
|
-
const av = String(a[field] ?? '');
|
|
846
|
-
const bv = String(b[field] ?? '');
|
|
847
|
-
const diff = av.localeCompare(bv);
|
|
848
|
-
if (diff !== 0)
|
|
849
|
-
return dir === 'DESC' ? -diff : diff;
|
|
850
|
-
}
|
|
851
|
-
return 0;
|
|
852
|
-
});
|
|
853
|
-
}
|
|
854
|
-
// Apply offset and limit
|
|
855
|
-
if (subQuery?.offset != null || subQuery?.limit != null) {
|
|
856
|
-
const start = subQuery.offset ?? 0;
|
|
857
|
-
const end = subQuery.limit != null ? start + subQuery.limit : undefined;
|
|
858
|
-
hydrated = hydrated.slice(start, end);
|
|
859
|
-
}
|
|
860
|
-
inst[relName] = hydrated;
|
|
861
|
-
// Recurse for nested includes
|
|
862
|
-
if (nestedInclude && hydrated.length > 0) {
|
|
863
|
-
await hydrateRelations(TargetClass, hydrated, perspective, nestedInclude);
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
continue; // skip the forward-relation path below
|
|
868
|
-
}
|
|
869
|
-
// ── Forward relations (hasMany / hasOne) ──────────────────────────────
|
|
870
|
-
// Collect all unique URIs across all instances for batch-friendly lookup.
|
|
871
|
-
// IMPORTANT: We cache each instance's raw value NOW (before the async
|
|
872
|
-
// findAll) so that concurrent getData() calls on the same instance can't
|
|
873
|
-
// overwrite the relation field between the uriSet relation and the
|
|
874
|
-
// post-await assignment loop. Without this cache, a concurrent call
|
|
875
|
-
// can replace the raw URI strings with hydrated model objects, causing
|
|
876
|
-
// the `typeof v === 'string'` check to fail and the array to end up empty.
|
|
877
|
-
const uriSet = new Set();
|
|
878
|
-
const rawCache = new Map();
|
|
879
|
-
for (const inst of instances) {
|
|
880
|
-
const raw = inst[relName];
|
|
881
|
-
rawCache.set(inst, Array.isArray(raw) ? [...raw] : raw);
|
|
882
|
-
if (raw == null)
|
|
883
|
-
continue;
|
|
884
|
-
if (Array.isArray(raw)) {
|
|
885
|
-
for (const v of raw) {
|
|
886
|
-
if (typeof v === 'string')
|
|
887
|
-
uriSet.add(v);
|
|
888
|
-
// Handle already-hydrated instances (from a concurrent call)
|
|
889
|
-
else if (v && typeof v === 'object' && typeof v.id === 'string')
|
|
890
|
-
uriSet.add(v.id);
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
else if (typeof raw === 'string') {
|
|
894
|
-
uriSet.add(raw);
|
|
895
|
-
}
|
|
896
|
-
else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
|
|
897
|
-
uriSet.add(raw.id);
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
if (uriSet.size === 0)
|
|
901
|
-
continue;
|
|
902
|
-
// Hydrate related instances using findAll to ensure conformance checking.
|
|
903
|
-
// findAll validates model membership via graph traversal (required predicates / flags),
|
|
904
|
-
// so non-conforming linked URIs are silently dropped — matching the documented behaviour.
|
|
905
|
-
const hydrated = new Map();
|
|
906
|
-
const whereWithIds = {
|
|
907
|
-
id: Array.from(uriSet),
|
|
908
|
-
...(subQuery?.where ?? {}),
|
|
909
|
-
};
|
|
910
|
-
const fetchQuery = {
|
|
911
|
-
where: whereWithIds,
|
|
912
|
-
...(subQuery?.order && { order: subQuery.order }),
|
|
913
|
-
...(subQuery?.properties && { properties: subQuery.properties }),
|
|
914
|
-
};
|
|
915
|
-
const results = await TargetClass.findAll(perspective, fetchQuery);
|
|
916
|
-
for (const result of results) {
|
|
917
|
-
hydrated.set(result.id, result);
|
|
918
|
-
}
|
|
919
|
-
// Replace raw URIs with hydrated instances on each parent instance.
|
|
920
|
-
// Use the cached raw values captured BEFORE the async findAll to avoid
|
|
921
|
-
// the race condition where a concurrent getData() already replaced the
|
|
922
|
-
// strings with hydrated objects.
|
|
923
|
-
for (const inst of instances) {
|
|
924
|
-
const raw = rawCache.get(inst);
|
|
925
|
-
if (raw == null)
|
|
926
|
-
continue;
|
|
927
|
-
if (Array.isArray(raw)) {
|
|
928
|
-
// Map URIs → instances; handle both raw strings and already-hydrated objects
|
|
929
|
-
let resolved = raw
|
|
930
|
-
.map((v) => {
|
|
931
|
-
if (typeof v === 'string') {
|
|
932
|
-
return hydrated.has(v) ? hydrated.get(v) : null;
|
|
933
|
-
}
|
|
934
|
-
// Already a hydrated model instance (from a concurrent call)
|
|
935
|
-
if (v && typeof v === 'object' && typeof v.id === 'string') {
|
|
936
|
-
return hydrated.has(v.id) ? hydrated.get(v.id) : v;
|
|
937
|
-
}
|
|
938
|
-
return null;
|
|
939
|
-
})
|
|
940
|
-
.filter((v) => v !== null);
|
|
941
|
-
// Per-instance sort (client-side, after filtering)
|
|
942
|
-
if (subQuery?.order) {
|
|
943
|
-
const orderEntries = Object.entries(subQuery.order);
|
|
944
|
-
resolved = resolved.sort((a, b) => {
|
|
945
|
-
for (const [field, dir] of orderEntries) {
|
|
946
|
-
const av = String(a[field] ?? '');
|
|
947
|
-
const bv = String(b[field] ?? '');
|
|
948
|
-
const diff = av.localeCompare(bv);
|
|
949
|
-
if (diff !== 0)
|
|
950
|
-
return dir === 'DESC' ? -diff : diff;
|
|
951
|
-
}
|
|
952
|
-
return 0;
|
|
953
|
-
});
|
|
954
|
-
}
|
|
955
|
-
// Per-instance limit / offset
|
|
956
|
-
if (subQuery?.offset != null || subQuery?.limit != null) {
|
|
957
|
-
const start = subQuery.offset ?? 0;
|
|
958
|
-
const end = subQuery.limit != null ? start + subQuery.limit : undefined;
|
|
959
|
-
resolved = resolved.slice(start, end);
|
|
960
|
-
}
|
|
961
|
-
// Enforce maxCount guard — single-valued relations keep only the last item
|
|
962
|
-
if (meta.maxCount === 1) {
|
|
963
|
-
if (resolved.length > 1) {
|
|
964
|
-
console.warn(`include: relation "${relName}" has maxCount 1 but ${resolved.length} values found; keeping the last`);
|
|
965
|
-
}
|
|
966
|
-
inst[relName] = resolved.length > 0
|
|
967
|
-
? resolved[resolved.length - 1]
|
|
968
|
-
: null;
|
|
969
|
-
}
|
|
970
|
-
else {
|
|
971
|
-
inst[relName] = resolved;
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
else if (typeof raw === 'string' && hydrated.has(raw)) {
|
|
975
|
-
inst[relName] = hydrated.get(raw);
|
|
976
|
-
}
|
|
977
|
-
else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
|
|
978
|
-
// Already-hydrated object — look up refreshed version or keep as-is
|
|
979
|
-
inst[relName] = hydrated.has(raw.id) ? hydrated.get(raw.id) : raw;
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
// Recurse for nested includes
|
|
983
|
-
if (nestedInclude) {
|
|
984
|
-
const hydratedInstances = Array.from(hydrated.values());
|
|
985
|
-
await hydrateRelations(TargetClass, hydratedInstances, perspective, nestedInclude);
|
|
986
|
-
}
|
|
987
|
-
}
|
|
988
|
-
}
|