@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.3
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 +564 -461
- package/lib/index.js +561 -462
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/src/model/Ad4mModel.d.ts +9 -17
- package/lib/src/model/Ad4mModel.js +34 -148
- package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
- package/lib/src/model/ModelQueryBuilder.js +8 -14
- package/lib/src/model/shacl-gen.js +115 -46
- package/lib/src/model/types.d.ts +138 -3
- package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
- package/lib/src/perspectives/PerspectiveClient.js +5 -6
- package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
- package/lib/src/perspectives/PerspectiveProxy.js +10 -9
- package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
- package/lib/src/perspectives/SparqlBindings.js +65 -0
- package/lib/src/shacl/SHACLShape.d.ts +18 -0
- package/lib/src/shacl/SHACLShape.js +83 -0
- package/package.json +8 -11
- package/src/index.ts +1 -0
- package/src/model/Ad4mModel.test.ts +23 -64
- package/src/model/Ad4mModel.ts +52 -159
- package/src/model/ModelQueryBuilder.ts +17 -23
- package/src/model/relation-filtering.test.ts +46 -39
- package/src/model/shacl-gen.ts +122 -53
- package/src/model/shacl-roundtrip.test.ts +197 -0
- package/src/model/types-typed-query.test.ts +360 -0
- package/src/model/types.ts +194 -3
- package/src/perspectives/PerspectiveClient.ts +6 -8
- package/src/perspectives/PerspectiveProxy.ts +13 -13
- package/src/perspectives/SparqlBindings.ts +79 -0
- package/src/shacl/SHACLShape.test.ts +110 -0
- package/src/shacl/SHACLShape.ts +125 -0
|
@@ -7,8 +7,6 @@
|
|
|
7
7
|
* decorators.ts stays focused on decorator registration logic.
|
|
8
8
|
*/
|
|
9
9
|
import { SHACLShape } from "../shacl/SHACLShape";
|
|
10
|
-
import { escapeQueryString } from "../utils";
|
|
11
|
-
import { compileWhereClause } from "./query-utils";
|
|
12
10
|
import { propertyNameToSetterName } from "./util";
|
|
13
11
|
/**
|
|
14
12
|
* Build a SHACL shape for a model class.
|
|
@@ -25,7 +23,6 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
|
|
|
25
23
|
const obj = target.prototype;
|
|
26
24
|
// ── Determine namespace from first property or relation ─────────────
|
|
27
25
|
let namespace = "ad4m://";
|
|
28
|
-
const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
|
|
29
26
|
// Try properties first
|
|
30
27
|
if (Object.keys(properties).length > 0) {
|
|
31
28
|
const firstProp = properties[Object.keys(properties)[0]];
|
|
@@ -37,8 +34,8 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
|
|
|
37
34
|
}
|
|
38
35
|
}
|
|
39
36
|
// Fall back to relations if no properties
|
|
40
|
-
else if (Object.keys(
|
|
41
|
-
const firstRel =
|
|
37
|
+
else if (Object.keys(allRelationsMeta).length > 0) {
|
|
38
|
+
const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
|
|
42
39
|
if (firstRel.predicate) {
|
|
43
40
|
const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
|
|
44
41
|
if (match) {
|
|
@@ -115,6 +112,12 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
|
|
|
115
112
|
if (propMeta.resolveLanguage) {
|
|
116
113
|
propShape.resolveLanguage = propMeta.resolveLanguage;
|
|
117
114
|
}
|
|
115
|
+
// Explicit getter SPARQL — the executor evaluates this when
|
|
116
|
+
// hydrating the property, in addition to (or instead of)
|
|
117
|
+
// reading raw links via `propMeta.through`.
|
|
118
|
+
if (propMeta.getter) {
|
|
119
|
+
propShape.getter = propMeta.getter;
|
|
120
|
+
}
|
|
118
121
|
// ── Setter actions ──────────────────────────────────────────────
|
|
119
122
|
if (propMeta.prologSetter) {
|
|
120
123
|
console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
|
|
@@ -153,63 +156,82 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
|
|
|
153
156
|
shape.addProperty(propShape);
|
|
154
157
|
}
|
|
155
158
|
// ── Convert relations to SHACL property shapes ─────────────────────
|
|
156
|
-
for (const relName in
|
|
157
|
-
const relMeta =
|
|
158
|
-
|
|
159
|
+
for (const relName in allRelationsMeta) {
|
|
160
|
+
const relMeta = allRelationsMeta[relName];
|
|
161
|
+
// Getter-only relations (no `through`) have no real link predicate
|
|
162
|
+
// but still need a SHACL property entry so the executor can find
|
|
163
|
+
// the getter expression. Synthesize a deterministic IRI so the
|
|
164
|
+
// SHACL graph is well-formed; the predicate is never used to match
|
|
165
|
+
// links because the getter is the sole source of values. Use
|
|
166
|
+
// slash separators so the result is a valid IRI (colons in the
|
|
167
|
+
// authority confuse strict SPARQL IRI parsers).
|
|
168
|
+
if (!relMeta.predicate && !relMeta.getter)
|
|
159
169
|
continue;
|
|
170
|
+
const synthesizedPath = relMeta.predicate
|
|
171
|
+
|| `ad4m://getter/${subjectName}/${relName}`;
|
|
160
172
|
const relShape = {
|
|
161
173
|
name: relName,
|
|
162
|
-
path:
|
|
174
|
+
path: synthesizedPath,
|
|
163
175
|
};
|
|
164
176
|
// Relations typically contain IRIs
|
|
165
177
|
relShape.nodeKind = 'IRI';
|
|
178
|
+
// Encode relation kind so the executor can derive direction and
|
|
179
|
+
// scalar-vs-collection rendering without consulting the JS class.
|
|
180
|
+
relShape.relationKind = relMeta.kind;
|
|
181
|
+
// Scalar relations cap at 1.
|
|
182
|
+
if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
|
|
183
|
+
relShape.maxCount = 1;
|
|
184
|
+
}
|
|
185
|
+
else if (relMeta.maxCount !== undefined) {
|
|
186
|
+
relShape.maxCount = relMeta.maxCount;
|
|
187
|
+
}
|
|
188
|
+
// Encode opt-out of type filtering (default true; only emit when false).
|
|
189
|
+
if (relMeta.filter === false) {
|
|
190
|
+
relShape.filter = false;
|
|
191
|
+
}
|
|
166
192
|
// AD4M-specific metadata
|
|
167
193
|
if (relMeta.local !== undefined) {
|
|
168
194
|
relShape.local = relMeta.local;
|
|
169
195
|
}
|
|
170
|
-
// Adder
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
196
|
+
// Adder / Remover actions — only meaningful for relations backed
|
|
197
|
+
// by a real link predicate. Getter-only relations are read-only.
|
|
198
|
+
if (relMeta.predicate) {
|
|
199
|
+
relShape.adder = [{
|
|
200
|
+
action: "addLink",
|
|
201
|
+
source: "this",
|
|
202
|
+
predicate: relMeta.predicate,
|
|
203
|
+
target: "value",
|
|
204
|
+
...(relMeta.local && { local: true })
|
|
205
|
+
}];
|
|
206
|
+
relShape.remover = [{
|
|
207
|
+
action: "removeLink",
|
|
208
|
+
source: "this",
|
|
209
|
+
predicate: relMeta.predicate,
|
|
210
|
+
target: "value",
|
|
211
|
+
...(relMeta.local && { local: true })
|
|
212
|
+
}];
|
|
213
|
+
}
|
|
186
214
|
// ── Build Getter (conformance filter) ───────────────────────────
|
|
187
215
|
// Priority chain:
|
|
188
216
|
// 1. Explicit getter string → use verbatim
|
|
189
|
-
// 2.
|
|
190
|
-
//
|
|
217
|
+
// 2. target + filter !== false → auto-derive conformance getter
|
|
218
|
+
// from the shape. Where-clause filtering is applied as a
|
|
219
|
+
// post-getter pass via `whereFilter` / `wherePredicates`, which
|
|
220
|
+
// use `parse_literal_value` and so transparently handle
|
|
221
|
+
// `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
|
|
222
|
+
// comparisons can't.
|
|
191
223
|
if (relMeta.getter) {
|
|
192
224
|
relShape.getter = relMeta.getter;
|
|
193
225
|
}
|
|
194
|
-
else if (relMeta.
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
? TargetClass.getModelMetadata?.() ?? null
|
|
199
|
-
: null;
|
|
200
|
-
const conditions = compileWhereClause(relMeta.where, targetMetadata);
|
|
201
|
-
if (conditions.length > 0) {
|
|
202
|
-
const escapedPredicate = escapeQueryString(relMeta.predicate);
|
|
203
|
-
relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
catch (e) {
|
|
207
|
-
// Target metadata may not be available yet
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
else if (relMeta.target && relMeta.filter !== false) {
|
|
226
|
+
else if (relMeta.target
|
|
227
|
+
&& relMeta.filter !== false
|
|
228
|
+
&& relMeta.kind !== 'belongsToOne'
|
|
229
|
+
&& relMeta.kind !== 'belongsToMany') {
|
|
211
230
|
// Lazy conformance filter: store deferred reference,
|
|
212
|
-
// resolve on first access via a getter on relShape
|
|
231
|
+
// resolve on first access via a getter on relShape.
|
|
232
|
+
// Skipped for reverse relations (belongsTo*) because the
|
|
233
|
+
// auto-derived getter assumes forward direction; the executor's
|
|
234
|
+
// `resolve_reverse_relations` already populates these correctly.
|
|
213
235
|
const targetThunk = relMeta.target;
|
|
214
236
|
const predicate = relMeta.predicate;
|
|
215
237
|
let resolved = false;
|
|
@@ -246,6 +268,8 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
|
|
|
246
268
|
});
|
|
247
269
|
}
|
|
248
270
|
// ── sh:class — target shape reference ───────────────────────────
|
|
271
|
+
// Also emit ad4m:targetClassName so the executor can look up the
|
|
272
|
+
// target class shape through its in-memory cache by bare name.
|
|
249
273
|
if (relMeta.target) {
|
|
250
274
|
try {
|
|
251
275
|
const TargetClass = relMeta.target();
|
|
@@ -253,9 +277,54 @@ export function buildSHACL(subjectName, target, properties, allRelationsMeta, co
|
|
|
253
277
|
if (targetSHACL?.shape?.nodeShapeUri) {
|
|
254
278
|
relShape.class = targetSHACL.shape.nodeShapeUri;
|
|
255
279
|
}
|
|
280
|
+
if (targetSHACL?.name) {
|
|
281
|
+
relShape.targetClassName = targetSHACL.name;
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
const targetProto = TargetClass.prototype;
|
|
285
|
+
if (targetProto?.className) {
|
|
286
|
+
relShape.targetClassName = targetProto.className;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
catch (e) {
|
|
291
|
+
// Target class resolution failed (typically a circular
|
|
292
|
+
// decorator dependency). Since the executor no longer
|
|
293
|
+
// receives target metadata over the wire, dropping the
|
|
294
|
+
// reference here would turn a transient build-time issue
|
|
295
|
+
// into a permanent broken-include at query time. Log
|
|
296
|
+
// loudly so the failure is discoverable.
|
|
297
|
+
console.warn(`[shacl-gen] Failed to resolve target class for relation `
|
|
298
|
+
+ `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// ── Where-clause metadata for post-getter filtering ─────────────
|
|
302
|
+
// The executor uses these to apply where conditions against the
|
|
303
|
+
// target class without needing the target's ModelMetadata at query time.
|
|
304
|
+
if (relMeta.where) {
|
|
305
|
+
relShape.whereFilter = relMeta.where;
|
|
306
|
+
try {
|
|
307
|
+
const TargetClass = relMeta.target?.();
|
|
308
|
+
const targetMetadata = TargetClass
|
|
309
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
310
|
+
: null;
|
|
311
|
+
if (targetMetadata?.properties) {
|
|
312
|
+
const predicates = {};
|
|
313
|
+
for (const propName of Object.keys(relMeta.where)) {
|
|
314
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
315
|
+
continue;
|
|
316
|
+
const propMeta = targetMetadata.properties[propName];
|
|
317
|
+
if (propMeta?.predicate) {
|
|
318
|
+
predicates[propName] = propMeta.predicate;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (Object.keys(predicates).length > 0) {
|
|
322
|
+
relShape.wherePredicates = predicates;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
256
325
|
}
|
|
257
326
|
catch (e) {
|
|
258
|
-
// Target
|
|
327
|
+
// Target metadata may not be available yet
|
|
259
328
|
}
|
|
260
329
|
}
|
|
261
330
|
shape.addProperty(relShape);
|
package/lib/src/model/types.d.ts
CHANGED
|
@@ -89,11 +89,12 @@ export interface IncludeProjection {
|
|
|
89
89
|
/** When true, attaches an integer count instead of a list. */
|
|
90
90
|
count?: true;
|
|
91
91
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
92
|
+
* Bare class name of the projection target. Set automatically by
|
|
93
|
+
* `prepareModelQueryParams`; the executor resolves the target's shape
|
|
94
|
+
* through its in-memory cache when applying projection where filters.
|
|
94
95
|
* @internal
|
|
95
96
|
*/
|
|
96
|
-
|
|
97
|
+
targetClassName?: string;
|
|
97
98
|
/** Post-hydration where clause applied to the target instances. */
|
|
98
99
|
where?: Where;
|
|
99
100
|
/** Limit results (when 1, the attached value is unwrapped to a scalar). */
|
|
@@ -142,6 +143,139 @@ export type Query = {
|
|
|
142
143
|
* ```
|
|
143
144
|
*/
|
|
144
145
|
export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
|
|
146
|
+
/** Keys of T that are user-declared (not methods, not inherited from Ad4mModel). */
|
|
147
|
+
export type ModelDataKeys<T extends Ad4mModel> = {
|
|
148
|
+
[K in keyof T]: K extends keyof Ad4mModel ? never : T[K] extends (...args: any[]) => any ? never : K;
|
|
149
|
+
}[keyof T];
|
|
150
|
+
/** Keys of T that can appear in a `where` clause — scalars and scalar arrays.
|
|
151
|
+
* Excludes typed Ad4mModel references (single or array); `string[]`/`number[]`
|
|
152
|
+
* remain included because they're often filterable even when also used as
|
|
153
|
+
* link targets.
|
|
154
|
+
*
|
|
155
|
+
* Iterates over `keyof T` directly (not `ModelDataKeys<T>`) to preserve the
|
|
156
|
+
* key constraint — mapped types over computed type aliases sometimes widen
|
|
157
|
+
* to `string | undefined` in the key position, which then breaks indexing. */
|
|
158
|
+
export type PropertyKeysOf<T extends Ad4mModel> = {
|
|
159
|
+
[K in keyof T]: K extends ModelDataKeys<T> ? NonNullable<T[K]> extends Ad4mModel ? never : NonNullable<T[K]> extends Ad4mModel[] ? never : K : never;
|
|
160
|
+
}[keyof T];
|
|
161
|
+
/** Keys of T that can appear in `include` — typed Ad4mModel references AND
|
|
162
|
+
* `string[]` link-target arrays (the `@HasMany` + `string[]` pattern that
|
|
163
|
+
* AD4M uses for relations without a target class thunk). Handles both
|
|
164
|
+
* `?: Foo` (optional → `Foo | undefined`) and `Foo | null` field shapes, and
|
|
165
|
+
* optional/nullable array variants (`?: Foo[]`, `Foo[] | null`). */
|
|
166
|
+
export type RelationKeysOf<T extends Ad4mModel> = {
|
|
167
|
+
[K in keyof T]: K extends ModelDataKeys<T> ? NonNullable<T[K]> extends Ad4mModel ? K : NonNullable<T[K]> extends Ad4mModel[] ? K : NonNullable<T[K]> extends string[] ? K : never : never;
|
|
168
|
+
}[keyof T];
|
|
169
|
+
/** The model type referenced by a relation field K on T.
|
|
170
|
+
* Falls back to `Ad4mModel` (loose) for the `string[]` relation pattern,
|
|
171
|
+
* since no target class is available at the type level. */
|
|
172
|
+
export type RelatedModel<T extends Ad4mModel, K extends RelationKeysOf<T>> = NonNullable<T[K]> extends (infer U)[] ? (U extends Ad4mModel ? U : Ad4mModel) : NonNullable<T[K]> extends Ad4mModel ? NonNullable<T[K]> : Ad4mModel;
|
|
173
|
+
/** True when T has no statically-declared data fields (e.g. fromSHACL classes). */
|
|
174
|
+
type HasNoTypedFields<T extends Ad4mModel> = [
|
|
175
|
+
PropertyKeysOf<T> | RelationKeysOf<T>
|
|
176
|
+
] extends [never] ? true : false;
|
|
177
|
+
export type StringWhereOps = {
|
|
178
|
+
not?: string | string[];
|
|
179
|
+
contains?: string;
|
|
180
|
+
};
|
|
181
|
+
export type NumericWhereOps = {
|
|
182
|
+
not?: number | number[];
|
|
183
|
+
lt?: number;
|
|
184
|
+
lte?: number;
|
|
185
|
+
gt?: number;
|
|
186
|
+
gte?: number;
|
|
187
|
+
between?: [number, number];
|
|
188
|
+
};
|
|
189
|
+
export type TypedWhereCondition<V> = V extends string ? string | string[] | StringWhereOps : V extends number ? number | number[] | NumericWhereOps : V extends boolean ? boolean : V extends Array<infer U> ? U extends string ? string | string[] | StringWhereOps : U extends number ? number | number[] | NumericWhereOps : WhereCondition : WhereCondition;
|
|
190
|
+
/** Strict Where: keys constrained to T's properties, plus the well-known
|
|
191
|
+
* link-metadata fields (`id`/`author`/`timestamp`). */
|
|
192
|
+
type StrictTypedWhere<T extends Ad4mModel> = {
|
|
193
|
+
[K in PropertyKeysOf<T>]?: TypedWhereCondition<T[K]>;
|
|
194
|
+
} & {
|
|
195
|
+
base?: string | string[];
|
|
196
|
+
id?: string | string[];
|
|
197
|
+
author?: WhereCondition;
|
|
198
|
+
timestamp?: WhereCondition;
|
|
199
|
+
};
|
|
200
|
+
/** Public typed `where` for a model class. Falls back to the loose `Where`
|
|
201
|
+
* shape when T has no declared fields (e.g. fromSHACL-derived classes). */
|
|
202
|
+
export type TypedWhere<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? Where : StrictTypedWhere<T>;
|
|
203
|
+
type StrictTypedOrder<T extends Ad4mModel> = {
|
|
204
|
+
[K in PropertyKeysOf<T> | 'timestamp' | 'author' | 'createdAt' | 'updatedAt']?: 'ASC' | 'DESC';
|
|
205
|
+
};
|
|
206
|
+
export type TypedOrder<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? Order : StrictTypedOrder<T>;
|
|
207
|
+
/** Sub-query for an eager-loaded relation — inherits the target model's constraints. */
|
|
208
|
+
export type TypedRelationSubQuery<U extends Ad4mModel> = {
|
|
209
|
+
where?: TypedWhere<U>;
|
|
210
|
+
order?: TypedOrder<U>;
|
|
211
|
+
include?: TypedIncludeMap<U>;
|
|
212
|
+
limit?: number;
|
|
213
|
+
offset?: number;
|
|
214
|
+
};
|
|
215
|
+
/** Projection — `from` must be a real relation on T; `where`/`order` constrained to that target.
|
|
216
|
+
* Modelled as a discriminated union so the literal `count: true` and `limit: 1`
|
|
217
|
+
* variants narrow inference into `IncludeExtras` (count → number, limit-1 → scalar). */
|
|
218
|
+
export type TypedIncludeProjection<T extends Ad4mModel> = {
|
|
219
|
+
[K in RelationKeysOf<T>]: {
|
|
220
|
+
from: K;
|
|
221
|
+
count: true;
|
|
222
|
+
} | {
|
|
223
|
+
from: K;
|
|
224
|
+
limit: 1;
|
|
225
|
+
where?: TypedWhere<RelatedModel<T, K>>;
|
|
226
|
+
order?: TypedOrder<RelatedModel<T, K>>;
|
|
227
|
+
} | {
|
|
228
|
+
from: K;
|
|
229
|
+
limit?: number;
|
|
230
|
+
where?: TypedWhere<RelatedModel<T, K>>;
|
|
231
|
+
order?: TypedOrder<RelatedModel<T, K>>;
|
|
232
|
+
};
|
|
233
|
+
}[RelationKeysOf<T>];
|
|
234
|
+
type StrictTypedIncludeMap<T extends Ad4mModel> = {
|
|
235
|
+
[K in RelationKeysOf<T>]?: boolean | TypedRelationSubQuery<RelatedModel<T, K>>;
|
|
236
|
+
} & {
|
|
237
|
+
[K in `$${string}`]?: TypedIncludeProjection<T>;
|
|
238
|
+
};
|
|
239
|
+
export type TypedIncludeMap<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? IncludeMap : StrictTypedIncludeMap<T>;
|
|
240
|
+
/**
|
|
241
|
+
* Given a model T and an `include` literal I, compute the extra fields
|
|
242
|
+
* contributed by `$`-prefixed projection keys.
|
|
243
|
+
*
|
|
244
|
+
* - `{ count: true }` → `number`
|
|
245
|
+
* - `{ from: R, limit: 1 }` → `RelatedModel<T,R> | null`
|
|
246
|
+
* - `{ from: R }` (no limit/1) → `RelatedModel<T,R>[]`
|
|
247
|
+
*
|
|
248
|
+
* Returns `unknown` (intersection-neutral) when `I` has no `$`-keys, so that
|
|
249
|
+
* `T & IncludeExtras<T, I>` collapses back to `T` and downstream type
|
|
250
|
+
* predicates (`(x): x is T => ...`) keep working unchanged.
|
|
251
|
+
*/
|
|
252
|
+
export type IncludeExtras<T extends Ad4mModel, I> = I extends Record<string, any> ? Extract<keyof I, `$${string}`> extends never ? unknown : {
|
|
253
|
+
[K in Extract<keyof I, `$${string}`>]: I[K] extends {
|
|
254
|
+
count: true;
|
|
255
|
+
} ? number : I[K] extends {
|
|
256
|
+
from: infer R;
|
|
257
|
+
limit: 1;
|
|
258
|
+
} ? (R extends RelationKeysOf<T> ? RelatedModel<T, R> | null : never) : I[K] extends {
|
|
259
|
+
from: infer R;
|
|
260
|
+
} ? (R extends RelationKeysOf<T> ? RelatedModel<T, R>[] : never) : unknown;
|
|
261
|
+
} : unknown;
|
|
262
|
+
type StrictTypedQuery<T extends Ad4mModel> = {
|
|
263
|
+
parent?: ParentScope;
|
|
264
|
+
properties?: PropertyKeysOf<T>[];
|
|
265
|
+
include?: TypedIncludeMap<T>;
|
|
266
|
+
includeAll?: boolean;
|
|
267
|
+
where?: TypedWhere<T>;
|
|
268
|
+
order?: TypedOrder<T>;
|
|
269
|
+
offset?: number;
|
|
270
|
+
limit?: number;
|
|
271
|
+
count?: boolean;
|
|
272
|
+
deepQuery?: boolean;
|
|
273
|
+
};
|
|
274
|
+
export type TypedQuery<T extends Ad4mModel> = HasNoTypedFields<T> extends true ? Query : StrictTypedQuery<T>;
|
|
275
|
+
/** Helper that extracts the `include` literal from a TypedQuery for use with IncludeExtras. */
|
|
276
|
+
export type IncludeOf<Q> = Q extends {
|
|
277
|
+
include?: infer I;
|
|
278
|
+
} ? I : undefined;
|
|
145
279
|
/**
|
|
146
280
|
* Options accepted by the instance `get()` method.
|
|
147
281
|
*
|
|
@@ -227,3 +361,4 @@ export interface ModelMetadata {
|
|
|
227
361
|
/** Map of relation name to metadata */
|
|
228
362
|
relations: Record<string, RelationMetadata>;
|
|
229
363
|
}
|
|
364
|
+
export {};
|
|
@@ -27,7 +27,7 @@ export declare class PerspectiveClient {
|
|
|
27
27
|
publishSnapshotByUUID(uuid: string): Promise<string | null>;
|
|
28
28
|
queryLinks(uuid: string, query: LinkQuery): Promise<LinkExpression[]>;
|
|
29
29
|
queryProlog(uuid: string, query: string): Promise<unknown>;
|
|
30
|
-
querySparql(uuid: string, query: string): Promise<
|
|
30
|
+
querySparql<T = any>(uuid: string, query: string): Promise<T>;
|
|
31
31
|
subscribeQuery(uuid: string, query: string): Promise<{
|
|
32
32
|
subscriptionId: string;
|
|
33
33
|
result: AllInstancesResult;
|
|
@@ -37,9 +37,9 @@ export declare class PerspectiveClient {
|
|
|
37
37
|
subscribeToQueryUpdates(subscriptionId: string, onData: (result: AllInstancesResult) => void): () => void;
|
|
38
38
|
keepAliveQuery(uuid: string, subscriptionId: string): Promise<boolean>;
|
|
39
39
|
disposeQuerySubscription(uuid: string, subscriptionId: string): Promise<boolean>;
|
|
40
|
-
modelQuery(uuid: string, className: string, queryJson: string
|
|
41
|
-
evaluateGetters(uuid: string, className: string, instanceIds: string[],
|
|
42
|
-
modelSubscribe(uuid: string, className: string, queryJson: string
|
|
40
|
+
modelQuery(uuid: string, className: string, queryJson: string): Promise<any>;
|
|
41
|
+
evaluateGetters(uuid: string, className: string, instanceIds: string[], propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
|
|
42
|
+
modelSubscribe(uuid: string, className: string, queryJson: string): Promise<{
|
|
43
43
|
subscriptionId: string;
|
|
44
44
|
result: any;
|
|
45
45
|
}>;
|
|
@@ -148,22 +148,21 @@ export class PerspectiveClient {
|
|
|
148
148
|
}
|
|
149
149
|
return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
|
|
150
150
|
}
|
|
151
|
-
async modelQuery(uuid, className, queryJson
|
|
152
|
-
const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson
|
|
151
|
+
async modelQuery(uuid, className, queryJson) {
|
|
152
|
+
const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
|
|
153
153
|
return JSON.parse(resultJson);
|
|
154
154
|
}
|
|
155
|
-
async evaluateGetters(uuid, className, instanceIds,
|
|
155
|
+
async evaluateGetters(uuid, className, instanceIds, propertyNames) {
|
|
156
156
|
const resultJson = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
|
|
157
157
|
uuid,
|
|
158
158
|
class_name: className,
|
|
159
159
|
instance_ids: instanceIds,
|
|
160
|
-
shape_json: shapeJson,
|
|
161
160
|
...(propertyNames && { property_names: propertyNames }),
|
|
162
161
|
});
|
|
163
162
|
return JSON.parse(resultJson);
|
|
164
163
|
}
|
|
165
|
-
async modelSubscribe(uuid, className, queryJson
|
|
166
|
-
const response = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson
|
|
164
|
+
async modelSubscribe(uuid, className, queryJson) {
|
|
165
|
+
const response = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
|
|
167
166
|
return {
|
|
168
167
|
subscriptionId: response.subscription_id,
|
|
169
168
|
result: JSON.parse(response.result)
|
|
@@ -318,16 +318,19 @@ export declare class PerspectiveProxy {
|
|
|
318
318
|
* @param query - SPARQL query string
|
|
319
319
|
* @returns Query results as parsed JSON
|
|
320
320
|
*/
|
|
321
|
-
querySparql(query: string): Promise<
|
|
321
|
+
querySparql<T = any>(query: string): Promise<T>;
|
|
322
322
|
/**
|
|
323
323
|
* Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
|
|
324
324
|
*
|
|
325
|
+
* The executor resolves the model's shape from the perspective's SHACL
|
|
326
|
+
* triples (written by `addSdna`). Callers no longer ship shape
|
|
327
|
+
* metadata with the query; the perspective is the source of truth.
|
|
328
|
+
*
|
|
325
329
|
* @param className - The model class name (e.g. "Recipe")
|
|
326
330
|
* @param queryJson - Structured query as JSON string
|
|
327
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
328
331
|
* @returns Object with `instances` array and `totalCount`
|
|
329
332
|
*/
|
|
330
|
-
modelQuery(className: string, queryJson: string
|
|
333
|
+
modelQuery(className: string, queryJson: string): Promise<{
|
|
331
334
|
instances: any[];
|
|
332
335
|
totalCount: number;
|
|
333
336
|
}>;
|
|
@@ -340,11 +343,10 @@ export declare class PerspectiveProxy {
|
|
|
340
343
|
*
|
|
341
344
|
* @param className - The model class name (e.g. "Message")
|
|
342
345
|
* @param instanceIds - Array of instance base expression URIs
|
|
343
|
-
* @param shapeJson - Shape metadata JSON from the model class
|
|
344
346
|
* @param propertyNames - Optional subset of property names to evaluate
|
|
345
347
|
* @returns Map of instance ID → evaluated property values
|
|
346
348
|
*/
|
|
347
|
-
evaluateGetters(className: string, instanceIds: string[],
|
|
349
|
+
evaluateGetters(className: string, instanceIds: string[], propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
|
|
348
350
|
/**
|
|
349
351
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
350
352
|
* internally in Rust, registers a subscription, runs the initial query, and
|
|
@@ -355,10 +357,9 @@ export declare class PerspectiveProxy {
|
|
|
355
357
|
*
|
|
356
358
|
* @param className - The model class name
|
|
357
359
|
* @param queryJson - JSON-serialized query parameters (same as modelQuery)
|
|
358
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
359
360
|
* @returns Object with `subscriptionId` and initial `result`
|
|
360
361
|
*/
|
|
361
|
-
modelSubscribe(className: string, queryJson: string
|
|
362
|
+
modelSubscribe(className: string, queryJson: string): Promise<{
|
|
362
363
|
subscriptionId: string;
|
|
363
364
|
result: any;
|
|
364
365
|
}>;
|
|
@@ -540,13 +540,16 @@ export class PerspectiveProxy {
|
|
|
540
540
|
/**
|
|
541
541
|
* Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
|
|
542
542
|
*
|
|
543
|
+
* The executor resolves the model's shape from the perspective's SHACL
|
|
544
|
+
* triples (written by `addSdna`). Callers no longer ship shape
|
|
545
|
+
* metadata with the query; the perspective is the source of truth.
|
|
546
|
+
*
|
|
543
547
|
* @param className - The model class name (e.g. "Recipe")
|
|
544
548
|
* @param queryJson - Structured query as JSON string
|
|
545
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
546
549
|
* @returns Object with `instances` array and `totalCount`
|
|
547
550
|
*/
|
|
548
|
-
async modelQuery(className, queryJson
|
|
549
|
-
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
551
|
+
async modelQuery(className, queryJson) {
|
|
552
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
550
553
|
}
|
|
551
554
|
/**
|
|
552
555
|
* Evaluate property getters for a batch of instances in a single RPC call.
|
|
@@ -557,12 +560,11 @@ export class PerspectiveProxy {
|
|
|
557
560
|
*
|
|
558
561
|
* @param className - The model class name (e.g. "Message")
|
|
559
562
|
* @param instanceIds - Array of instance base expression URIs
|
|
560
|
-
* @param shapeJson - Shape metadata JSON from the model class
|
|
561
563
|
* @param propertyNames - Optional subset of property names to evaluate
|
|
562
564
|
* @returns Map of instance ID → evaluated property values
|
|
563
565
|
*/
|
|
564
|
-
async evaluateGetters(className, instanceIds,
|
|
565
|
-
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds,
|
|
566
|
+
async evaluateGetters(className, instanceIds, propertyNames) {
|
|
567
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
|
|
566
568
|
}
|
|
567
569
|
/**
|
|
568
570
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
@@ -574,11 +576,10 @@ export class PerspectiveProxy {
|
|
|
574
576
|
*
|
|
575
577
|
* @param className - The model class name
|
|
576
578
|
* @param queryJson - JSON-serialized query parameters (same as modelQuery)
|
|
577
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
578
579
|
* @returns Object with `subscriptionId` and initial `result`
|
|
579
580
|
*/
|
|
580
|
-
async modelSubscribe(className, queryJson
|
|
581
|
-
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
581
|
+
async modelSubscribe(className, queryJson) {
|
|
582
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
582
583
|
}
|
|
583
584
|
/**
|
|
584
585
|
* Adds a new link to the perspective.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
|
|
3
|
+
*
|
|
4
|
+
* AD4M stores non-string property values as URL-encoded `Literal` payloads
|
|
5
|
+
* (see {@link Literal}). When raw SPARQL queries pull these values out of the
|
|
6
|
+
* RDF store the bindings are still in encoded form; consumers must decode
|
|
7
|
+
* before use. The helpers here centralise that decode step so each call site
|
|
8
|
+
* can pick the variant matching its declared binding type.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* interface MessageBinding {
|
|
13
|
+
* id: string;
|
|
14
|
+
* timestamp: string; // raw literal — decode with parseLitNumber
|
|
15
|
+
* body?: string; // raw literal — decode with parseLit
|
|
16
|
+
* }
|
|
17
|
+
* const rows = await perspective.querySparql<MessageBinding[]>(query);
|
|
18
|
+
* const ts = parseLitNumber(rows[0].timestamp); // number
|
|
19
|
+
* const body = rows[0].body ? parseLit(rows[0].body) : '';
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
/** Common AD4M link binding — matches the `?source/?predicate/?target/?author/?timestamp` pattern. */
|
|
23
|
+
export interface LinkBinding {
|
|
24
|
+
source: string;
|
|
25
|
+
predicate: string;
|
|
26
|
+
target: string;
|
|
27
|
+
author?: string;
|
|
28
|
+
timestamp?: string;
|
|
29
|
+
}
|
|
30
|
+
/** COUNT(?x) result binding — SPARQL returns counts as string literals. */
|
|
31
|
+
export interface CountBinding {
|
|
32
|
+
count: string;
|
|
33
|
+
}
|
|
34
|
+
/** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
|
|
35
|
+
export declare function parseSparqlCount(result: CountBinding[] | undefined | null): number;
|
|
36
|
+
/**
|
|
37
|
+
* Decode a `Literal`-encoded SPARQL binding back to a plain string.
|
|
38
|
+
*
|
|
39
|
+
* Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
|
|
40
|
+
* input. Falls through to the raw value if decoding fails (defensive — the
|
|
41
|
+
* binding may already be a plain string for unwrapped properties).
|
|
42
|
+
*/
|
|
43
|
+
export declare function parseLit(val: string | undefined | null): string;
|
|
44
|
+
/** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
|
|
45
|
+
export declare function parseLitNumber(val: string | undefined | null): number;
|
|
46
|
+
/** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
|
|
47
|
+
export declare function parseLitBoolean(val: string | undefined | null): boolean;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
|
|
3
|
+
*
|
|
4
|
+
* AD4M stores non-string property values as URL-encoded `Literal` payloads
|
|
5
|
+
* (see {@link Literal}). When raw SPARQL queries pull these values out of the
|
|
6
|
+
* RDF store the bindings are still in encoded form; consumers must decode
|
|
7
|
+
* before use. The helpers here centralise that decode step so each call site
|
|
8
|
+
* can pick the variant matching its declared binding type.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* interface MessageBinding {
|
|
13
|
+
* id: string;
|
|
14
|
+
* timestamp: string; // raw literal — decode with parseLitNumber
|
|
15
|
+
* body?: string; // raw literal — decode with parseLit
|
|
16
|
+
* }
|
|
17
|
+
* const rows = await perspective.querySparql<MessageBinding[]>(query);
|
|
18
|
+
* const ts = parseLitNumber(rows[0].timestamp); // number
|
|
19
|
+
* const body = rows[0].body ? parseLit(rows[0].body) : '';
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
import { Literal } from "../Literal";
|
|
23
|
+
/** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
|
|
24
|
+
export function parseSparqlCount(result) {
|
|
25
|
+
if (!result || result.length === 0)
|
|
26
|
+
return 0;
|
|
27
|
+
const raw = result[0].count;
|
|
28
|
+
const n = parseInt(raw, 10);
|
|
29
|
+
return Number.isNaN(n) ? 0 : n;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Decode a `Literal`-encoded SPARQL binding back to a plain string.
|
|
33
|
+
*
|
|
34
|
+
* Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
|
|
35
|
+
* input. Falls through to the raw value if decoding fails (defensive — the
|
|
36
|
+
* binding may already be a plain string for unwrapped properties).
|
|
37
|
+
*/
|
|
38
|
+
export function parseLit(val) {
|
|
39
|
+
if (val === undefined || val === null || val === '')
|
|
40
|
+
return '';
|
|
41
|
+
try {
|
|
42
|
+
const result = Literal.fromUrl(val).get();
|
|
43
|
+
if (result && typeof result === 'object') {
|
|
44
|
+
return result.data ?? JSON.stringify(result);
|
|
45
|
+
}
|
|
46
|
+
return String(result);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return val;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
|
|
53
|
+
export function parseLitNumber(val) {
|
|
54
|
+
if (val === undefined || val === null || val === '')
|
|
55
|
+
return 0;
|
|
56
|
+
const decoded = parseLit(val);
|
|
57
|
+
const n = Number(decoded);
|
|
58
|
+
return Number.isNaN(n) ? 0 : n;
|
|
59
|
+
}
|
|
60
|
+
/** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
|
|
61
|
+
export function parseLitBoolean(val) {
|
|
62
|
+
if (val === undefined || val === null || val === '')
|
|
63
|
+
return false;
|
|
64
|
+
return parseLit(val) === 'true';
|
|
65
|
+
}
|