@coasys/ad4m 0.13.0-test-6 → 0.13.0-test-7

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.
Files changed (39) hide show
  1. package/lib/index.cjs +111 -36
  2. package/lib/index.js +111 -36
  3. package/lib/src/model/Ad4mModel.d.ts +15 -0
  4. package/lib/src/model/Ad4mModel.js +94 -28
  5. package/lib/src/model/Ad4mModel.test.js +1434 -688
  6. package/lib/src/model/ModelQueryBuilder.js +17 -8
  7. package/lib/src/model/Subject.js +6 -6
  8. package/lib/src/model/hydration-batch.d.ts +34 -0
  9. package/lib/src/model/hydration-batch.js +147 -0
  10. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  11. package/lib/src/model/hydration-batching.test.js +456 -0
  12. package/lib/src/model/model-manifest.d.ts +41 -0
  13. package/lib/src/model/model-manifest.js +11 -0
  14. package/lib/src/model/query-cache.test.d.ts +1 -0
  15. package/lib/src/model/query-cache.test.js +43 -0
  16. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  17. package/lib/src/model/query-sparql-batch.js +260 -0
  18. package/lib/src/model/query-sparql.test.d.ts +1 -0
  19. package/lib/src/model/query-sparql.test.js +312 -0
  20. package/lib/src/model/relation-filtering.test.js +15 -15
  21. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  22. package/lib/src/model/subscription-delta.test.js +180 -0
  23. package/lib/src/model/subscription-pool.d.ts +39 -0
  24. package/lib/src/model/subscription-pool.js +165 -0
  25. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  26. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  27. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  28. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  29. package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
  30. package/lib/src/runtime/RuntimeResolver.js +197 -4
  31. package/lib/src/schema.gql +27 -1
  32. package/lib/src/shacl/SHACLShape.test.js +82 -0
  33. package/package.json +8 -11
  34. package/src/model/Ad4mModel.ts +97 -26
  35. package/src/model/ModelQueryBuilder.ts +17 -7
  36. package/lib/src/model/query-surreal.d.ts +0 -44
  37. package/lib/src/model/query-surreal.js +0 -249
  38. package/lib/src/model/surreal-utils.d.ts +0 -42
  39. package/lib/src/model/surreal-utils.js +0 -128
@@ -351,8 +351,14 @@ export class ModelQueryBuilder {
351
351
  const parseResults = (raw) => {
352
352
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
353
353
  };
354
- // Parse initial results
355
- const initialResults = parseResults(initialModelResult);
354
+ // Resolve non-literal (file-language) properties — handles both raw URI strings
355
+ // and already-resolved FileData objects returned by the Rust executor.
356
+ const resolveAndReturn = async (instances) => {
357
+ await ctor.resolveNonLiteralProps(this.perspective, instances);
358
+ return instances;
359
+ };
360
+ // Parse initial results (with non-literal resolution)
361
+ const initialResults = await resolveAndReturn(parseResults(initialModelResult));
356
362
  // Track last emitted result fingerprint to suppress duplicate callbacks
357
363
  let lastResultFingerprint = null;
358
364
  const buildFingerprint = (results) => {
@@ -365,12 +371,15 @@ export class ModelQueryBuilder {
365
371
  // When Rust re-runs the model query and finds changed results, it pushes them.
366
372
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
367
373
  try {
368
- const results = parseResults(rawResult);
369
- const fp = buildFingerprint(results);
370
- if (fp === lastResultFingerprint)
371
- return;
372
- lastResultFingerprint = fp;
373
- callback(results);
374
+ resolveAndReturn(parseResults(rawResult)).then((results) => {
375
+ const fp = buildFingerprint(results);
376
+ if (fp === lastResultFingerprint)
377
+ return;
378
+ lastResultFingerprint = fp;
379
+ callback(results);
380
+ }).catch((e) => {
381
+ console.error('Model subscription update resolve error:', e);
382
+ });
374
383
  }
375
384
  catch (e) {
376
385
  console.error('Model subscription update parse error:', e);
@@ -55,12 +55,12 @@ export class Subject {
55
55
  Object.defineProperty(this, p, {
56
56
  configurable: true,
57
57
  get: async () => {
58
- // Use SurrealDB for data queries
58
+ // Use SPARQL for data queries
59
59
  try {
60
- return await __classPrivateFieldGet(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), p);
60
+ return await __classPrivateFieldGet(this, _Subject_perspective, "f").getPropertyValueViaSparql(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), p);
61
61
  }
62
62
  catch (err) {
63
- console.warn(`Failed to get property ${p} via SurrealDB:`, err);
63
+ console.warn(`Failed to get property ${p} via SPARQL:`, err);
64
64
  return undefined;
65
65
  }
66
66
  }
@@ -94,12 +94,12 @@ export class Subject {
94
94
  Object.defineProperty(this, c, {
95
95
  configurable: true,
96
96
  get: async () => {
97
- // Use SurrealDB for data queries
97
+ // Use SPARQL for data queries
98
98
  try {
99
- return await __classPrivateFieldGet(this, _Subject_perspective, "f").getRelationValuesViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), c);
99
+ return await __classPrivateFieldGet(this, _Subject_perspective, "f").getRelationValuesViaSparql(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), c);
100
100
  }
101
101
  catch (err) {
102
- console.warn(`Failed to get relation ${c} via SurrealDB:`, err);
102
+ console.warn(`Failed to get relation ${c} via SPARQL:`, err);
103
103
  return [];
104
104
  }
105
105
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Batch hydration for SPARQL batch query results.
3
+ *
4
+ * Takes the flat rows returned by `buildBatchSPARQLQuery()` (each tagged
5
+ * with ?depth, ?parentBase, ?relationName) and reconstructs a tree of
6
+ * model instances.
7
+ *
8
+ * @module
9
+ */
10
+ import type { IncludeMap } from "./types";
11
+ /**
12
+ * A row returned by the batch SPARQL query.
13
+ */
14
+ interface BatchRow {
15
+ depth: string;
16
+ parentBase: string;
17
+ relationName: string;
18
+ source: string;
19
+ predicate: string;
20
+ target: string;
21
+ author: string;
22
+ timestamp: string;
23
+ }
24
+ /**
25
+ * Hydrate batch SPARQL results into a tree of model instances.
26
+ *
27
+ * @param rows - Flat rows from the batch SPARQL query
28
+ * @param rootClass - The root model class (extends Ad4mModel)
29
+ * @param includeMap - The include specification from the query
30
+ * @param perspective - The PerspectiveProxy for creating instances
31
+ * @returns Array of hydrated root instances with relations populated
32
+ */
33
+ export declare function hydrateBatchResult<T>(rows: BatchRow[], rootClass: any, includeMap: IncludeMap, perspective: any): Promise<T[]>;
34
+ export {};
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Batch hydration for SPARQL batch query results.
3
+ *
4
+ * Takes the flat rows returned by `buildBatchSPARQLQuery()` (each tagged
5
+ * with ?depth, ?parentBase, ?relationName) and reconstructs a tree of
6
+ * model instances.
7
+ *
8
+ * @module
9
+ */
10
+ import { hydrateFromLinks, evaluateCustomGettersForInstance } from "./hydration";
11
+ import { getRelationsMetadata } from "./decorators";
12
+ /**
13
+ * Group batch rows by (depth, source) → array of links, preserving parentBase/relationName.
14
+ */
15
+ function groupBatchRows(rows) {
16
+ const byDepth = new Map();
17
+ for (const row of rows) {
18
+ const depth = parseInt(row.depth, 10);
19
+ if (!byDepth.has(depth))
20
+ byDepth.set(depth, new Map());
21
+ const depthMap = byDepth.get(depth);
22
+ const key = row.source;
23
+ if (!depthMap.has(key)) {
24
+ depthMap.set(key, {
25
+ source_uri: key,
26
+ parentBase: row.parentBase,
27
+ relationName: row.relationName,
28
+ links: [],
29
+ });
30
+ }
31
+ depthMap.get(key).links.push({
32
+ predicate: row.predicate,
33
+ target: row.target,
34
+ author: row.author,
35
+ timestamp: row.timestamp,
36
+ });
37
+ }
38
+ const result = new Map();
39
+ for (const [depth, map] of byDepth) {
40
+ result.set(depth, Array.from(map.values()));
41
+ }
42
+ return result;
43
+ }
44
+ /**
45
+ * Hydrate batch SPARQL results into a tree of model instances.
46
+ *
47
+ * @param rows - Flat rows from the batch SPARQL query
48
+ * @param rootClass - The root model class (extends Ad4mModel)
49
+ * @param includeMap - The include specification from the query
50
+ * @param perspective - The PerspectiveProxy for creating instances
51
+ * @returns Array of hydrated root instances with relations populated
52
+ */
53
+ export async function hydrateBatchResult(rows, rootClass, includeMap, perspective) {
54
+ if (!rows || rows.length === 0)
55
+ return [];
56
+ const grouped = groupBatchRows(rows);
57
+ // Hydrate root instances (depth 0)
58
+ const rootInstances = grouped.get(0) || [];
59
+ const metadata = rootClass.getModelMetadata();
60
+ const instances = [];
61
+ const instanceMap = new Map();
62
+ for (const group of rootInstances) {
63
+ const instance = new rootClass(perspective, group.source_uri);
64
+ await hydrateFromLinks(instance, group.links, metadata, perspective);
65
+ await evaluateCustomGettersForInstance(instance, perspective, metadata);
66
+ instances.push(instance);
67
+ instanceMap.set(group.source_uri, instance);
68
+ }
69
+ // Hydrate each depth level and wire to parents
70
+ const relMeta = getRelationsMetadata(rootClass);
71
+ const maxDepth = Math.max(...Array.from(grouped.keys()), 0);
72
+ // Build a map of depth → (class, relMetadata, parentInstanceMap)
73
+ // For depth 1, parents are root instances; for deeper depths, we need
74
+ // the instances from the previous level.
75
+ const depthInstanceMaps = new Map();
76
+ depthInstanceMaps.set(0, instanceMap);
77
+ // Build depth→class mapping from include tree
78
+ const depthClassMap = new Map();
79
+ buildDepthClassMap(rootClass, includeMap, 0, { value: 1 }, depthClassMap);
80
+ for (let depth = 1; depth <= maxDepth; depth++) {
81
+ const depthGroups = grouped.get(depth) || [];
82
+ if (depthGroups.length === 0)
83
+ continue;
84
+ const depthInfo = depthClassMap.get(depth);
85
+ if (!depthInfo)
86
+ continue;
87
+ const TargetClass = depthInfo.targetClass;
88
+ const targetMetadata = TargetClass.getModelMetadata
89
+ ? TargetClass.getModelMetadata()
90
+ : { className: "Unknown", properties: {}, relations: {} };
91
+ const currentDepthInstances = new Map();
92
+ // Group by parentBase to wire children to parents
93
+ for (const group of depthGroups) {
94
+ const instance = new TargetClass(perspective, group.source_uri);
95
+ await hydrateFromLinks(instance, group.links, targetMetadata, perspective);
96
+ await evaluateCustomGettersForInstance(instance, perspective, targetMetadata);
97
+ currentDepthInstances.set(group.source_uri, instance);
98
+ // Wire to parent
99
+ // Find the parent depth's instance map
100
+ // The parentBase should exist in one of the prior depth maps
101
+ for (let pd = depth - 1; pd >= 0; pd--) {
102
+ const parentMap = depthInstanceMaps.get(pd);
103
+ if (parentMap && parentMap.has(group.parentBase)) {
104
+ const parent = parentMap.get(group.parentBase);
105
+ const relName = group.relationName;
106
+ // Determine relation metadata to know if it's an array or single
107
+ const parentRelMeta = getRelationsMetadata(pd === 0 ? rootClass : (depthClassMap.get(pd)?.targetClass || rootClass));
108
+ const rel = parentRelMeta[relName];
109
+ if (rel) {
110
+ if (rel.kind === 'hasMany' || rel.kind === 'belongsToMany') {
111
+ if (!Array.isArray(parent[relName])) {
112
+ parent[relName] = [];
113
+ }
114
+ parent[relName].push(instance);
115
+ }
116
+ else {
117
+ parent[relName] = instance;
118
+ }
119
+ }
120
+ break;
121
+ }
122
+ }
123
+ }
124
+ depthInstanceMaps.set(depth, currentDepthInstances);
125
+ }
126
+ return instances;
127
+ }
128
+ /**
129
+ * Build a mapping from depth number to target class info.
130
+ */
131
+ function buildDepthClassMap(parentClass, includeMap, _parentDepth, nextDepth, result) {
132
+ const relMeta = getRelationsMetadata(parentClass);
133
+ for (const [relName, includeValue] of Object.entries(includeMap)) {
134
+ const meta = relMeta[relName];
135
+ if (!meta || !meta.target)
136
+ continue;
137
+ const TargetClass = meta.target();
138
+ const depth = nextDepth.value++;
139
+ const nestedInclude = typeof includeValue === 'object' && includeValue !== null
140
+ ? includeValue.include
141
+ : undefined;
142
+ result.set(depth, { targetClass: TargetClass, includeMap: nestedInclude });
143
+ if (nestedInclude) {
144
+ buildDepthClassMap(TargetClass, nestedInclude, depth, nextDepth, result);
145
+ }
146
+ }
147
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Tests for batched hydrateRelations() — verifies the N+1 → 1 SPARQL optimisation.
3
+ *
4
+ * We mock PerspectiveProxy to count querySparql / get calls and verify
5
+ * that the batched path issues 1 SPARQL query instead of N perspective.get() calls.
6
+ */
7
+ export {};