@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
|
@@ -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
|
-
}
|
|
@@ -30,6 +30,7 @@ export declare function formatQueryValue(value: any): string;
|
|
|
30
30
|
*/
|
|
31
31
|
export declare function buildWhereCondition(predicate: string, condition: WhereCondition, opts?: {
|
|
32
32
|
resolveLanguage?: string;
|
|
33
|
+
varIndex?: number;
|
|
33
34
|
}): string;
|
|
34
35
|
/**
|
|
35
36
|
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
@@ -56,6 +56,7 @@ export function buildWhereCondition(predicate, condition, opts) {
|
|
|
56
56
|
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
57
57
|
// For language-resolved properties, values are plain URIs
|
|
58
58
|
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
59
|
+
const varSuffix = opts?.varIndex ?? 0;
|
|
59
60
|
function formatValue(v) {
|
|
60
61
|
if (typeof v === 'string') {
|
|
61
62
|
return isLiteral
|
|
@@ -65,8 +66,46 @@ export function buildWhereCondition(predicate, condition, opts) {
|
|
|
65
66
|
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
66
67
|
return `<literal:string:${v}>`;
|
|
67
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* For literal properties, generate a FILTER-based match that handles both
|
|
71
|
+
* the raw value and the literal-encoded value. This mirrors the Rust
|
|
72
|
+
* `build_projection_where_patterns` approach which uses:
|
|
73
|
+
* FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
|
|
74
|
+
* This is more robust than exact IRI matching because it handles edge cases
|
|
75
|
+
* where the stored format might vary.
|
|
76
|
+
*/
|
|
77
|
+
function formatLiteralFilter(varName, v) {
|
|
78
|
+
const raw = escapeQueryString(String(v));
|
|
79
|
+
const encoded = encodeURIComponent(String(v))
|
|
80
|
+
.replace(/!/g, '%21')
|
|
81
|
+
.replace(/'/g, '%27')
|
|
82
|
+
.replace(/\(/g, '%28')
|
|
83
|
+
.replace(/\)/g, '%29')
|
|
84
|
+
.replace(/\*/g, '%2A');
|
|
85
|
+
if (typeof v === 'string') {
|
|
86
|
+
return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
|
|
87
|
+
}
|
|
88
|
+
else if (typeof v === 'number') {
|
|
89
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
|
|
90
|
+
}
|
|
91
|
+
else if (typeof v === 'boolean') {
|
|
92
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
|
|
93
|
+
}
|
|
94
|
+
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
95
|
+
}
|
|
68
96
|
if (Array.isArray(condition)) {
|
|
69
97
|
// Array values → FILTER IN
|
|
98
|
+
if (isLiteral) {
|
|
99
|
+
const varName = `?_wc${varSuffix}`;
|
|
100
|
+
const inValues = condition.flatMap(v => {
|
|
101
|
+
const raw = escapeQueryString(String(v));
|
|
102
|
+
const encoded = encodeURIComponent(String(v))
|
|
103
|
+
.replace(/!/g, '%21').replace(/'/g, '%27')
|
|
104
|
+
.replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
|
|
105
|
+
return [`"${raw}"`, `"literal:string:${encoded}"`];
|
|
106
|
+
}).join(', ');
|
|
107
|
+
return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
|
|
108
|
+
}
|
|
70
109
|
const formattedValues = condition.map(formatValue).join(', ');
|
|
71
110
|
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
72
111
|
}
|
|
@@ -98,6 +137,12 @@ export function buildWhereCondition(predicate, condition, opts) {
|
|
|
98
137
|
}
|
|
99
138
|
else {
|
|
100
139
|
// Simple equality
|
|
140
|
+
if (isLiteral) {
|
|
141
|
+
// Use FILTER matching (mirrors Rust build_projection_where_patterns)
|
|
142
|
+
// to handle both raw values and literal-encoded IRIs robustly.
|
|
143
|
+
const varName = `?_wc${varSuffix}`;
|
|
144
|
+
return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
|
|
145
|
+
}
|
|
101
146
|
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
102
147
|
}
|
|
103
148
|
}
|
|
@@ -135,7 +180,7 @@ export function compileWhereClause(where, metadata) {
|
|
|
135
180
|
// No metadata — treat name as raw predicate URI
|
|
136
181
|
predicate = propertyName;
|
|
137
182
|
}
|
|
138
|
-
const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
|
|
183
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
|
|
139
184
|
if (cond) {
|
|
140
185
|
conditions.push(cond);
|
|
141
186
|
}
|
package/lib/src/model/types.d.ts
CHANGED
|
@@ -122,12 +122,11 @@ export type Query = {
|
|
|
122
122
|
count?: boolean;
|
|
123
123
|
/**
|
|
124
124
|
* When true, SPARQL property getters (@Property with `getter`) ARE evaluated
|
|
125
|
-
* during collection hydration.
|
|
126
|
-
*
|
|
125
|
+
* during collection hydration. Defaults to true — getters run post-pagination
|
|
126
|
+
* via batched VALUES queries so the cost is O(getters), not O(instances × getters).
|
|
127
127
|
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
-
* and use `Ad4mModel.evaluateGetters()` on visible items only.
|
|
128
|
+
* Set to false to explicitly skip getter evaluation for performance-sensitive
|
|
129
|
+
* queries where getter-backed properties are not needed.
|
|
131
130
|
*/
|
|
132
131
|
deepQuery?: boolean;
|
|
133
132
|
};
|
|
@@ -39,6 +39,7 @@ export declare class PerspectiveClient {
|
|
|
39
39
|
keepAliveQuery(uuid: string, subscriptionId: string): Promise<boolean>;
|
|
40
40
|
disposeQuerySubscription(uuid: string, subscriptionId: string): Promise<boolean>;
|
|
41
41
|
modelQuery(uuid: string, className: string, queryJson: string, shapeJson?: string): Promise<any>;
|
|
42
|
+
evaluateGetters(uuid: string, className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
|
|
42
43
|
modelSubscribe(uuid: string, className: string, queryJson: string, shapeJson?: string): Promise<{
|
|
43
44
|
subscriptionId: string;
|
|
44
45
|
result: any;
|
|
@@ -160,6 +160,16 @@ export class PerspectiveClient {
|
|
|
160
160
|
const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
|
|
161
161
|
return JSON.parse(resultJson);
|
|
162
162
|
}
|
|
163
|
+
async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
|
|
164
|
+
const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
|
|
165
|
+
uuid,
|
|
166
|
+
class_name: className,
|
|
167
|
+
instance_ids: instanceIds,
|
|
168
|
+
shape_json: shapeJson,
|
|
169
|
+
...(propertyNames && { property_names: propertyNames }),
|
|
170
|
+
});
|
|
171
|
+
return JSON.parse(resultJson);
|
|
172
|
+
}
|
|
163
173
|
async modelSubscribe(uuid, className, queryJson, shapeJson) {
|
|
164
174
|
const response = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
|
|
165
175
|
return {
|
|
@@ -331,6 +331,20 @@ export declare class PerspectiveProxy {
|
|
|
331
331
|
instances: any[];
|
|
332
332
|
totalCount: number;
|
|
333
333
|
}>;
|
|
334
|
+
/**
|
|
335
|
+
* Evaluate property getters for a batch of instances in a single RPC call.
|
|
336
|
+
* Returns a map of `{ instanceId: { prop: value, ... } }`.
|
|
337
|
+
*
|
|
338
|
+
* Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading
|
|
339
|
+
* getter-backed properties on visible items (e.g. `replyingTo` on messages).
|
|
340
|
+
*
|
|
341
|
+
* @param className - The model class name (e.g. "Message")
|
|
342
|
+
* @param instanceIds - Array of instance base expression URIs
|
|
343
|
+
* @param shapeJson - Shape metadata JSON from the model class
|
|
344
|
+
* @param propertyNames - Optional subset of property names to evaluate
|
|
345
|
+
* @returns Map of instance ID → evaluated property values
|
|
346
|
+
*/
|
|
347
|
+
evaluateGetters(className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
|
|
334
348
|
/**
|
|
335
349
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
336
350
|
* internally in Rust, registers a subscription, runs the initial query, and
|
|
@@ -551,6 +551,22 @@ export class PerspectiveProxy {
|
|
|
551
551
|
async modelQuery(className, queryJson, shapeJson) {
|
|
552
552
|
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
|
|
553
553
|
}
|
|
554
|
+
/**
|
|
555
|
+
* Evaluate property getters for a batch of instances in a single RPC call.
|
|
556
|
+
* Returns a map of `{ instanceId: { prop: value, ... } }`.
|
|
557
|
+
*
|
|
558
|
+
* Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading
|
|
559
|
+
* getter-backed properties on visible items (e.g. `replyingTo` on messages).
|
|
560
|
+
*
|
|
561
|
+
* @param className - The model class name (e.g. "Message")
|
|
562
|
+
* @param instanceIds - Array of instance base expression URIs
|
|
563
|
+
* @param shapeJson - Shape metadata JSON from the model class
|
|
564
|
+
* @param propertyNames - Optional subset of property names to evaluate
|
|
565
|
+
* @returns Map of instance ID → evaluated property values
|
|
566
|
+
*/
|
|
567
|
+
async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
|
|
568
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
|
|
569
|
+
}
|
|
554
570
|
/**
|
|
555
571
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
556
572
|
* internally in Rust, registers a subscription, runs the initial query, and
|
package/package.json
CHANGED
|
@@ -5,6 +5,12 @@
|
|
|
5
5
|
"module": "lib/index.js",
|
|
6
6
|
"types": "lib/src/index.d.ts",
|
|
7
7
|
"type": "module",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "patch-package && tsc && pnpm run bundle",
|
|
10
|
+
"bundle": "rollup -c rollup.config.js",
|
|
11
|
+
"test": "jest --forceExit",
|
|
12
|
+
"generate:api-types": "cd ../rust-executor && TS_RS_EXPORT_DIR=../core/src/generated/api/ cargo test --lib 2>/dev/null && echo \"API types generated to core/src/generated/api/\""
|
|
13
|
+
},
|
|
8
14
|
"repository": {
|
|
9
15
|
"type": "git",
|
|
10
16
|
"url": "git+https://github.com/coasys/ad4m.git"
|
|
@@ -48,11 +54,8 @@
|
|
|
48
54
|
"ws": "8.13.0"
|
|
49
55
|
},
|
|
50
56
|
"patchedDependencies": {},
|
|
51
|
-
"
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
"generate:api-types": "cd ../rust-executor && TS_RS_EXPORT_DIR=../core/src/generated/api/ cargo test --lib 2>/dev/null && echo \"API types generated to core/src/generated/api/\""
|
|
57
|
-
}
|
|
58
|
-
}
|
|
57
|
+
"pnpm": {
|
|
58
|
+
"patchedDependencies": {}
|
|
59
|
+
},
|
|
60
|
+
"version": "0.13.0-test-5"
|
|
61
|
+
}
|
package/src/Ad4mClient.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { RuntimeClient } from './runtime/RuntimeClient'
|
|
|
6
6
|
import { ExpressionClient } from './expression/ExpressionClient'
|
|
7
7
|
import { AIClient } from './ai/AIClient'
|
|
8
8
|
import { ApiClient } from './apiClient'
|
|
9
|
+
import { Ad4mModel } from './model/Ad4mModel'
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Client for the Ad4m interface wrapping WebSocket RPC calls
|
|
@@ -42,6 +43,15 @@ export class Ad4mClient {
|
|
|
42
43
|
this.#perspectiveClient.setNeighbourhoodClient(this.#neighbourhoodClient)
|
|
43
44
|
this.#perspectiveClient.setAIClient(this.#aiClient)
|
|
44
45
|
this.#runtimeClient = new RuntimeClient(baseUrl, token, subscribe, this.#apiClient)
|
|
46
|
+
|
|
47
|
+
// Register with AD4M DevTools if the bridge is installed (e.g. browser extension)
|
|
48
|
+
try {
|
|
49
|
+
const dt = (globalThis as any).__AD4M_DEVTOOLS__;
|
|
50
|
+
if (dt) {
|
|
51
|
+
dt._client = this;
|
|
52
|
+
dt._Ad4mModel = Ad4mModel;
|
|
53
|
+
}
|
|
54
|
+
} catch {}
|
|
45
55
|
}
|
|
46
56
|
|
|
47
57
|
get agent(): AgentClient {
|