@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-2
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/lib/index.cjs +1392 -777
- package/lib/index.js +1376 -775
- package/lib/src/Literal.js +6 -5
- package/lib/src/agent/AgentClient.d.ts +5 -1
- package/lib/src/agent/AgentClient.js +48 -2
- package/lib/src/expression/ExpressionRef.js +2 -2
- package/lib/src/language/Language.d.ts +41 -3
- package/lib/src/model/Ad4mModel.d.ts +28 -28
- package/lib/src/model/Ad4mModel.js +129 -101
- package/lib/src/model/Ad4mModel.test.js +1543 -535
- package/lib/src/model/ModelQueryBuilder.d.ts +48 -34
- package/lib/src/model/ModelQueryBuilder.js +163 -78
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/decorators.d.ts +14 -8
- package/lib/src/model/decorators.js +41 -14
- package/lib/src/model/hydration-batch.d.ts +34 -0
- package/lib/src/model/hydration-batch.js +147 -0
- package/lib/src/model/hydration.d.ts +3 -3
- package/lib/src/model/hydration.js +106 -36
- package/lib/src/model/index.d.ts +4 -1
- package/lib/src/model/index.js +4 -1
- package/lib/src/model/json-schema.js +2 -2
- package/lib/src/model/query-cache.d.ts +30 -0
- package/lib/src/model/query-cache.js +66 -0
- package/lib/src/model/query-cache.test.d.ts +1 -0
- package/lib/src/model/query-cache.test.js +43 -0
- package/lib/src/model/query-common.d.ts +1 -1
- package/lib/src/model/query-common.js +1 -1
- package/lib/src/model/query-sparql-batch.d.ts +17 -0
- package/lib/src/model/query-sparql-batch.js +260 -0
- package/lib/src/model/query-sparql.d.ts +47 -0
- package/lib/src/model/query-sparql.js +336 -0
- package/lib/src/model/query-utils.d.ts +45 -0
- package/lib/src/model/query-utils.js +140 -0
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/sdna.js +1 -1
- package/lib/src/model/shacl-gen.js +42 -18
- package/lib/src/model/subscription-pool.d.ts +39 -0
- package/lib/src/model/subscription-pool.js +119 -0
- package/lib/src/model/types.d.ts +3 -3
- package/lib/src/model/types.js +1 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -17
- package/lib/src/perspectives/PerspectiveClient.js +5 -57
- package/lib/src/perspectives/PerspectiveProxy.d.ts +51 -30
- package/lib/src/perspectives/PerspectiveProxy.js +224 -177
- package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveResolver.js +0 -11
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
- package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
- package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
- package/lib/src/runtime/RuntimeResolver.js +56 -0
- package/lib/src/schema.gql +11 -1
- package/lib/src/shacl/SHACLFlow.d.ts +1 -1
- package/lib/src/shacl/SHACLFlow.js +9 -9
- package/lib/src/shacl/SHACLShape.d.ts +1 -1
- package/lib/src/shacl/SHACLShape.js +38 -38
- package/lib/src/typeDefs.js +11 -1
- package/lib/src/utils.d.ts +6 -6
- package/lib/src/utils.js +6 -6
- package/package.json +1 -1
- package/src/Literal.test.ts +10 -5
- package/src/Literal.ts +6 -5
- package/src/agent/AgentClient.ts +53 -1
- package/src/expression/ExpressionRef.ts +2 -2
- package/src/language/Language.ts +48 -3
- package/src/model/Ad4mModel.test.ts +1515 -565
- package/src/model/Ad4mModel.ts +142 -102
- package/src/model/ModelQueryBuilder.ts +185 -86
- package/src/model/Subject.ts +6 -6
- package/src/model/decorators.ts +51 -22
- package/src/model/hydration-batch.ts +205 -0
- package/src/model/hydration.ts +102 -39
- package/src/model/index.ts +4 -1
- package/src/model/json-schema.ts +2 -2
- package/src/model/query-cache.test.ts +54 -0
- package/src/model/query-cache.ts +79 -0
- package/src/model/query-common.ts +1 -1
- package/src/model/query-sparql-batch.ts +301 -0
- package/src/model/query-sparql.ts +363 -0
- package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
- package/src/model/relation-filtering.test.ts +15 -15
- package/src/model/sdna.ts +1 -1
- package/src/model/shacl-gen.ts +42 -17
- package/src/model/subscription-pool.ts +163 -0
- package/src/model/types.ts +3 -3
- package/src/perspectives/PerspectiveClient.ts +5 -61
- package/src/perspectives/PerspectiveProxy.ts +226 -181
- package/src/perspectives/PerspectiveResolver.ts +0 -8
- package/src/perspectives/WakerSubscriptionManager.ts +8 -9
- package/src/runtime/RuntimeResolver.ts +43 -0
- package/src/shacl/SHACLFlow.ts +9 -9
- package/src/shacl/SHACLShape.ts +39 -39
- package/src/utils.ts +6 -6
- package/src/model/query-surreal.ts +0 -280
|
@@ -1,16 +1,26 @@
|
|
|
1
1
|
import { capitalize } from "./util";
|
|
2
2
|
import { buildSDNA } from "./sdna";
|
|
3
3
|
import { buildSHACL } from "./shacl-gen";
|
|
4
|
-
import {
|
|
4
|
+
import { escapeQueryString } from "../utils";
|
|
5
5
|
/** Registry of property metadata keyed by constructor → { propName → metadata } */
|
|
6
6
|
const propertyRegistry = new WeakMap();
|
|
7
7
|
/** Registry of relation metadata keyed by constructor → { propName → metadata } */
|
|
8
8
|
const relationRegistry = new WeakMap();
|
|
9
|
+
/** Memoisation cache for getPropertiesMetadata — avoids repeated prototype-chain walks */
|
|
10
|
+
const propertiesMetadataCache = new WeakMap();
|
|
11
|
+
/** Memoisation cache for getRelationsMetadata — avoids repeated prototype-chain walks */
|
|
12
|
+
const relationsMetadataCache = new WeakMap();
|
|
13
|
+
/** Memoisation cache for generateSHACL — avoids recomputing SHACL shapes */
|
|
14
|
+
const shaclCache = new WeakMap();
|
|
9
15
|
/**
|
|
10
16
|
* Retrieve property metadata for a given class constructor.
|
|
11
17
|
* Walks the prototype chain so subclass decorators compose with parent decorators.
|
|
18
|
+
* Results are memoised per class constructor.
|
|
12
19
|
*/
|
|
13
20
|
export function getPropertiesMetadata(ctor) {
|
|
21
|
+
const cached = propertiesMetadataCache.get(ctor);
|
|
22
|
+
if (cached)
|
|
23
|
+
return cached;
|
|
14
24
|
const result = {};
|
|
15
25
|
const chain = [];
|
|
16
26
|
let current = ctor;
|
|
@@ -23,13 +33,18 @@ export function getPropertiesMetadata(ctor) {
|
|
|
23
33
|
if (meta)
|
|
24
34
|
Object.assign(result, meta);
|
|
25
35
|
}
|
|
36
|
+
propertiesMetadataCache.set(ctor, result);
|
|
26
37
|
return result;
|
|
27
38
|
}
|
|
28
39
|
/**
|
|
29
40
|
* Retrieve relation metadata for a given class constructor.
|
|
30
41
|
* Walks the prototype chain so subclass decorators compose with parent decorators.
|
|
42
|
+
* Results are memoised per class constructor.
|
|
31
43
|
*/
|
|
32
44
|
export function getRelationsMetadata(ctor) {
|
|
45
|
+
const cached = relationsMetadataCache.get(ctor);
|
|
46
|
+
if (cached)
|
|
47
|
+
return cached;
|
|
33
48
|
const result = {};
|
|
34
49
|
const chain = [];
|
|
35
50
|
let current = ctor;
|
|
@@ -42,6 +57,18 @@ export function getRelationsMetadata(ctor) {
|
|
|
42
57
|
if (meta)
|
|
43
58
|
Object.assign(result, meta);
|
|
44
59
|
}
|
|
60
|
+
relationsMetadataCache.set(ctor, result);
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Get or compute memoised SHACL for a class. Used by @Model decorator.
|
|
65
|
+
*/
|
|
66
|
+
export function getMemoizedSHACL(target, compute) {
|
|
67
|
+
const cached = shaclCache.get(target);
|
|
68
|
+
if (cached)
|
|
69
|
+
return cached;
|
|
70
|
+
const result = compute();
|
|
71
|
+
shaclCache.set(target, result);
|
|
45
72
|
return result;
|
|
46
73
|
}
|
|
47
74
|
/**
|
|
@@ -67,7 +94,7 @@ export function setRelationRegistryEntry(ctor, relName, meta) {
|
|
|
67
94
|
*
|
|
68
95
|
* Inspects the target class's property metadata to derive:
|
|
69
96
|
* - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
|
|
70
|
-
* - `getter`: Pre-computed
|
|
97
|
+
* - `getter`: Pre-computed graph traversal expression that traverses outgoing links and filters
|
|
71
98
|
* target nodes to only those conforming to the target shape.
|
|
72
99
|
*
|
|
73
100
|
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
@@ -78,7 +105,8 @@ export function buildConformanceFilter(relationPredicate, targetClass) {
|
|
|
78
105
|
try {
|
|
79
106
|
const targetProps = getPropertiesMetadata(targetClass);
|
|
80
107
|
const conditions = [];
|
|
81
|
-
const
|
|
108
|
+
const sparqlConditions = [];
|
|
109
|
+
let varIdx = 0;
|
|
82
110
|
// 1. Flags — check predicate + value
|
|
83
111
|
for (const [_propName, propMeta] of Object.entries(targetProps)) {
|
|
84
112
|
if (propMeta.flag && propMeta.initial && propMeta.through) {
|
|
@@ -87,7 +115,7 @@ export function buildConformanceFilter(relationPredicate, targetClass) {
|
|
|
87
115
|
predicate: propMeta.through,
|
|
88
116
|
value: propMeta.initial,
|
|
89
117
|
});
|
|
90
|
-
|
|
118
|
+
sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> <${escapeQueryString(propMeta.initial)}> .`);
|
|
91
119
|
}
|
|
92
120
|
}
|
|
93
121
|
// 2. Required (non-flag) properties — check predicate exists
|
|
@@ -98,14 +126,13 @@ export function buildConformanceFilter(relationPredicate, targetClass) {
|
|
|
98
126
|
type: 'required',
|
|
99
127
|
predicate: propMeta.through,
|
|
100
128
|
});
|
|
101
|
-
|
|
129
|
+
sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> ?_v${varIdx++} .`);
|
|
102
130
|
}
|
|
103
131
|
}
|
|
104
132
|
if (conditions.length === 0) {
|
|
105
133
|
return undefined;
|
|
106
134
|
}
|
|
107
|
-
const
|
|
108
|
-
const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
|
|
135
|
+
const getter = `SELECT ?target WHERE { <Base> <${escapeQueryString(relationPredicate)}> ?target . ${sparqlConditions.join(' ')} }`;
|
|
109
136
|
return { getter, conformanceConditions: conditions };
|
|
110
137
|
}
|
|
111
138
|
catch (e) {
|
|
@@ -126,8 +153,8 @@ function applyPropertyMetadata(opts) {
|
|
|
126
153
|
if (opts.required && !opts.initial) {
|
|
127
154
|
throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
|
|
128
155
|
}
|
|
129
|
-
if (!opts.through && !opts.prologGetter) {
|
|
130
|
-
throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
|
|
156
|
+
if (!opts.through && !opts.prologGetter && !opts.getter) {
|
|
157
|
+
throw new Error("SubjectProperty requires either 'through' or 'prologGetter' or 'getter' option");
|
|
131
158
|
}
|
|
132
159
|
// Write to WeakMap registry (keyed by constructor)
|
|
133
160
|
const ctor = target.constructor;
|
|
@@ -312,7 +339,7 @@ export function Model(opts) {
|
|
|
312
339
|
return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
|
|
313
340
|
};
|
|
314
341
|
target.generateSHACL = function () {
|
|
315
|
-
return buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter);
|
|
342
|
+
return getMemoizedSHACL(target, () => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter));
|
|
316
343
|
};
|
|
317
344
|
Object.defineProperty(target, 'type', { configurable: true });
|
|
318
345
|
};
|
|
@@ -335,7 +362,7 @@ export function Model(opts) {
|
|
|
335
362
|
* Properties are optional by default. When a model instance is created without
|
|
336
363
|
* providing a value for an optional property, no link is added to the graph.
|
|
337
364
|
* Set `required: true` explicitly when a property must always be present (this
|
|
338
|
-
* also adds a `"literal
|
|
365
|
+
* also adds a `"literal:string:uninitialized"` sentinel as the initial value
|
|
339
366
|
* so that the SDNA constructor creates a placeholder link).
|
|
340
367
|
*
|
|
341
368
|
* @example
|
|
@@ -374,7 +401,7 @@ export function Model(opts) {
|
|
|
374
401
|
* @param {PropertyOptions} opts - Property configuration
|
|
375
402
|
* @param {string} opts.through - The predicate URI for the property
|
|
376
403
|
* @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
|
|
377
|
-
* @param {string} [opts.initial] - Initial value (defaults to "literal
|
|
404
|
+
* @param {string} [opts.initial] - Initial value (defaults to "literal:string:uninitialized" when required)
|
|
378
405
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
379
406
|
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
380
407
|
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
@@ -387,7 +414,7 @@ export function Property(opts) {
|
|
|
387
414
|
required,
|
|
388
415
|
readOnly: opts.readOnly ?? false,
|
|
389
416
|
resolveLanguage: opts.resolveLanguage ?? "literal",
|
|
390
|
-
initial: opts.initial ?? (required ? "literal
|
|
417
|
+
initial: opts.initial ?? (required ? "literal:string:uninitialized" : undefined),
|
|
391
418
|
});
|
|
392
419
|
}
|
|
393
420
|
/**
|
|
@@ -476,7 +503,7 @@ function resolveRelationArgs(first, second) {
|
|
|
476
503
|
}
|
|
477
504
|
if (opts.where) {
|
|
478
505
|
throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
|
|
479
|
-
'Use `where` for DSL-based filtering, or `getter` for raw
|
|
506
|
+
'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');
|
|
480
507
|
}
|
|
481
508
|
return opts;
|
|
482
509
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch hydration for SPARQL batch query results.
|
|
3
|
+
*
|
|
4
|
+
* Takes the flat rows returned by `buildBatchSPARQLQuery()` (each tagged
|
|
5
|
+
* with ?depth, ?parentBase, ?relationName) and reconstructs a tree of
|
|
6
|
+
* model instances.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type { IncludeMap } from "./types";
|
|
11
|
+
/**
|
|
12
|
+
* A row returned by the batch SPARQL query.
|
|
13
|
+
*/
|
|
14
|
+
interface BatchRow {
|
|
15
|
+
depth: string;
|
|
16
|
+
parentBase: string;
|
|
17
|
+
relationName: string;
|
|
18
|
+
source: string;
|
|
19
|
+
predicate: string;
|
|
20
|
+
target: string;
|
|
21
|
+
author: string;
|
|
22
|
+
timestamp: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Hydrate batch SPARQL results into a tree of model instances.
|
|
26
|
+
*
|
|
27
|
+
* @param rows - Flat rows from the batch SPARQL query
|
|
28
|
+
* @param rootClass - The root model class (extends Ad4mModel)
|
|
29
|
+
* @param includeMap - The include specification from the query
|
|
30
|
+
* @param perspective - The PerspectiveProxy for creating instances
|
|
31
|
+
* @returns Array of hydrated root instances with relations populated
|
|
32
|
+
*/
|
|
33
|
+
export declare function hydrateBatchResult<T>(rows: BatchRow[], rootClass: any, includeMap: IncludeMap, perspective: any): Promise<T[]>;
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch hydration for SPARQL batch query results.
|
|
3
|
+
*
|
|
4
|
+
* Takes the flat rows returned by `buildBatchSPARQLQuery()` (each tagged
|
|
5
|
+
* with ?depth, ?parentBase, ?relationName) and reconstructs a tree of
|
|
6
|
+
* model instances.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { hydrateFromLinks, evaluateCustomGettersForInstance } from "./hydration";
|
|
11
|
+
import { getRelationsMetadata } from "./decorators";
|
|
12
|
+
/**
|
|
13
|
+
* Group batch rows by (depth, source) → array of links, preserving parentBase/relationName.
|
|
14
|
+
*/
|
|
15
|
+
function groupBatchRows(rows) {
|
|
16
|
+
const byDepth = new Map();
|
|
17
|
+
for (const row of rows) {
|
|
18
|
+
const depth = parseInt(row.depth, 10);
|
|
19
|
+
if (!byDepth.has(depth))
|
|
20
|
+
byDepth.set(depth, new Map());
|
|
21
|
+
const depthMap = byDepth.get(depth);
|
|
22
|
+
const key = row.source;
|
|
23
|
+
if (!depthMap.has(key)) {
|
|
24
|
+
depthMap.set(key, {
|
|
25
|
+
source_uri: key,
|
|
26
|
+
parentBase: row.parentBase,
|
|
27
|
+
relationName: row.relationName,
|
|
28
|
+
links: [],
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
depthMap.get(key).links.push({
|
|
32
|
+
predicate: row.predicate,
|
|
33
|
+
target: row.target,
|
|
34
|
+
author: row.author,
|
|
35
|
+
timestamp: row.timestamp,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
const result = new Map();
|
|
39
|
+
for (const [depth, map] of byDepth) {
|
|
40
|
+
result.set(depth, Array.from(map.values()));
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Hydrate batch SPARQL results into a tree of model instances.
|
|
46
|
+
*
|
|
47
|
+
* @param rows - Flat rows from the batch SPARQL query
|
|
48
|
+
* @param rootClass - The root model class (extends Ad4mModel)
|
|
49
|
+
* @param includeMap - The include specification from the query
|
|
50
|
+
* @param perspective - The PerspectiveProxy for creating instances
|
|
51
|
+
* @returns Array of hydrated root instances with relations populated
|
|
52
|
+
*/
|
|
53
|
+
export async function hydrateBatchResult(rows, rootClass, includeMap, perspective) {
|
|
54
|
+
if (!rows || rows.length === 0)
|
|
55
|
+
return [];
|
|
56
|
+
const grouped = groupBatchRows(rows);
|
|
57
|
+
// Hydrate root instances (depth 0)
|
|
58
|
+
const rootInstances = grouped.get(0) || [];
|
|
59
|
+
const metadata = rootClass.getModelMetadata();
|
|
60
|
+
const instances = [];
|
|
61
|
+
const instanceMap = new Map();
|
|
62
|
+
for (const group of rootInstances) {
|
|
63
|
+
const instance = new rootClass(perspective, group.source_uri);
|
|
64
|
+
await hydrateFromLinks(instance, group.links, metadata, perspective);
|
|
65
|
+
await evaluateCustomGettersForInstance(instance, perspective, metadata);
|
|
66
|
+
instances.push(instance);
|
|
67
|
+
instanceMap.set(group.source_uri, instance);
|
|
68
|
+
}
|
|
69
|
+
// Hydrate each depth level and wire to parents
|
|
70
|
+
const relMeta = getRelationsMetadata(rootClass);
|
|
71
|
+
const maxDepth = Math.max(...Array.from(grouped.keys()), 0);
|
|
72
|
+
// Build a map of depth → (class, relMetadata, parentInstanceMap)
|
|
73
|
+
// For depth 1, parents are root instances; for deeper depths, we need
|
|
74
|
+
// the instances from the previous level.
|
|
75
|
+
const depthInstanceMaps = new Map();
|
|
76
|
+
depthInstanceMaps.set(0, instanceMap);
|
|
77
|
+
// Build depth→class mapping from include tree
|
|
78
|
+
const depthClassMap = new Map();
|
|
79
|
+
buildDepthClassMap(rootClass, includeMap, 0, { value: 1 }, depthClassMap);
|
|
80
|
+
for (let depth = 1; depth <= maxDepth; depth++) {
|
|
81
|
+
const depthGroups = grouped.get(depth) || [];
|
|
82
|
+
if (depthGroups.length === 0)
|
|
83
|
+
continue;
|
|
84
|
+
const depthInfo = depthClassMap.get(depth);
|
|
85
|
+
if (!depthInfo)
|
|
86
|
+
continue;
|
|
87
|
+
const TargetClass = depthInfo.targetClass;
|
|
88
|
+
const targetMetadata = TargetClass.getModelMetadata
|
|
89
|
+
? TargetClass.getModelMetadata()
|
|
90
|
+
: { className: "Unknown", properties: {}, relations: {} };
|
|
91
|
+
const currentDepthInstances = new Map();
|
|
92
|
+
// Group by parentBase to wire children to parents
|
|
93
|
+
for (const group of depthGroups) {
|
|
94
|
+
const instance = new TargetClass(perspective, group.source_uri);
|
|
95
|
+
await hydrateFromLinks(instance, group.links, targetMetadata, perspective);
|
|
96
|
+
await evaluateCustomGettersForInstance(instance, perspective, targetMetadata);
|
|
97
|
+
currentDepthInstances.set(group.source_uri, instance);
|
|
98
|
+
// Wire to parent
|
|
99
|
+
// Find the parent depth's instance map
|
|
100
|
+
// The parentBase should exist in one of the prior depth maps
|
|
101
|
+
for (let pd = depth - 1; pd >= 0; pd--) {
|
|
102
|
+
const parentMap = depthInstanceMaps.get(pd);
|
|
103
|
+
if (parentMap && parentMap.has(group.parentBase)) {
|
|
104
|
+
const parent = parentMap.get(group.parentBase);
|
|
105
|
+
const relName = group.relationName;
|
|
106
|
+
// Determine relation metadata to know if it's an array or single
|
|
107
|
+
const parentRelMeta = getRelationsMetadata(pd === 0 ? rootClass : (depthClassMap.get(pd)?.targetClass || rootClass));
|
|
108
|
+
const rel = parentRelMeta[relName];
|
|
109
|
+
if (rel) {
|
|
110
|
+
if (rel.kind === 'hasMany' || rel.kind === 'belongsToMany') {
|
|
111
|
+
if (!Array.isArray(parent[relName])) {
|
|
112
|
+
parent[relName] = [];
|
|
113
|
+
}
|
|
114
|
+
parent[relName].push(instance);
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
parent[relName] = instance;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
depthInstanceMaps.set(depth, currentDepthInstances);
|
|
125
|
+
}
|
|
126
|
+
return instances;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Build a mapping from depth number to target class info.
|
|
130
|
+
*/
|
|
131
|
+
function buildDepthClassMap(parentClass, includeMap, _parentDepth, nextDepth, result) {
|
|
132
|
+
const relMeta = getRelationsMetadata(parentClass);
|
|
133
|
+
for (const [relName, includeValue] of Object.entries(includeMap)) {
|
|
134
|
+
const meta = relMeta[relName];
|
|
135
|
+
if (!meta || !meta.target)
|
|
136
|
+
continue;
|
|
137
|
+
const TargetClass = meta.target();
|
|
138
|
+
const depth = nextDepth.value++;
|
|
139
|
+
const nestedInclude = typeof includeValue === 'object' && includeValue !== null
|
|
140
|
+
? includeValue.include
|
|
141
|
+
: undefined;
|
|
142
|
+
result.set(depth, { targetClass: TargetClass, includeMap: nestedInclude });
|
|
143
|
+
if (nestedInclude) {
|
|
144
|
+
buildDepthClassMap(TargetClass, nestedInclude, depth, nextDepth, result);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* hydration.ts — Instance hydration helpers extracted from Ad4mModel.
|
|
3
3
|
*
|
|
4
4
|
* Pure / stateless functions that populate Ad4mModel instances from
|
|
5
|
-
* raw link arrays, Prolog tuples, or
|
|
5
|
+
* raw link arrays, Prolog tuples, or query results. None of these
|
|
6
6
|
* functions depend on the `Ad4mModel` class at runtime — they accept
|
|
7
7
|
* the instance, metadata, or perspective as explicit parameters.
|
|
8
8
|
*/
|
|
@@ -60,7 +60,7 @@ export declare function hydrateFromLinks(instance: any, links: Array<{
|
|
|
60
60
|
*/
|
|
61
61
|
export declare function assignValuesToInstance(perspective: PerspectiveProxy, instance: any, values: ValueTuple[]): Promise<void>;
|
|
62
62
|
/**
|
|
63
|
-
* Builds a
|
|
63
|
+
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
64
64
|
* is known but no explicit `getter` string was supplied.
|
|
65
65
|
*
|
|
66
66
|
* The generated getter traverses outgoing links matching the relation's
|
|
@@ -72,7 +72,7 @@ export declare function assignValuesToInstance(perspective: PerspectiveProxy, in
|
|
|
72
72
|
*
|
|
73
73
|
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
74
74
|
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
75
|
-
* @returns A
|
|
75
|
+
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
76
76
|
* conditions could be derived from the target model.
|
|
77
77
|
*/
|
|
78
78
|
export declare function buildConformanceGetter(relationPredicate: string, targetClass: any): string | undefined;
|
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
* hydration.ts — Instance hydration helpers extracted from Ad4mModel.
|
|
3
3
|
*
|
|
4
4
|
* Pure / stateless functions that populate Ad4mModel instances from
|
|
5
|
-
* raw link arrays, Prolog tuples, or
|
|
5
|
+
* raw link arrays, Prolog tuples, or query results. None of these
|
|
6
6
|
* functions depend on the `Ad4mModel` class at runtime — they accept
|
|
7
7
|
* the instance, metadata, or perspective as explicit parameters.
|
|
8
8
|
*/
|
|
9
9
|
import { Literal } from "../Literal";
|
|
10
10
|
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
11
11
|
import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter } from "./decorators";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
12
|
+
import { compileWhereClause } from "./query-utils";
|
|
13
|
+
import { escapeQueryString } from "../utils";
|
|
14
14
|
// ──────────────────────────────────────────────────────────
|
|
15
15
|
// Pure helpers
|
|
16
16
|
// ──────────────────────────────────────────────────────────
|
|
@@ -102,7 +102,7 @@ export async function hydratePropertyValue(target, propMeta, perspective, expect
|
|
|
102
102
|
if (propMeta.resolveLanguage != null &&
|
|
103
103
|
propMeta.resolveLanguage !== 'literal' &&
|
|
104
104
|
typeof target === 'string' &&
|
|
105
|
-
!target.startsWith('literal
|
|
105
|
+
!target.startsWith('literal:')) {
|
|
106
106
|
try {
|
|
107
107
|
const expression = await perspective.getExpression(target);
|
|
108
108
|
if (expression) {
|
|
@@ -121,7 +121,7 @@ export async function hydratePropertyValue(target, propMeta, perspective, expect
|
|
|
121
121
|
// Literal URI parsing
|
|
122
122
|
else if (propMeta.resolveLanguage === 'literal' &&
|
|
123
123
|
typeof target === 'string' &&
|
|
124
|
-
target.startsWith('literal
|
|
124
|
+
target.startsWith('literal:')) {
|
|
125
125
|
try {
|
|
126
126
|
const parsed = Literal.fromUrl(target).get();
|
|
127
127
|
value = parsed.data !== undefined ? parsed.data : parsed;
|
|
@@ -355,10 +355,10 @@ export async function assignValuesToInstance(perspective, instance, values) {
|
|
|
355
355
|
Object.assign(instance, writableProps);
|
|
356
356
|
}
|
|
357
357
|
// ──────────────────────────────────────────────────────────
|
|
358
|
-
//
|
|
358
|
+
// SPARQL custom getter evaluation
|
|
359
359
|
// ──────────────────────────────────────────────────────────
|
|
360
360
|
/**
|
|
361
|
-
* Builds a
|
|
361
|
+
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
362
362
|
* is known but no explicit `getter` string was supplied.
|
|
363
363
|
*
|
|
364
364
|
* The generated getter traverses outgoing links matching the relation's
|
|
@@ -370,7 +370,7 @@ export async function assignValuesToInstance(perspective, instance, values) {
|
|
|
370
370
|
*
|
|
371
371
|
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
372
372
|
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
373
|
-
* @returns A
|
|
373
|
+
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
374
374
|
* conditions could be derived from the target model.
|
|
375
375
|
*/
|
|
376
376
|
export function buildConformanceGetter(relationPredicate, targetClass) {
|
|
@@ -389,7 +389,7 @@ export function buildConformanceGetter(relationPredicate, targetClass) {
|
|
|
389
389
|
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
390
390
|
*/
|
|
391
391
|
export async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
|
|
392
|
-
const safeBaseExpression =
|
|
392
|
+
const safeBaseExpression = `<${instance.id}>`;
|
|
393
393
|
// Build projection filter — when requestedProperties is active, only
|
|
394
394
|
// evaluate getters for fields that are requested (or included).
|
|
395
395
|
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
@@ -400,12 +400,28 @@ export async function evaluateCustomGettersForInstance(instance, perspective, me
|
|
|
400
400
|
continue;
|
|
401
401
|
if (propMeta.getter) {
|
|
402
402
|
try {
|
|
403
|
-
|
|
404
|
-
const
|
|
405
|
-
//
|
|
406
|
-
const
|
|
407
|
-
if (
|
|
408
|
-
|
|
403
|
+
const rawGetter = propMeta.getter;
|
|
404
|
+
const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
|
|
405
|
+
// If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
|
|
406
|
+
const trimmed = getterWithBase.trim().toUpperCase();
|
|
407
|
+
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
408
|
+
const result = await perspective.querySparql(getterWithBase);
|
|
409
|
+
if (trimmed.startsWith('ASK')) {
|
|
410
|
+
instance[propName] = result === true || result === 'true';
|
|
411
|
+
}
|
|
412
|
+
else if (result && result.length > 0) {
|
|
413
|
+
// Get first binding's first value
|
|
414
|
+
const firstRow = result[0];
|
|
415
|
+
const firstKey = Object.keys(firstRow)[0];
|
|
416
|
+
const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
|
|
417
|
+
if (val !== undefined && val !== null && val !== 'None' && val !== '') {
|
|
418
|
+
instance[propName] = val;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
else {
|
|
423
|
+
// Legacy SurrealDB-style getter — no longer supported
|
|
424
|
+
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
409
425
|
}
|
|
410
426
|
}
|
|
411
427
|
catch (error) {
|
|
@@ -421,12 +437,11 @@ export async function evaluateCustomGettersForInstance(instance, perspective, me
|
|
|
421
437
|
const meta = relMeta;
|
|
422
438
|
// Determine the getter to execute:
|
|
423
439
|
// 1. Explicit `getter` always wins
|
|
424
|
-
// 2. `
|
|
425
|
-
// 3. If `target` is set and `filter !== false`, auto-generate from target metadata
|
|
440
|
+
// 2. If `target` is set and `filter !== false`, auto-generate conformance getter
|
|
426
441
|
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
427
|
-
// because buildConformanceGetter traverses outgoing links
|
|
428
|
-
//
|
|
429
|
-
//
|
|
442
|
+
// because buildConformanceGetter traverses outgoing links which is wrong for
|
|
443
|
+
// reverse relations. Their values are already populated by the reverse link
|
|
444
|
+
// lookup in instancesFromQueryResult / getData.
|
|
430
445
|
let getter = meta.getter;
|
|
431
446
|
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
432
447
|
try {
|
|
@@ -434,14 +449,35 @@ export async function evaluateCustomGettersForInstance(instance, perspective, me
|
|
|
434
449
|
const targetMetadata = TargetClass
|
|
435
450
|
? TargetClass.getModelMetadata?.() ?? null
|
|
436
451
|
: null;
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
452
|
+
// Check if all where conditions can be SPARQL-filtered.
|
|
453
|
+
// literal-resolved properties store signed expressions (literal:json:{…}),
|
|
454
|
+
// not raw literal:string: IRIs, so SPARQL exact-match fails for them.
|
|
455
|
+
let allSparqlFilterable = true;
|
|
456
|
+
if (targetMetadata) {
|
|
457
|
+
for (const propName of Object.keys(meta.where)) {
|
|
458
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
459
|
+
continue;
|
|
460
|
+
const propMeta = targetMetadata.properties[propName];
|
|
461
|
+
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
462
|
+
allSparqlFilterable = false;
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
else {
|
|
468
|
+
allSparqlFilterable = false;
|
|
441
469
|
}
|
|
470
|
+
if (allSparqlFilterable) {
|
|
471
|
+
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
472
|
+
if (conditions.length > 0) {
|
|
473
|
+
const escapedPredicate = escapeQueryString(meta.predicate);
|
|
474
|
+
getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// If not filterable, fall through to buildConformanceGetter + JS post-filter below
|
|
442
478
|
}
|
|
443
479
|
catch (e) {
|
|
444
|
-
|
|
480
|
+
console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
|
|
445
481
|
}
|
|
446
482
|
}
|
|
447
483
|
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
@@ -458,23 +494,57 @@ export async function evaluateCustomGettersForInstance(instance, perspective, me
|
|
|
458
494
|
}
|
|
459
495
|
if (getter) {
|
|
460
496
|
try {
|
|
461
|
-
|
|
462
|
-
const
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
497
|
+
const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
|
|
498
|
+
const trimmed = getterWithBase.trim().toUpperCase();
|
|
499
|
+
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
500
|
+
// Native SPARQL getter — execute directly
|
|
501
|
+
const result = await perspective.querySparql(getterWithBase);
|
|
502
|
+
if (result && result.length > 0) {
|
|
503
|
+
const values = result.map((r) => {
|
|
504
|
+
const firstKey = Object.keys(r)[0];
|
|
505
|
+
return r[firstKey]?.value ?? r[firstKey];
|
|
506
|
+
}).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
507
|
+
instance[relName] = values;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
else {
|
|
511
|
+
// Legacy SurrealDB-style getter — no longer supported
|
|
512
|
+
console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
|
|
472
513
|
}
|
|
473
514
|
}
|
|
474
515
|
catch (error) {
|
|
475
516
|
console.warn(`Failed to evaluate getter for ${relName}:`, error);
|
|
476
517
|
}
|
|
477
518
|
}
|
|
519
|
+
// JS post-filter for where conditions that couldn't be SPARQL-filtered
|
|
520
|
+
// (e.g. literal-resolved properties storing signed expressions)
|
|
521
|
+
const currentValues = instance[relName];
|
|
522
|
+
if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
|
|
523
|
+
const TargetClass = meta.target?.();
|
|
524
|
+
if (TargetClass) {
|
|
525
|
+
const filtered = [];
|
|
526
|
+
for (const targetId of currentValues) {
|
|
527
|
+
try {
|
|
528
|
+
const inst = new TargetClass(perspective, targetId);
|
|
529
|
+
await inst.get();
|
|
530
|
+
let matches = true;
|
|
531
|
+
for (const [prop, expected] of Object.entries(meta.where)) {
|
|
532
|
+
if (inst[prop] !== expected) {
|
|
533
|
+
matches = false;
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (matches)
|
|
538
|
+
filtered.push(targetId);
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
// If we can't hydrate, keep the value (conservative)
|
|
542
|
+
filtered.push(targetId);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
instance[relName] = filtered;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
478
548
|
}
|
|
479
549
|
}
|
|
480
550
|
/**
|
package/lib/src/model/index.d.ts
CHANGED
|
@@ -13,8 +13,11 @@ export * from "./query-common";
|
|
|
13
13
|
export * from "./query-prolog";
|
|
14
14
|
export * from "./prolog-facts";
|
|
15
15
|
export * from "./json-schema";
|
|
16
|
-
export * from "./query-
|
|
16
|
+
export * from "./query-utils";
|
|
17
|
+
export * from "./query-sparql";
|
|
17
18
|
export * from "./hydration";
|
|
18
19
|
export * from "./ModelQueryBuilder";
|
|
19
20
|
export * from "./sdna";
|
|
20
21
|
export * from "./shacl-gen";
|
|
22
|
+
export * from "./query-cache";
|
|
23
|
+
export * from "./subscription-pool";
|
package/lib/src/model/index.js
CHANGED
|
@@ -13,8 +13,11 @@ export * from "./query-common";
|
|
|
13
13
|
export * from "./query-prolog";
|
|
14
14
|
export * from "./prolog-facts";
|
|
15
15
|
export * from "./json-schema";
|
|
16
|
-
export * from "./query-
|
|
16
|
+
export * from "./query-utils";
|
|
17
|
+
export * from "./query-sparql";
|
|
17
18
|
export * from "./hydration";
|
|
18
19
|
export * from "./ModelQueryBuilder";
|
|
19
20
|
export * from "./sdna";
|
|
20
21
|
export * from "./shacl-gen";
|
|
22
|
+
export * from "./query-cache";
|
|
23
|
+
export * from "./subscription-pool";
|
|
@@ -263,14 +263,14 @@ export function buildModelFromJSONSchema(BaseClass, schema, options) {
|
|
|
263
263
|
}
|
|
264
264
|
// Default resolveLanguage to 'literal' for all remaining property types,
|
|
265
265
|
// matching the @Property decorator behaviour. Without this, string values
|
|
266
|
-
// stored as literal
|
|
266
|
+
// stored as literal: URLs are returned unparsed.
|
|
267
267
|
if (resolveLanguage === undefined || resolveLanguage === null) {
|
|
268
268
|
resolveLanguage = 'literal';
|
|
269
269
|
}
|
|
270
270
|
// If property is required, ensure it has an initial value
|
|
271
271
|
if (isRequired && !initial) {
|
|
272
272
|
if (isObjectType(propertySchema)) {
|
|
273
|
-
initial = 'literal
|
|
273
|
+
initial = 'literal:json:{}';
|
|
274
274
|
}
|
|
275
275
|
else {
|
|
276
276
|
initial = "ad4m://undefined";
|