@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.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 +825 -653
- package/lib/index.js +812 -654
- package/lib/src/Ad4mClient.d.ts +1 -0
- package/lib/src/Ad4mClient.js +1 -1
- package/lib/src/ai/AIClient.js +1 -1
- package/lib/src/apiClient.d.ts +4 -1
- package/lib/src/apiClient.js +6 -1
- package/lib/src/index.d.ts +4 -0
- package/lib/src/index.js +4 -0
- package/lib/src/model/Ad4mModel.d.ts +9 -32
- package/lib/src/model/Ad4mModel.js +36 -266
- package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
- package/lib/src/model/ModelQueryBuilder.js +20 -36
- package/lib/src/model/decorators.d.ts +7 -4
- package/lib/src/model/shacl-gen.js +120 -47
- package/lib/src/model/types.d.ts +140 -4
- 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/NodeExpression.d.ts +44 -0
- package/lib/src/shacl/NodeExpression.js +39 -0
- package/lib/src/shacl/SHACLShape.d.ts +23 -0
- package/lib/src/shacl/SHACLShape.js +115 -1
- package/lib/src/shacl/builders.d.ts +58 -0
- package/lib/src/shacl/builders.js +76 -0
- package/lib/src/shacl/index.d.ts +36 -0
- package/lib/src/shacl/index.js +33 -0
- package/package.json +8 -11
- package/src/Ad4mClient.ts +2 -2
- package/src/ai/AIClient.ts +1 -1
- package/src/apiClient.ts +8 -1
- package/src/index.ts +4 -0
- package/src/model/Ad4mModel.test.ts +33 -74
- package/src/model/Ad4mModel.ts +54 -272
- package/src/model/ModelQueryBuilder.ts +29 -46
- package/src/model/decorators.ts +7 -4
- package/src/model/relation-filtering.test.ts +46 -39
- package/src/model/shacl-gen.ts +128 -54
- package/src/model/shacl-roundtrip.test.ts +197 -0
- package/src/model/types-typed-query.test.ts +360 -0
- package/src/model/types.ts +196 -4
- package/src/perspectives/PerspectiveClient.ts +6 -8
- package/src/perspectives/PerspectiveProxy.ts +13 -13
- package/src/perspectives/SparqlBindings.ts +79 -0
- package/src/shacl/NodeExpression.ts +54 -0
- package/src/shacl/SHACLShape.test.ts +172 -0
- package/src/shacl/SHACLShape.ts +173 -1
- package/src/shacl/builders.ts +86 -0
- package/src/shacl/index.ts +72 -0
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Link } from "../links/Links";
|
|
|
3
3
|
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
4
4
|
import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
5
5
|
import { makeRandomId } from "./util";
|
|
6
|
-
import { getPropertiesMetadata, getRelationsMetadata,
|
|
6
|
+
import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
|
|
7
7
|
import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
|
|
8
8
|
import { formatQueryValue, compileWhereClause } from "./query-utils";
|
|
9
9
|
import { resolveParentPredicate } from "./query-common";
|
|
@@ -21,101 +21,15 @@ import type {
|
|
|
21
21
|
GetOptions, AllInstancesResult, ResultsWithTotalCount,
|
|
22
22
|
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
23
23
|
IncludeProjection,
|
|
24
|
+
TypedQuery, IncludeExtras, IncludeOf,
|
|
24
25
|
} from "./types";
|
|
25
26
|
|
|
26
27
|
|
|
27
|
-
// ---------------------------------------------------------------------------
|
|
28
|
-
// Default decoder for file-storage (non-literal resolveLanguage) properties
|
|
29
|
-
// ---------------------------------------------------------------------------
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* When the Rust executor resolves a non-literal expression it may return a
|
|
33
|
-
* `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
|
|
34
|
-
* raw URI string. If the model class has no custom `transform` registered
|
|
35
|
-
* (e.g. it was synthesised from a SHACL shape at runtime) we still want to
|
|
36
|
-
* decode the content rather than passing raw `FileData` to callers.
|
|
37
|
-
*
|
|
38
|
-
* Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
|
|
39
|
-
* - `application/json` (default when `file_type` is absent) → JSON.parse
|
|
40
|
-
* - anything else → raw decoded string
|
|
41
|
-
*
|
|
42
|
-
* If `resolved` is not a `FileData` object the value is returned unchanged so
|
|
43
|
-
* that callers can use this as a safe unconditional fallback.
|
|
44
|
-
*/
|
|
45
|
-
function defaultFileDecode(resolved: unknown): unknown {
|
|
46
|
-
if (
|
|
47
|
-
resolved !== null &&
|
|
48
|
-
typeof resolved === 'object' &&
|
|
49
|
-
'data_base64' in (resolved as object)
|
|
50
|
-
) {
|
|
51
|
-
const fd = resolved as { data_base64: string; file_type?: string };
|
|
52
|
-
let raw: string;
|
|
53
|
-
try {
|
|
54
|
-
raw = atob(fd.data_base64);
|
|
55
|
-
} catch {
|
|
56
|
-
return resolved; // malformed base64 — keep as-is
|
|
57
|
-
}
|
|
58
|
-
const isJson = !fd.file_type || fd.file_type === 'application/json';
|
|
59
|
-
if (isJson) {
|
|
60
|
-
try { return JSON.parse(raw); } catch { return raw; }
|
|
61
|
-
}
|
|
62
|
-
return raw;
|
|
63
|
-
}
|
|
64
|
-
return resolved;
|
|
65
|
-
}
|
|
66
28
|
|
|
67
29
|
// ---------------------------------------------------------------------------
|
|
68
30
|
// Helpers for Rust-side include resolution
|
|
69
31
|
// ---------------------------------------------------------------------------
|
|
70
32
|
|
|
71
|
-
/**
|
|
72
|
-
* Recursively enrich relation metadata in the shape with target class shapes
|
|
73
|
-
* so the Rust endpoint can resolve includes in-process (no extra GraphQL
|
|
74
|
-
* round-trips per relation).
|
|
75
|
-
*/
|
|
76
|
-
function enrichShapeForIncludes(
|
|
77
|
-
metadata: ModelMetadata,
|
|
78
|
-
include: IncludeMap,
|
|
79
|
-
allRelMeta: Record<string, RelationMetadataEntry>,
|
|
80
|
-
): void {
|
|
81
|
-
for (const [relName, includeVal] of Object.entries(include)) {
|
|
82
|
-
if (!includeVal) continue;
|
|
83
|
-
const meta = allRelMeta[relName];
|
|
84
|
-
if (!meta?.target) continue;
|
|
85
|
-
|
|
86
|
-
const TargetClass = meta.target() as typeof Ad4mModel;
|
|
87
|
-
// Deep-copy so we don't mutate the cached metadata
|
|
88
|
-
const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
|
|
89
|
-
|
|
90
|
-
// Ensure the relation is in metadata.relations (fallback for edge cases)
|
|
91
|
-
if (!metadata.relations[relName]) {
|
|
92
|
-
metadata.relations[relName] = {
|
|
93
|
-
name: relName,
|
|
94
|
-
predicate: meta.predicate,
|
|
95
|
-
direction:
|
|
96
|
-
meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
|
|
97
|
-
? 'reverse'
|
|
98
|
-
: 'forward',
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
const rel = metadata.relations[relName] as any;
|
|
102
|
-
rel.kind = meta.kind;
|
|
103
|
-
rel.maxCount = meta.maxCount;
|
|
104
|
-
rel.targetShape = targetMeta;
|
|
105
|
-
rel.targetClassName = targetMeta.className;
|
|
106
|
-
|
|
107
|
-
// Recurse for nested includes
|
|
108
|
-
const nested =
|
|
109
|
-
typeof includeVal === 'object' && includeVal !== null
|
|
110
|
-
? (includeVal as any).include
|
|
111
|
-
: undefined;
|
|
112
|
-
if (nested) {
|
|
113
|
-
const targetRelMeta = getRelationsMetadata(TargetClass as any);
|
|
114
|
-
enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
33
|
/**
|
|
120
34
|
* Construct a model class instance from a plain JSON object returned by the
|
|
121
35
|
* Rust endpoint. Recursively converts included relation values (which come
|
|
@@ -166,19 +80,6 @@ function jsonToModelInstance<T extends Ad4mModel>(
|
|
|
166
80
|
instance[key] = value;
|
|
167
81
|
}
|
|
168
82
|
|
|
169
|
-
// Apply property transform functions from decorators (only for literal-resolved
|
|
170
|
-
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
171
|
-
// asynchronously in executeModelQuery).
|
|
172
|
-
try {
|
|
173
|
-
const propsMeta = getPropertiesMetadata(ModelClass as any);
|
|
174
|
-
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
175
|
-
const o = opts as any;
|
|
176
|
-
if (typeof o.transform !== 'function' || !(propName in json)) continue;
|
|
177
|
-
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
178
|
-
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
|
|
179
|
-
instance[propName] = o.transform(instance[propName]);
|
|
180
|
-
}
|
|
181
|
-
} catch (e) { console.debug('jsonToModelInstance: transform metadata unavailable:', e); }
|
|
182
83
|
|
|
183
84
|
// Recursively convert included relation values to class instances
|
|
184
85
|
if (include) {
|
|
@@ -442,8 +343,8 @@ export class Ad4mModel {
|
|
|
442
343
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
443
344
|
...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
|
|
444
345
|
...(options.local !== undefined && { local: options.local }),
|
|
445
|
-
...(options.
|
|
446
|
-
...(options.
|
|
346
|
+
...(options.flag !== undefined && { flag: options.flag }),
|
|
347
|
+
...(options.transform !== undefined && { transform: options.transform })
|
|
447
348
|
};
|
|
448
349
|
}
|
|
449
350
|
|
|
@@ -867,13 +768,14 @@ export class Ad4mModel {
|
|
|
867
768
|
|
|
868
769
|
/**
|
|
869
770
|
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
870
|
-
* Returns the className
|
|
771
|
+
* Returns the className and queryJson that the Rust executor expects.
|
|
772
|
+
* Shape resolution happens server-side from the perspective's SHACL triples.
|
|
871
773
|
* @internal
|
|
872
774
|
*/
|
|
873
775
|
static prepareModelQueryParams(
|
|
874
776
|
query: Query = {},
|
|
875
777
|
classNameOverride?: string | null,
|
|
876
|
-
): { className: string; queryJson: string;
|
|
778
|
+
): { className: string; queryJson: string; metadata: ModelMetadata } {
|
|
877
779
|
const metadata = this.getModelMetadata();
|
|
878
780
|
const className = classNameOverride || metadata.className;
|
|
879
781
|
|
|
@@ -909,16 +811,18 @@ export class Ad4mModel {
|
|
|
909
811
|
}
|
|
910
812
|
if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
|
|
911
813
|
if (Object.keys(projections).length > 0) {
|
|
912
|
-
//
|
|
814
|
+
// Tag each projection with its target class name so the executor can
|
|
815
|
+
// resolve the target shape through its in-memory cache when applying
|
|
816
|
+
// projection where-clause filters.
|
|
913
817
|
const allRelMeta = getRelationsMetadata(this as any);
|
|
914
818
|
for (const [, proj] of Object.entries(projections)) {
|
|
915
819
|
const relMeta = allRelMeta[proj.from];
|
|
916
|
-
if (!proj.
|
|
820
|
+
if (!proj.targetClassName && relMeta?.target) {
|
|
917
821
|
try {
|
|
918
822
|
const TargetClass = relMeta.target();
|
|
919
823
|
const targetMeta = (TargetClass as any).getModelMetadata?.();
|
|
920
|
-
if (targetMeta) {
|
|
921
|
-
proj.
|
|
824
|
+
if (targetMeta?.className) {
|
|
825
|
+
proj.targetClassName = targetMeta.className;
|
|
922
826
|
}
|
|
923
827
|
} catch (e) { console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e); }
|
|
924
828
|
}
|
|
@@ -935,59 +839,13 @@ export class Ad4mModel {
|
|
|
935
839
|
if (query.count !== undefined) queryInput.count = query.count;
|
|
936
840
|
queryInput.deepQuery = query.deepQuery ?? true;
|
|
937
841
|
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
// Pre-compute conformance getters for Rust-side evaluation.
|
|
944
|
-
// Where clauses are NOT compiled into getter SPARQL because stored
|
|
945
|
-
// property values are signed expression envelopes (literal:json:...),
|
|
946
|
-
// not simple literal:string:X values. Instead, where clauses are
|
|
947
|
-
// attached as metadata for Rust-side post-evaluation filtering.
|
|
948
|
-
{
|
|
949
|
-
const allRelMeta = getRelationsMetadata(this as any);
|
|
950
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
951
|
-
const rel = relMeta as any;
|
|
952
|
-
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
953
|
-
const meta = allRelMeta[relName];
|
|
954
|
-
if (!meta?.target) continue;
|
|
955
|
-
try {
|
|
956
|
-
const TargetClass = meta.target();
|
|
957
|
-
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
958
|
-
|
|
959
|
-
if (filter) {
|
|
960
|
-
rel.getter = filter.getter;
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
// Attach where-clause metadata for Rust-side post-getter filtering
|
|
964
|
-
if (rel.where) {
|
|
965
|
-
try {
|
|
966
|
-
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
967
|
-
if (targetMetadata) {
|
|
968
|
-
const predicates: Record<string, string> = {};
|
|
969
|
-
for (const propName of Object.keys(rel.where)) {
|
|
970
|
-
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
971
|
-
const propMeta = targetMetadata.properties[propName];
|
|
972
|
-
if (propMeta?.predicate) {
|
|
973
|
-
predicates[propName] = propMeta.predicate;
|
|
974
|
-
}
|
|
975
|
-
}
|
|
976
|
-
if (Object.keys(predicates).length > 0) {
|
|
977
|
-
rel.whereFilter = rel.where;
|
|
978
|
-
rel.wherePredicates = predicates;
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
} catch (e) { console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e); }
|
|
982
|
-
}
|
|
983
|
-
} catch (e) { console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e); }
|
|
984
|
-
}
|
|
985
|
-
}
|
|
842
|
+
// Conformance getters, where filters, and target shapes for includes
|
|
843
|
+
// are all resolved by the executor from the perspective's SHACL triples
|
|
844
|
+
// — no client-side pre-computation is needed any more.
|
|
986
845
|
|
|
987
846
|
return {
|
|
988
847
|
className,
|
|
989
848
|
queryJson: JSON.stringify(queryInput),
|
|
990
|
-
shapeJson: JSON.stringify(metadata),
|
|
991
849
|
metadata,
|
|
992
850
|
};
|
|
993
851
|
}
|
|
@@ -1010,59 +868,6 @@ export class Ad4mModel {
|
|
|
1010
868
|
return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
1011
869
|
}
|
|
1012
870
|
|
|
1013
|
-
/**
|
|
1014
|
-
* Resolve non-literal (file-language) properties on an array of already-constructed
|
|
1015
|
-
* model instances. Handles two cases:
|
|
1016
|
-
*
|
|
1017
|
-
* 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
|
|
1018
|
-
* 2. The Rust executor already resolved the expression and returned a `FileData` object
|
|
1019
|
-
* (happens when the perspective backend eagerly fetches file content) → apply transform
|
|
1020
|
-
* (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
|
|
1021
|
-
* synthesised model classes).
|
|
1022
|
-
*
|
|
1023
|
-
* Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
|
|
1024
|
-
* duplicating logic or introducing a circular dependency.
|
|
1025
|
-
* @internal
|
|
1026
|
-
*/
|
|
1027
|
-
static async resolveNonLiteralProps<T extends Ad4mModel>(
|
|
1028
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1029
|
-
perspective: PerspectiveProxy,
|
|
1030
|
-
instances: T[],
|
|
1031
|
-
): Promise<void> {
|
|
1032
|
-
const propsMeta = getPropertiesMetadata(this as any);
|
|
1033
|
-
const resolveProps = Object.entries(propsMeta).filter(
|
|
1034
|
-
([, opts]: [string, any]) =>
|
|
1035
|
-
opts.resolveLanguage != null &&
|
|
1036
|
-
opts.resolveLanguage !== 'literal',
|
|
1037
|
-
);
|
|
1038
|
-
if (resolveProps.length === 0) return;
|
|
1039
|
-
|
|
1040
|
-
await Promise.all(
|
|
1041
|
-
instances.map(async (inst: any) => {
|
|
1042
|
-
for (const [propName, opts] of resolveProps) {
|
|
1043
|
-
const val = inst[propName];
|
|
1044
|
-
const transform = (opts as any).transform;
|
|
1045
|
-
const applyTransform = (resolved: unknown) =>
|
|
1046
|
-
typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
|
|
1047
|
-
|
|
1048
|
-
if (typeof val === 'string' && val && !val.startsWith('literal:')) {
|
|
1049
|
-
// Case 1: raw URI — fetch from language runtime
|
|
1050
|
-
try {
|
|
1051
|
-
const expression = await perspective.getExpression(val);
|
|
1052
|
-
if (expression) {
|
|
1053
|
-
let resolved: any;
|
|
1054
|
-
try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
|
|
1055
|
-
inst[propName] = applyTransform(resolved);
|
|
1056
|
-
}
|
|
1057
|
-
} catch (e) { console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e); }
|
|
1058
|
-
} else if (val !== null && val !== undefined && typeof val === 'object') {
|
|
1059
|
-
// Case 2: already resolved by Rust — apply transform / default decode
|
|
1060
|
-
inst[propName] = applyTransform(val);
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
}),
|
|
1064
|
-
);
|
|
1065
|
-
}
|
|
1066
871
|
|
|
1067
872
|
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
1068
873
|
|
|
@@ -1080,13 +885,13 @@ export class Ad4mModel {
|
|
|
1080
885
|
query: Query = {},
|
|
1081
886
|
classNameOverride?: string | null,
|
|
1082
887
|
): Promise<ResultsWithTotalCount<T>> {
|
|
1083
|
-
// Delegate
|
|
1084
|
-
//
|
|
1085
|
-
const { className, queryJson
|
|
888
|
+
// Delegate query input building to the shared prepareModelQueryParams
|
|
889
|
+
// helper. The executor resolves the shape from SHACL server-side.
|
|
890
|
+
const { className, queryJson } = this.prepareModelQueryParams(
|
|
1086
891
|
query, classNameOverride,
|
|
1087
892
|
);
|
|
1088
893
|
|
|
1089
|
-
const result = await perspective.modelQuery(className, queryJson
|
|
894
|
+
const result = await perspective.modelQuery(className, queryJson);
|
|
1090
895
|
|
|
1091
896
|
// Convert JSON instances to model class instances, recursively constructing
|
|
1092
897
|
// class instances for any included relations resolved by Rust.
|
|
@@ -1094,12 +899,6 @@ export class Ad4mModel {
|
|
|
1094
899
|
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
1095
900
|
});
|
|
1096
901
|
|
|
1097
|
-
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1098
|
-
// value is a content-addressed hash that must be fetched from the language
|
|
1099
|
-
// runtime). The Rust endpoint may return either a raw target URI (string)
|
|
1100
|
-
// or an already-resolved FileData object — both cases are handled here.
|
|
1101
|
-
await (this as any).resolveNonLiteralProps(perspective, instances);
|
|
1102
|
-
|
|
1103
902
|
// Take snapshots for dirty tracking (exclude $-prefixed projection keys)
|
|
1104
903
|
const snapshotRelations = query.include
|
|
1105
904
|
? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
|
|
@@ -1139,19 +938,18 @@ export class Ad4mModel {
|
|
|
1139
938
|
* });
|
|
1140
939
|
* ```
|
|
1141
940
|
*/
|
|
1142
|
-
static async findAll<T extends Ad4mModel>(
|
|
941
|
+
static async findAll<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1143
942
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1144
943
|
perspective: PerspectiveProxy,
|
|
1145
|
-
query
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
if (query.properties && query.properties.length === 0) {
|
|
944
|
+
query?: Q,
|
|
945
|
+
): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]> {
|
|
946
|
+
const q = (query ?? {}) as Query;
|
|
947
|
+
if (q.properties && q.properties.length === 0) {
|
|
1150
948
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
1151
949
|
}
|
|
1152
950
|
|
|
1153
|
-
const { results } = await this.executeModelQuery(perspective,
|
|
1154
|
-
return results;
|
|
951
|
+
const { results } = await this.executeModelQuery(perspective, q);
|
|
952
|
+
return results as (T & IncludeExtras<T, IncludeOf<Q>>)[];
|
|
1155
953
|
}
|
|
1156
954
|
|
|
1157
955
|
/**
|
|
@@ -1174,15 +972,13 @@ export class Ad4mModel {
|
|
|
1174
972
|
* }
|
|
1175
973
|
* ```
|
|
1176
974
|
*/
|
|
1177
|
-
static async findOne<T extends Ad4mModel>(
|
|
975
|
+
static async findOne<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1178
976
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1179
977
|
perspective: PerspectiveProxy,
|
|
1180
|
-
query
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
const limitedQuery = { ...query, limit: 1 };
|
|
1185
|
-
const results = await this.findAll(perspective, limitedQuery);
|
|
978
|
+
query?: Q,
|
|
979
|
+
): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null> {
|
|
980
|
+
const limitedQuery = { ...((query ?? {}) as Query), limit: 1 } as Q;
|
|
981
|
+
const results = await this.findAll<T, Q>(perspective, limitedQuery);
|
|
1186
982
|
return results[0] ?? null;
|
|
1187
983
|
}
|
|
1188
984
|
|
|
@@ -1203,14 +999,13 @@ export class Ad4mModel {
|
|
|
1203
999
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
1204
1000
|
* ```
|
|
1205
1001
|
*/
|
|
1206
|
-
static async findAllAndCount<T extends Ad4mModel>(
|
|
1002
|
+
static async findAllAndCount<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1207
1003
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1208
1004
|
perspective: PerspectiveProxy,
|
|
1209
|
-
query
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
return await this.executeModelQuery(perspective, query);
|
|
1005
|
+
query?: Q,
|
|
1006
|
+
): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>> {
|
|
1007
|
+
const out = await this.executeModelQuery(perspective, (query ?? {}) as Query);
|
|
1008
|
+
return out as ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>;
|
|
1214
1009
|
}
|
|
1215
1010
|
|
|
1216
1011
|
/**
|
|
@@ -1230,18 +1025,16 @@ export class Ad4mModel {
|
|
|
1230
1025
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1231
1026
|
* ```
|
|
1232
1027
|
*/
|
|
1233
|
-
static async paginate<T extends Ad4mModel>(
|
|
1028
|
+
static async paginate<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(
|
|
1234
1029
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1235
1030
|
perspective: PerspectiveProxy,
|
|
1236
1031
|
pageSize: number,
|
|
1237
1032
|
pageNumber: number,
|
|
1238
|
-
query?:
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
): Promise<PaginationResult<T>> {
|
|
1242
|
-
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1033
|
+
query?: Q,
|
|
1034
|
+
): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>> {
|
|
1035
|
+
const paginationQuery = { ...((query ?? {}) as Query), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1243
1036
|
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
1244
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1037
|
+
return { results: results as (T & IncludeExtras<T, IncludeOf<Q>>)[], totalCount, pageSize, pageNumber };
|
|
1245
1038
|
}
|
|
1246
1039
|
|
|
1247
1040
|
/**
|
|
@@ -1270,8 +1063,12 @@ export class Ad4mModel {
|
|
|
1270
1063
|
* });
|
|
1271
1064
|
* ```
|
|
1272
1065
|
*/
|
|
1273
|
-
static async count
|
|
1274
|
-
|
|
1066
|
+
static async count<T extends Ad4mModel>(
|
|
1067
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1068
|
+
perspective: PerspectiveProxy,
|
|
1069
|
+
query?: TypedQuery<T>,
|
|
1070
|
+
): Promise<number> {
|
|
1071
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...((query ?? {}) as Query), limit: 0 });
|
|
1275
1072
|
return totalCount;
|
|
1276
1073
|
}
|
|
1277
1074
|
|
|
@@ -1635,28 +1432,13 @@ export class Ad4mModel {
|
|
|
1635
1432
|
if (instances.length === 0) return;
|
|
1636
1433
|
const metadata = this.getModelMetadata();
|
|
1637
1434
|
|
|
1638
|
-
// Pre-compute conformance getters so the shape sent to Rust includes them
|
|
1639
|
-
const allRelMeta = getRelationsMetadata(this as any);
|
|
1640
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1641
|
-
const rel = relMeta as any;
|
|
1642
|
-
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
1643
|
-
const meta = allRelMeta[relName];
|
|
1644
|
-
if (!meta?.target) continue;
|
|
1645
|
-
try {
|
|
1646
|
-
const TargetClass = meta.target();
|
|
1647
|
-
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1648
|
-
if (filter) rel.getter = filter.getter;
|
|
1649
|
-
} catch (e) { console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e); }
|
|
1650
|
-
}
|
|
1651
|
-
|
|
1652
|
-
const shapeJson = JSON.stringify(metadata);
|
|
1653
1435
|
const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
|
|
1654
1436
|
|
|
1655
|
-
//
|
|
1437
|
+
// The executor reads getter SPARQL from the perspective's SHACL triples
|
|
1438
|
+
// (written by `addSdna`), so no shape JSON is shipped with the call.
|
|
1656
1439
|
const result = await perspective.evaluateGetters(
|
|
1657
1440
|
metadata.className,
|
|
1658
1441
|
instanceIds,
|
|
1659
|
-
shapeJson,
|
|
1660
1442
|
propertyNames,
|
|
1661
1443
|
);
|
|
1662
1444
|
|
|
@@ -2067,11 +1849,11 @@ export class Ad4mModel {
|
|
|
2067
1849
|
* ```
|
|
2068
1850
|
*/
|
|
2069
1851
|
static query<T extends Ad4mModel>(
|
|
2070
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
2071
|
-
perspective: PerspectiveProxy,
|
|
2072
|
-
query?:
|
|
1852
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1853
|
+
perspective: PerspectiveProxy,
|
|
1854
|
+
query?: TypedQuery<T>,
|
|
2073
1855
|
): ModelQueryBuilder<T> {
|
|
2074
|
-
return new ModelQueryBuilder<T>(perspective, this as any, query);
|
|
1856
|
+
return new ModelQueryBuilder<T>(perspective, this as any, (query ?? {}) as Query);
|
|
2075
1857
|
}
|
|
2076
1858
|
|
|
2077
1859
|
/**
|
|
@@ -10,6 +10,7 @@ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
|
10
10
|
import type {
|
|
11
11
|
Where, Order, IncludeMap, Query,
|
|
12
12
|
ResultsWithTotalCount, PaginationResult,
|
|
13
|
+
TypedWhere, TypedOrder, TypedIncludeMap, PropertyKeysOf,
|
|
13
14
|
} from "./types";
|
|
14
15
|
|
|
15
16
|
/** Query builder for Ad4mModel queries.
|
|
@@ -80,8 +81,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
80
81
|
* })
|
|
81
82
|
* ```
|
|
82
83
|
*/
|
|
83
|
-
where(conditions:
|
|
84
|
-
this.queryParams.where = conditions;
|
|
84
|
+
where(conditions: TypedWhere<T>): ModelQueryBuilder<T> {
|
|
85
|
+
this.queryParams.where = conditions as Where;
|
|
85
86
|
return this;
|
|
86
87
|
}
|
|
87
88
|
|
|
@@ -96,8 +97,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
96
97
|
* .order({ createdAt: "DESC" })
|
|
97
98
|
* ```
|
|
98
99
|
*/
|
|
99
|
-
order(orderBy:
|
|
100
|
-
this.queryParams.order = orderBy;
|
|
100
|
+
order(orderBy: TypedOrder<T>): ModelQueryBuilder<T> {
|
|
101
|
+
this.queryParams.order = orderBy as Order;
|
|
101
102
|
return this;
|
|
102
103
|
}
|
|
103
104
|
|
|
@@ -218,8 +219,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
218
219
|
* .properties(["name", "description", "rating"])
|
|
219
220
|
* ```
|
|
220
221
|
*/
|
|
221
|
-
properties(properties: string[]): ModelQueryBuilder<T> {
|
|
222
|
-
this.queryParams.properties = properties;
|
|
222
|
+
properties(properties: PropertyKeysOf<T>[] | string[]): ModelQueryBuilder<T> {
|
|
223
|
+
this.queryParams.properties = properties as string[];
|
|
223
224
|
return this;
|
|
224
225
|
}
|
|
225
226
|
|
|
@@ -272,8 +273,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
272
273
|
* .run();
|
|
273
274
|
* ```
|
|
274
275
|
*/
|
|
275
|
-
include(map:
|
|
276
|
-
this.queryParams.include = map;
|
|
276
|
+
include(map: TypedIncludeMap<T>): ModelQueryBuilder<T> {
|
|
277
|
+
this.queryParams.include = map as IncludeMap;
|
|
277
278
|
return this;
|
|
278
279
|
}
|
|
279
280
|
|
|
@@ -282,14 +283,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
282
283
|
return this;
|
|
283
284
|
}
|
|
284
285
|
|
|
285
|
-
/**
|
|
286
|
-
* Sets the query engine to use.
|
|
287
|
-
* @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
|
|
288
|
-
*/
|
|
289
|
-
engine(_eng: 'sparql' | 'prolog'): ModelQueryBuilder<T> {
|
|
290
|
-
return this;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
286
|
/**
|
|
294
287
|
* Executes the query once and returns the results.
|
|
295
288
|
*
|
|
@@ -377,15 +370,16 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
377
370
|
|
|
378
371
|
const ctor = this.ctor;
|
|
379
372
|
|
|
380
|
-
// Build the model query params (className, queryJson
|
|
381
|
-
|
|
373
|
+
// Build the model query params (className, queryJson). The executor
|
|
374
|
+
// resolves the shape from the perspective's SHACL triples.
|
|
375
|
+
const { className, queryJson } = (ctor as any).prepareModelQueryParams(
|
|
382
376
|
this.queryParams, this.modelClassName
|
|
383
377
|
);
|
|
384
378
|
|
|
385
379
|
// Register model subscription via Rust — this builds trigger SPARQL internally,
|
|
386
380
|
// registers the subscription, and runs the initial query in one call.
|
|
387
381
|
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(
|
|
388
|
-
className, queryJson
|
|
382
|
+
className, queryJson
|
|
389
383
|
);
|
|
390
384
|
|
|
391
385
|
// Convert JSON instances to model class instances
|
|
@@ -393,15 +387,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
393
387
|
return (ctor as any).parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
|
|
394
388
|
};
|
|
395
389
|
|
|
396
|
-
//
|
|
397
|
-
|
|
398
|
-
const resolveAndReturn = async (instances: T[]): Promise<T[]> => {
|
|
399
|
-
await (ctor as any).resolveNonLiteralProps(this.perspective, instances);
|
|
400
|
-
return instances;
|
|
401
|
-
};
|
|
402
|
-
|
|
403
|
-
// Parse initial results (with non-literal resolution)
|
|
404
|
-
const initialResults = await resolveAndReturn(parseResults(initialModelResult));
|
|
390
|
+
// Transforms are now applied by the Rust executor during hydration
|
|
391
|
+
const initialResults = parseResults(initialModelResult);
|
|
405
392
|
|
|
406
393
|
// Track last emitted result fingerprint to suppress duplicate callbacks
|
|
407
394
|
let lastResultFingerprint: string | null = null;
|
|
@@ -419,20 +406,16 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
419
406
|
subscriptionId,
|
|
420
407
|
(rawResult: any) => {
|
|
421
408
|
try {
|
|
422
|
-
const
|
|
423
|
-
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
callback(results);
|
|
433
|
-
}).catch((e) => {
|
|
434
|
-
console.error('Model subscription update resolve error:', e);
|
|
435
|
-
});
|
|
409
|
+
const results = parseResults(rawResult);
|
|
410
|
+
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
|
|
411
|
+
const fp = buildFingerprint(results);
|
|
412
|
+
if (fp === lastResultFingerprint) {
|
|
413
|
+
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
|
|
417
|
+
lastResultFingerprint = fp;
|
|
418
|
+
callback(results);
|
|
436
419
|
} catch (e) {
|
|
437
420
|
console.error('Model subscription update parse error:', e);
|
|
438
421
|
}
|
|
@@ -558,12 +541,12 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
558
541
|
this.dispose();
|
|
559
542
|
|
|
560
543
|
const countParams = { ...this.queryParams, limit: 0 };
|
|
561
|
-
const { className, queryJson
|
|
544
|
+
const { className, queryJson } = (this.ctor as any).prepareModelQueryParams(
|
|
562
545
|
countParams, this.modelClassName
|
|
563
546
|
);
|
|
564
547
|
|
|
565
548
|
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(
|
|
566
|
-
className, queryJson
|
|
549
|
+
className, queryJson
|
|
567
550
|
);
|
|
568
551
|
|
|
569
552
|
const parseCount = (raw: any): number => {
|
|
@@ -712,12 +695,12 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
712
695
|
const subscriptionParams = { ...(this.queryParams || {}) };
|
|
713
696
|
delete subscriptionParams.limit;
|
|
714
697
|
delete subscriptionParams.offset;
|
|
715
|
-
const { className, queryJson
|
|
698
|
+
const { className, queryJson } = (ctor as any).prepareModelQueryParams(
|
|
716
699
|
subscriptionParams, this.modelClassName
|
|
717
700
|
);
|
|
718
701
|
|
|
719
702
|
const { subscriptionId } = await this.perspective.modelSubscribe(
|
|
720
|
-
className, queryJson
|
|
703
|
+
className, queryJson
|
|
721
704
|
);
|
|
722
705
|
|
|
723
706
|
// Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
|
package/src/model/decorators.ts
CHANGED
|
@@ -274,11 +274,14 @@ export interface PropertyOptions {
|
|
|
274
274
|
local?: boolean;
|
|
275
275
|
|
|
276
276
|
/**
|
|
277
|
-
* Optional transform
|
|
278
|
-
* This is
|
|
279
|
-
*
|
|
277
|
+
* Optional transform expression to modify the property value.
|
|
278
|
+
* This is a SHACL-AF Node Expression that runs in the Rust model query engine.
|
|
279
|
+
* Examples: `fileToDataUri`, `concat(literal('prefix_'), focus())`, etc.
|
|
280
|
+
* Builders (`focus`, `literal`, `path`, `exists`, `ifExpr`, `concat`,
|
|
281
|
+
* `coalesce`, `fn`) and the `fileToDataUri` built-in are exported from
|
|
282
|
+
* the package root: `import { concat, literal, focus } from '@coasys/ad4m'`.
|
|
280
283
|
*/
|
|
281
|
-
transform?: (
|
|
284
|
+
transform?: import('../shacl/NodeExpression').NodeExpression;
|
|
282
285
|
|
|
283
286
|
/**
|
|
284
287
|
* Allowed values for this property (enum constraint).
|