@coasys/ad4m 0.13.0-test-4 → 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/lib/index.cjs +833 -971
- package/lib/index.js +834 -969
- package/lib/src/Ad4mClient.js +10 -0
- package/lib/src/model/Ad4mModel.d.ts +20 -7
- package/lib/src/model/Ad4mModel.js +90 -68
- package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
- package/lib/src/model/ModelQueryBuilder.js +29 -11
- package/lib/src/model/hydration.d.ts +2 -39
- package/lib/src/model/hydration.js +2 -260
- package/lib/src/model/query-utils.d.ts +1 -0
- package/lib/src/model/query-utils.js +46 -1
- package/lib/src/model/types.d.ts +4 -5
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.js +10 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
- package/lib/src/perspectives/PerspectiveProxy.js +16 -0
- package/package.json +11 -8
- package/src/Ad4mClient.ts +10 -0
- package/src/model/Ad4mModel.test.ts +58 -297
- package/src/model/Ad4mModel.ts +99 -69
- package/src/model/ModelQueryBuilder.ts +29 -11
- package/src/model/hydration.ts +2 -279
- package/src/model/query-utils.ts +47 -2
- package/src/model/types.ts +4 -5
- package/src/perspectives/PerspectiveClient.ts +19 -0
- package/src/perspectives/PerspectiveProxy.ts +24 -0
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -15,7 +15,6 @@ import { buildSPARQLQuery } from "./query-sparql";
|
|
|
15
15
|
import { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
16
16
|
import {
|
|
17
17
|
normalizeValue,
|
|
18
|
-
evaluateCustomGettersForInstance,
|
|
19
18
|
} from "./hydration";
|
|
20
19
|
import type {
|
|
21
20
|
ParentScope, IncludeMap, Query,
|
|
@@ -745,6 +744,7 @@ export class Ad4mModel {
|
|
|
745
744
|
const query: Query = {
|
|
746
745
|
where: { id: this._baseExpression },
|
|
747
746
|
limit: 1,
|
|
747
|
+
deepQuery: true, // Single-instance get() always evaluates property getters
|
|
748
748
|
};
|
|
749
749
|
if (opts?.properties) query.properties = opts.properties;
|
|
750
750
|
if (opts?.include) query.include = opts.include;
|
|
@@ -850,6 +850,7 @@ export class Ad4mModel {
|
|
|
850
850
|
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
851
851
|
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
852
852
|
if (query.count !== undefined) queryInput.count = query.count;
|
|
853
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
853
854
|
|
|
854
855
|
if (query.include) {
|
|
855
856
|
const allRelMeta = getRelationsMetadata(this as any);
|
|
@@ -868,10 +869,10 @@ export class Ad4mModel {
|
|
|
868
869
|
const TargetClass = meta.target();
|
|
869
870
|
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
870
871
|
|
|
871
|
-
//
|
|
872
|
-
//
|
|
873
|
-
//
|
|
874
|
-
//
|
|
872
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
873
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
874
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
875
|
+
// that can't be matched by value in SPARQL.
|
|
875
876
|
let whereConditions: string[] = [];
|
|
876
877
|
if (rel.where) {
|
|
877
878
|
try {
|
|
@@ -881,13 +882,11 @@ export class Ad4mModel {
|
|
|
881
882
|
for (const propName of Object.keys(rel.where)) {
|
|
882
883
|
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
883
884
|
const propMeta = targetMetadata.properties[propName];
|
|
884
|
-
if (propMeta &&
|
|
885
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
885
886
|
allSparqlFilterable = false;
|
|
886
887
|
break;
|
|
887
888
|
}
|
|
888
889
|
}
|
|
889
|
-
} else {
|
|
890
|
-
allSparqlFilterable = false;
|
|
891
890
|
}
|
|
892
891
|
if (allSparqlFilterable) {
|
|
893
892
|
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
@@ -1014,6 +1013,7 @@ export class Ad4mModel {
|
|
|
1014
1013
|
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
1015
1014
|
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
1016
1015
|
if (query.count !== undefined) queryInput.count = query.count;
|
|
1016
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
1017
1017
|
|
|
1018
1018
|
// Enrich relation metadata with target class shapes for Rust-side
|
|
1019
1019
|
// include resolution. This eliminates per-relation GraphQL round-trips
|
|
@@ -1044,10 +1044,10 @@ export class Ad4mModel {
|
|
|
1044
1044
|
const TargetClass = meta.target();
|
|
1045
1045
|
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1046
1046
|
|
|
1047
|
-
//
|
|
1048
|
-
//
|
|
1049
|
-
//
|
|
1050
|
-
//
|
|
1047
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
1048
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
1049
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
1050
|
+
// that can't be matched by value in SPARQL.
|
|
1051
1051
|
let whereConditions: string[] = [];
|
|
1052
1052
|
if (rel.where) {
|
|
1053
1053
|
try {
|
|
@@ -1057,13 +1057,11 @@ export class Ad4mModel {
|
|
|
1057
1057
|
for (const propName of Object.keys(rel.where)) {
|
|
1058
1058
|
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
1059
1059
|
const propMeta = targetMetadata.properties[propName];
|
|
1060
|
-
if (propMeta &&
|
|
1060
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
1061
1061
|
allSparqlFilterable = false;
|
|
1062
1062
|
break;
|
|
1063
1063
|
}
|
|
1064
1064
|
}
|
|
1065
|
-
} else {
|
|
1066
|
-
allSparqlFilterable = false;
|
|
1067
1065
|
}
|
|
1068
1066
|
if (allSparqlFilterable) {
|
|
1069
1067
|
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
@@ -1095,6 +1093,14 @@ export class Ad4mModel {
|
|
|
1095
1093
|
const shapeJson = JSON.stringify(metadata);
|
|
1096
1094
|
const queryJson = JSON.stringify(queryInput);
|
|
1097
1095
|
|
|
1096
|
+
// TEMP DEBUG: Log getters with where-clause filters to diagnose CI failure
|
|
1097
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1098
|
+
const rel = relMeta as any;
|
|
1099
|
+
if (rel.where) {
|
|
1100
|
+
console.log(`[MODEL_QUERY_DEBUG] relation="${relName}" getter=${rel.getter ?? 'NONE'} where=${JSON.stringify(rel.where)}`);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1098
1104
|
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
1099
1105
|
|
|
1100
1106
|
// Convert JSON instances to model class instances, recursively constructing
|
|
@@ -1132,43 +1138,6 @@ export class Ad4mModel {
|
|
|
1132
1138
|
);
|
|
1133
1139
|
}
|
|
1134
1140
|
|
|
1135
|
-
// Relation conformance getters are evaluated Rust-side via evaluate_getters()
|
|
1136
|
-
// in model_query.rs. However, for relations with non-SPARQL-filterable where
|
|
1137
|
-
// clauses (e.g. properties stored as signed expressions), we still need
|
|
1138
|
-
// TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
|
|
1139
|
-
// with skipPropertyGetters ensures conformance + JS post-filtering for
|
|
1140
|
-
// where clauses that couldn't be compiled to SPARQL.
|
|
1141
|
-
const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set<string>();
|
|
1142
|
-
for (const inst of instances) {
|
|
1143
|
-
// Save included relation values that came from Rust hydration
|
|
1144
|
-
const savedIncluded: Record<string, any> = {};
|
|
1145
|
-
for (const relName of includedRelNames) {
|
|
1146
|
-
if ((inst as any)[relName] !== undefined) {
|
|
1147
|
-
savedIncluded[relName] = (inst as any)[relName];
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
await evaluateCustomGettersForInstance(inst, perspective, metadata, {
|
|
1152
|
-
skipPropertyGetters: true,
|
|
1153
|
-
});
|
|
1154
|
-
|
|
1155
|
-
// Restore hydrated include objects that were overwritten by conformance getters
|
|
1156
|
-
for (const [relName, value] of Object.entries(savedIncluded)) {
|
|
1157
|
-
(inst as any)[relName] = value;
|
|
1158
|
-
}
|
|
1159
|
-
|
|
1160
|
-
// Fix cardinality for non-included HasOne/BelongsToOne relations:
|
|
1161
|
-
// The conformance getter always produces arrays; unwrap to scalar.
|
|
1162
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1163
|
-
if (includedRelNames.has(relName)) continue;
|
|
1164
|
-
const kind = (relMeta as any).kind;
|
|
1165
|
-
if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray((inst as any)[relName])) {
|
|
1166
|
-
const arr = (inst as any)[relName] as any[];
|
|
1167
|
-
(inst as any)[relName] = arr.length > 0 ? arr[0] : null;
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
1141
|
// Take snapshots for dirty tracking
|
|
1173
1142
|
const snapshotRelations = queryInput.include;
|
|
1174
1143
|
for (const inst of instances) {
|
|
@@ -1675,10 +1644,10 @@ export class Ad4mModel {
|
|
|
1675
1644
|
/**
|
|
1676
1645
|
* Evaluate SPARQL getters for a batch of instances on demand.
|
|
1677
1646
|
*
|
|
1678
|
-
*
|
|
1679
|
-
*
|
|
1680
|
-
*
|
|
1681
|
-
* a
|
|
1647
|
+
* Since deepQuery defaults to true, property getters are evaluated
|
|
1648
|
+
* automatically during collection queries. Use this method when
|
|
1649
|
+
* deepQuery was explicitly set to false and you want to lazily
|
|
1650
|
+
* resolve getter-backed properties for a subset of instances.
|
|
1682
1651
|
*
|
|
1683
1652
|
* @param instances - Array of model instances to evaluate getters on
|
|
1684
1653
|
* @param perspective - The perspective to query against
|
|
@@ -1687,8 +1656,8 @@ export class Ad4mModel {
|
|
|
1687
1656
|
*
|
|
1688
1657
|
* @example
|
|
1689
1658
|
* ```typescript
|
|
1690
|
-
* const messages = await Message.
|
|
1691
|
-
* // messages[i].replyingTo is undefined (getter skipped
|
|
1659
|
+
* const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
|
|
1660
|
+
* // messages[i].replyingTo is undefined (getter skipped)
|
|
1692
1661
|
*
|
|
1693
1662
|
* // Evaluate getters for the visible subset
|
|
1694
1663
|
* await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
|
|
@@ -1702,11 +1671,33 @@ export class Ad4mModel {
|
|
|
1702
1671
|
): Promise<void> {
|
|
1703
1672
|
if (instances.length === 0) return;
|
|
1704
1673
|
const metadata = this.getModelMetadata();
|
|
1705
|
-
const opts = propertyNames && propertyNames.length > 0
|
|
1706
|
-
? { requestedProperties: propertyNames }
|
|
1707
|
-
: undefined;
|
|
1708
1674
|
|
|
1709
|
-
//
|
|
1675
|
+
// Pre-compute conformance getters so the shape sent to Rust includes them
|
|
1676
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
1677
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1678
|
+
const rel = relMeta as any;
|
|
1679
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
1680
|
+
const meta = allRelMeta[relName];
|
|
1681
|
+
if (!meta?.target) continue;
|
|
1682
|
+
try {
|
|
1683
|
+
const TargetClass = meta.target();
|
|
1684
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1685
|
+
if (filter) rel.getter = filter.getter;
|
|
1686
|
+
} catch (_) { /* target class may not be available */ }
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
const shapeJson = JSON.stringify(metadata);
|
|
1690
|
+
const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
|
|
1691
|
+
|
|
1692
|
+
// Single RPC call evaluates all getters in-process on the executor
|
|
1693
|
+
const result = await perspective.evaluateGetters(
|
|
1694
|
+
metadata.className,
|
|
1695
|
+
instanceIds,
|
|
1696
|
+
shapeJson,
|
|
1697
|
+
propertyNames,
|
|
1698
|
+
);
|
|
1699
|
+
|
|
1700
|
+
// Determine which property names were evaluated for snapshot sync
|
|
1710
1701
|
const evaluatedPropertyNames: string[] = [];
|
|
1711
1702
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1712
1703
|
if ((propMeta as any).getter) {
|
|
@@ -1715,14 +1706,25 @@ export class Ad4mModel {
|
|
|
1715
1706
|
}
|
|
1716
1707
|
}
|
|
1717
1708
|
}
|
|
1709
|
+
// Also include relation getters
|
|
1710
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1711
|
+
if ((relMeta as any).getter) {
|
|
1712
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
|
|
1713
|
+
evaluatedPropertyNames.push(relName);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1718
1717
|
|
|
1718
|
+
// Apply results to instances and sync snapshots
|
|
1719
1719
|
for (const instance of instances) {
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1720
|
+
const id = (instance as any).id || (instance as any)._baseExpression;
|
|
1721
|
+
const props = result[id];
|
|
1722
|
+
if (props) {
|
|
1723
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1724
|
+
(instance as any)[key] = value;
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
// Sync snapshot so isDirty() doesn't flag getter-only changes
|
|
1726
1728
|
const modelInstance = instance as Ad4mModel;
|
|
1727
1729
|
if (modelInstance._snapshot) {
|
|
1728
1730
|
for (const propName of evaluatedPropertyNames) {
|
|
@@ -2171,7 +2173,24 @@ export class Ad4mModel {
|
|
|
2171
2173
|
* @param name - Class name to assign (e.g. "Channel")
|
|
2172
2174
|
* @returns Generated Ad4mModel subclass, ready for querying
|
|
2173
2175
|
*/
|
|
2174
|
-
|
|
2176
|
+
/**
|
|
2177
|
+
* Synthesise an `Ad4mModel` subclass from a SHACL shape.
|
|
2178
|
+
*
|
|
2179
|
+
* @param shape - The SHACL shape to synthesise from.
|
|
2180
|
+
* @param name - The model name (e.g. "Channel").
|
|
2181
|
+
* @param classResolver - Optional thunk factory. When provided, any collection
|
|
2182
|
+
* property that carries a `sh:class` URI will have its `target` wired up lazily:
|
|
2183
|
+
* `target: () => classResolver(localName)`. Because `target` is only called at
|
|
2184
|
+
* query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
|
|
2185
|
+
* resolver just needs to return the correct class by the time a query runs —
|
|
2186
|
+
* making it safe to pass a closure over a registry object that is still being
|
|
2187
|
+
* populated (e.g. the `result` record inside `getModelClasses`).
|
|
2188
|
+
*/
|
|
2189
|
+
static fromSHACL(
|
|
2190
|
+
shape: SHACLShape,
|
|
2191
|
+
name: string,
|
|
2192
|
+
classResolver?: (localName: string) => typeof Ad4mModel | undefined,
|
|
2193
|
+
): typeof Ad4mModel {
|
|
2175
2194
|
const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
|
|
2176
2195
|
(DynamicModelClass as any).className = name;
|
|
2177
2196
|
(DynamicModelClass.prototype as any).className = name;
|
|
@@ -2216,9 +2235,20 @@ export class Ad4mModel {
|
|
|
2216
2235
|
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
2217
2236
|
|
|
2218
2237
|
if (isCollection) {
|
|
2238
|
+
// Derive a lazy `target` thunk when a sh:class URI is present and a
|
|
2239
|
+
// classResolver was supplied. The thunk is evaluated at query time so
|
|
2240
|
+
// it is safe even if the target class hasn't been registered yet.
|
|
2241
|
+
let targetThunk: (() => typeof Ad4mModel) | undefined;
|
|
2242
|
+
if (prop.class && classResolver) {
|
|
2243
|
+
const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
|
|
2244
|
+
const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
|
|
2245
|
+
targetThunk = () => classResolver(localName) as typeof Ad4mModel;
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2219
2248
|
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
2220
2249
|
predicate: prop.path,
|
|
2221
2250
|
kind: 'hasMany',
|
|
2251
|
+
...(targetThunk !== undefined && { target: targetThunk }),
|
|
2222
2252
|
...(prop.local !== undefined && { local: prop.local }),
|
|
2223
2253
|
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
2224
2254
|
});
|
|
@@ -224,25 +224,25 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
224
224
|
}
|
|
225
225
|
|
|
226
226
|
/**
|
|
227
|
-
*
|
|
227
|
+
* Controls whether SPARQL property getters are evaluated during hydration.
|
|
228
228
|
*
|
|
229
|
-
* By default, collection queries
|
|
230
|
-
* Call `.deepQuery()`
|
|
229
|
+
* By default, collection queries evaluate property getters (deepQuery=true).
|
|
230
|
+
* Call `.deepQuery(false)` to skip getter evaluation for performance.
|
|
231
231
|
*
|
|
232
|
+
* @param enabled - Whether to evaluate property getters (default: true)
|
|
232
233
|
* @returns The query builder for chaining
|
|
233
234
|
*
|
|
234
235
|
* @example
|
|
235
236
|
* ```typescript
|
|
236
237
|
* const messages = await Message.query(perspective)
|
|
237
238
|
* .parent(channel)
|
|
238
|
-
* .deepQuery()
|
|
239
|
+
* .deepQuery(false) // skip property getters for performance
|
|
239
240
|
* .limit(30)
|
|
240
241
|
* .get();
|
|
241
|
-
* // messages[i].replyingTo is populated
|
|
242
242
|
* ```
|
|
243
243
|
*/
|
|
244
|
-
deepQuery(): ModelQueryBuilder<T> {
|
|
245
|
-
|
|
244
|
+
deepQuery(enabled: boolean = true): ModelQueryBuilder<T> {
|
|
245
|
+
this.queryParams.deepQuery = enabled;
|
|
246
246
|
return this;
|
|
247
247
|
}
|
|
248
248
|
|
|
@@ -425,9 +425,15 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
425
425
|
},
|
|
426
426
|
);
|
|
427
427
|
|
|
428
|
-
// Set up keepalive
|
|
428
|
+
// Set up keepalive with failure tracking
|
|
429
|
+
let keepaliveFailures = 0;
|
|
429
430
|
const keepaliveTimer = setInterval(() => {
|
|
430
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
431
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
432
|
+
keepaliveFailures = 0;
|
|
433
|
+
}).catch((e: any) => {
|
|
434
|
+
keepaliveFailures++;
|
|
435
|
+
console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
436
|
+
});
|
|
431
437
|
}, 30000);
|
|
432
438
|
|
|
433
439
|
// Store dispose function
|
|
@@ -540,8 +546,14 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
540
546
|
},
|
|
541
547
|
);
|
|
542
548
|
|
|
549
|
+
let keepaliveFailures = 0;
|
|
543
550
|
const keepaliveTimer = setInterval(() => {
|
|
544
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
551
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
552
|
+
keepaliveFailures = 0;
|
|
553
|
+
}).catch((e: any) => {
|
|
554
|
+
keepaliveFailures++;
|
|
555
|
+
console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
556
|
+
});
|
|
545
557
|
}, 30000);
|
|
546
558
|
|
|
547
559
|
this.currentSubscription = {
|
|
@@ -667,8 +679,14 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
667
679
|
},
|
|
668
680
|
);
|
|
669
681
|
|
|
682
|
+
let keepaliveFailures = 0;
|
|
670
683
|
const keepaliveTimer = setInterval(() => {
|
|
671
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
684
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
685
|
+
keepaliveFailures = 0;
|
|
686
|
+
}).catch((e: any) => {
|
|
687
|
+
keepaliveFailures++;
|
|
688
|
+
console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
689
|
+
});
|
|
672
690
|
}, 30000);
|
|
673
691
|
|
|
674
692
|
this.currentSubscription = {
|
package/src/model/hydration.ts
CHANGED
|
@@ -1,23 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* hydration.ts — Instance hydration helpers extracted from Ad4mModel.
|
|
3
3
|
*
|
|
4
|
-
* After the Rust model_query pipeline migration
|
|
5
|
-
*
|
|
4
|
+
* After the Rust model_query pipeline migration, most hydration logic moved
|
|
5
|
+
* to Rust. This file retains:
|
|
6
6
|
* - normalizeValue() — snapshot dirty-tracking
|
|
7
|
-
* - matchesCondition() — JS-side post-filter (used by evaluateCustomGettersForInstance)
|
|
8
|
-
* - evaluateCustomGettersForInstance() — lazy getter evaluation (Ad4mModel.evaluateGetters)
|
|
9
|
-
* - buildConformanceGetter() — conformance SPARQL generation for relation getters
|
|
10
7
|
*/
|
|
11
8
|
|
|
12
|
-
import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
13
|
-
import { buildConformanceFilter } from "./decorators";
|
|
14
|
-
import { compileWhereClause } from "./query-utils";
|
|
15
|
-
import { escapeQueryString } from "../utils";
|
|
16
|
-
import type {
|
|
17
|
-
RelationMetadata, ModelMetadata,
|
|
18
|
-
WhereCondition,
|
|
19
|
-
} from "./types";
|
|
20
|
-
|
|
21
9
|
// ──────────────────────────────────────────────────────────
|
|
22
10
|
// Pure helpers
|
|
23
11
|
// ──────────────────────────────────────────────────────────
|
|
@@ -36,269 +24,4 @@ export function normalizeValue(value: any): any {
|
|
|
36
24
|
return value;
|
|
37
25
|
}
|
|
38
26
|
|
|
39
|
-
/**
|
|
40
|
-
* Checks if a value matches a where-condition (for post-query filtering).
|
|
41
|
-
*/
|
|
42
|
-
export function matchesCondition(value: any, condition: WhereCondition): boolean {
|
|
43
|
-
// Handle array values (IN clause)
|
|
44
|
-
if (Array.isArray(condition)) {
|
|
45
|
-
return (condition as any[]).includes(value);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// Handle operator object
|
|
49
|
-
if (typeof condition === 'object' && condition !== null) {
|
|
50
|
-
const ops = condition as any;
|
|
51
|
-
|
|
52
|
-
// Special case: 'not' operator (exclusive with other operators)
|
|
53
|
-
if (ops.not !== undefined) {
|
|
54
|
-
if (Array.isArray(ops.not)) {
|
|
55
|
-
return !(ops.not as any[]).includes(value);
|
|
56
|
-
} else {
|
|
57
|
-
return value !== ops.not;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
|
|
62
|
-
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
63
|
-
return value >= ops.between[0] && value <= ops.between[1];
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
|
|
67
|
-
// and return true only if ALL conditions are satisfied
|
|
68
|
-
let allConditionsMet = true;
|
|
69
|
-
|
|
70
|
-
if (ops.gt !== undefined) {
|
|
71
|
-
allConditionsMet = allConditionsMet && (value > ops.gt);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
if (ops.gte !== undefined) {
|
|
75
|
-
allConditionsMet = allConditionsMet && (value >= ops.gte);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
if (ops.lt !== undefined) {
|
|
79
|
-
allConditionsMet = allConditionsMet && (value < ops.lt);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
if (ops.lte !== undefined) {
|
|
83
|
-
allConditionsMet = allConditionsMet && (value <= ops.lte);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
if (ops.contains !== undefined) {
|
|
87
|
-
if (typeof value === 'string') {
|
|
88
|
-
allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
|
|
89
|
-
} else if (Array.isArray(value)) {
|
|
90
|
-
allConditionsMet = allConditionsMet && value.includes(ops.contains);
|
|
91
|
-
} else {
|
|
92
|
-
allConditionsMet = false;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
return allConditionsMet;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// Simple equality
|
|
100
|
-
return value === condition;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// ──────────────────────────────────────────────────────────
|
|
104
|
-
// SPARQL custom getter evaluation
|
|
105
|
-
// ──────────────────────────────────────────────────────────
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
109
|
-
* is known but no explicit `getter` string was supplied.
|
|
110
|
-
*
|
|
111
|
-
* The generated getter traverses outgoing links matching the relation's
|
|
112
|
-
* predicate and then filters the target nodes to only those that conform to
|
|
113
|
-
* the target model's shape (required properties / flags).
|
|
114
|
-
*
|
|
115
|
-
* Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
|
|
116
|
-
* so the same logic is used at shape-definition time and at query time.
|
|
117
|
-
*
|
|
118
|
-
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
119
|
-
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
120
|
-
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
121
|
-
* conditions could be derived from the target model.
|
|
122
|
-
*/
|
|
123
|
-
export function buildConformanceGetter(
|
|
124
|
-
relationPredicate: string,
|
|
125
|
-
targetClass: any
|
|
126
|
-
): string | undefined {
|
|
127
|
-
const filter = buildConformanceFilter(relationPredicate, targetClass);
|
|
128
|
-
if (!filter) {
|
|
129
|
-
const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
|
|
130
|
-
console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
|
|
131
|
-
return undefined;
|
|
132
|
-
}
|
|
133
|
-
return filter.getter;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Evaluates custom SurrealQL getters for properties and relations on a specific instance.
|
|
138
|
-
*
|
|
139
|
-
* For relations that declare a `target` but no explicit `getter`, a conformance
|
|
140
|
-
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
141
|
-
*/
|
|
142
|
-
|
|
143
|
-
export async function evaluateCustomGettersForInstance(
|
|
144
|
-
instance: any,
|
|
145
|
-
perspective: PerspectiveProxy,
|
|
146
|
-
metadata: ModelMetadata,
|
|
147
|
-
options?: { requestedProperties?: string[]; include?: Record<string, any>; skipPropertyGetters?: boolean }
|
|
148
|
-
): Promise<void> {
|
|
149
|
-
const safeBaseExpression = `<${instance.id}>`;
|
|
150
|
-
|
|
151
|
-
// Build projection filter — when requestedProperties is active, only
|
|
152
|
-
// evaluate getters for fields that are requested (or included).
|
|
153
|
-
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
154
|
-
const projectionSet = projectionActive ? new Set(options!.requestedProperties) : null;
|
|
155
|
-
|
|
156
|
-
// Evaluate property getters (skip when caller only wants relation type-filtering)
|
|
157
|
-
if (!options?.skipPropertyGetters) {
|
|
158
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
159
|
-
if (projectionSet && !projectionSet.has(propName)) continue;
|
|
160
|
-
if ((propMeta as any).getter) {
|
|
161
|
-
try {
|
|
162
|
-
const rawGetter = (propMeta as any).getter;
|
|
163
|
-
const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
|
|
164
|
-
|
|
165
|
-
// If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
|
|
166
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
167
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
168
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
169
|
-
if (trimmed.startsWith('ASK')) {
|
|
170
|
-
instance[propName] = result === true || result === 'true';
|
|
171
|
-
} else if (result && result.length > 0) {
|
|
172
|
-
// Get first binding's first value
|
|
173
|
-
const firstRow = result[0];
|
|
174
|
-
const firstKey = Object.keys(firstRow)[0];
|
|
175
|
-
const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
|
|
176
|
-
if (val !== undefined && val !== null && val !== 'None' && val !== '') {
|
|
177
|
-
instance[propName] = val;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
} else {
|
|
181
|
-
// Legacy SurrealDB-style getter — safety guard for getters that don't match
|
|
182
|
-
// SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
183
|
-
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
184
|
-
}
|
|
185
|
-
} catch (error) {
|
|
186
|
-
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
} // end skipPropertyGetters guard
|
|
191
|
-
|
|
192
|
-
// Evaluate relation getters (explicit or auto-generated from target)
|
|
193
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
194
|
-
// Skip relations excluded by property projection (unless in include map)
|
|
195
|
-
if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include)) continue;
|
|
196
|
-
const meta = relMeta as RelationMetadata;
|
|
197
|
-
|
|
198
|
-
// Determine the getter to execute:
|
|
199
|
-
// 1. Explicit `getter` always wins
|
|
200
|
-
// 2. If `target` is set and `filter !== false`, auto-generate conformance getter
|
|
201
|
-
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
202
|
-
// because buildConformanceGetter traverses outgoing links which is wrong for
|
|
203
|
-
// reverse relations. Their values are already populated by the reverse link
|
|
204
|
-
// lookup in instancesFromQueryResult / getData.
|
|
205
|
-
let getter = meta.getter;
|
|
206
|
-
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
207
|
-
try {
|
|
208
|
-
const TargetClass = meta.target?.();
|
|
209
|
-
const targetMetadata = TargetClass
|
|
210
|
-
? (TargetClass as any).getModelMetadata?.() ?? null
|
|
211
|
-
: null;
|
|
212
|
-
|
|
213
|
-
// Check if all where conditions can be SPARQL-filtered.
|
|
214
|
-
// literal-resolved properties store signed expressions (literal:json:{…}),
|
|
215
|
-
// not raw literal:string: IRIs, so SPARQL exact-match fails for them.
|
|
216
|
-
let allSparqlFilterable = true;
|
|
217
|
-
if (targetMetadata) {
|
|
218
|
-
for (const propName of Object.keys(meta.where)) {
|
|
219
|
-
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
220
|
-
const propMeta = targetMetadata.properties[propName];
|
|
221
|
-
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
222
|
-
allSparqlFilterable = false;
|
|
223
|
-
break;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
} else {
|
|
227
|
-
allSparqlFilterable = false;
|
|
228
|
-
}
|
|
229
27
|
|
|
230
|
-
if (allSparqlFilterable) {
|
|
231
|
-
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
232
|
-
if (conditions.length > 0) {
|
|
233
|
-
const escapedPredicate = escapeQueryString(meta.predicate);
|
|
234
|
-
getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
// If not filterable, fall through to buildConformanceGetter + JS post-filter below
|
|
238
|
-
} catch (e) {
|
|
239
|
-
console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
243
|
-
try {
|
|
244
|
-
const TargetClass = meta.target();
|
|
245
|
-
getter = buildConformanceGetter(meta.predicate, TargetClass);
|
|
246
|
-
if (!getter) {
|
|
247
|
-
console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
|
|
248
|
-
}
|
|
249
|
-
} catch (e) {
|
|
250
|
-
console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
if (getter) {
|
|
255
|
-
try {
|
|
256
|
-
const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
|
|
257
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
258
|
-
|
|
259
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
260
|
-
// Native SPARQL getter — execute directly
|
|
261
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
262
|
-
if (result && result.length > 0) {
|
|
263
|
-
const values = result.map((r: any) => {
|
|
264
|
-
const firstKey = Object.keys(r)[0];
|
|
265
|
-
return r[firstKey]?.value ?? r[firstKey];
|
|
266
|
-
}).filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
267
|
-
instance[relName] = values;
|
|
268
|
-
}
|
|
269
|
-
} else {
|
|
270
|
-
// Legacy SurrealDB-style getter — safety guard for relation getters that don't
|
|
271
|
-
// match SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
272
|
-
console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
|
|
273
|
-
}
|
|
274
|
-
} catch (error) {
|
|
275
|
-
console.warn(`Failed to evaluate getter for ${relName}:`, error);
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// JS post-filter for where conditions that couldn't be SPARQL-filtered
|
|
280
|
-
// (e.g. literal-resolved properties storing signed expressions)
|
|
281
|
-
const currentValues = instance[relName];
|
|
282
|
-
if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
|
|
283
|
-
const TargetClass = meta.target?.();
|
|
284
|
-
if (TargetClass) {
|
|
285
|
-
const filtered: string[] = [];
|
|
286
|
-
for (const targetId of currentValues) {
|
|
287
|
-
try {
|
|
288
|
-
const inst = new (TargetClass as any)(perspective, targetId);
|
|
289
|
-
await inst.get();
|
|
290
|
-
let matches = true;
|
|
291
|
-
for (const [prop, expected] of Object.entries(meta.where)) {
|
|
292
|
-
if ((inst as any)[prop] !== expected) { matches = false; break; }
|
|
293
|
-
}
|
|
294
|
-
if (matches) filtered.push(targetId);
|
|
295
|
-
} catch {
|
|
296
|
-
// If we can't hydrate, keep the value (conservative)
|
|
297
|
-
filtered.push(targetId);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
instance[relName] = filtered;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
}
|