@coasys/ad4m 0.13.0-test-4 → 0.13.0-test-6
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 +1507 -1372
- package/lib/index.js +1505 -1370
- package/lib/src/Ad4mClient.d.ts +1 -1
- package/lib/src/Ad4mClient.js +12 -1
- package/lib/src/agent/AgentClient.d.ts +16 -0
- package/lib/src/agent/AgentClient.js +74 -4
- package/lib/src/cache/PersistentCache.d.ts +40 -0
- package/lib/src/cache/PersistentCache.js +139 -0
- package/lib/src/expression/ExpressionClient.d.ts +8 -0
- package/lib/src/expression/ExpressionClient.js +113 -5
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/src/model/Ad4mModel.d.ts +20 -7
- package/lib/src/model/Ad4mModel.js +102 -108
- package/lib/src/model/Ad4mModel.test.js +688 -1434
- package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
- package/lib/src/model/ModelQueryBuilder.js +29 -20
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/hydration.d.ts +2 -39
- package/lib/src/model/hydration.js +2 -260
- package/lib/src/model/query-surreal.d.ts +44 -0
- package/lib/src/model/query-surreal.js +249 -0
- package/lib/src/model/query-utils.d.ts +1 -0
- package/lib/src/model/query-utils.js +46 -1
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/surreal-utils.d.ts +42 -0
- package/lib/src/model/surreal-utils.js +128 -0
- package/lib/src/model/types.d.ts +4 -6
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
- package/lib/src/perspectives/PerspectiveClient.js +15 -13
- package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
- package/lib/src/perspectives/PerspectiveProxy.js +16 -3
- package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveResolver.js +11 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
- package/lib/src/runtime/RuntimeResolver.js +4 -197
- package/lib/src/schema.gql +1 -27
- package/lib/src/shacl/SHACLShape.test.js +0 -82
- package/package.json +11 -8
- package/src/Ad4mClient.test.ts +14 -4
- package/src/Ad4mClient.ts +12 -1
- package/src/agent/AgentClient.ts +84 -2
- package/src/cache/PersistentCache.ts +145 -0
- package/src/cache/cache.test.ts +713 -0
- package/src/expression/ExpressionClient.ts +137 -3
- package/src/index.ts +1 -0
- package/src/model/Ad4mModel.test.ts +59 -358
- package/src/model/Ad4mModel.ts +112 -108
- package/src/model/ModelQueryBuilder.ts +29 -17
- package/src/model/hydration.ts +2 -279
- package/src/model/query-utils.ts +47 -2
- package/src/model/types.ts +5 -6
- package/src/perspectives/PerspectiveClient.ts +26 -17
- package/src/perspectives/PerspectiveProxy.ts +24 -3
- package/lib/src/model/hydration-batch.d.ts +0 -34
- package/lib/src/model/hydration-batch.js +0 -147
- package/lib/src/model/hydration-batching.test.d.ts +0 -7
- package/lib/src/model/hydration-batching.test.js +0 -456
- package/lib/src/model/model-manifest.d.ts +0 -41
- package/lib/src/model/model-manifest.js +0 -11
- package/lib/src/model/query-cache.test.d.ts +0 -1
- package/lib/src/model/query-cache.test.js +0 -43
- package/lib/src/model/query-sparql-batch.d.ts +0 -17
- package/lib/src/model/query-sparql-batch.js +0 -260
- package/lib/src/model/query-sparql.test.d.ts +0 -1
- package/lib/src/model/query-sparql.test.js +0 -312
- package/lib/src/model/subscription-delta.test.d.ts +0 -24
- package/lib/src/model/subscription-delta.test.js +0 -180
- package/lib/src/model/subscription-pool.d.ts +0 -39
- package/lib/src/model/subscription-pool.js +0 -165
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveClient.test.js +0 -224
|
@@ -158,24 +158,24 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
158
158
|
*/
|
|
159
159
|
properties(properties: string[]): ModelQueryBuilder<T>;
|
|
160
160
|
/**
|
|
161
|
-
*
|
|
161
|
+
* Controls whether SPARQL property getters are evaluated during hydration.
|
|
162
162
|
*
|
|
163
|
-
* By default, collection queries
|
|
164
|
-
* Call `.deepQuery()`
|
|
163
|
+
* By default, collection queries evaluate property getters (deepQuery=true).
|
|
164
|
+
* Call `.deepQuery(false)` to skip getter evaluation for performance.
|
|
165
165
|
*
|
|
166
|
+
* @param enabled - Whether to evaluate property getters (default: true)
|
|
166
167
|
* @returns The query builder for chaining
|
|
167
168
|
*
|
|
168
169
|
* @example
|
|
169
170
|
* ```typescript
|
|
170
171
|
* const messages = await Message.query(perspective)
|
|
171
172
|
* .parent(channel)
|
|
172
|
-
* .deepQuery()
|
|
173
|
+
* .deepQuery(false) // skip property getters for performance
|
|
173
174
|
* .limit(30)
|
|
174
175
|
* .get();
|
|
175
|
-
* // messages[i].replyingTo is populated
|
|
176
176
|
* ```
|
|
177
177
|
*/
|
|
178
|
-
deepQuery(): ModelQueryBuilder<T>;
|
|
178
|
+
deepQuery(enabled?: boolean): ModelQueryBuilder<T>;
|
|
179
179
|
/**
|
|
180
180
|
* Specifies which relations to eager-load (hydrate into model instances).
|
|
181
181
|
*
|
|
@@ -201,25 +201,25 @@ export class ModelQueryBuilder {
|
|
|
201
201
|
return this;
|
|
202
202
|
}
|
|
203
203
|
/**
|
|
204
|
-
*
|
|
204
|
+
* Controls whether SPARQL property getters are evaluated during hydration.
|
|
205
205
|
*
|
|
206
|
-
* By default, collection queries
|
|
207
|
-
* Call `.deepQuery()`
|
|
206
|
+
* By default, collection queries evaluate property getters (deepQuery=true).
|
|
207
|
+
* Call `.deepQuery(false)` to skip getter evaluation for performance.
|
|
208
208
|
*
|
|
209
|
+
* @param enabled - Whether to evaluate property getters (default: true)
|
|
209
210
|
* @returns The query builder for chaining
|
|
210
211
|
*
|
|
211
212
|
* @example
|
|
212
213
|
* ```typescript
|
|
213
214
|
* const messages = await Message.query(perspective)
|
|
214
215
|
* .parent(channel)
|
|
215
|
-
* .deepQuery()
|
|
216
|
+
* .deepQuery(false) // skip property getters for performance
|
|
216
217
|
* .limit(30)
|
|
217
218
|
* .get();
|
|
218
|
-
* // messages[i].replyingTo is populated
|
|
219
219
|
* ```
|
|
220
220
|
*/
|
|
221
|
-
deepQuery() {
|
|
222
|
-
this.queryParams.deepQuery =
|
|
221
|
+
deepQuery(enabled = true) {
|
|
222
|
+
this.queryParams.deepQuery = enabled;
|
|
223
223
|
return this;
|
|
224
224
|
}
|
|
225
225
|
/**
|
|
@@ -364,11 +364,6 @@ export class ModelQueryBuilder {
|
|
|
364
364
|
// Listen for subscription updates via the same GraphQL subscription channel.
|
|
365
365
|
// When Rust re-runs the model query and finds changed results, it pushes them.
|
|
366
366
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
|
|
367
|
-
// Skip delayed #init# messages — initial data was already returned
|
|
368
|
-
// synchronously from modelSubscribe(). Late init messages contain stale
|
|
369
|
-
// data that would overwrite real subscription updates.
|
|
370
|
-
if (rawResult && rawResult.isInit)
|
|
371
|
-
return;
|
|
372
367
|
try {
|
|
373
368
|
const results = parseResults(rawResult);
|
|
374
369
|
const fp = buildFingerprint(results);
|
|
@@ -381,9 +376,15 @@ export class ModelQueryBuilder {
|
|
|
381
376
|
console.error('Model subscription update parse error:', e);
|
|
382
377
|
}
|
|
383
378
|
});
|
|
384
|
-
// Set up keepalive
|
|
379
|
+
// Set up keepalive with failure tracking
|
|
380
|
+
let keepaliveFailures = 0;
|
|
385
381
|
const keepaliveTimer = setInterval(() => {
|
|
386
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
382
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
383
|
+
keepaliveFailures = 0;
|
|
384
|
+
}).catch((e) => {
|
|
385
|
+
keepaliveFailures++;
|
|
386
|
+
console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
387
|
+
});
|
|
387
388
|
}, 30000);
|
|
388
389
|
// Store dispose function
|
|
389
390
|
this.currentSubscription = {
|
|
@@ -469,8 +470,6 @@ export class ModelQueryBuilder {
|
|
|
469
470
|
};
|
|
470
471
|
const initialCount = parseCount(initialModelResult);
|
|
471
472
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
|
|
472
|
-
if (rawResult && rawResult.isInit)
|
|
473
|
-
return;
|
|
474
473
|
try {
|
|
475
474
|
callback(parseCount(rawResult));
|
|
476
475
|
}
|
|
@@ -478,8 +477,14 @@ export class ModelQueryBuilder {
|
|
|
478
477
|
console.error('Count subscription update parse error:', e);
|
|
479
478
|
}
|
|
480
479
|
});
|
|
480
|
+
let keepaliveFailures = 0;
|
|
481
481
|
const keepaliveTimer = setInterval(() => {
|
|
482
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
482
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
483
|
+
keepaliveFailures = 0;
|
|
484
|
+
}).catch((e) => {
|
|
485
|
+
keepaliveFailures++;
|
|
486
|
+
console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
487
|
+
});
|
|
483
488
|
}, 30000);
|
|
484
489
|
this.currentSubscription = {
|
|
485
490
|
dispose: () => {
|
|
@@ -578,12 +583,16 @@ export class ModelQueryBuilder {
|
|
|
578
583
|
callback({ results, totalCount, pageSize, pageNumber });
|
|
579
584
|
};
|
|
580
585
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
|
|
581
|
-
if (rawResult && rawResult.isInit)
|
|
582
|
-
return;
|
|
583
586
|
processResults().catch(e => console.error('Paginate subscription error:', e));
|
|
584
587
|
});
|
|
588
|
+
let keepaliveFailures = 0;
|
|
585
589
|
const keepaliveTimer = setInterval(() => {
|
|
586
|
-
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).
|
|
590
|
+
this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
|
|
591
|
+
keepaliveFailures = 0;
|
|
592
|
+
}).catch((e) => {
|
|
593
|
+
keepaliveFailures++;
|
|
594
|
+
console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
|
|
595
|
+
});
|
|
587
596
|
}, 30000);
|
|
588
597
|
this.currentSubscription = {
|
|
589
598
|
dispose: () => {
|
package/lib/src/model/Subject.js
CHANGED
|
@@ -55,12 +55,12 @@ export class Subject {
|
|
|
55
55
|
Object.defineProperty(this, p, {
|
|
56
56
|
configurable: true,
|
|
57
57
|
get: async () => {
|
|
58
|
-
// Use
|
|
58
|
+
// Use SurrealDB for data queries
|
|
59
59
|
try {
|
|
60
|
-
return await __classPrivateFieldGet(this, _Subject_perspective, "f").
|
|
60
|
+
return await __classPrivateFieldGet(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), p);
|
|
61
61
|
}
|
|
62
62
|
catch (err) {
|
|
63
|
-
console.warn(`Failed to get property ${p} via
|
|
63
|
+
console.warn(`Failed to get property ${p} via SurrealDB:`, err);
|
|
64
64
|
return undefined;
|
|
65
65
|
}
|
|
66
66
|
}
|
|
@@ -94,12 +94,12 @@ export class Subject {
|
|
|
94
94
|
Object.defineProperty(this, c, {
|
|
95
95
|
configurable: true,
|
|
96
96
|
get: async () => {
|
|
97
|
-
// Use
|
|
97
|
+
// Use SurrealDB for data queries
|
|
98
98
|
try {
|
|
99
|
-
return await __classPrivateFieldGet(this, _Subject_perspective, "f").
|
|
99
|
+
return await __classPrivateFieldGet(this, _Subject_perspective, "f").getRelationValuesViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), c);
|
|
100
100
|
}
|
|
101
101
|
catch (err) {
|
|
102
|
-
console.warn(`Failed to get relation ${c} via
|
|
102
|
+
console.warn(`Failed to get relation ${c} via SurrealDB:`, err);
|
|
103
103
|
return [];
|
|
104
104
|
}
|
|
105
105
|
}
|
|
@@ -1,50 +1,13 @@
|
|
|
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
|
-
import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
12
|
-
import type { ModelMetadata, WhereCondition } from "./types";
|
|
13
8
|
/**
|
|
14
9
|
* Normalize a value for snapshot storage.
|
|
15
10
|
* Arrays of model instances are reduced to their `.id` strings so that
|
|
16
11
|
* dirty-tracking compares stable identifiers instead of object references.
|
|
17
12
|
*/
|
|
18
13
|
export declare function normalizeValue(value: any): any;
|
|
19
|
-
/**
|
|
20
|
-
* Checks if a value matches a where-condition (for post-query filtering).
|
|
21
|
-
*/
|
|
22
|
-
export declare function matchesCondition(value: any, condition: WhereCondition): boolean;
|
|
23
|
-
/**
|
|
24
|
-
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
25
|
-
* is known but no explicit `getter` string was supplied.
|
|
26
|
-
*
|
|
27
|
-
* The generated getter traverses outgoing links matching the relation's
|
|
28
|
-
* predicate and then filters the target nodes to only those that conform to
|
|
29
|
-
* the target model's shape (required properties / flags).
|
|
30
|
-
*
|
|
31
|
-
* Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
|
|
32
|
-
* so the same logic is used at shape-definition time and at query time.
|
|
33
|
-
*
|
|
34
|
-
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
35
|
-
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
36
|
-
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
37
|
-
* conditions could be derived from the target model.
|
|
38
|
-
*/
|
|
39
|
-
export declare function buildConformanceGetter(relationPredicate: string, targetClass: any): string | undefined;
|
|
40
|
-
/**
|
|
41
|
-
* Evaluates custom SurrealQL getters for properties and relations on a specific instance.
|
|
42
|
-
*
|
|
43
|
-
* For relations that declare a `target` but no explicit `getter`, a conformance
|
|
44
|
-
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
45
|
-
*/
|
|
46
|
-
export declare function evaluateCustomGettersForInstance(instance: any, perspective: PerspectiveProxy, metadata: ModelMetadata, options?: {
|
|
47
|
-
requestedProperties?: string[];
|
|
48
|
-
include?: Record<string, any>;
|
|
49
|
-
skipPropertyGetters?: boolean;
|
|
50
|
-
}): Promise<void>;
|
|
@@ -1,16 +1,10 @@
|
|
|
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
|
-
import { buildConformanceFilter } from "./decorators";
|
|
12
|
-
import { compileWhereClause } from "./query-utils";
|
|
13
|
-
import { escapeQueryString } from "../utils";
|
|
14
8
|
// ──────────────────────────────────────────────────────────
|
|
15
9
|
// Pure helpers
|
|
16
10
|
// ──────────────────────────────────────────────────────────
|
|
@@ -25,255 +19,3 @@ export function normalizeValue(value) {
|
|
|
25
19
|
}
|
|
26
20
|
return value;
|
|
27
21
|
}
|
|
28
|
-
/**
|
|
29
|
-
* Checks if a value matches a where-condition (for post-query filtering).
|
|
30
|
-
*/
|
|
31
|
-
export function matchesCondition(value, condition) {
|
|
32
|
-
// Handle array values (IN clause)
|
|
33
|
-
if (Array.isArray(condition)) {
|
|
34
|
-
return condition.includes(value);
|
|
35
|
-
}
|
|
36
|
-
// Handle operator object
|
|
37
|
-
if (typeof condition === 'object' && condition !== null) {
|
|
38
|
-
const ops = condition;
|
|
39
|
-
// Special case: 'not' operator (exclusive with other operators)
|
|
40
|
-
if (ops.not !== undefined) {
|
|
41
|
-
if (Array.isArray(ops.not)) {
|
|
42
|
-
return !ops.not.includes(value);
|
|
43
|
-
}
|
|
44
|
-
else {
|
|
45
|
-
return value !== ops.not;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
// Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
|
|
49
|
-
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
50
|
-
return value >= ops.between[0] && value <= ops.between[1];
|
|
51
|
-
}
|
|
52
|
-
// For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
|
|
53
|
-
// and return true only if ALL conditions are satisfied
|
|
54
|
-
let allConditionsMet = true;
|
|
55
|
-
if (ops.gt !== undefined) {
|
|
56
|
-
allConditionsMet = allConditionsMet && (value > ops.gt);
|
|
57
|
-
}
|
|
58
|
-
if (ops.gte !== undefined) {
|
|
59
|
-
allConditionsMet = allConditionsMet && (value >= ops.gte);
|
|
60
|
-
}
|
|
61
|
-
if (ops.lt !== undefined) {
|
|
62
|
-
allConditionsMet = allConditionsMet && (value < ops.lt);
|
|
63
|
-
}
|
|
64
|
-
if (ops.lte !== undefined) {
|
|
65
|
-
allConditionsMet = allConditionsMet && (value <= ops.lte);
|
|
66
|
-
}
|
|
67
|
-
if (ops.contains !== undefined) {
|
|
68
|
-
if (typeof value === 'string') {
|
|
69
|
-
allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
|
|
70
|
-
}
|
|
71
|
-
else if (Array.isArray(value)) {
|
|
72
|
-
allConditionsMet = allConditionsMet && value.includes(ops.contains);
|
|
73
|
-
}
|
|
74
|
-
else {
|
|
75
|
-
allConditionsMet = false;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
return allConditionsMet;
|
|
79
|
-
}
|
|
80
|
-
// Simple equality
|
|
81
|
-
return value === condition;
|
|
82
|
-
}
|
|
83
|
-
// ──────────────────────────────────────────────────────────
|
|
84
|
-
// SPARQL custom getter evaluation
|
|
85
|
-
// ──────────────────────────────────────────────────────────
|
|
86
|
-
/**
|
|
87
|
-
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
88
|
-
* is known but no explicit `getter` string was supplied.
|
|
89
|
-
*
|
|
90
|
-
* The generated getter traverses outgoing links matching the relation's
|
|
91
|
-
* predicate and then filters the target nodes to only those that conform to
|
|
92
|
-
* the target model's shape (required properties / flags).
|
|
93
|
-
*
|
|
94
|
-
* Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
|
|
95
|
-
* so the same logic is used at shape-definition time and at query time.
|
|
96
|
-
*
|
|
97
|
-
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
98
|
-
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
99
|
-
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
100
|
-
* conditions could be derived from the target model.
|
|
101
|
-
*/
|
|
102
|
-
export function buildConformanceGetter(relationPredicate, targetClass) {
|
|
103
|
-
const filter = buildConformanceFilter(relationPredicate, targetClass);
|
|
104
|
-
if (!filter) {
|
|
105
|
-
const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
|
|
106
|
-
console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
|
|
107
|
-
return undefined;
|
|
108
|
-
}
|
|
109
|
-
return filter.getter;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Evaluates custom SurrealQL getters for properties and relations on a specific instance.
|
|
113
|
-
*
|
|
114
|
-
* For relations that declare a `target` but no explicit `getter`, a conformance
|
|
115
|
-
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
116
|
-
*/
|
|
117
|
-
export async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
|
|
118
|
-
const safeBaseExpression = `<${instance.id}>`;
|
|
119
|
-
// Build projection filter — when requestedProperties is active, only
|
|
120
|
-
// evaluate getters for fields that are requested (or included).
|
|
121
|
-
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
122
|
-
const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
|
|
123
|
-
// Evaluate property getters (skip when caller only wants relation type-filtering)
|
|
124
|
-
if (!options?.skipPropertyGetters) {
|
|
125
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
126
|
-
if (projectionSet && !projectionSet.has(propName))
|
|
127
|
-
continue;
|
|
128
|
-
if (propMeta.getter) {
|
|
129
|
-
try {
|
|
130
|
-
const rawGetter = propMeta.getter;
|
|
131
|
-
const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
|
|
132
|
-
// If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
|
|
133
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
134
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
135
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
136
|
-
if (trimmed.startsWith('ASK')) {
|
|
137
|
-
instance[propName] = result === true || result === 'true';
|
|
138
|
-
}
|
|
139
|
-
else if (result && result.length > 0) {
|
|
140
|
-
// Get first binding's first value
|
|
141
|
-
const firstRow = result[0];
|
|
142
|
-
const firstKey = Object.keys(firstRow)[0];
|
|
143
|
-
const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
|
|
144
|
-
if (val !== undefined && val !== null && val !== 'None' && val !== '') {
|
|
145
|
-
instance[propName] = val;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
else {
|
|
150
|
-
// Legacy SurrealDB-style getter — safety guard for getters that don't match
|
|
151
|
-
// SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
152
|
-
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
catch (error) {
|
|
156
|
-
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
} // end skipPropertyGetters guard
|
|
161
|
-
// Evaluate relation getters (explicit or auto-generated from target)
|
|
162
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
163
|
-
// Skip relations excluded by property projection (unless in include map)
|
|
164
|
-
if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
|
|
165
|
-
continue;
|
|
166
|
-
const meta = relMeta;
|
|
167
|
-
// Determine the getter to execute:
|
|
168
|
-
// 1. Explicit `getter` always wins
|
|
169
|
-
// 2. If `target` is set and `filter !== false`, auto-generate conformance getter
|
|
170
|
-
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
171
|
-
// because buildConformanceGetter traverses outgoing links which is wrong for
|
|
172
|
-
// reverse relations. Their values are already populated by the reverse link
|
|
173
|
-
// lookup in instancesFromQueryResult / getData.
|
|
174
|
-
let getter = meta.getter;
|
|
175
|
-
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
176
|
-
try {
|
|
177
|
-
const TargetClass = meta.target?.();
|
|
178
|
-
const targetMetadata = TargetClass
|
|
179
|
-
? TargetClass.getModelMetadata?.() ?? null
|
|
180
|
-
: null;
|
|
181
|
-
// Check if all where conditions can be SPARQL-filtered.
|
|
182
|
-
// literal-resolved properties store signed expressions (literal:json:{…}),
|
|
183
|
-
// not raw literal:string: IRIs, so SPARQL exact-match fails for them.
|
|
184
|
-
let allSparqlFilterable = true;
|
|
185
|
-
if (targetMetadata) {
|
|
186
|
-
for (const propName of Object.keys(meta.where)) {
|
|
187
|
-
if (['id', 'author', 'timestamp'].includes(propName))
|
|
188
|
-
continue;
|
|
189
|
-
const propMeta = targetMetadata.properties[propName];
|
|
190
|
-
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
191
|
-
allSparqlFilterable = false;
|
|
192
|
-
break;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
else {
|
|
197
|
-
allSparqlFilterable = false;
|
|
198
|
-
}
|
|
199
|
-
if (allSparqlFilterable) {
|
|
200
|
-
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
201
|
-
if (conditions.length > 0) {
|
|
202
|
-
const escapedPredicate = escapeQueryString(meta.predicate);
|
|
203
|
-
getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
// If not filterable, fall through to buildConformanceGetter + JS post-filter below
|
|
207
|
-
}
|
|
208
|
-
catch (e) {
|
|
209
|
-
console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
213
|
-
try {
|
|
214
|
-
const TargetClass = meta.target();
|
|
215
|
-
getter = buildConformanceGetter(meta.predicate, TargetClass);
|
|
216
|
-
if (!getter) {
|
|
217
|
-
console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
catch (e) {
|
|
221
|
-
console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
if (getter) {
|
|
225
|
-
try {
|
|
226
|
-
const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
|
|
227
|
-
const trimmed = getterWithBase.trim().toUpperCase();
|
|
228
|
-
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
229
|
-
// Native SPARQL getter — execute directly
|
|
230
|
-
const result = await perspective.querySparql(getterWithBase);
|
|
231
|
-
if (result && result.length > 0) {
|
|
232
|
-
const values = result.map((r) => {
|
|
233
|
-
const firstKey = Object.keys(r)[0];
|
|
234
|
-
return r[firstKey]?.value ?? r[firstKey];
|
|
235
|
-
}).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
236
|
-
instance[relName] = values;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
else {
|
|
240
|
-
// Legacy SurrealDB-style getter — safety guard for relation getters that don't
|
|
241
|
-
// match SPARQL patterns (SELECT/ASK). Logs a warning but does not crash.
|
|
242
|
-
console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
catch (error) {
|
|
246
|
-
console.warn(`Failed to evaluate getter for ${relName}:`, error);
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
// JS post-filter for where conditions that couldn't be SPARQL-filtered
|
|
250
|
-
// (e.g. literal-resolved properties storing signed expressions)
|
|
251
|
-
const currentValues = instance[relName];
|
|
252
|
-
if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
|
|
253
|
-
const TargetClass = meta.target?.();
|
|
254
|
-
if (TargetClass) {
|
|
255
|
-
const filtered = [];
|
|
256
|
-
for (const targetId of currentValues) {
|
|
257
|
-
try {
|
|
258
|
-
const inst = new TargetClass(perspective, targetId);
|
|
259
|
-
await inst.get();
|
|
260
|
-
let matches = true;
|
|
261
|
-
for (const [prop, expected] of Object.entries(meta.where)) {
|
|
262
|
-
if (inst[prop] !== expected) {
|
|
263
|
-
matches = false;
|
|
264
|
-
break;
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
if (matches)
|
|
268
|
-
filtered.push(targetId);
|
|
269
|
-
}
|
|
270
|
-
catch {
|
|
271
|
-
// If we can't hydrate, keep the value (conservative)
|
|
272
|
-
filtered.push(targetId);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
instance[relName] = filtered;
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SurrealQL query building utilities for Ad4mModel.
|
|
3
|
+
*
|
|
4
|
+
* Contains the graph-traversal WHERE clause builder, legacy
|
|
5
|
+
* subquery-based clause builders, SELECT-field builders, and
|
|
6
|
+
* the main `buildSurrealQLQuery()` function that produces a
|
|
7
|
+
* complete SurrealQL query string from a `Query` object.
|
|
8
|
+
*
|
|
9
|
+
* All functions are stateless — model metadata and relation metadata
|
|
10
|
+
* are passed in as parameters instead of accessed via `this`.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import type { RelationMetadataEntry } from "./decorators";
|
|
15
|
+
import type { Where, Query, ModelMetadata } from "./types";
|
|
16
|
+
/**
|
|
17
|
+
* Builds WHERE clause filters using SurrealDB graph traversal syntax.
|
|
18
|
+
*
|
|
19
|
+
* Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
|
|
20
|
+
* filters that SurrealDB can optimize via graph indexes.
|
|
21
|
+
*
|
|
22
|
+
* @param metadata - Model metadata from `getModelMetadata()`
|
|
23
|
+
* @param allRelationsMetadata - Full relation metadata (needed for belongs-to
|
|
24
|
+
* direction detection)
|
|
25
|
+
* @param where - User-supplied where conditions
|
|
26
|
+
* @returns Combined AND-joined condition string, or empty string
|
|
27
|
+
*/
|
|
28
|
+
export declare function buildGraphTraversalWhereClause(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, where?: Where): string;
|
|
29
|
+
/**
|
|
30
|
+
* Builds a complete SurrealQL query from a Query object and model metadata.
|
|
31
|
+
*
|
|
32
|
+
* This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
|
|
33
|
+
* It produces a graph-traversal query that:
|
|
34
|
+
* 1. Filters nodes by required predicates (conformance check)
|
|
35
|
+
* 2. Applies user WHERE conditions
|
|
36
|
+
* 3. Fetches all outgoing links for hydration
|
|
37
|
+
*
|
|
38
|
+
* @param metadata - Model metadata from `getModelMetadata()`
|
|
39
|
+
* @param allRelationsMetadata - Full relation registry (for belongs-to detection)
|
|
40
|
+
* @param query - Query parameters
|
|
41
|
+
* @param modelClass - The model class (for `resolveParentPredicate`)
|
|
42
|
+
* @returns Complete SurrealQL query string
|
|
43
|
+
*/
|
|
44
|
+
export declare function buildSurrealQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
|