@coasys/ad4m 0.13.0-test-7 → 0.13.0-test-8-profile-cache-fix

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 (63) hide show
  1. package/lib/index.cjs +1121 -835
  2. package/lib/index.js +1108 -835
  3. package/lib/src/Ad4mClient.d.ts +4 -1
  4. package/lib/src/Ad4mClient.js +2 -2
  5. package/lib/src/agent/AgentClient.d.ts +3 -0
  6. package/lib/src/agent/AgentClient.js +27 -5
  7. package/lib/src/ai/AIClient.js +1 -1
  8. package/lib/src/apiClient.d.ts +5 -1
  9. package/lib/src/apiClient.js +14 -6
  10. package/lib/src/index.d.ts +4 -0
  11. package/lib/src/index.js +4 -0
  12. package/lib/src/model/Ad4mModel.d.ts +30 -36
  13. package/lib/src/model/Ad4mModel.js +93 -382
  14. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  15. package/lib/src/model/ModelQueryBuilder.js +142 -62
  16. package/lib/src/model/decorators.d.ts +7 -4
  17. package/lib/src/model/decorators.js +0 -7
  18. package/lib/src/model/query-sparql.d.ts +0 -10
  19. package/lib/src/model/query-sparql.js +12 -17
  20. package/lib/src/model/shacl-gen.js +120 -47
  21. package/lib/src/model/types.d.ts +140 -4
  22. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -4
  23. package/lib/src/perspectives/PerspectiveClient.js +22 -6
  24. package/lib/src/perspectives/PerspectiveProxy.d.ts +27 -7
  25. package/lib/src/perspectives/PerspectiveProxy.js +60 -12
  26. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  27. package/lib/src/perspectives/SparqlBindings.js +65 -0
  28. package/lib/src/perspectives/WakerSubscriptionManager.js +5 -4
  29. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  30. package/lib/src/shacl/NodeExpression.js +39 -0
  31. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  32. package/lib/src/shacl/SHACLShape.js +115 -1
  33. package/lib/src/shacl/builders.d.ts +58 -0
  34. package/lib/src/shacl/builders.js +76 -0
  35. package/lib/src/shacl/index.d.ts +36 -0
  36. package/lib/src/shacl/index.js +33 -0
  37. package/package.json +1 -1
  38. package/src/Ad4mClient.ts +7 -2
  39. package/src/agent/AgentClient.ts +35 -7
  40. package/src/ai/AIClient.ts +1 -1
  41. package/src/apiClient.ts +17 -6
  42. package/src/index.ts +4 -0
  43. package/src/model/Ad4mModel.test.ts +274 -72
  44. package/src/model/Ad4mModel.ts +140 -420
  45. package/src/model/ModelQueryBuilder.ts +136 -71
  46. package/src/model/decorators.ts +7 -13
  47. package/src/model/query-sparql.test.ts +36 -20
  48. package/src/model/query-sparql.ts +12 -18
  49. package/src/model/relation-filtering.test.ts +46 -39
  50. package/src/model/shacl-gen.ts +128 -54
  51. package/src/model/shacl-roundtrip.test.ts +197 -0
  52. package/src/model/types-typed-query.test.ts +360 -0
  53. package/src/model/types.ts +196 -4
  54. package/src/perspectives/PerspectiveClient.ts +24 -8
  55. package/src/perspectives/PerspectiveProxy.test.ts +85 -1
  56. package/src/perspectives/PerspectiveProxy.ts +65 -20
  57. package/src/perspectives/SparqlBindings.ts +79 -0
  58. package/src/perspectives/WakerSubscriptionManager.ts +5 -4
  59. package/src/shacl/NodeExpression.ts +54 -0
  60. package/src/shacl/SHACLShape.test.ts +172 -0
  61. package/src/shacl/SHACLShape.ts +173 -1
  62. package/src/shacl/builders.ts +86 -0
  63. package/src/shacl/index.ts +72 -0
package/lib/index.cjs CHANGED
@@ -23,7 +23,7 @@ function nextId() {
23
23
  return String(++_idCounter);
24
24
  }
25
25
  class ApiClient {
26
- constructor(baseUrl, token) {
26
+ constructor(baseUrl, token, webSocketImpl, fetchImpl) {
27
27
  // ── WebSocket RPC core ──────────────────────────────────────────────────
28
28
  this._ws = null;
29
29
  this._wsCallbacks = new Set();
@@ -36,9 +36,15 @@ class ApiClient {
36
36
  this._wsPingTimer = null;
37
37
  this.baseUrl = baseUrl;
38
38
  this.token = token;
39
+ this._webSocketImpl = webSocketImpl;
40
+ this._fetchImpl = fetchImpl;
39
41
  }
40
42
  getBaseUrl() { return this.baseUrl; }
41
43
  getToken() { return this.token; }
44
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
45
+ doFetch(url, init) {
46
+ return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init);
47
+ }
42
48
  setToken(token) {
43
49
  this.token = token;
44
50
  }
@@ -51,7 +57,7 @@ class ApiClient {
51
57
  return tokenParam ? `${wsBase}${path}?${tokenParam}` : `${wsBase}${path}`;
52
58
  }
53
59
  _ensureWs() {
54
- if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) {
60
+ if (this._ws && (this._ws.readyState === 1 /* OPEN */ || this._ws.readyState === 0 /* CONNECTING */)) {
55
61
  return;
56
62
  }
57
63
  // Prevent duplicate connections from concurrent callers
@@ -62,7 +68,8 @@ class ApiClient {
62
68
  this._wsReadyResolve = resolve;
63
69
  });
64
70
  const url = this._getWsUrl();
65
- const ws = new WebSocket(url);
71
+ const WsImpl = this._webSocketImpl ?? WebSocket;
72
+ const ws = new WsImpl(url);
66
73
  this._ws = ws;
67
74
  ws.onopen = () => {
68
75
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
@@ -112,12 +119,13 @@ class ApiClient {
112
119
  // Reset the readiness promise so future calls reconnect
113
120
  this._wsReady = null;
114
121
  // Reject all pending calls
122
+ const hadPendingCalls = this._pendingCalls.size > 0;
115
123
  for (const [id, pending] of this._pendingCalls) {
116
124
  clearTimeout(pending.timer);
117
125
  pending.reject(new RpcError(503, 'WebSocket connection closed'));
118
126
  }
119
127
  this._pendingCalls.clear();
120
- if (!this._wsClosed && (this._wsCallbacks.size > 0 || this._pendingCalls.size > 0)) {
128
+ if (!this._wsClosed && (this._wsCallbacks.size > 0 || hadPendingCalls)) {
121
129
  this._scheduleReconnect();
122
130
  }
123
131
  };
@@ -125,7 +133,7 @@ class ApiClient {
125
133
  _startPing() {
126
134
  this._stopPing();
127
135
  this._wsPingTimer = setInterval(() => {
128
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
136
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
129
137
  this._ws.send(JSON.stringify({ type: 'ping' }));
130
138
  }
131
139
  }, 30000);
@@ -178,7 +186,7 @@ class ApiClient {
178
186
  reject,
179
187
  timer,
180
188
  });
181
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
189
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
182
190
  this._ws.send(JSON.stringify(message));
183
191
  }
184
192
  else {
@@ -955,6 +963,46 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
955
963
  };
956
964
  }
957
965
 
966
+ /**
967
+ * SHACL-AF Node Expressions for property transforms.
968
+ *
969
+ * A `NodeExpression` is a JSON-serializable tree that describes how to transform
970
+ * a resolved property value. Unlike JS lambdas, these are portable, inspectable,
971
+ * and can be executed in the Rust model query engine.
972
+ *
973
+ * Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
974
+ */
975
+ /**
976
+ * Type guard to check if a value is a valid NodeExpression.
977
+ */
978
+ function isNodeExpression(v) {
979
+ if (typeof v !== 'object' || v === null)
980
+ return false;
981
+ const obj = v;
982
+ const type = obj.type;
983
+ switch (type) {
984
+ case 'focus':
985
+ return typeof obj.type === 'string';
986
+ case 'literal':
987
+ return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
988
+ case 'path':
989
+ return typeof obj.predicate === 'string';
990
+ case 'exists':
991
+ return isNodeExpression(obj.expr);
992
+ case 'if':
993
+ return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
994
+ (obj.else === undefined || isNodeExpression(obj.else));
995
+ case 'concat':
996
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
997
+ case 'coalesce':
998
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
999
+ case 'function':
1000
+ return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
1001
+ default:
1002
+ return false;
1003
+ }
1004
+ }
1005
+
958
1006
  /**
959
1007
  * Extract namespace from a URI
960
1008
  * Examples:
@@ -1285,7 +1333,7 @@ class SHACLShape {
1285
1333
  target: `literal:${prop.writable}`
1286
1334
  });
1287
1335
  }
1288
- if (prop.resolveLanguage) {
1336
+ if (prop.resolveLanguage != null) {
1289
1337
  links.push({
1290
1338
  source: propShapeId,
1291
1339
  predicate: "ad4m://resolveLanguage",
@@ -1342,6 +1390,48 @@ class SHACLShape {
1342
1390
  target: `literal:string:${JSON.stringify(prop.in)}`
1343
1391
  });
1344
1392
  }
1393
+ if (prop.relationKind) {
1394
+ links.push({
1395
+ source: propShapeId,
1396
+ predicate: "ad4m://relationKind",
1397
+ target: `literal:string:${prop.relationKind}`
1398
+ });
1399
+ }
1400
+ if (prop.targetClassName) {
1401
+ links.push({
1402
+ source: propShapeId,
1403
+ predicate: "ad4m://targetClassName",
1404
+ target: `literal:string:${prop.targetClassName}`
1405
+ });
1406
+ }
1407
+ if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
1408
+ links.push({
1409
+ source: propShapeId,
1410
+ predicate: "ad4m://whereFilter",
1411
+ target: `literal:string:${JSON.stringify(prop.whereFilter)}`
1412
+ });
1413
+ }
1414
+ if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
1415
+ links.push({
1416
+ source: propShapeId,
1417
+ predicate: "ad4m://wherePredicates",
1418
+ target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
1419
+ });
1420
+ }
1421
+ if (prop.filter !== undefined) {
1422
+ links.push({
1423
+ source: propShapeId,
1424
+ predicate: "ad4m://filter",
1425
+ target: `literal:${prop.filter}`
1426
+ });
1427
+ }
1428
+ if (prop.transform && typeof prop.transform === 'object') {
1429
+ links.push({
1430
+ source: propShapeId,
1431
+ predicate: "ad4m://transform",
1432
+ target: `literal:string:${JSON.stringify(prop.transform)}`
1433
+ });
1434
+ }
1345
1435
  }
1346
1436
  return links;
1347
1437
  }
@@ -1523,6 +1613,60 @@ class SHACLShape {
1523
1613
  // Ignore parse errors
1524
1614
  }
1525
1615
  }
1616
+ const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
1617
+ if (relationKindLink) {
1618
+ const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1619
+ if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
1620
+ prop.relationKind = val;
1621
+ }
1622
+ }
1623
+ const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
1624
+ if (targetClassNameLink) {
1625
+ prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1626
+ }
1627
+ const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
1628
+ if (whereFilterLink) {
1629
+ try {
1630
+ const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1631
+ prop.whereFilter = JSON.parse(jsonStr);
1632
+ }
1633
+ catch (e) {
1634
+ // Ignore parse errors
1635
+ }
1636
+ }
1637
+ const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
1638
+ if (wherePredicatesLink) {
1639
+ try {
1640
+ const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1641
+ prop.wherePredicates = JSON.parse(jsonStr);
1642
+ }
1643
+ catch (e) {
1644
+ // Ignore parse errors
1645
+ }
1646
+ }
1647
+ const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
1648
+ if (filterLink) {
1649
+ let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
1650
+ if (val.startsWith('boolean:'))
1651
+ val = val.substring(8);
1652
+ prop.filter = val === 'true';
1653
+ }
1654
+ const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
1655
+ if (transformLink) {
1656
+ const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1657
+ try {
1658
+ const parsed = JSON.parse(jsonStr);
1659
+ if (!isNodeExpression(parsed)) {
1660
+ throw new Error(`Invalid transform for property ${propShapeId}: ` +
1661
+ `payload is not a valid NodeExpression. Received: ${jsonStr}`);
1662
+ }
1663
+ prop.transform = parsed;
1664
+ }
1665
+ catch (e) {
1666
+ throw new Error(`Failed to deserialize transform for property ${propShapeId}: ` +
1667
+ `${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`);
1668
+ }
1669
+ }
1526
1670
  shape.addProperty(prop);
1527
1671
  }
1528
1672
  return shape;
@@ -1559,6 +1703,12 @@ class SHACLShape {
1559
1703
  conformance_conditions: p.conformanceConditions,
1560
1704
  class: p.class,
1561
1705
  in: p.in,
1706
+ relation_kind: p.relationKind,
1707
+ target_class_name: p.targetClassName,
1708
+ where_filter: p.whereFilter,
1709
+ where_predicates: p.wherePredicates,
1710
+ filter: p.filter,
1711
+ transform: p.transform,
1562
1712
  })),
1563
1713
  constructor_actions: this.constructor_actions,
1564
1714
  destructor_actions: this.destructor_actions,
@@ -1572,6 +1722,11 @@ class SHACLShape {
1572
1722
  ? new SHACLShape(json.node_shape_uri, json.target_class)
1573
1723
  : new SHACLShape(json.target_class);
1574
1724
  for (const p of json.properties || []) {
1725
+ // Validate transform if present
1726
+ if (p.transform && !isNodeExpression(p.transform)) {
1727
+ throw new Error(`Invalid transform for property ${p.name}: ` +
1728
+ `payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`);
1729
+ }
1575
1730
  shape.addProperty({
1576
1731
  path: p.path,
1577
1732
  name: p.name,
@@ -1593,6 +1748,12 @@ class SHACLShape {
1593
1748
  conformanceConditions: p.conformance_conditions,
1594
1749
  class: p.class,
1595
1750
  in: p.in,
1751
+ relationKind: p.relation_kind,
1752
+ targetClassName: p.target_class_name,
1753
+ whereFilter: p.where_filter,
1754
+ wherePredicates: p.where_predicates,
1755
+ filter: p.filter,
1756
+ transform: p.transform,
1596
1757
  });
1597
1758
  }
1598
1759
  if (json.constructor_actions) {
@@ -1610,303 +1771,61 @@ class SHACLShape {
1610
1771
  }
1611
1772
  }
1612
1773
 
1613
- function formatList(list) {
1614
- if (!list?.length) {
1615
- return "";
1616
- }
1617
- if (list.length === 1) {
1618
- return list.toString();
1619
- }
1620
- if (list.length === 2) {
1621
- return list.join(' and ');
1622
- }
1623
- return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
1624
- }
1625
- function capSentence(cap) {
1626
- const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
1627
- const domain = cap.with.domain === "*" ? "" : cap.with.domain;
1628
- const pointers = cap.with.pointers.includes("*")
1629
- ? ["all AD4M data"]
1630
- : cap.with.pointers;
1631
- return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
1632
- }
1633
- /**
1634
- * Escapes a string value for safe use in query strings.
1635
- *
1636
- * @description
1637
- * Prevents SQL injection by properly escaping special characters in string values
1638
- * that will be interpolated into query strings. This handles the most common
1639
- * special characters that could break SQL queries or enable injection attacks.
1640
- *
1641
- * Single quotes, backslashes, and other special characters are escaped using
1642
- * backslash notation, which is the standard escaping mechanism for query.
1643
- *
1644
- * @param value - The string value to escape
1645
- * @returns The escaped string safe for query interpolation (without surrounding quotes)
1646
- *
1647
- * @example
1648
- * ```typescript
1649
- * const userInput = "user's input with 'quotes'";
1650
- * const escaped = escapeQueryString(userInput);
1651
- * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
1652
- * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
1653
- * ```
1654
- */
1655
- function escapeQueryString(value) {
1656
- return value
1657
- .replace(/\\/g, '\\\\') // Backslash -> \\
1658
- .replace(/'/g, "\\'") // Single quote -> \'
1659
- .replace(/"/g, '\\"') // Double quote -> \"
1660
- .replace(/\n/g, '\\n') // Newline -> \n
1661
- .replace(/\r/g, '\\r') // Carriage return -> \r
1662
- .replace(/\t/g, '\\t'); // Tab -> \t
1663
- }
1664
-
1665
- /**
1666
- * Shared query compilation utilities.
1667
- *
1668
- * These functions are used by both the runtime query builder (`Ad4mModel`) and
1669
- * the compile-time SHACL generator (`decorators.ts`).
1670
- *
1671
- * All output uses native SPARQL syntax.
1672
- */
1673
1774
  /**
1674
- * Format a JavaScript value for embedding in a query expression.
1775
+ * SHACL shape generation for AD4M model classes.
1675
1776
  *
1676
- * - Strings are single-quoted with backslash / quote / newline escaping
1677
- * - Numbers and booleans are passed through as-is
1678
- * - Arrays are recursed
1777
+ * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
1778
+ * from a model's property and relation metadata. The heavy lifting used
1779
+ * to live inside the `@Model` decorator closure — it is extracted here so
1780
+ * decorators.ts stays focused on decorator registration logic.
1679
1781
  */
1680
- function formatQueryValue(value) {
1681
- if (typeof value === 'string') {
1682
- // Escape backslashes first, then single quotes and other special characters
1683
- const escaped = value
1684
- .replace(/\\/g, '\\\\') // Backslash -> \\
1685
- .replace(/'/g, "\\'") // Single quote -> \'
1686
- .replace(/"/g, '\\"') // Double quote -> \"
1687
- .replace(/\n/g, '\\n') // Newline -> \n
1688
- .replace(/\r/g, '\\r') // Carriage return -> \r
1689
- .replace(/\t/g, '\\t'); // Tab -> \t
1690
- return `'${escaped}'`;
1691
- }
1692
- else if (typeof value === 'number' || typeof value === 'boolean') {
1693
- return String(value);
1694
- }
1695
- else if (Array.isArray(value)) {
1696
- return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
1697
- }
1698
- else {
1699
- return String(value);
1700
- }
1701
- }
1702
1782
  /**
1703
- * Compile a single Where condition for a property into a SPARQL triple pattern
1704
- * that can be embedded in a getter's WHERE clause.
1705
- *
1706
- * The generated pattern operates on `?target` — e.g.:
1707
- * `?target <pred> <value> .`
1708
- * `FILTER EXISTS { ?target <pred> ?_v0 }`
1783
+ * Build a SHACL shape for a model class.
1709
1784
  *
1710
- * @param predicate - The predicate URI for the property
1711
- * @param condition - The Where condition value
1712
- * @param opts - Optional settings (e.g. `resolveLanguage`)
1713
- * @returns A single SPARQL condition string
1785
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
1786
+ * @param target - The class constructor (used for prototype access,
1787
+ * inheritance chain, and relation target resolution)
1788
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
1789
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
1790
+ * @param conformanceFilterFn - Injected conformance-filter builder
1791
+ * (avoids circular dependency back into decorators.ts)
1714
1792
  */
1715
- function buildWhereCondition(predicate, condition, opts) {
1716
- const escapedPredicate = escapeQueryString(predicate);
1717
- // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
1718
- // For language-resolved properties, we match against the plain URI
1719
- // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
1720
- // For language-resolved properties, values are plain URIs
1721
- const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
1722
- const varSuffix = opts?.varIndex ?? 0;
1723
- function formatValue(v) {
1724
- if (typeof v === 'string') {
1725
- return isLiteral
1726
- ? `<literal:string:${escapeQueryString(v)}>`
1727
- : `<${escapeQueryString(v)}>`;
1793
+ function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
1794
+ const obj = target.prototype;
1795
+ // ── Determine namespace from first property or relation ─────────────
1796
+ let namespace = "ad4m://";
1797
+ // Try properties first
1798
+ if (Object.keys(properties).length > 0) {
1799
+ const firstProp = properties[Object.keys(properties)[0]];
1800
+ if (firstProp.through) {
1801
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
1802
+ if (match) {
1803
+ namespace = match[1];
1804
+ }
1728
1805
  }
1729
- // Numbers/booleans — also stored as literal:string: in AD4M
1730
- return `<literal:string:${v}>`;
1731
1806
  }
1732
- /**
1733
- * For literal properties, generate a FILTER-based match that handles both
1734
- * the raw value and the literal-encoded value. This mirrors the Rust
1735
- * `build_projection_where_patterns` approach which uses:
1736
- * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
1737
- * This is more robust than exact IRI matching because it handles edge cases
1738
- * where the stored format might vary.
1739
- */
1740
- function formatLiteralFilter(varName, v) {
1741
- const raw = escapeQueryString(String(v));
1742
- const encoded = encodeURIComponent(String(v))
1743
- .replace(/!/g, '%21')
1744
- .replace(/'/g, '%27')
1745
- .replace(/\(/g, '%28')
1746
- .replace(/\)/g, '%29')
1747
- .replace(/\*/g, '%2A');
1748
- if (typeof v === 'string') {
1749
- return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
1750
- }
1751
- else if (typeof v === 'number') {
1752
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
1753
- }
1754
- else if (typeof v === 'boolean') {
1755
- return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
1807
+ // Fall back to relations if no properties
1808
+ else if (Object.keys(allRelationsMeta).length > 0) {
1809
+ const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
1810
+ if (firstRel.predicate) {
1811
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
1812
+ if (match) {
1813
+ namespace = match[1];
1814
+ }
1756
1815
  }
1757
- return `FILTER(STR(${varName}) = "${raw}")`;
1758
1816
  }
1759
- if (Array.isArray(condition)) {
1760
- // Array values → FILTER IN
1761
- if (isLiteral) {
1762
- const varName = `?_wc${varSuffix}`;
1763
- const inValues = condition.flatMap(v => {
1764
- const raw = escapeQueryString(String(v));
1765
- const encoded = encodeURIComponent(String(v))
1766
- .replace(/!/g, '%21').replace(/'/g, '%27')
1767
- .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
1768
- return [`"${raw}"`, `"literal:string:${encoded}"`];
1769
- }).join(', ');
1770
- return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
1771
- }
1772
- const formattedValues = condition.map(formatValue).join(', ');
1773
- return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
1774
- }
1775
- else if (typeof condition === 'object' && condition !== null) {
1776
- // Operator object
1777
- const ops = condition;
1778
- const parts = [];
1779
- if (ops.not !== undefined) {
1780
- if (Array.isArray(ops.not)) {
1781
- const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
1782
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1783
- // so O(N²) behavior is bounded by the number of values for this property.
1784
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
1785
- }
1786
- else {
1787
- // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
1788
- // so O(N²) behavior is bounded by the number of values for this property.
1789
- parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
1790
- }
1791
- }
1792
- // Comparison operators — ensure property exists
1793
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1794
- ops.lt !== undefined || ops.lte !== undefined ||
1795
- ops.between !== undefined || ops.contains !== undefined;
1796
- if (hasComparisonOps) {
1797
- parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
1798
- }
1799
- return parts.join(' ');
1800
- }
1801
- else {
1802
- // Simple equality
1803
- if (isLiteral) {
1804
- // Use FILTER matching (mirrors Rust build_projection_where_patterns)
1805
- // to handle both raw values and literal-encoded IRIs robustly.
1806
- const varName = `?_wc${varSuffix}`;
1807
- return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
1808
- }
1809
- return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
1810
- }
1811
- }
1812
- /**
1813
- * Compile a full `Where` clause to an array of SPARQL condition strings.
1814
- *
1815
- * When `metadata` is provided, property names are resolved to predicates
1816
- * using the model's property metadata. When `metadata` is `null`, property
1817
- * names are treated as raw predicate URIs.
1818
- *
1819
- * Only handles **regular properties** — special fields (`id`, `author`,
1820
- * `timestamp`) and relation fields are skipped (they are only relevant at
1821
- * runtime query time, not for compile-time getter generation).
1822
- */
1823
- function compileWhereClause(where, metadata) {
1824
- const conditions = [];
1825
- for (const [propertyName, condition] of Object.entries(where)) {
1826
- // Skip special fields that don't apply at compile time
1827
- if (['id', 'author', 'timestamp'].includes(propertyName))
1828
- continue;
1829
- let predicate;
1830
- let resolveLanguage;
1831
- if (metadata) {
1832
- const propMeta = metadata.properties[propertyName];
1833
- if (propMeta) {
1834
- predicate = propMeta.predicate;
1835
- resolveLanguage = propMeta.resolveLanguage;
1836
- }
1837
- else {
1838
- // Property not found in metadata — treat name as raw predicate URI
1839
- predicate = propertyName;
1840
- }
1841
- }
1842
- else {
1843
- // No metadata — treat name as raw predicate URI
1844
- predicate = propertyName;
1845
- }
1846
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
1847
- if (cond) {
1848
- conditions.push(cond);
1849
- }
1850
- }
1851
- return conditions;
1852
- }
1853
-
1854
- /**
1855
- * SHACL shape generation for AD4M model classes.
1856
- *
1857
- * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
1858
- * from a model's property and relation metadata. The heavy lifting used
1859
- * to live inside the `@Model` decorator closure — it is extracted here so
1860
- * decorators.ts stays focused on decorator registration logic.
1861
- */
1862
- /**
1863
- * Build a SHACL shape for a model class.
1864
- *
1865
- * @param subjectName - The model's registered name (from `@Model({ name })`)
1866
- * @param target - The class constructor (used for prototype access,
1867
- * inheritance chain, and relation target resolution)
1868
- * @param properties - Merged property metadata (from `getPropertiesMetadata`)
1869
- * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
1870
- * @param conformanceFilterFn - Injected conformance-filter builder
1871
- * (avoids circular dependency back into decorators.ts)
1872
- */
1873
- function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
1874
- const obj = target.prototype;
1875
- // ── Determine namespace from first property or relation ─────────────
1876
- let namespace = "ad4m://";
1877
- const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
1878
- // Try properties first
1879
- if (Object.keys(properties).length > 0) {
1880
- const firstProp = properties[Object.keys(properties)[0]];
1881
- if (firstProp.through) {
1882
- const match = firstProp.through.match(/^([^:]+:\/\/)/);
1883
- if (match) {
1884
- namespace = match[1];
1885
- }
1886
- }
1887
- }
1888
- // Fall back to relations if no properties
1889
- else if (Object.keys(relations).length > 0) {
1890
- const firstRel = relations[Object.keys(relations)[0]];
1891
- if (firstRel.predicate) {
1892
- const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
1893
- if (match) {
1894
- namespace = match[1];
1895
- }
1896
- }
1897
- }
1898
- // ── Create SHACL shape ──────────────────────────────────────────────
1899
- const shapeUri = `${namespace}${subjectName}Shape`;
1900
- const targetClass = `${namespace}${subjectName}`;
1901
- const shape = new SHACLShape(shapeUri, targetClass);
1902
- // Detect @Model inheritance — if the parent class also has
1903
- // generateSHACL it is itself a @Model and we reference its shape
1904
- // via sh:node so SHACL validators can walk the hierarchy.
1905
- const parentCtor = Object.getPrototypeOf(target);
1906
- if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
1907
- const parentSHACL = parentCtor.generateSHACL();
1908
- if (parentSHACL?.shape?.nodeShapeUri) {
1909
- shape.addParentShape(parentSHACL.shape.nodeShapeUri);
1817
+ // ── Create SHACL shape ──────────────────────────────────────────────
1818
+ const shapeUri = `${namespace}${subjectName}Shape`;
1819
+ const targetClass = `${namespace}${subjectName}`;
1820
+ const shape = new SHACLShape(shapeUri, targetClass);
1821
+ // Detect @Model inheritance — if the parent class also has
1822
+ // generateSHACL it is itself a @Model and we reference its shape
1823
+ // via sh:node so SHACL validators can walk the hierarchy.
1824
+ const parentCtor = Object.getPrototypeOf(target);
1825
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
1826
+ const parentSHACL = parentCtor.generateSHACL();
1827
+ if (parentSHACL?.shape?.nodeShapeUri) {
1828
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
1910
1829
  }
1911
1830
  }
1912
1831
  // ── Constructor / Destructor actions ────────────────────────────────
@@ -1961,9 +1880,19 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1961
1880
  if (propMeta.writable !== undefined) {
1962
1881
  propShape.writable = propMeta.writable;
1963
1882
  }
1964
- if (propMeta.resolveLanguage) {
1883
+ if (propMeta.resolveLanguage != null) {
1965
1884
  propShape.resolveLanguage = propMeta.resolveLanguage;
1966
1885
  }
1886
+ // Explicit getter SPARQL — the executor evaluates this when
1887
+ // hydrating the property, in addition to (or instead of)
1888
+ // reading raw links via `propMeta.through`.
1889
+ if (propMeta.getter) {
1890
+ propShape.getter = propMeta.getter;
1891
+ }
1892
+ // Serializable transform expression (SHACL-AF Node Expression)
1893
+ if (propMeta.transform) {
1894
+ propShape.transform = propMeta.transform;
1895
+ }
1967
1896
  // ── Setter actions ──────────────────────────────────────────────
1968
1897
  if (propMeta.prologSetter) {
1969
1898
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
@@ -2002,63 +1931,82 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2002
1931
  shape.addProperty(propShape);
2003
1932
  }
2004
1933
  // ── Convert relations to SHACL property shapes ─────────────────────
2005
- for (const relName in relations) {
2006
- const relMeta = relations[relName];
2007
- if (!relMeta.predicate)
1934
+ for (const relName in allRelationsMeta) {
1935
+ const relMeta = allRelationsMeta[relName];
1936
+ // Getter-only relations (no `through`) have no real link predicate
1937
+ // but still need a SHACL property entry so the executor can find
1938
+ // the getter expression. Synthesize a deterministic IRI so the
1939
+ // SHACL graph is well-formed; the predicate is never used to match
1940
+ // links because the getter is the sole source of values. Use
1941
+ // slash separators so the result is a valid IRI (colons in the
1942
+ // authority confuse strict SPARQL IRI parsers).
1943
+ if (!relMeta.predicate && !relMeta.getter)
2008
1944
  continue;
1945
+ const synthesizedPath = relMeta.predicate
1946
+ || `ad4m://getter/${subjectName}/${relName}`;
2009
1947
  const relShape = {
2010
1948
  name: relName,
2011
- path: relMeta.predicate,
1949
+ path: synthesizedPath,
2012
1950
  };
2013
1951
  // Relations typically contain IRIs
2014
1952
  relShape.nodeKind = 'IRI';
1953
+ // Encode relation kind so the executor can derive direction and
1954
+ // scalar-vs-collection rendering without consulting the JS class.
1955
+ relShape.relationKind = relMeta.kind;
1956
+ // Scalar relations cap at 1.
1957
+ if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
1958
+ relShape.maxCount = 1;
1959
+ }
1960
+ else if (relMeta.maxCount !== undefined) {
1961
+ relShape.maxCount = relMeta.maxCount;
1962
+ }
1963
+ // Encode opt-out of type filtering (default true; only emit when false).
1964
+ if (relMeta.filter === false) {
1965
+ relShape.filter = false;
1966
+ }
2015
1967
  // AD4M-specific metadata
2016
1968
  if (relMeta.local !== undefined) {
2017
1969
  relShape.local = relMeta.local;
2018
1970
  }
2019
- // Adder action
2020
- relShape.adder = [{
2021
- action: "addLink",
2022
- source: "this",
2023
- predicate: relMeta.predicate,
2024
- target: "value",
2025
- ...(relMeta.local && { local: true })
2026
- }];
2027
- // Remover action
2028
- relShape.remover = [{
2029
- action: "removeLink",
2030
- source: "this",
2031
- predicate: relMeta.predicate,
2032
- target: "value",
2033
- ...(relMeta.local && { local: true })
2034
- }];
1971
+ // Adder / Remover actions — only meaningful for relations backed
1972
+ // by a real link predicate. Getter-only relations are read-only.
1973
+ if (relMeta.predicate) {
1974
+ relShape.adder = [{
1975
+ action: "addLink",
1976
+ source: "this",
1977
+ predicate: relMeta.predicate,
1978
+ target: "value",
1979
+ ...(relMeta.local && { local: true })
1980
+ }];
1981
+ relShape.remover = [{
1982
+ action: "removeLink",
1983
+ source: "this",
1984
+ predicate: relMeta.predicate,
1985
+ target: "value",
1986
+ ...(relMeta.local && { local: true })
1987
+ }];
1988
+ }
2035
1989
  // ── Build Getter (conformance filter) ───────────────────────────
2036
1990
  // Priority chain:
2037
1991
  // 1. Explicit getter string → use verbatim
2038
- // 2. `where` clause → compile DSL to SPARQL getter
2039
- // 3. target + filter !== false → auto-derive from shape
1992
+ // 2. target + filter !== false → auto-derive conformance getter
1993
+ // from the shape. Where-clause filtering is applied as a
1994
+ // post-getter pass via `whereFilter` / `wherePredicates`, which
1995
+ // use `parse_literal_value` and so transparently handle
1996
+ // `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
1997
+ // comparisons can't.
2040
1998
  if (relMeta.getter) {
2041
1999
  relShape.getter = relMeta.getter;
2042
2000
  }
2043
- else if (relMeta.where) {
2044
- try {
2045
- const TargetClass = relMeta.target?.();
2046
- const targetMetadata = TargetClass
2047
- ? TargetClass.getModelMetadata?.() ?? null
2048
- : null;
2049
- const conditions = compileWhereClause(relMeta.where, targetMetadata);
2050
- if (conditions.length > 0) {
2051
- const escapedPredicate = escapeQueryString(relMeta.predicate);
2052
- relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
2053
- }
2054
- }
2055
- catch (e) {
2056
- // Target metadata may not be available yet
2057
- }
2058
- }
2059
- else if (relMeta.target && relMeta.filter !== false) {
2001
+ else if (relMeta.target
2002
+ && relMeta.filter !== false
2003
+ && relMeta.kind !== 'belongsToOne'
2004
+ && relMeta.kind !== 'belongsToMany') {
2060
2005
  // Lazy conformance filter: store deferred reference,
2061
- // resolve on first access via a getter on relShape
2006
+ // resolve on first access via a getter on relShape.
2007
+ // Skipped for reverse relations (belongsTo*) because the
2008
+ // auto-derived getter assumes forward direction; the executor's
2009
+ // `resolve_reverse_relations` already populates these correctly.
2062
2010
  const targetThunk = relMeta.target;
2063
2011
  const predicate = relMeta.predicate;
2064
2012
  let resolved = false;
@@ -2095,6 +2043,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2095
2043
  });
2096
2044
  }
2097
2045
  // ── sh:class — target shape reference ───────────────────────────
2046
+ // Also emit ad4m:targetClassName so the executor can look up the
2047
+ // target class shape through its in-memory cache by bare name.
2098
2048
  if (relMeta.target) {
2099
2049
  try {
2100
2050
  const TargetClass = relMeta.target();
@@ -2102,9 +2052,54 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2102
2052
  if (targetSHACL?.shape?.nodeShapeUri) {
2103
2053
  relShape.class = targetSHACL.shape.nodeShapeUri;
2104
2054
  }
2055
+ if (targetSHACL?.name) {
2056
+ relShape.targetClassName = targetSHACL.name;
2057
+ }
2058
+ else {
2059
+ const targetProto = TargetClass.prototype;
2060
+ if (targetProto?.className) {
2061
+ relShape.targetClassName = targetProto.className;
2062
+ }
2063
+ }
2064
+ }
2065
+ catch (e) {
2066
+ // Target class resolution failed (typically a circular
2067
+ // decorator dependency). Since the executor no longer
2068
+ // receives target metadata over the wire, dropping the
2069
+ // reference here would turn a transient build-time issue
2070
+ // into a permanent broken-include at query time. Log
2071
+ // loudly so the failure is discoverable.
2072
+ console.warn(`[shacl-gen] Failed to resolve target class for relation `
2073
+ + `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
2074
+ }
2075
+ }
2076
+ // ── Where-clause metadata for post-getter filtering ─────────────
2077
+ // The executor uses these to apply where conditions against the
2078
+ // target class without needing the target's ModelMetadata at query time.
2079
+ if (relMeta.where) {
2080
+ relShape.whereFilter = relMeta.where;
2081
+ try {
2082
+ const TargetClass = relMeta.target?.();
2083
+ const targetMetadata = TargetClass
2084
+ ? TargetClass.getModelMetadata?.() ?? null
2085
+ : null;
2086
+ if (targetMetadata?.properties) {
2087
+ const predicates = {};
2088
+ for (const propName of Object.keys(relMeta.where)) {
2089
+ if (['id', 'author', 'timestamp'].includes(propName))
2090
+ continue;
2091
+ const propMeta = targetMetadata.properties[propName];
2092
+ if (propMeta?.predicate) {
2093
+ predicates[propName] = propMeta.predicate;
2094
+ }
2095
+ }
2096
+ if (Object.keys(predicates).length > 0) {
2097
+ relShape.wherePredicates = predicates;
2098
+ }
2099
+ }
2105
2100
  }
2106
2101
  catch (e) {
2107
- // Target class may not be available yet
2102
+ // Target metadata may not be available yet
2108
2103
  }
2109
2104
  }
2110
2105
  shape.addProperty(relShape);
@@ -2122,6 +2117,58 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
2122
2117
  };
2123
2118
  }
2124
2119
 
2120
+ function formatList(list) {
2121
+ if (!list?.length) {
2122
+ return "";
2123
+ }
2124
+ if (list.length === 1) {
2125
+ return list.toString();
2126
+ }
2127
+ if (list.length === 2) {
2128
+ return list.join(' and ');
2129
+ }
2130
+ return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
2131
+ }
2132
+ function capSentence(cap) {
2133
+ const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
2134
+ const domain = cap.with.domain === "*" ? "" : cap.with.domain;
2135
+ const pointers = cap.with.pointers.includes("*")
2136
+ ? ["all AD4M data"]
2137
+ : cap.with.pointers;
2138
+ return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
2139
+ }
2140
+ /**
2141
+ * Escapes a string value for safe use in query strings.
2142
+ *
2143
+ * @description
2144
+ * Prevents SQL injection by properly escaping special characters in string values
2145
+ * that will be interpolated into query strings. This handles the most common
2146
+ * special characters that could break SQL queries or enable injection attacks.
2147
+ *
2148
+ * Single quotes, backslashes, and other special characters are escaped using
2149
+ * backslash notation, which is the standard escaping mechanism for query.
2150
+ *
2151
+ * @param value - The string value to escape
2152
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
2153
+ *
2154
+ * @example
2155
+ * ```typescript
2156
+ * const userInput = "user's input with 'quotes'";
2157
+ * const escaped = escapeQueryString(userInput);
2158
+ * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
2159
+ * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
2160
+ * ```
2161
+ */
2162
+ function escapeQueryString(value) {
2163
+ return value
2164
+ .replace(/\\/g, '\\\\') // Backslash -> \\
2165
+ .replace(/'/g, "\\'") // Single quote -> \'
2166
+ .replace(/"/g, '\\"') // Double quote -> \"
2167
+ .replace(/\n/g, '\\n') // Newline -> \n
2168
+ .replace(/\r/g, '\\r') // Carriage return -> \r
2169
+ .replace(/\t/g, '\\t'); // Tab -> \t
2170
+ }
2171
+
2125
2172
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
2126
2173
  const propertyRegistry = new WeakMap();
2127
2174
  /** Registry of relation metadata keyed by constructor → { propName → metadata } */
@@ -2641,15 +2688,8 @@ function resolveRelationArgs(first, second) {
2641
2688
  return opts;
2642
2689
  }
2643
2690
  function HasMany(first, second) {
2644
- const explicitThrough = typeof first === 'function' ? second?.through : first.through;
2645
2691
  const opts = resolveRelationArgs(first, second);
2646
2692
  return function (target, key) {
2647
- if (!explicitThrough && !opts.getter) {
2648
- const className = (target.constructor?.name) ?? 'unknown';
2649
- console.warn(`@HasMany on ${className}.${String(key)} has no 'through' predicate — defaulting to 'ad4m://has_child'. ` +
2650
- `Add { through: 'ad4m://has_child' } to silence this warning, or use a semantic predicate ` +
2651
- `like { through: 'myns://has_${String(key)}' } for efficient targeted queries.`);
2652
- }
2653
2693
  // --- relation registry ---
2654
2694
  const ctor = target.constructor;
2655
2695
  if (!relationRegistry.has(ctor))
@@ -3745,13 +3785,16 @@ class PerspectiveProxy {
3745
3785
  /**
3746
3786
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
3747
3787
  *
3788
+ * The executor resolves the model's shape from the perspective's SHACL
3789
+ * triples (written by `addSdna`). Callers no longer ship shape
3790
+ * metadata with the query; the perspective is the source of truth.
3791
+ *
3748
3792
  * @param className - The model class name (e.g. "Recipe")
3749
3793
  * @param queryJson - Structured query as JSON string
3750
- * @param shapeJson - Optional shape metadata JSON from the model class
3751
3794
  * @returns Object with `instances` array and `totalCount`
3752
3795
  */
3753
- async modelQuery(className, queryJson, shapeJson) {
3754
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3796
+ async modelQuery(className, queryJson) {
3797
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3755
3798
  }
3756
3799
  /**
3757
3800
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -3762,12 +3805,11 @@ class PerspectiveProxy {
3762
3805
  *
3763
3806
  * @param className - The model class name (e.g. "Message")
3764
3807
  * @param instanceIds - Array of instance base expression URIs
3765
- * @param shapeJson - Shape metadata JSON from the model class
3766
3808
  * @param propertyNames - Optional subset of property names to evaluate
3767
3809
  * @returns Map of instance ID → evaluated property values
3768
3810
  */
3769
- async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
3770
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
3811
+ async evaluateGetters(className, instanceIds, propertyNames) {
3812
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
3771
3813
  }
3772
3814
  /**
3773
3815
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
@@ -3779,11 +3821,10 @@ class PerspectiveProxy {
3779
3821
  *
3780
3822
  * @param className - The model class name
3781
3823
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
3782
- * @param shapeJson - Optional shape metadata JSON from the model class
3783
3824
  * @returns Object with `subscriptionId` and initial `result`
3784
3825
  */
3785
- async modelSubscribe(className, queryJson, shapeJson) {
3786
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
3826
+ async modelSubscribe(className, queryJson) {
3827
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
3787
3828
  }
3788
3829
  /**
3789
3830
  * Adds a new link to the perspective.
@@ -3971,17 +4012,30 @@ class PerspectiveProxy {
3971
4012
  async removeListener(type, cb) {
3972
4013
  if (type === 'link-added') {
3973
4014
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
3974
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
4015
+ if (index >= 0)
4016
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
3975
4017
  }
3976
4018
  else if (type === 'link-removed') {
3977
4019
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
3978
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
4020
+ if (index >= 0)
4021
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
3979
4022
  }
3980
4023
  else if (type === 'link-updated') {
3981
4024
  const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
3982
- __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
4025
+ if (index >= 0)
4026
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
3983
4027
  }
3984
4028
  }
4029
+ /** Clean up all subscriptions registered by this proxy.
4030
+ * Call this when the proxy is no longer needed to prevent subscription leaks.
4031
+ * After calling dispose(), the proxy should not be used. */
4032
+ dispose() {
4033
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeAllListeners(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4034
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").length = 0;
4035
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").length = 0;
4036
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").length = 0;
4037
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").length = 0;
4038
+ }
3985
4039
  /**
3986
4040
  * Creates a snapshot of the current perspective state.
3987
4041
  * Useful for backup or sharing.
@@ -4271,6 +4325,40 @@ class PerspectiveProxy {
4271
4325
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
4272
4326
  return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
4273
4327
  }
4328
+ /**
4329
+ * Batch variant of addSdna — registers multiple SDNA entries in a single RPC call.
4330
+ * Acquires the Rust-side mutex once for the entire batch.
4331
+ */
4332
+ async addSdnaAll(entries) {
4333
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdnaBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, entries);
4334
+ }
4335
+ /**
4336
+ * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.
4337
+ * Skips classes already registered on this perspective instance.
4338
+ */
4339
+ async ensureSubjectClasses(jsClasses) {
4340
+ const entries = [];
4341
+ for (const jsClass of jsClasses) {
4342
+ const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
4343
+ if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
4344
+ continue;
4345
+ if (!jsClass.generateSHACL) {
4346
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
4347
+ }
4348
+ const { shape } = jsClass.generateSHACL();
4349
+ entries.push({
4350
+ name: className,
4351
+ sdnaType: 'subject_class',
4352
+ shaclJson: JSON.stringify(shape.toJSON()),
4353
+ });
4354
+ }
4355
+ if (entries.length === 0)
4356
+ return;
4357
+ await this.addSdnaAll(entries);
4358
+ for (const entry of entries) {
4359
+ __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(entry.name);
4360
+ }
4361
+ }
4274
4362
  /**
4275
4363
  * Adds a subject class to the perspective.
4276
4364
  * Alias for addSdna() with sdnaType='subject_class'.
@@ -5378,22 +5466,21 @@ class PerspectiveClient {
5378
5466
  }
5379
5467
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5380
5468
  }
5381
- async modelQuery(uuid, className, queryJson, shapeJson) {
5382
- const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5469
+ async modelQuery(uuid, className, queryJson) {
5470
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
5383
5471
  return JSON.parse(resultJson);
5384
5472
  }
5385
- async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {
5473
+ async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5386
5474
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5387
5475
  uuid,
5388
5476
  class_name: className,
5389
5477
  instance_ids: instanceIds,
5390
- shape_json: shapeJson,
5391
5478
  ...(propertyNames && { property_names: propertyNames }),
5392
5479
  });
5393
5480
  return JSON.parse(resultJson);
5394
5481
  }
5395
- async modelSubscribe(uuid, className, queryJson, shapeJson) {
5396
- const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });
5482
+ async modelSubscribe(uuid, className, queryJson) {
5483
+ const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
5397
5484
  return {
5398
5485
  subscriptionId: response.subscription_id,
5399
5486
  result: JSON.parse(response.result)
@@ -5439,6 +5526,9 @@ class PerspectiveClient {
5439
5526
  async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {
5440
5527
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson });
5441
5528
  }
5529
+ async addSdnaBatch(uuid, entries) {
5530
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || "" })) });
5531
+ }
5442
5532
  async executeCommands(uuid, commands, expression, parameters, batchId) {
5443
5533
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });
5444
5534
  }
@@ -5546,7 +5636,21 @@ class PerspectiveClient {
5546
5636
  __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5547
5637
  await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5548
5638
  }
5549
- getNeighbourhoodProxy(uuid) {
5639
+ /** Unsubscribe all link/sync-state listeners registered for the given perspective UUID.
5640
+ * Called by PerspectiveProxy.dispose() to prevent subscription leaks. */
5641
+ removeAllListeners(uuid) {
5642
+ const unsubs = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid);
5643
+ if (unsubs) {
5644
+ for (const fn of unsubs) {
5645
+ try {
5646
+ fn();
5647
+ }
5648
+ catch { }
5649
+ }
5650
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").delete(uuid);
5651
+ }
5652
+ }
5653
+ getNeighbourhoodProxy(uuid) {
5550
5654
  return new NeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveClient_neighbourhoodClient, "f"), uuid);
5551
5655
  }
5552
5656
  async createBatch(uuid) {
@@ -5725,6 +5829,7 @@ class AgentClient {
5725
5829
  // L1: in-memory promise cache with timestamps for TTL
5726
5830
  _AgentClient_memCache.set(this, new Map());
5727
5831
  // L2: persistent cache (IndexedDB in browser, NullCache in Node)
5832
+ // Entries are wrapped with a timestamp so the TTL can be enforced across restarts.
5728
5833
  _AgentClient_persistent.set(this, void 0);
5729
5834
  // Self-DID for event-driven invalidation (no TTL for own profile)
5730
5835
  _AgentClient_selfDid.set(this, null);
@@ -5748,6 +5853,11 @@ class AgentClient {
5748
5853
  const agent = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.get');
5749
5854
  let agentObject = new Agent(agent.did, agent.perspective);
5750
5855
  agentObject.directMessageLanguage = agent.directMessageLanguage;
5856
+ // Auto-set selfDid so event-driven cache invalidation works
5857
+ // without requiring apps to call setSelfDid() manually
5858
+ if (agentObject.did && !__classPrivateFieldGet$7(this, _AgentClient_selfDid, "f")) {
5859
+ __classPrivateFieldSet$7(this, _AgentClient_selfDid, agentObject.did, "f");
5860
+ }
5751
5861
  return agentObject;
5752
5862
  }
5753
5863
  async status() {
@@ -5784,13 +5894,14 @@ class AgentClient {
5784
5894
  // Deduplicate: store the promise immediately so concurrent calls share one RPC
5785
5895
  const promise = (async () => {
5786
5896
  // L2: check persistent cache before network
5787
- const persisted = await __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").get(did);
5788
- if (persisted) {
5789
- return persisted;
5897
+ const entry = await __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").get(did);
5898
+ // entry.agent may be undefined for pre-TTL cache entries (migration) — treat as expired
5899
+ if (entry?.agent && (now - (entry.ts ?? 0)) < AgentClient.REMOTE_AGENT_TTL_L2_MS) {
5900
+ return entry.agent;
5790
5901
  }
5791
5902
  // L3: network fetch
5792
5903
  const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.byDid', { did });
5793
- __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(did, result); // fire-and-forget write to L2
5904
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(did, { agent: result, ts: Date.now() }); // fire-and-forget write to L2
5794
5905
  return result;
5795
5906
  })();
5796
5907
  __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(did, { promise, ts: now });
@@ -5835,6 +5946,12 @@ class AgentClient {
5835
5946
  const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { publicPerspective: cleanedPerspective });
5836
5947
  const agent = new Agent(a.did, a.perspective);
5837
5948
  agent.directMessageLanguage = a.directMessageLanguage;
5949
+ // Immediately update byDID cache so subsequent byDID() calls
5950
+ // return fresh data without waiting for the subscription event
5951
+ if (agent.did) {
5952
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
5953
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
5954
+ }
5838
5955
  return agent;
5839
5956
  }
5840
5957
  async mutatePublicPerspective(mutations) {
@@ -5859,6 +5976,12 @@ class AgentClient {
5859
5976
  const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { dmLanguage: directMessageLanguage });
5860
5977
  const agent = new Agent(a.did, a.perspective);
5861
5978
  agent.directMessageLanguage = a.directMessageLanguage;
5979
+ // Immediately update byDID cache so subsequent byDID() calls
5980
+ // return fresh data without waiting for the subscription event
5981
+ if (agent.did) {
5982
+ __classPrivateFieldGet$7(this, _AgentClient_memCache, "f").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });
5983
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
5984
+ }
5862
5985
  return agent;
5863
5986
  }
5864
5987
  async addEntanglementProofs(proofs) {
@@ -5889,7 +6012,7 @@ class AgentClient {
5889
6012
  promise: Promise.resolve(agent),
5890
6013
  ts: Date.now(),
5891
6014
  });
5892
- __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, agent); // fire-and-forget
6015
+ __classPrivateFieldGet$7(this, _AgentClient_persistent, "f").put(agent.did, { agent, ts: Date.now() }); // fire-and-forget
5893
6016
  }
5894
6017
  __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, "f").forEach((cb) => cb(agent));
5895
6018
  }
@@ -5993,6 +6116,9 @@ class AgentClient {
5993
6116
  _AgentClient_apiClient = new WeakMap(), _AgentClient_baseUrl = new WeakMap(), _AgentClient_token = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap(), _AgentClient_unsubscribers = new WeakMap(), _AgentClient_memCache = new WeakMap(), _AgentClient_persistent = new WeakMap(), _AgentClient_selfDid = new WeakMap();
5994
6117
  /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
5995
6118
  AgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes
6119
+ /** TTL for remote agent profiles in the L2 (IndexedDB) cache (ms).
6120
+ * After this window any restart triggers a fresh network fetch. */
6121
+ AgentClient.REMOTE_AGENT_TTL_L2_MS = 5 * 60000; // 5 minutes
5996
6122
 
5997
6123
  var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5998
6124
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -13754,7 +13880,7 @@ class AIClient {
13754
13880
  // Use slice to get only the relevant portion of the underlying ArrayBuffer
13755
13881
  // (Float32Array may be a view over a larger buffer)
13756
13882
  const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
13757
- const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13883
+ const response = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13758
13884
  method: 'POST',
13759
13885
  headers: {
13760
13886
  'Content-Type': 'application/octet-stream',
@@ -14216,7 +14342,9 @@ function escapeSPARQL(value) {
14216
14342
  .replace(/"/g, '\\"')
14217
14343
  .replace(/\n/g, "\\n")
14218
14344
  .replace(/\r/g, "\\r")
14219
- .replace(/\t/g, "\\t");
14345
+ .replace(/\t/g, "\\t")
14346
+ .replace(/\0/g, "")
14347
+ .replace(/\f/g, "\\u000C");
14220
14348
  }
14221
14349
  /**
14222
14350
  * Format a value as a SPARQL string literal (double-quoted).
@@ -14231,8 +14359,14 @@ function formatSPARQLValue(value) {
14231
14359
  * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
14232
14360
  * All AD4M link source/predicate/target values become IRIs in angle brackets.
14233
14361
  * The Rust SPARQL service transparently transforms these to valid IRI format.
14362
+ *
14363
+ * Rejects characters that would break or inject into a SPARQL IRI token,
14364
+ * matching the Rust-side `validate_iri()` function.
14234
14365
  */
14235
14366
  function iri(value) {
14367
+ if (/[<>{}" ]/.test(value)) {
14368
+ throw new Error(`Invalid IRI component: '${value}'`);
14369
+ }
14236
14370
  return `<${value}>`;
14237
14371
  }
14238
14372
  /**
@@ -14378,21 +14512,8 @@ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
14378
14512
  ?_reifier <ad4m://ontology/timestamp> ?timestamp .
14379
14513
  ${filterClause}
14380
14514
  }
14381
- ${buildSPARQLOrderLimitOffset()}
14382
14515
  `.trim();
14383
14516
  }
14384
- /**
14385
- * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
14386
- *
14387
- * NOTE: The outer SELECT returns multiple rows per instance (one per link),
14388
- * so LIMIT/OFFSET at the outer level would cut off links mid-instance.
14389
- * This function is kept for backward compatibility and always returns "".
14390
- * SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
14391
- * using buildPaginationSubquery().
14392
- */
14393
- function buildSPARQLOrderLimitOffset(_metadata, query) {
14394
- return "";
14395
- }
14396
14517
  /**
14397
14518
  * Build an inner subquery that selects DISTINCT ?source URIs with
14398
14519
  * ORDER BY, LIMIT, and OFFSET applied at the instance level.
@@ -14439,7 +14560,7 @@ function buildPaginationSubquery(joinPatterns, filterExpressions, metadata, quer
14439
14560
  { SELECT DISTINCT ?source${tsSelect} WHERE {${innerJoin}${orderJoinPatterns.join('')}${tsPattern}
14440
14561
  FILTER(isIRI(?source))
14441
14562
  ${innerFilter}
14442
- } GROUP BY ?source ${orderByClause} ${limitClause} ${offsetClause} }\n`;
14563
+ } ${orderByClause} ${limitClause} ${offsetClause} }\n`;
14443
14564
  }
14444
14565
  /**
14445
14566
  * Build SPARQL FILTER expressions from user `where` conditions.
@@ -14491,8 +14612,8 @@ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
14491
14612
  const useParseLiteral = isLiteralStoredProperty(propMeta);
14492
14613
  // For literal-stored properties, push equality/IN/NOT filters to SPARQL using
14493
14614
  // <ad4m://fn/parse_literal>() which extracts the raw value from literal: IRIs.
14494
- // The correct SPARQL syntax is <ad4m://fn/parse_literal>(?var) — NOT fn::parse_literal
14495
- // (which was SurrealDB syntax that Oxigraph rejects at parse time).
14615
+ // Use IRI form <ad4m://fn/parse_literal>(?var); the namespaced form
14616
+ // fn::parse_literal is invalid SPARQL and Oxigraph rejects it at parse time.
14496
14617
  // Comparison operators (gt/lt/gte/lte/between/contains) remain JS-only because
14497
14618
  // parse_literal returns strings and numeric/date comparisons would be unreliable.
14498
14619
  // JS post-filter in instancesFromQueryResult remains as a safety net for all cases.
@@ -14835,13 +14956,6 @@ class ModelQueryBuilder {
14835
14956
  this.modelClassName = className;
14836
14957
  return this;
14837
14958
  }
14838
- /**
14839
- * Sets the query engine to use.
14840
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
14841
- */
14842
- engine(_eng) {
14843
- return this;
14844
- }
14845
14959
  /**
14846
14960
  * Executes the query once and returns the results.
14847
14961
  *
@@ -14885,8 +14999,10 @@ class ModelQueryBuilder {
14885
14999
  * ```
14886
15000
  */
14887
15001
  async first() {
15002
+ const savedLimit = this.queryParams.limit;
14888
15003
  this.queryParams.limit = 1;
14889
15004
  const results = await this.get();
15005
+ this.queryParams.limit = savedLimit;
14890
15006
  return results[0] ?? null;
14891
15007
  }
14892
15008
  /**
@@ -14921,23 +15037,18 @@ class ModelQueryBuilder {
14921
15037
  // Clean up any existing subscription
14922
15038
  this.dispose();
14923
15039
  const ctor = this.ctor;
14924
- // Build the model query params (className, queryJson, shapeJson)
14925
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
15040
+ // Build the model query params (className, queryJson). The executor
15041
+ // resolves the shape from the perspective's SHACL triples.
15042
+ const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
14926
15043
  // Register model subscription via Rust — this builds trigger SPARQL internally,
14927
15044
  // registers the subscription, and runs the initial query in one call.
14928
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15045
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
14929
15046
  // Convert JSON instances to model class instances
14930
15047
  const parseResults = (raw) => {
14931
15048
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
14932
15049
  };
14933
- // Resolve non-literal (file-language) properties — handles both raw URI strings
14934
- // and already-resolved FileData objects returned by the Rust executor.
14935
- const resolveAndReturn = async (instances) => {
14936
- await ctor.resolveNonLiteralProps(this.perspective, instances);
14937
- return instances;
14938
- };
14939
- // Parse initial results (with non-literal resolution)
14940
- const initialResults = await resolveAndReturn(parseResults(initialModelResult));
15050
+ // Transforms are now applied by the Rust executor during hydration
15051
+ const initialResults = parseResults(initialModelResult);
14941
15052
  // Track last emitted result fingerprint to suppress duplicate callbacks
14942
15053
  let lastResultFingerprint = null;
14943
15054
  const buildFingerprint = (results) => {
@@ -14950,34 +15061,65 @@ class ModelQueryBuilder {
14950
15061
  // When Rust re-runs the model query and finds changed results, it pushes them.
14951
15062
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
14952
15063
  try {
14953
- resolveAndReturn(parseResults(rawResult)).then((results) => {
14954
- const fp = buildFingerprint(results);
14955
- if (fp === lastResultFingerprint)
14956
- return;
14957
- lastResultFingerprint = fp;
14958
- callback(results);
14959
- }).catch((e) => {
14960
- console.error('Model subscription update resolve error:', e);
14961
- });
15064
+ const results = parseResults(rawResult);
15065
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
15066
+ const fp = buildFingerprint(results);
15067
+ if (fp === lastResultFingerprint) {
15068
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
15069
+ return;
15070
+ }
15071
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
15072
+ lastResultFingerprint = fp;
15073
+ callback(results);
14962
15074
  }
14963
15075
  catch (e) {
14964
15076
  console.error('Model subscription update parse error:', e);
14965
15077
  }
14966
15078
  });
14967
- // Set up keepalive with failure tracking
14968
- let keepaliveFailures = 0;
14969
- const keepaliveTimer = setInterval(() => {
14970
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
14971
- keepaliveFailures = 0;
14972
- }).catch((e) => {
14973
- keepaliveFailures++;
14974
- console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
14975
- });
14976
- }, 30000);
15079
+ // Set up keepalive with recovery — uses setTimeout loop so we can
15080
+ // break out and resubscribe when the server evicts the subscription.
15081
+ let disposed = false;
15082
+ let keepaliveTimer;
15083
+ let resubscribeAttempts = 0;
15084
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15085
+ const keepaliveLoop = async () => {
15086
+ if (disposed)
15087
+ return;
15088
+ try {
15089
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15090
+ resubscribeAttempts = 0; // Reset on success
15091
+ }
15092
+ catch (e) {
15093
+ console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);
15094
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15095
+ resubscribeAttempts++;
15096
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15097
+ console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15098
+ await new Promise(r => setTimeout(r, backoffMs));
15099
+ try {
15100
+ unsubscribe();
15101
+ await this.subscribe(callback);
15102
+ }
15103
+ catch (resubErr) {
15104
+ console.error('Model subscription resubscribe failed:', resubErr);
15105
+ }
15106
+ }
15107
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15108
+ console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15109
+ }
15110
+ return; // new subscription owns its own keepalive loop
15111
+ }
15112
+ if (!disposed) {
15113
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15114
+ }
15115
+ };
15116
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
14977
15117
  // Store dispose function
14978
15118
  this.currentSubscription = {
14979
15119
  dispose: () => {
14980
- clearInterval(keepaliveTimer);
15120
+ disposed = true;
15121
+ if (keepaliveTimer)
15122
+ clearTimeout(keepaliveTimer);
14981
15123
  unsubscribe();
14982
15124
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
14983
15125
  },
@@ -15050,8 +15192,8 @@ class ModelQueryBuilder {
15050
15192
  // Clean up any existing subscription
15051
15193
  this.dispose();
15052
15194
  const countParams = { ...this.queryParams, limit: 0 };
15053
- const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15054
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15195
+ const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
15196
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
15055
15197
  const parseCount = (raw) => {
15056
15198
  const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
15057
15199
  return data.totalCount ?? 0;
@@ -15065,18 +15207,47 @@ class ModelQueryBuilder {
15065
15207
  console.error('Count subscription update parse error:', e);
15066
15208
  }
15067
15209
  });
15068
- let keepaliveFailures = 0;
15069
- const keepaliveTimer = setInterval(() => {
15070
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15071
- keepaliveFailures = 0;
15072
- }).catch((e) => {
15073
- keepaliveFailures++;
15074
- console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15075
- });
15076
- }, 30000);
15210
+ let disposed = false;
15211
+ let keepaliveTimer;
15212
+ let resubscribeAttempts = 0;
15213
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15214
+ const keepaliveLoop = async () => {
15215
+ if (disposed)
15216
+ return;
15217
+ try {
15218
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15219
+ resubscribeAttempts = 0;
15220
+ }
15221
+ catch (e) {
15222
+ console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);
15223
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15224
+ resubscribeAttempts++;
15225
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15226
+ console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15227
+ await new Promise(r => setTimeout(r, backoffMs));
15228
+ try {
15229
+ unsubscribe();
15230
+ await this.countSubscribe(callback);
15231
+ }
15232
+ catch (resubErr) {
15233
+ console.error('Count subscription resubscribe failed:', resubErr);
15234
+ }
15235
+ }
15236
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15237
+ console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15238
+ }
15239
+ return;
15240
+ }
15241
+ if (!disposed) {
15242
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15243
+ }
15244
+ };
15245
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15077
15246
  this.currentSubscription = {
15078
15247
  dispose: () => {
15079
- clearInterval(keepaliveTimer);
15248
+ disposed = true;
15249
+ if (keepaliveTimer)
15250
+ clearTimeout(keepaliveTimer);
15080
15251
  unsubscribe();
15081
15252
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
15082
15253
  },
@@ -15157,8 +15328,8 @@ class ModelQueryBuilder {
15157
15328
  const subscriptionParams = { ...(this.queryParams || {}) };
15158
15329
  delete subscriptionParams.limit;
15159
15330
  delete subscriptionParams.offset;
15160
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15161
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
15331
+ const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
15332
+ const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
15162
15333
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
15163
15334
  const paginatedQuery = {
15164
15335
  ...(this.queryParams || {}),
@@ -15171,20 +15342,50 @@ class ModelQueryBuilder {
15171
15342
  callback({ results, totalCount, pageSize, pageNumber });
15172
15343
  };
15173
15344
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15345
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
15174
15346
  processResults().catch(e => console.error('Paginate subscription error:', e));
15175
15347
  });
15176
- let keepaliveFailures = 0;
15177
- const keepaliveTimer = setInterval(() => {
15178
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
15179
- keepaliveFailures = 0;
15180
- }).catch((e) => {
15181
- keepaliveFailures++;
15182
- console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
15183
- });
15184
- }, 30000);
15348
+ let disposed = false;
15349
+ let keepaliveTimer;
15350
+ let resubscribeAttempts = 0;
15351
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
15352
+ const keepaliveLoop = async () => {
15353
+ if (disposed)
15354
+ return;
15355
+ try {
15356
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
15357
+ resubscribeAttempts = 0;
15358
+ }
15359
+ catch (e) {
15360
+ console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);
15361
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
15362
+ resubscribeAttempts++;
15363
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
15364
+ console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
15365
+ await new Promise(r => setTimeout(r, backoffMs));
15366
+ try {
15367
+ unsubscribe();
15368
+ await this.paginateSubscribe(pageSize, pageNumber, callback);
15369
+ }
15370
+ catch (resubErr) {
15371
+ console.error('Paginate subscription resubscribe failed:', resubErr);
15372
+ }
15373
+ }
15374
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
15375
+ console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
15376
+ }
15377
+ return;
15378
+ }
15379
+ if (!disposed) {
15380
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15381
+ }
15382
+ };
15383
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
15185
15384
  this.currentSubscription = {
15186
15385
  dispose: () => {
15187
- clearInterval(keepaliveTimer);
15386
+ disposed = true;
15387
+ if (keepaliveTimer)
15388
+ clearTimeout(keepaliveTimer);
15188
15389
  unsubscribe();
15189
15390
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
15190
15391
  },
@@ -15224,91 +15425,9 @@ function normalizeValue(value) {
15224
15425
  return value;
15225
15426
  }
15226
15427
 
15227
- // ---------------------------------------------------------------------------
15228
- // Default decoder for file-storage (non-literal resolveLanguage) properties
15229
- // ---------------------------------------------------------------------------
15230
- /**
15231
- * When the Rust executor resolves a non-literal expression it may return a
15232
- * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
15233
- * raw URI string. If the model class has no custom `transform` registered
15234
- * (e.g. it was synthesised from a SHACL shape at runtime) we still want to
15235
- * decode the content rather than passing raw `FileData` to callers.
15236
- *
15237
- * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
15238
- * - `application/json` (default when `file_type` is absent) → JSON.parse
15239
- * - anything else → raw decoded string
15240
- *
15241
- * If `resolved` is not a `FileData` object the value is returned unchanged so
15242
- * that callers can use this as a safe unconditional fallback.
15243
- */
15244
- function defaultFileDecode(resolved) {
15245
- if (resolved !== null &&
15246
- typeof resolved === 'object' &&
15247
- 'data_base64' in resolved) {
15248
- const fd = resolved;
15249
- let raw;
15250
- try {
15251
- raw = atob(fd.data_base64);
15252
- }
15253
- catch {
15254
- return resolved; // malformed base64 — keep as-is
15255
- }
15256
- const isJson = !fd.file_type || fd.file_type === 'application/json';
15257
- if (isJson) {
15258
- try {
15259
- return JSON.parse(raw);
15260
- }
15261
- catch {
15262
- return raw;
15263
- }
15264
- }
15265
- return raw;
15266
- }
15267
- return resolved;
15268
- }
15269
15428
  // ---------------------------------------------------------------------------
15270
15429
  // Helpers for Rust-side include resolution
15271
15430
  // ---------------------------------------------------------------------------
15272
- /**
15273
- * Recursively enrich relation metadata in the shape with target class shapes
15274
- * so the Rust endpoint can resolve includes in-process (no extra GraphQL
15275
- * round-trips per relation).
15276
- */
15277
- function enrichShapeForIncludes(metadata, include, allRelMeta) {
15278
- for (const [relName, includeVal] of Object.entries(include)) {
15279
- if (!includeVal)
15280
- continue;
15281
- const meta = allRelMeta[relName];
15282
- if (!meta?.target)
15283
- continue;
15284
- const TargetClass = meta.target();
15285
- // Deep-copy so we don't mutate the cached metadata
15286
- const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
15287
- // Ensure the relation is in metadata.relations (fallback for edge cases)
15288
- if (!metadata.relations[relName]) {
15289
- metadata.relations[relName] = {
15290
- name: relName,
15291
- predicate: meta.predicate,
15292
- direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
15293
- ? 'reverse'
15294
- : 'forward',
15295
- };
15296
- }
15297
- const rel = metadata.relations[relName];
15298
- rel.kind = meta.kind;
15299
- rel.maxCount = meta.maxCount;
15300
- rel.targetShape = targetMeta;
15301
- rel.targetClassName = targetMeta.className;
15302
- // Recurse for nested includes
15303
- const nested = typeof includeVal === 'object' && includeVal !== null
15304
- ? includeVal.include
15305
- : undefined;
15306
- if (nested) {
15307
- const targetRelMeta = getRelationsMetadata(TargetClass);
15308
- enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
15309
- }
15310
- }
15311
- }
15312
15431
  /**
15313
15432
  * Construct a model class instance from a plain JSON object returned by the
15314
15433
  * Rust endpoint. Recursively converts included relation values (which come
@@ -15353,22 +15472,6 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15353
15472
  }
15354
15473
  instance[key] = value;
15355
15474
  }
15356
- // Apply property transform functions from decorators (only for literal-resolved
15357
- // or no-resolveLanguage properties; non-literal properties are resolved + transformed
15358
- // asynchronously in executeModelQuery).
15359
- try {
15360
- const propsMeta = getPropertiesMetadata(ModelClass);
15361
- for (const [propName, opts] of Object.entries(propsMeta)) {
15362
- const o = opts;
15363
- if (typeof o.transform !== 'function' || !(propName in json))
15364
- continue;
15365
- // Skip non-literal resolveLanguage props — they need async expression resolution first
15366
- if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
15367
- continue;
15368
- instance[propName] = o.transform(instance[propName]);
15369
- }
15370
- }
15371
- catch (_) { /* no metadata available */ }
15372
15475
  // Recursively convert included relation values to class instances
15373
15476
  if (include) {
15374
15477
  const relMeta = getRelationsMetadata(ModelClass);
@@ -15606,8 +15709,8 @@ class Ad4mModel {
15606
15709
  ...(options.getter !== undefined && { getter: options.getter }),
15607
15710
  ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
15608
15711
  ...(options.local !== undefined && { local: options.local }),
15609
- ...(options.transform !== undefined && { transform: options.transform }),
15610
- ...(options.flag !== undefined && { flag: options.flag })
15712
+ ...(options.flag !== undefined && { flag: options.flag }),
15713
+ ...(options.transform !== undefined && { transform: options.transform })
15611
15714
  };
15612
15715
  }
15613
15716
  // Extract relations (relations) from WeakMap registry
@@ -15792,6 +15895,7 @@ class Ad4mModel {
15792
15895
  * • `null` / empty object — skip ALL relations (used by bare
15793
15896
  * subscriptions that don't eagerly load relations).
15794
15897
  */
15898
+ /** @internal */
15795
15899
  takeSnapshot(includedRelations) {
15796
15900
  const ctor = this.constructor;
15797
15901
  const metadata = ctor.getModelMetadata();
@@ -15987,164 +16091,14 @@ class Ad4mModel {
15987
16091
  }
15988
16092
  /**
15989
16093
  * Build the JSON parameters needed for a model query/subscription endpoint.
15990
- * Returns the className, queryJson, and shapeJson that the Rust executor expects.
16094
+ * Returns the className and queryJson that the Rust executor expects.
16095
+ * Shape resolution happens server-side from the perspective's SHACL triples.
15991
16096
  * @internal
15992
16097
  */
15993
16098
  static prepareModelQueryParams(query = {}, classNameOverride) {
15994
- const metadata = this.getModelMetadata();
15995
- const className = classNameOverride || metadata.className;
15996
- const queryInput = {};
15997
- if (query.parent) {
15998
- const parentPredicate = resolveParentPredicate(query.parent, this);
15999
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
16000
- }
16001
- if (query.properties)
16002
- queryInput.properties = query.properties;
16003
- if (query.include)
16004
- queryInput.include = query.include;
16005
- if (query.where)
16006
- queryInput.where = query.where;
16007
- if (query.order) {
16008
- queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
16009
- }
16010
- if (query.offset !== undefined)
16011
- queryInput.offset = query.offset;
16012
- if (query.limit !== undefined)
16013
- queryInput.limit = query.limit;
16014
- if (query.count !== undefined)
16015
- queryInput.count = query.count;
16016
- queryInput.deepQuery = query.deepQuery ?? true;
16017
- if (query.include) {
16018
- const allRelMeta = getRelationsMetadata(this);
16019
- enrichShapeForIncludes(metadata, query.include, allRelMeta);
16020
- }
16021
- // Pre-compute conformance getters for Rust-side evaluation.
16022
- // Where clauses are NOT compiled into getter SPARQL because stored
16023
- // property values are signed expression envelopes (literal:json:...),
16024
- // not simple literal:string:X values. Instead, where clauses are
16025
- // attached as metadata for Rust-side post-evaluation filtering.
16026
- {
16027
- const allRelMeta = getRelationsMetadata(this);
16028
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16029
- const rel = relMeta;
16030
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16031
- continue;
16032
- const meta = allRelMeta[relName];
16033
- if (!meta?.target)
16034
- continue;
16035
- try {
16036
- const TargetClass = meta.target();
16037
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16038
- if (filter) {
16039
- rel.getter = filter.getter;
16040
- }
16041
- // Attach where-clause metadata for Rust-side post-getter filtering
16042
- if (rel.where) {
16043
- try {
16044
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16045
- if (targetMetadata) {
16046
- const predicates = {};
16047
- for (const propName of Object.keys(rel.where)) {
16048
- if (['id', 'author', 'timestamp'].includes(propName))
16049
- continue;
16050
- const propMeta = targetMetadata.properties[propName];
16051
- if (propMeta?.predicate) {
16052
- predicates[propName] = propMeta.predicate;
16053
- }
16054
- }
16055
- if (Object.keys(predicates).length > 0) {
16056
- rel.whereFilter = rel.where;
16057
- rel.wherePredicates = predicates;
16058
- }
16059
- }
16060
- }
16061
- catch (_) { }
16062
- }
16063
- }
16064
- catch (_) { }
16065
- }
16066
- }
16067
- return {
16068
- className,
16069
- queryJson: JSON.stringify(queryInput),
16070
- shapeJson: JSON.stringify(metadata),
16071
- };
16072
- }
16073
- /**
16074
- * Parse raw model query/subscription result JSON into typed model instances.
16075
- * Used by ModelQueryBuilder to convert subscription updates without circular imports.
16076
- * @internal
16077
- */
16078
- static parseModelResult(perspective, raw, include, properties) {
16079
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
16080
- const arr = data.instances || data;
16081
- if (!Array.isArray(arr))
16082
- return [];
16083
- return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
16084
- }
16085
- /**
16086
- * Resolve non-literal (file-language) properties on an array of already-constructed
16087
- * model instances. Handles two cases:
16088
- *
16089
- * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
16090
- * 2. The Rust executor already resolved the expression and returned a `FileData` object
16091
- * (happens when the perspective backend eagerly fetches file content) → apply transform
16092
- * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
16093
- * synthesised model classes).
16094
- *
16095
- * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
16096
- * duplicating logic or introducing a circular dependency.
16097
- * @internal
16098
- */
16099
- static async resolveNonLiteralProps(perspective, instances) {
16100
- const propsMeta = getPropertiesMetadata(this);
16101
- const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
16102
- opts.resolveLanguage !== 'literal');
16103
- if (resolveProps.length === 0)
16104
- return;
16105
- await Promise.all(instances.map(async (inst) => {
16106
- for (const [propName, opts] of resolveProps) {
16107
- const val = inst[propName];
16108
- const transform = opts.transform;
16109
- const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
16110
- if (typeof val === 'string' && val && !val.startsWith('literal:')) {
16111
- // Case 1: raw URI — fetch from language runtime
16112
- try {
16113
- const expression = await perspective.getExpression(val);
16114
- if (expression) {
16115
- let resolved;
16116
- try {
16117
- resolved = JSON.parse(expression.data);
16118
- }
16119
- catch {
16120
- resolved = expression.data;
16121
- }
16122
- inst[propName] = applyTransform(resolved);
16123
- }
16124
- }
16125
- catch (_) { /* resolution failed — keep raw value */ }
16126
- }
16127
- else if (val !== null && val !== undefined && typeof val === 'object') {
16128
- // Case 2: already resolved by Rust — apply transform / default decode
16129
- inst[propName] = applyTransform(val);
16130
- }
16131
- }
16132
- }));
16133
- }
16134
- // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
16135
- /**
16136
- * Execute a model query via the executor-side endpoint.
16137
- *
16138
- * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
16139
- * with a single RPC to the executor that handles everything in Rust.
16140
- *
16141
- * @internal
16142
- */
16143
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
16144
16099
  const metadata = this.getModelMetadata();
16145
16100
  const className = classNameOverride || metadata.className;
16146
16101
  // Expand includeAll: true to a full IncludeMap covering every forward relation.
16147
- // Done before queryInput is built so all downstream uses of query.include see the expansion.
16148
16102
  if (query.includeAll) {
16149
16103
  const allRelMeta = getRelationsMetadata(this);
16150
16104
  const expanded = {};
@@ -16153,11 +16107,8 @@ class Ad4mModel {
16153
16107
  expanded[relName] = true;
16154
16108
  }
16155
16109
  }
16156
- // Explicit include entries take precedence over the expansion
16157
16110
  query = { ...query, include: { ...expanded, ...query.include } };
16158
16111
  }
16159
- // Build the query input that the Rust endpoint expects.
16160
- // Convert the TS Query type to the executor's ModelQueryInput format.
16161
16112
  const queryInput = {};
16162
16113
  if (query.parent) {
16163
16114
  const parentPredicate = resolveParentPredicate(query.parent, this);
@@ -16181,19 +16132,23 @@ class Ad4mModel {
16181
16132
  if (Object.keys(normalIncludes).length > 0)
16182
16133
  queryInput.include = normalIncludes;
16183
16134
  if (Object.keys(projections).length > 0) {
16184
- // Enrich projections with target shapes so Rust can apply where clause filtering
16135
+ // Tag each projection with its target class name so the executor can
16136
+ // resolve the target shape through its in-memory cache when applying
16137
+ // projection where-clause filters.
16185
16138
  const allRelMeta = getRelationsMetadata(this);
16186
16139
  for (const [, proj] of Object.entries(projections)) {
16187
16140
  const relMeta = allRelMeta[proj.from];
16188
- if (!proj.targetShape && relMeta?.target) {
16141
+ if (!proj.targetClassName && relMeta?.target) {
16189
16142
  try {
16190
16143
  const TargetClass = relMeta.target();
16191
16144
  const targetMeta = TargetClass.getModelMetadata?.();
16192
- if (targetMeta) {
16193
- proj.targetShape = targetMeta;
16145
+ if (targetMeta?.className) {
16146
+ proj.targetClassName = targetMeta.className;
16194
16147
  }
16195
16148
  }
16196
- catch (_) { /* target class may not be available */ }
16149
+ catch (e) {
16150
+ console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e);
16151
+ }
16197
16152
  }
16198
16153
  }
16199
16154
  queryInput.projections = projections;
@@ -16202,7 +16157,6 @@ class Ad4mModel {
16202
16157
  if (query.where)
16203
16158
  queryInput.where = query.where;
16204
16159
  if (query.order) {
16205
- // Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
16206
16160
  queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
16207
16161
  }
16208
16162
  if (query.offset !== undefined)
@@ -16212,88 +16166,52 @@ class Ad4mModel {
16212
16166
  if (query.count !== undefined)
16213
16167
  queryInput.count = query.count;
16214
16168
  queryInput.deepQuery = query.deepQuery ?? true;
16215
- // Enrich relation metadata with target class shapes for Rust-side
16216
- // include resolution. This eliminates per-relation GraphQL round-trips
16217
- // by letting the Rust endpoint resolve includes in-process.
16218
- if (queryInput.include) {
16219
- const allRelMeta = getRelationsMetadata(this);
16220
- enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
16221
- }
16222
- // ── Pre-compute conformance getters for Rust-side evaluation ──────
16223
- // For each relation with a target class and filter !== false, compute
16224
- // the conformance getter SPARQL so Rust can evaluate it in-process
16225
- // (eliminating N × querySparql round-trips per instance).
16226
- // When a relation has a `where` clause, compile the where conditions
16227
- // into the getter SPARQL so Rust applies them during evaluation.
16228
- {
16229
- const allRelMeta = getRelationsMetadata(this);
16230
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16231
- const rel = relMeta;
16232
- if (rel.getter)
16233
- continue; // explicit getter already set
16234
- if (rel.direction === 'reverse')
16235
- continue; // reverse relations use reverse link lookup
16236
- if (rel.filter === false)
16237
- continue; // opt-out of conformance filtering
16238
- const meta = allRelMeta[relName];
16239
- if (!meta?.target)
16240
- continue;
16241
- try {
16242
- const TargetClass = meta.target();
16243
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16244
- if (filter) {
16245
- rel.getter = filter.getter;
16246
- }
16247
- // Attach where-clause metadata for Rust-side post-getter filtering.
16248
- // Property values are signed expression envelopes (literal:json:...)
16249
- // and cannot be matched by SPARQL FILTER on the raw IRI.
16250
- if (rel.where) {
16251
- try {
16252
- const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
16253
- if (targetMetadata) {
16254
- const predicates = {};
16255
- for (const propName of Object.keys(rel.where)) {
16256
- if (['id', 'author', 'timestamp'].includes(propName))
16257
- continue;
16258
- const propMeta = targetMetadata.properties[propName];
16259
- if (propMeta?.predicate) {
16260
- predicates[propName] = propMeta.predicate;
16261
- }
16262
- }
16263
- if (Object.keys(predicates).length > 0) {
16264
- rel.whereFilter = rel.where;
16265
- rel.wherePredicates = predicates;
16266
- }
16267
- }
16268
- }
16269
- catch (_) { /* target metadata unavailable */ }
16270
- }
16271
- }
16272
- catch (e) {
16273
- // Target class may not be available; skip silently
16274
- }
16275
- }
16276
- }
16277
- // Send shape metadata to the executor so it knows the model structure.
16278
- // This is more reliable than reading SHACL from the store because
16279
- // the TS decorators are the definitive source of truth.
16280
- const shapeJson = JSON.stringify(metadata);
16281
- const queryJson = JSON.stringify(queryInput);
16282
- const result = await perspective.modelQuery(className, queryJson, shapeJson);
16169
+ // Conformance getters, where filters, and target shapes for includes
16170
+ // are all resolved by the executor from the perspective's SHACL triples
16171
+ // — no client-side pre-computation is needed any more.
16172
+ return {
16173
+ className,
16174
+ queryJson: JSON.stringify(queryInput),
16175
+ metadata,
16176
+ };
16177
+ }
16178
+ /**
16179
+ * Parse raw model query/subscription result JSON into typed model instances.
16180
+ * Used by ModelQueryBuilder to convert subscription updates without circular imports.
16181
+ * @internal
16182
+ */
16183
+ static parseModelResult(perspective, raw, include, properties) {
16184
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
16185
+ const arr = data.instances || data;
16186
+ if (!Array.isArray(arr))
16187
+ return [];
16188
+ return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
16189
+ }
16190
+ // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
16191
+ /**
16192
+ * Execute a model query via the executor-side endpoint.
16193
+ *
16194
+ * This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
16195
+ * with a single RPC to the executor that handles everything in Rust.
16196
+ *
16197
+ * @internal
16198
+ */
16199
+ static async executeModelQuery(perspective, query = {}, classNameOverride) {
16200
+ // Delegate query input building to the shared prepareModelQueryParams
16201
+ // helper. The executor resolves the shape from SHACL server-side.
16202
+ const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16203
+ const result = await perspective.modelQuery(className, queryJson);
16283
16204
  // Convert JSON instances to model class instances, recursively constructing
16284
16205
  // class instances for any included relations resolved by Rust.
16285
16206
  const instances = result.instances.map((json) => {
16286
16207
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
16287
16208
  });
16288
- // Resolve non-literal expressions (e.g. file languages where the stored
16289
- // value is a content-addressed hash that must be fetched from the language
16290
- // runtime). The Rust endpoint may return either a raw target URI (string)
16291
- // or an already-resolved FileData object — both cases are handled here.
16292
- await this.resolveNonLiteralProps(perspective, instances);
16293
- // Take snapshots for dirty tracking
16294
- const snapshotRelations = queryInput.include;
16209
+ // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
16210
+ const snapshotRelations = query.include
16211
+ ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
16212
+ : undefined;
16295
16213
  for (const inst of instances) {
16296
- inst.takeSnapshot(snapshotRelations);
16214
+ inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
16297
16215
  }
16298
16216
  return {
16299
16217
  results: instances,
@@ -16305,15 +16223,14 @@ class Ad4mModel {
16305
16223
  *
16306
16224
  * @param perspective - The perspective to search in
16307
16225
  * @param query - Optional query parameters to filter results
16308
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
16226
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16227
+ * All queries now use the Rust SPARQL pipeline.
16309
16228
  * @returns Array of matching models
16310
16229
  *
16311
16230
  * @example
16312
16231
  * ```typescript
16313
- * // Get all recipes (uses SPARQL by default)
16314
16232
  * const allRecipes = await Recipe.findAll(perspective);
16315
16233
  *
16316
- * // Get recipes with specific criteria (uses SPARQL)
16317
16234
  * const recipes = await Recipe.findAll(perspective, {
16318
16235
  * where: {
16319
16236
  * name: "Pasta",
@@ -16322,16 +16239,14 @@ class Ad4mModel {
16322
16239
  * order: { createdAt: "DESC" },
16323
16240
  * limit: 10
16324
16241
  * });
16325
- *
16326
- * // Explicitly use Prolog (legacy, for backward compatibility)
16327
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
16328
16242
  * ```
16329
16243
  */
16330
- static async findAll(perspective, query = {}, _engine) {
16331
- if (query.properties && query.properties.length === 0) {
16244
+ static async findAll(perspective, query) {
16245
+ const q = (query ?? {});
16246
+ if (q.properties && q.properties.length === 0) {
16332
16247
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16333
16248
  }
16334
- const { results } = await this.executeModelQuery(perspective, query);
16249
+ const { results } = await this.executeModelQuery(perspective, q);
16335
16250
  return results;
16336
16251
  }
16337
16252
  /**
@@ -16341,7 +16256,7 @@ class Ad4mModel {
16341
16256
  *
16342
16257
  * @param perspective - The perspective to search in
16343
16258
  * @param query - Optional query parameters to filter results
16344
- * @param useSPARQL - Whether to use SPARQL (default: true) or Prolog (legacy)
16259
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16345
16260
  * @returns The first matching instance, or `null`
16346
16261
  *
16347
16262
  * @example
@@ -16354,8 +16269,8 @@ class Ad4mModel {
16354
16269
  * }
16355
16270
  * ```
16356
16271
  */
16357
- static async findOne(perspective, query = {}, _engine) {
16358
- const limitedQuery = { ...query, limit: 1 };
16272
+ static async findOne(perspective, query) {
16273
+ const limitedQuery = { ...(query ?? {}), limit: 1 };
16359
16274
  const results = await this.findAll(perspective, limitedQuery);
16360
16275
  return results[0] ?? null;
16361
16276
  }
@@ -16364,7 +16279,7 @@ class Ad4mModel {
16364
16279
  *
16365
16280
  * @param perspective - The perspective to search in
16366
16281
  * @param query - Optional query parameters to filter results
16367
- * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
16282
+ * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.
16368
16283
  * @returns Object containing results array and total count
16369
16284
  *
16370
16285
  * @example
@@ -16374,13 +16289,11 @@ class Ad4mModel {
16374
16289
  * limit: 10
16375
16290
  * });
16376
16291
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16377
- *
16378
- * // Use Prolog explicitly (legacy)
16379
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
16380
16292
  * ```
16381
16293
  */
16382
- static async findAllAndCount(perspective, query = {}, _engine) {
16383
- return await this.executeModelQuery(perspective, query);
16294
+ static async findAllAndCount(perspective, query) {
16295
+ const out = await this.executeModelQuery(perspective, (query ?? {}));
16296
+ return out;
16384
16297
  }
16385
16298
  /**
16386
16299
  * Helper function for pagination with explicit page size and number.
@@ -16399,10 +16312,10 @@ class Ad4mModel {
16399
16312
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16400
16313
  * ```
16401
16314
  */
16402
- static async paginate(perspective, pageSize, pageNumber, query, _engine) {
16403
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16315
+ static async paginate(perspective, pageSize, pageNumber, query) {
16316
+ const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16404
16317
  const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
16405
- return { results, totalCount, pageSize, pageNumber };
16318
+ return { results: results, totalCount, pageSize, pageNumber };
16406
16319
  }
16407
16320
  /**
16408
16321
  * Generates a SPARQL COUNT query for the model.
@@ -16429,8 +16342,8 @@ class Ad4mModel {
16429
16342
  * });
16430
16343
  * ```
16431
16344
  */
16432
- static async count(perspective, query = {}) {
16433
- const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
16345
+ static async count(perspective, query) {
16346
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
16434
16347
  return totalCount;
16435
16348
  }
16436
16349
  async setProperty(key, value, batchId) {
@@ -16741,27 +16654,10 @@ class Ad4mModel {
16741
16654
  if (instances.length === 0)
16742
16655
  return;
16743
16656
  const metadata = this.getModelMetadata();
16744
- // Pre-compute conformance getters so the shape sent to Rust includes them
16745
- const allRelMeta = getRelationsMetadata(this);
16746
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
16747
- const rel = relMeta;
16748
- if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
16749
- continue;
16750
- const meta = allRelMeta[relName];
16751
- if (!meta?.target)
16752
- continue;
16753
- try {
16754
- const TargetClass = meta.target();
16755
- const filter = buildConformanceFilter(meta.predicate, TargetClass);
16756
- if (filter)
16757
- rel.getter = filter.getter;
16758
- }
16759
- catch (_) { /* target class may not be available */ }
16760
- }
16761
- const shapeJson = JSON.stringify(metadata);
16762
16657
  const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
16763
- // Single RPC call evaluates all getters in-process on the executor
16764
- const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);
16658
+ // The executor reads getter SPARQL from the perspective's SHACL triples
16659
+ // (written by `addSdna`), so no shape JSON is shipped with the call.
16660
+ const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
16765
16661
  // Determine which property names were evaluated for snapshot sync
16766
16662
  const evaluatedPropertyNames = [];
16767
16663
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
@@ -17052,6 +16948,22 @@ class Ad4mModel {
17052
16948
  static async register(perspective) {
17053
16949
  await perspective.ensureSDNASubjectClass(this);
17054
16950
  }
16951
+ /**
16952
+ * Batch-registers multiple model classes on a perspective in a single RPC call.
16953
+ * This is significantly faster than calling `register()` on each model individually
16954
+ * because it eliminates N-1 round-trips and mutex acquisitions.
16955
+ *
16956
+ * @param perspective - The perspective to register the models on
16957
+ * @param models - Array of Ad4mModel subclasses to register
16958
+ *
16959
+ * @example
16960
+ * ```typescript
16961
+ * await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);
16962
+ * ```
16963
+ */
16964
+ static async registerAll(perspective, models) {
16965
+ await perspective.ensureSubjectClasses(models);
16966
+ }
17055
16967
  /**
17056
16968
  * Executes a set of model operations inside a single batch (transaction).
17057
16969
  *
@@ -17109,7 +17021,7 @@ class Ad4mModel {
17109
17021
  * ```
17110
17022
  */
17111
17023
  static query(perspective, query) {
17112
- return new ModelQueryBuilder(perspective, this, query);
17024
+ return new ModelQueryBuilder(perspective, this, (query ?? {}));
17113
17025
  }
17114
17026
  /**
17115
17027
  * Creates an Ad4mModel class from a JSON Schema definition.
@@ -17296,7 +17208,7 @@ var _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_a
17296
17208
  * for the respective functionality.
17297
17209
  */
17298
17210
  class Ad4mClient {
17299
- constructor(baseUrl, token, subscribe = true) {
17211
+ constructor(baseUrl, token, subscribe = true, options) {
17300
17212
  _Ad4mClient_baseUrl.set(this, void 0);
17301
17213
  _Ad4mClient_token.set(this, void 0);
17302
17214
  _Ad4mClient_apiClient.set(this, void 0);
@@ -17309,7 +17221,7 @@ class Ad4mClient {
17309
17221
  _Ad4mClient_aiClient.set(this, void 0);
17310
17222
  __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
17311
17223
  __classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
17312
- __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token), "f");
17224
+ __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
17313
17225
  __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17314
17226
  __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17315
17227
  __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
@@ -17518,6 +17430,71 @@ class PerspectiveHandle {
17518
17430
  }
17519
17431
  }
17520
17432
 
17433
+ /**
17434
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
17435
+ *
17436
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
17437
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
17438
+ * RDF store the bindings are still in encoded form; consumers must decode
17439
+ * before use. The helpers here centralise that decode step so each call site
17440
+ * can pick the variant matching its declared binding type.
17441
+ *
17442
+ * @example
17443
+ * ```ts
17444
+ * interface MessageBinding {
17445
+ * id: string;
17446
+ * timestamp: string; // raw literal — decode with parseLitNumber
17447
+ * body?: string; // raw literal — decode with parseLit
17448
+ * }
17449
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
17450
+ * const ts = parseLitNumber(rows[0].timestamp); // number
17451
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
17452
+ * ```
17453
+ */
17454
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
17455
+ function parseSparqlCount(result) {
17456
+ if (!result || result.length === 0)
17457
+ return 0;
17458
+ const raw = result[0].count;
17459
+ const n = parseInt(raw, 10);
17460
+ return Number.isNaN(n) ? 0 : n;
17461
+ }
17462
+ /**
17463
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
17464
+ *
17465
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
17466
+ * input. Falls through to the raw value if decoding fails (defensive — the
17467
+ * binding may already be a plain string for unwrapped properties).
17468
+ */
17469
+ function parseLit(val) {
17470
+ if (val === undefined || val === null || val === '')
17471
+ return '';
17472
+ try {
17473
+ const result = Literal.fromUrl(val).get();
17474
+ if (result && typeof result === 'object') {
17475
+ return result.data ?? JSON.stringify(result);
17476
+ }
17477
+ return String(result);
17478
+ }
17479
+ catch {
17480
+ return val;
17481
+ }
17482
+ }
17483
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
17484
+ function parseLitNumber(val) {
17485
+ if (val === undefined || val === null || val === '')
17486
+ return 0;
17487
+ const decoded = parseLit(val);
17488
+ const n = Number(decoded);
17489
+ return Number.isNaN(n) ? 0 : n;
17490
+ }
17491
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
17492
+ function parseLitBoolean(val) {
17493
+ if (val === undefined || val === null || val === '')
17494
+ return false;
17495
+ return parseLit(val) === 'true';
17496
+ }
17497
+
17521
17498
  /**
17522
17499
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
17523
17500
  *
@@ -17617,10 +17594,11 @@ class WakerSubscriptionManager {
17617
17594
  const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
17618
17595
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
17619
17596
  const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
17620
- if (Array.isArray(parentResult)) {
17621
- for (const link of parentResult) {
17622
- if (link && link.source) {
17623
- parents.push(link.source);
17597
+ const bindings = parentResult?.results?.bindings;
17598
+ if (Array.isArray(bindings)) {
17599
+ for (const binding of bindings) {
17600
+ if (binding?.source?.value) {
17601
+ parents.push(binding.source.value);
17624
17602
  }
17625
17603
  }
17626
17604
  }
@@ -17803,6 +17781,195 @@ function isIncludeProjection(val) {
17803
17781
  return typeof val === 'object' && val !== null && 'from' in val;
17804
17782
  }
17805
17783
 
17784
+ /**
17785
+ * Shared query compilation utilities.
17786
+ *
17787
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
17788
+ * the compile-time SHACL generator (`decorators.ts`).
17789
+ *
17790
+ * All output uses native SPARQL syntax.
17791
+ */
17792
+ /**
17793
+ * Format a JavaScript value for embedding in a query expression.
17794
+ *
17795
+ * - Strings are single-quoted with backslash / quote / newline escaping
17796
+ * - Numbers and booleans are passed through as-is
17797
+ * - Arrays are recursed
17798
+ */
17799
+ function formatQueryValue(value) {
17800
+ if (typeof value === 'string') {
17801
+ // Escape backslashes first, then single quotes and other special characters
17802
+ const escaped = value
17803
+ .replace(/\\/g, '\\\\') // Backslash -> \\
17804
+ .replace(/'/g, "\\'") // Single quote -> \'
17805
+ .replace(/"/g, '\\"') // Double quote -> \"
17806
+ .replace(/\n/g, '\\n') // Newline -> \n
17807
+ .replace(/\r/g, '\\r') // Carriage return -> \r
17808
+ .replace(/\t/g, '\\t'); // Tab -> \t
17809
+ return `'${escaped}'`;
17810
+ }
17811
+ else if (typeof value === 'number' || typeof value === 'boolean') {
17812
+ return String(value);
17813
+ }
17814
+ else if (Array.isArray(value)) {
17815
+ return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
17816
+ }
17817
+ else {
17818
+ return String(value);
17819
+ }
17820
+ }
17821
+ /**
17822
+ * Compile a single Where condition for a property into a SPARQL triple pattern
17823
+ * that can be embedded in a getter's WHERE clause.
17824
+ *
17825
+ * The generated pattern operates on `?target` — e.g.:
17826
+ * `?target <pred> <value> .`
17827
+ * `FILTER EXISTS { ?target <pred> ?_v0 }`
17828
+ *
17829
+ * @param predicate - The predicate URI for the property
17830
+ * @param condition - The Where condition value
17831
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
17832
+ * @returns A single SPARQL condition string
17833
+ */
17834
+ function buildWhereCondition(predicate, condition, opts) {
17835
+ const escapedPredicate = escapeQueryString(predicate);
17836
+ // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
17837
+ // For language-resolved properties, we match against the plain URI
17838
+ // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
17839
+ // For language-resolved properties, values are plain URIs
17840
+ const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
17841
+ const varSuffix = opts?.varIndex ?? 0;
17842
+ function formatValue(v) {
17843
+ if (typeof v === 'string') {
17844
+ return isLiteral
17845
+ ? `<literal:string:${escapeQueryString(v)}>`
17846
+ : `<${escapeQueryString(v)}>`;
17847
+ }
17848
+ // Numbers/booleans — also stored as literal:string: in AD4M
17849
+ return `<literal:string:${v}>`;
17850
+ }
17851
+ /**
17852
+ * For literal properties, generate a FILTER-based match that handles both
17853
+ * the raw value and the literal-encoded value. This mirrors the Rust
17854
+ * `build_projection_where_patterns` approach which uses:
17855
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
17856
+ * This is more robust than exact IRI matching because it handles edge cases
17857
+ * where the stored format might vary.
17858
+ */
17859
+ function formatLiteralFilter(varName, v) {
17860
+ const raw = escapeQueryString(String(v));
17861
+ const encoded = encodeURIComponent(String(v))
17862
+ .replace(/!/g, '%21')
17863
+ .replace(/'/g, '%27')
17864
+ .replace(/\(/g, '%28')
17865
+ .replace(/\)/g, '%29')
17866
+ .replace(/\*/g, '%2A');
17867
+ if (typeof v === 'string') {
17868
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
17869
+ }
17870
+ else if (typeof v === 'number') {
17871
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
17872
+ }
17873
+ else if (typeof v === 'boolean') {
17874
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
17875
+ }
17876
+ return `FILTER(STR(${varName}) = "${raw}")`;
17877
+ }
17878
+ if (Array.isArray(condition)) {
17879
+ // Array values → FILTER IN
17880
+ if (isLiteral) {
17881
+ const varName = `?_wc${varSuffix}`;
17882
+ const inValues = condition.flatMap(v => {
17883
+ const raw = escapeQueryString(String(v));
17884
+ const encoded = encodeURIComponent(String(v))
17885
+ .replace(/!/g, '%21').replace(/'/g, '%27')
17886
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
17887
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
17888
+ }).join(', ');
17889
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
17890
+ }
17891
+ const formattedValues = condition.map(formatValue).join(', ');
17892
+ return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
17893
+ }
17894
+ else if (typeof condition === 'object' && condition !== null) {
17895
+ // Operator object
17896
+ const ops = condition;
17897
+ const parts = [];
17898
+ if (ops.not !== undefined) {
17899
+ if (Array.isArray(ops.not)) {
17900
+ const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
17901
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17902
+ // so O(N²) behavior is bounded by the number of values for this property.
17903
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
17904
+ }
17905
+ else {
17906
+ // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
17907
+ // so O(N²) behavior is bounded by the number of values for this property.
17908
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
17909
+ }
17910
+ }
17911
+ // Comparison operators — ensure property exists
17912
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
17913
+ ops.lt !== undefined || ops.lte !== undefined ||
17914
+ ops.between !== undefined || ops.contains !== undefined;
17915
+ if (hasComparisonOps) {
17916
+ parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
17917
+ }
17918
+ return parts.join(' ');
17919
+ }
17920
+ else {
17921
+ // Simple equality
17922
+ if (isLiteral) {
17923
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
17924
+ // to handle both raw values and literal-encoded IRIs robustly.
17925
+ const varName = `?_wc${varSuffix}`;
17926
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
17927
+ }
17928
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
17929
+ }
17930
+ }
17931
+ /**
17932
+ * Compile a full `Where` clause to an array of SPARQL condition strings.
17933
+ *
17934
+ * When `metadata` is provided, property names are resolved to predicates
17935
+ * using the model's property metadata. When `metadata` is `null`, property
17936
+ * names are treated as raw predicate URIs.
17937
+ *
17938
+ * Only handles **regular properties** — special fields (`id`, `author`,
17939
+ * `timestamp`) and relation fields are skipped (they are only relevant at
17940
+ * runtime query time, not for compile-time getter generation).
17941
+ */
17942
+ function compileWhereClause(where, metadata) {
17943
+ const conditions = [];
17944
+ for (const [propertyName, condition] of Object.entries(where)) {
17945
+ // Skip special fields that don't apply at compile time
17946
+ if (['id', 'author', 'timestamp'].includes(propertyName))
17947
+ continue;
17948
+ let predicate;
17949
+ let resolveLanguage;
17950
+ if (metadata) {
17951
+ const propMeta = metadata.properties[propertyName];
17952
+ if (propMeta) {
17953
+ predicate = propMeta.predicate;
17954
+ resolveLanguage = propMeta.resolveLanguage;
17955
+ }
17956
+ else {
17957
+ // Property not found in metadata — treat name as raw predicate URI
17958
+ predicate = propertyName;
17959
+ }
17960
+ }
17961
+ else {
17962
+ // No metadata — treat name as raw predicate URI
17963
+ predicate = propertyName;
17964
+ }
17965
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
17966
+ if (cond) {
17967
+ conditions.push(cond);
17968
+ }
17969
+ }
17970
+ return conditions;
17971
+ }
17972
+
17806
17973
  class Neighbourhood {
17807
17974
  constructor(linkLanguage, meta) {
17808
17975
  this.linkLanguage = linkLanguage;
@@ -17835,6 +18002,112 @@ class ModelInput {
17835
18002
  class VoiceActivityParamsInput {
17836
18003
  }
17837
18004
 
18005
+ /**
18006
+ * Builder functions for SHACL-AF Node Expressions.
18007
+ *
18008
+ * These functions construct JSON-serializable expression trees for property transforms.
18009
+ * All builders return frozen objects to prevent accidental mutation.
18010
+ */
18011
+ /**
18012
+ * Identity expression: pass the focus node through unchanged.
18013
+ */
18014
+ function focus() {
18015
+ return Object.freeze({ type: 'focus' });
18016
+ }
18017
+ /**
18018
+ * Literal constant expression.
18019
+ */
18020
+ function literal(value) {
18021
+ return Object.freeze({ type: 'literal', value });
18022
+ }
18023
+ /**
18024
+ * Path expression: navigate to a property on the resolved object.
18025
+ * The predicate can be a full IRI (e.g., "file_storage://data_base64")
18026
+ * or a simple property name. The Rust evaluator will strip the namespace.
18027
+ */
18028
+ function path(predicate) {
18029
+ return Object.freeze({ type: 'path', predicate });
18030
+ }
18031
+ /**
18032
+ * Existence check: returns true if the inner expression is non-null and non-empty.
18033
+ */
18034
+ function exists(expr) {
18035
+ return Object.freeze({ type: 'exists', expr });
18036
+ }
18037
+ /**
18038
+ * Conditional expression with optional else branch.
18039
+ * Returns a chainable builder that supports `.then()` and `.else()`.
18040
+ */
18041
+ function ifExpr(cond) {
18042
+ return {
18043
+ then: (thenExpr) => ({
18044
+ else: (elseExpr) => {
18045
+ return Object.freeze({
18046
+ type: 'if',
18047
+ cond,
18048
+ then: thenExpr,
18049
+ ...(elseExpr !== undefined && { else: elseExpr }),
18050
+ });
18051
+ },
18052
+ // Allow chaining without explicit else()
18053
+ toExpression: () => Object.freeze({
18054
+ type: 'if',
18055
+ cond,
18056
+ then: thenExpr,
18057
+ }),
18058
+ }),
18059
+ };
18060
+ }
18061
+ /**
18062
+ * String concatenation: joins evaluated arguments as strings.
18063
+ * Null/undefined arguments are skipped.
18064
+ */
18065
+ function concat(...args) {
18066
+ return Object.freeze({ type: 'concat', args });
18067
+ }
18068
+ /**
18069
+ * Coalesce: returns the first non-null evaluated argument.
18070
+ */
18071
+ function coalesce(...args) {
18072
+ return Object.freeze({ type: 'coalesce', args });
18073
+ }
18074
+ /**
18075
+ * Function call: invoke a named transform function by IRI.
18076
+ * Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
18077
+ */
18078
+ function fn(iri, args = []) {
18079
+ return Object.freeze({ type: 'function', iri, args });
18080
+ }
18081
+
18082
+ /**
18083
+ * SHACL-AF Transform DSL — public API
18084
+ *
18085
+ * Re-exports builder functions and provides common built-in transforms.
18086
+ */
18087
+ /**
18088
+ * Built-in transform: FileData → data: URI
18089
+ *
18090
+ * Converts a file stored via FILE_STORAGE_LANGUAGE into a data: URL.
18091
+ * If the object has a `data_base64` field, returns:
18092
+ * `data:{file_type};base64,{data_base64}`
18093
+ * Otherwise passes through the input unchanged.
18094
+ *
18095
+ * This is the Rust equivalent of the JS `defaultFileDecode` function.
18096
+ *
18097
+ * Usage:
18098
+ * ```typescript
18099
+ * @Property({
18100
+ * through: 'we://image',
18101
+ * resolveLanguage: FILE_STORAGE_LANGUAGE,
18102
+ * transform: fileToDataUri,
18103
+ * })
18104
+ * avatar?: string;
18105
+ * ```
18106
+ */
18107
+ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
18108
+ .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
18109
+ .else(focus());
18110
+
17838
18111
  exports.AIClient = AIClient;
17839
18112
  exports.AIModel = Model;
17840
18113
  exports.AIModelLoadingStatus = AIModelLoadingStatus;
@@ -17944,17 +18217,22 @@ exports.buildModelFromJSONSchema = buildModelFromJSONSchema;
17944
18217
  exports.buildPaginationSubquery = buildPaginationSubquery;
17945
18218
  exports.buildSDNA = buildSDNA;
17946
18219
  exports.buildSHACL = buildSHACL;
17947
- exports.buildSPARQLOrderLimitOffset = buildSPARQLOrderLimitOffset;
17948
18220
  exports.buildSPARQLQuery = buildSPARQLQuery;
17949
18221
  exports.buildWhereCondition = buildWhereCondition;
17950
18222
  exports.capSentence = capSentence;
17951
18223
  exports.clearQueryCache = clearQueryCache;
18224
+ exports.coalesce = coalesce;
17952
18225
  exports.compileWhereClause = compileWhereClause;
18226
+ exports.concat = concat;
17953
18227
  exports.createPersistentCache = createPersistentCache;
17954
18228
  exports.determineNamespace = determineNamespace;
17955
18229
  exports.determinePredicate = determinePredicate;
17956
18230
  exports.escapeQueryString = escapeQueryString;
18231
+ exports.exists = exists;
17957
18232
  exports.exprRef2String = exprRef2String;
18233
+ exports.fileToDataUri = fileToDataUri;
18234
+ exports.fn = fn;
18235
+ exports.focus = focus;
17958
18236
  exports.formatList = formatList;
17959
18237
  exports.formatQueryValue = formatQueryValue;
17960
18238
  exports.formatSPARQLValue = formatSPARQLValue;
@@ -17965,19 +18243,27 @@ exports.getPropertiesMetadata = getPropertiesMetadata;
17965
18243
  exports.getPropertyOption = getPropertyOption;
17966
18244
  exports.getRelationsMetadata = getRelationsMetadata;
17967
18245
  exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
18246
+ exports.ifExpr = ifExpr;
17968
18247
  exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
17969
18248
  exports.isArrayType = isArrayType;
17970
18249
  exports.isExpression = isExpression;
17971
18250
  exports.isIncludeProjection = isIncludeProjection;
17972
18251
  exports.isLink = isLink;
18252
+ exports.isNodeExpression = isNodeExpression;
17973
18253
  exports.isNumericType = isNumericType;
17974
18254
  exports.isObjectType = isObjectType;
17975
18255
  exports.isSchemaType = isSchemaType;
17976
18256
  exports.linkEqual = linkEqual;
18257
+ exports.literal = literal;
17977
18258
  exports.normalizeNamespaceString = normalizeNamespaceString;
17978
18259
  exports.normalizeSchemaType = normalizeSchemaType;
17979
18260
  exports.normalizeValue = normalizeValue;
17980
18261
  exports.parseExprUrl = parseExprUrl;
18262
+ exports.parseLit = parseLit;
18263
+ exports.parseLitBoolean = parseLitBoolean;
18264
+ exports.parseLitNumber = parseLitNumber;
18265
+ exports.parseSparqlCount = parseSparqlCount;
18266
+ exports.path = path;
17981
18267
  exports.queryCacheSize = queryCacheSize;
17982
18268
  exports.resolveParentPredicate = resolveParentPredicate;
17983
18269
  exports.setCachedResult = setCachedResult;