@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +825 -653
- package/lib/index.js +812 -654
- package/lib/src/Ad4mClient.d.ts +1 -0
- package/lib/src/Ad4mClient.js +1 -1
- package/lib/src/ai/AIClient.js +1 -1
- package/lib/src/apiClient.d.ts +4 -1
- package/lib/src/apiClient.js +6 -1
- package/lib/src/index.d.ts +4 -0
- package/lib/src/index.js +4 -0
- package/lib/src/model/Ad4mModel.d.ts +9 -32
- package/lib/src/model/Ad4mModel.js +36 -266
- package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
- package/lib/src/model/ModelQueryBuilder.js +20 -36
- package/lib/src/model/decorators.d.ts +7 -4
- package/lib/src/model/shacl-gen.js +120 -47
- package/lib/src/model/types.d.ts +140 -4
- package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
- package/lib/src/perspectives/PerspectiveClient.js +5 -6
- package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
- package/lib/src/perspectives/PerspectiveProxy.js +10 -9
- package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
- package/lib/src/perspectives/SparqlBindings.js +65 -0
- package/lib/src/shacl/NodeExpression.d.ts +44 -0
- package/lib/src/shacl/NodeExpression.js +39 -0
- package/lib/src/shacl/SHACLShape.d.ts +23 -0
- package/lib/src/shacl/SHACLShape.js +115 -1
- package/lib/src/shacl/builders.d.ts +58 -0
- package/lib/src/shacl/builders.js +76 -0
- package/lib/src/shacl/index.d.ts +36 -0
- package/lib/src/shacl/index.js +33 -0
- package/package.json +8 -11
- package/src/Ad4mClient.ts +2 -2
- package/src/ai/AIClient.ts +1 -1
- package/src/apiClient.ts +8 -1
- package/src/index.ts +4 -0
- package/src/model/Ad4mModel.test.ts +33 -74
- package/src/model/Ad4mModel.ts +54 -272
- package/src/model/ModelQueryBuilder.ts +29 -46
- package/src/model/decorators.ts +7 -4
- package/src/model/relation-filtering.test.ts +46 -39
- package/src/model/shacl-gen.ts +128 -54
- package/src/model/shacl-roundtrip.test.ts +197 -0
- package/src/model/types-typed-query.test.ts +360 -0
- package/src/model/types.ts +196 -4
- package/src/perspectives/PerspectiveClient.ts +6 -8
- package/src/perspectives/PerspectiveProxy.ts +13 -13
- package/src/perspectives/SparqlBindings.ts +79 -0
- package/src/shacl/NodeExpression.ts +54 -0
- package/src/shacl/SHACLShape.test.ts +172 -0
- package/src/shacl/SHACLShape.ts +173 -1
- package/src/shacl/builders.ts +86 -0
- package/src/shacl/index.ts +72 -0
package/lib/index.js
CHANGED
|
@@ -19,7 +19,7 @@ function nextId() {
|
|
|
19
19
|
return String(++_idCounter);
|
|
20
20
|
}
|
|
21
21
|
class ApiClient {
|
|
22
|
-
constructor(baseUrl, token, webSocketImpl) {
|
|
22
|
+
constructor(baseUrl, token, webSocketImpl, fetchImpl) {
|
|
23
23
|
// ── WebSocket RPC core ──────────────────────────────────────────────────
|
|
24
24
|
this._ws = null;
|
|
25
25
|
this._wsCallbacks = new Set();
|
|
@@ -33,9 +33,14 @@ class ApiClient {
|
|
|
33
33
|
this.baseUrl = baseUrl;
|
|
34
34
|
this.token = token;
|
|
35
35
|
this._webSocketImpl = webSocketImpl;
|
|
36
|
+
this._fetchImpl = fetchImpl;
|
|
36
37
|
}
|
|
37
38
|
getBaseUrl() { return this.baseUrl; }
|
|
38
39
|
getToken() { return this.token; }
|
|
40
|
+
/** Perform an HTTP request, using an injected fetch implementation if provided. */
|
|
41
|
+
doFetch(url, init) {
|
|
42
|
+
return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init);
|
|
43
|
+
}
|
|
39
44
|
setToken(token) {
|
|
40
45
|
this.token = token;
|
|
41
46
|
}
|
|
@@ -954,6 +959,46 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
|
|
|
954
959
|
};
|
|
955
960
|
}
|
|
956
961
|
|
|
962
|
+
/**
|
|
963
|
+
* SHACL-AF Node Expressions for property transforms.
|
|
964
|
+
*
|
|
965
|
+
* A `NodeExpression` is a JSON-serializable tree that describes how to transform
|
|
966
|
+
* a resolved property value. Unlike JS lambdas, these are portable, inspectable,
|
|
967
|
+
* and can be executed in the Rust model query engine.
|
|
968
|
+
*
|
|
969
|
+
* Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
|
|
970
|
+
*/
|
|
971
|
+
/**
|
|
972
|
+
* Type guard to check if a value is a valid NodeExpression.
|
|
973
|
+
*/
|
|
974
|
+
function isNodeExpression(v) {
|
|
975
|
+
if (typeof v !== 'object' || v === null)
|
|
976
|
+
return false;
|
|
977
|
+
const obj = v;
|
|
978
|
+
const type = obj.type;
|
|
979
|
+
switch (type) {
|
|
980
|
+
case 'focus':
|
|
981
|
+
return typeof obj.type === 'string';
|
|
982
|
+
case 'literal':
|
|
983
|
+
return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
|
|
984
|
+
case 'path':
|
|
985
|
+
return typeof obj.predicate === 'string';
|
|
986
|
+
case 'exists':
|
|
987
|
+
return isNodeExpression(obj.expr);
|
|
988
|
+
case 'if':
|
|
989
|
+
return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
|
|
990
|
+
(obj.else === undefined || isNodeExpression(obj.else));
|
|
991
|
+
case 'concat':
|
|
992
|
+
return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
|
|
993
|
+
case 'coalesce':
|
|
994
|
+
return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
|
|
995
|
+
case 'function':
|
|
996
|
+
return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
|
|
997
|
+
default:
|
|
998
|
+
return false;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
|
|
957
1002
|
/**
|
|
958
1003
|
* Extract namespace from a URI
|
|
959
1004
|
* Examples:
|
|
@@ -1284,7 +1329,7 @@ class SHACLShape {
|
|
|
1284
1329
|
target: `literal:${prop.writable}`
|
|
1285
1330
|
});
|
|
1286
1331
|
}
|
|
1287
|
-
if (prop.resolveLanguage) {
|
|
1332
|
+
if (prop.resolveLanguage != null) {
|
|
1288
1333
|
links.push({
|
|
1289
1334
|
source: propShapeId,
|
|
1290
1335
|
predicate: "ad4m://resolveLanguage",
|
|
@@ -1341,6 +1386,48 @@ class SHACLShape {
|
|
|
1341
1386
|
target: `literal:string:${JSON.stringify(prop.in)}`
|
|
1342
1387
|
});
|
|
1343
1388
|
}
|
|
1389
|
+
if (prop.relationKind) {
|
|
1390
|
+
links.push({
|
|
1391
|
+
source: propShapeId,
|
|
1392
|
+
predicate: "ad4m://relationKind",
|
|
1393
|
+
target: `literal:string:${prop.relationKind}`
|
|
1394
|
+
});
|
|
1395
|
+
}
|
|
1396
|
+
if (prop.targetClassName) {
|
|
1397
|
+
links.push({
|
|
1398
|
+
source: propShapeId,
|
|
1399
|
+
predicate: "ad4m://targetClassName",
|
|
1400
|
+
target: `literal:string:${prop.targetClassName}`
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
|
|
1404
|
+
links.push({
|
|
1405
|
+
source: propShapeId,
|
|
1406
|
+
predicate: "ad4m://whereFilter",
|
|
1407
|
+
target: `literal:string:${JSON.stringify(prop.whereFilter)}`
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
|
|
1411
|
+
links.push({
|
|
1412
|
+
source: propShapeId,
|
|
1413
|
+
predicate: "ad4m://wherePredicates",
|
|
1414
|
+
target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
if (prop.filter !== undefined) {
|
|
1418
|
+
links.push({
|
|
1419
|
+
source: propShapeId,
|
|
1420
|
+
predicate: "ad4m://filter",
|
|
1421
|
+
target: `literal:${prop.filter}`
|
|
1422
|
+
});
|
|
1423
|
+
}
|
|
1424
|
+
if (prop.transform && typeof prop.transform === 'object') {
|
|
1425
|
+
links.push({
|
|
1426
|
+
source: propShapeId,
|
|
1427
|
+
predicate: "ad4m://transform",
|
|
1428
|
+
target: `literal:string:${JSON.stringify(prop.transform)}`
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1344
1431
|
}
|
|
1345
1432
|
return links;
|
|
1346
1433
|
}
|
|
@@ -1522,6 +1609,60 @@ class SHACLShape {
|
|
|
1522
1609
|
// Ignore parse errors
|
|
1523
1610
|
}
|
|
1524
1611
|
}
|
|
1612
|
+
const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
|
|
1613
|
+
if (relationKindLink) {
|
|
1614
|
+
const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1615
|
+
if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
|
|
1616
|
+
prop.relationKind = val;
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
|
|
1620
|
+
if (targetClassNameLink) {
|
|
1621
|
+
prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1622
|
+
}
|
|
1623
|
+
const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
|
|
1624
|
+
if (whereFilterLink) {
|
|
1625
|
+
try {
|
|
1626
|
+
const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1627
|
+
prop.whereFilter = JSON.parse(jsonStr);
|
|
1628
|
+
}
|
|
1629
|
+
catch (e) {
|
|
1630
|
+
// Ignore parse errors
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
|
|
1634
|
+
if (wherePredicatesLink) {
|
|
1635
|
+
try {
|
|
1636
|
+
const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1637
|
+
prop.wherePredicates = JSON.parse(jsonStr);
|
|
1638
|
+
}
|
|
1639
|
+
catch (e) {
|
|
1640
|
+
// Ignore parse errors
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
|
|
1644
|
+
if (filterLink) {
|
|
1645
|
+
let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
1646
|
+
if (val.startsWith('boolean:'))
|
|
1647
|
+
val = val.substring(8);
|
|
1648
|
+
prop.filter = val === 'true';
|
|
1649
|
+
}
|
|
1650
|
+
const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
|
|
1651
|
+
if (transformLink) {
|
|
1652
|
+
const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1653
|
+
try {
|
|
1654
|
+
const parsed = JSON.parse(jsonStr);
|
|
1655
|
+
if (!isNodeExpression(parsed)) {
|
|
1656
|
+
throw new Error(`Invalid transform for property ${propShapeId}: ` +
|
|
1657
|
+
`payload is not a valid NodeExpression. Received: ${jsonStr}`);
|
|
1658
|
+
}
|
|
1659
|
+
prop.transform = parsed;
|
|
1660
|
+
}
|
|
1661
|
+
catch (e) {
|
|
1662
|
+
throw new Error(`Failed to deserialize transform for property ${propShapeId}: ` +
|
|
1663
|
+
`${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`);
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1525
1666
|
shape.addProperty(prop);
|
|
1526
1667
|
}
|
|
1527
1668
|
return shape;
|
|
@@ -1558,6 +1699,12 @@ class SHACLShape {
|
|
|
1558
1699
|
conformance_conditions: p.conformanceConditions,
|
|
1559
1700
|
class: p.class,
|
|
1560
1701
|
in: p.in,
|
|
1702
|
+
relation_kind: p.relationKind,
|
|
1703
|
+
target_class_name: p.targetClassName,
|
|
1704
|
+
where_filter: p.whereFilter,
|
|
1705
|
+
where_predicates: p.wherePredicates,
|
|
1706
|
+
filter: p.filter,
|
|
1707
|
+
transform: p.transform,
|
|
1561
1708
|
})),
|
|
1562
1709
|
constructor_actions: this.constructor_actions,
|
|
1563
1710
|
destructor_actions: this.destructor_actions,
|
|
@@ -1571,6 +1718,11 @@ class SHACLShape {
|
|
|
1571
1718
|
? new SHACLShape(json.node_shape_uri, json.target_class)
|
|
1572
1719
|
: new SHACLShape(json.target_class);
|
|
1573
1720
|
for (const p of json.properties || []) {
|
|
1721
|
+
// Validate transform if present
|
|
1722
|
+
if (p.transform && !isNodeExpression(p.transform)) {
|
|
1723
|
+
throw new Error(`Invalid transform for property ${p.name}: ` +
|
|
1724
|
+
`payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`);
|
|
1725
|
+
}
|
|
1574
1726
|
shape.addProperty({
|
|
1575
1727
|
path: p.path,
|
|
1576
1728
|
name: p.name,
|
|
@@ -1592,6 +1744,12 @@ class SHACLShape {
|
|
|
1592
1744
|
conformanceConditions: p.conformance_conditions,
|
|
1593
1745
|
class: p.class,
|
|
1594
1746
|
in: p.in,
|
|
1747
|
+
relationKind: p.relation_kind,
|
|
1748
|
+
targetClassName: p.target_class_name,
|
|
1749
|
+
whereFilter: p.where_filter,
|
|
1750
|
+
wherePredicates: p.where_predicates,
|
|
1751
|
+
filter: p.filter,
|
|
1752
|
+
transform: p.transform,
|
|
1595
1753
|
});
|
|
1596
1754
|
}
|
|
1597
1755
|
if (json.constructor_actions) {
|
|
@@ -1609,303 +1767,61 @@ class SHACLShape {
|
|
|
1609
1767
|
}
|
|
1610
1768
|
}
|
|
1611
1769
|
|
|
1612
|
-
function formatList(list) {
|
|
1613
|
-
if (!list?.length) {
|
|
1614
|
-
return "";
|
|
1615
|
-
}
|
|
1616
|
-
if (list.length === 1) {
|
|
1617
|
-
return list.toString();
|
|
1618
|
-
}
|
|
1619
|
-
if (list.length === 2) {
|
|
1620
|
-
return list.join(' and ');
|
|
1621
|
-
}
|
|
1622
|
-
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
1623
|
-
}
|
|
1624
|
-
function capSentence(cap) {
|
|
1625
|
-
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
1626
|
-
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
1627
|
-
const pointers = cap.with.pointers.includes("*")
|
|
1628
|
-
? ["all AD4M data"]
|
|
1629
|
-
: cap.with.pointers;
|
|
1630
|
-
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
1631
|
-
}
|
|
1632
|
-
/**
|
|
1633
|
-
* Escapes a string value for safe use in query strings.
|
|
1634
|
-
*
|
|
1635
|
-
* @description
|
|
1636
|
-
* Prevents SQL injection by properly escaping special characters in string values
|
|
1637
|
-
* that will be interpolated into query strings. This handles the most common
|
|
1638
|
-
* special characters that could break SQL queries or enable injection attacks.
|
|
1639
|
-
*
|
|
1640
|
-
* Single quotes, backslashes, and other special characters are escaped using
|
|
1641
|
-
* backslash notation, which is the standard escaping mechanism for query.
|
|
1642
|
-
*
|
|
1643
|
-
* @param value - The string value to escape
|
|
1644
|
-
* @returns The escaped string safe for query interpolation (without surrounding quotes)
|
|
1645
|
-
*
|
|
1646
|
-
* @example
|
|
1647
|
-
* ```typescript
|
|
1648
|
-
* const userInput = "user's input with 'quotes'";
|
|
1649
|
-
* const escaped = escapeQueryString(userInput);
|
|
1650
|
-
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
1651
|
-
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
1652
|
-
* ```
|
|
1653
|
-
*/
|
|
1654
|
-
function escapeQueryString(value) {
|
|
1655
|
-
return value
|
|
1656
|
-
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
1657
|
-
.replace(/'/g, "\\'") // Single quote -> \'
|
|
1658
|
-
.replace(/"/g, '\\"') // Double quote -> \"
|
|
1659
|
-
.replace(/\n/g, '\\n') // Newline -> \n
|
|
1660
|
-
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
1661
|
-
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
1662
|
-
}
|
|
1663
|
-
|
|
1664
|
-
/**
|
|
1665
|
-
* Shared query compilation utilities.
|
|
1666
|
-
*
|
|
1667
|
-
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
1668
|
-
* the compile-time SHACL generator (`decorators.ts`).
|
|
1669
|
-
*
|
|
1670
|
-
* All output uses native SPARQL syntax.
|
|
1671
|
-
*/
|
|
1672
1770
|
/**
|
|
1673
|
-
*
|
|
1771
|
+
* SHACL shape generation for AD4M model classes.
|
|
1674
1772
|
*
|
|
1675
|
-
*
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1773
|
+
* Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
|
|
1774
|
+
* from a model's property and relation metadata. The heavy lifting used
|
|
1775
|
+
* to live inside the `@Model` decorator closure — it is extracted here so
|
|
1776
|
+
* decorators.ts stays focused on decorator registration logic.
|
|
1678
1777
|
*/
|
|
1679
|
-
function formatQueryValue(value) {
|
|
1680
|
-
if (typeof value === 'string') {
|
|
1681
|
-
// Escape backslashes first, then single quotes and other special characters
|
|
1682
|
-
const escaped = value
|
|
1683
|
-
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
1684
|
-
.replace(/'/g, "\\'") // Single quote -> \'
|
|
1685
|
-
.replace(/"/g, '\\"') // Double quote -> \"
|
|
1686
|
-
.replace(/\n/g, '\\n') // Newline -> \n
|
|
1687
|
-
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
1688
|
-
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
1689
|
-
return `'${escaped}'`;
|
|
1690
|
-
}
|
|
1691
|
-
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
1692
|
-
return String(value);
|
|
1693
|
-
}
|
|
1694
|
-
else if (Array.isArray(value)) {
|
|
1695
|
-
return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
|
|
1696
|
-
}
|
|
1697
|
-
else {
|
|
1698
|
-
return String(value);
|
|
1699
|
-
}
|
|
1700
|
-
}
|
|
1701
1778
|
/**
|
|
1702
|
-
*
|
|
1703
|
-
* that can be embedded in a getter's WHERE clause.
|
|
1704
|
-
*
|
|
1705
|
-
* The generated pattern operates on `?target` — e.g.:
|
|
1706
|
-
* `?target <pred> <value> .`
|
|
1707
|
-
* `FILTER EXISTS { ?target <pred> ?_v0 }`
|
|
1779
|
+
* Build a SHACL shape for a model class.
|
|
1708
1780
|
*
|
|
1709
|
-
* @param
|
|
1710
|
-
* @param
|
|
1711
|
-
*
|
|
1712
|
-
* @
|
|
1781
|
+
* @param subjectName - The model's registered name (from `@Model({ name })`)
|
|
1782
|
+
* @param target - The class constructor (used for prototype access,
|
|
1783
|
+
* inheritance chain, and relation target resolution)
|
|
1784
|
+
* @param properties - Merged property metadata (from `getPropertiesMetadata`)
|
|
1785
|
+
* @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
|
|
1786
|
+
* @param conformanceFilterFn - Injected conformance-filter builder
|
|
1787
|
+
* (avoids circular dependency back into decorators.ts)
|
|
1713
1788
|
*/
|
|
1714
|
-
function
|
|
1715
|
-
const
|
|
1716
|
-
//
|
|
1717
|
-
|
|
1718
|
-
//
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
: `<${escapeQueryString(v)}>`;
|
|
1789
|
+
function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
|
|
1790
|
+
const obj = target.prototype;
|
|
1791
|
+
// ── Determine namespace from first property or relation ─────────────
|
|
1792
|
+
let namespace = "ad4m://";
|
|
1793
|
+
// Try properties first
|
|
1794
|
+
if (Object.keys(properties).length > 0) {
|
|
1795
|
+
const firstProp = properties[Object.keys(properties)[0]];
|
|
1796
|
+
if (firstProp.through) {
|
|
1797
|
+
const match = firstProp.through.match(/^([^:]+:\/\/)/);
|
|
1798
|
+
if (match) {
|
|
1799
|
+
namespace = match[1];
|
|
1800
|
+
}
|
|
1727
1801
|
}
|
|
1728
|
-
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
1729
|
-
return `<literal:string:${v}>`;
|
|
1730
1802
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
function formatLiteralFilter(varName, v) {
|
|
1740
|
-
const raw = escapeQueryString(String(v));
|
|
1741
|
-
const encoded = encodeURIComponent(String(v))
|
|
1742
|
-
.replace(/!/g, '%21')
|
|
1743
|
-
.replace(/'/g, '%27')
|
|
1744
|
-
.replace(/\(/g, '%28')
|
|
1745
|
-
.replace(/\)/g, '%29')
|
|
1746
|
-
.replace(/\*/g, '%2A');
|
|
1747
|
-
if (typeof v === 'string') {
|
|
1748
|
-
return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
|
|
1749
|
-
}
|
|
1750
|
-
else if (typeof v === 'number') {
|
|
1751
|
-
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
|
|
1752
|
-
}
|
|
1753
|
-
else if (typeof v === 'boolean') {
|
|
1754
|
-
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
|
|
1803
|
+
// Fall back to relations if no properties
|
|
1804
|
+
else if (Object.keys(allRelationsMeta).length > 0) {
|
|
1805
|
+
const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
|
|
1806
|
+
if (firstRel.predicate) {
|
|
1807
|
+
const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
|
|
1808
|
+
if (match) {
|
|
1809
|
+
namespace = match[1];
|
|
1810
|
+
}
|
|
1755
1811
|
}
|
|
1756
|
-
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
1757
1812
|
}
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
}
|
|
1771
|
-
const formattedValues = condition.map(formatValue).join(', ');
|
|
1772
|
-
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
1773
|
-
}
|
|
1774
|
-
else if (typeof condition === 'object' && condition !== null) {
|
|
1775
|
-
// Operator object
|
|
1776
|
-
const ops = condition;
|
|
1777
|
-
const parts = [];
|
|
1778
|
-
if (ops.not !== undefined) {
|
|
1779
|
-
if (Array.isArray(ops.not)) {
|
|
1780
|
-
const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
|
|
1781
|
-
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
1782
|
-
// so O(N²) behavior is bounded by the number of values for this property.
|
|
1783
|
-
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
|
|
1784
|
-
}
|
|
1785
|
-
else {
|
|
1786
|
-
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
1787
|
-
// so O(N²) behavior is bounded by the number of values for this property.
|
|
1788
|
-
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
|
|
1789
|
-
}
|
|
1790
|
-
}
|
|
1791
|
-
// Comparison operators — ensure property exists
|
|
1792
|
-
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
1793
|
-
ops.lt !== undefined || ops.lte !== undefined ||
|
|
1794
|
-
ops.between !== undefined || ops.contains !== undefined;
|
|
1795
|
-
if (hasComparisonOps) {
|
|
1796
|
-
parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
|
|
1797
|
-
}
|
|
1798
|
-
return parts.join(' ');
|
|
1799
|
-
}
|
|
1800
|
-
else {
|
|
1801
|
-
// Simple equality
|
|
1802
|
-
if (isLiteral) {
|
|
1803
|
-
// Use FILTER matching (mirrors Rust build_projection_where_patterns)
|
|
1804
|
-
// to handle both raw values and literal-encoded IRIs robustly.
|
|
1805
|
-
const varName = `?_wc${varSuffix}`;
|
|
1806
|
-
return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
|
|
1807
|
-
}
|
|
1808
|
-
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
1809
|
-
}
|
|
1810
|
-
}
|
|
1811
|
-
/**
|
|
1812
|
-
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
1813
|
-
*
|
|
1814
|
-
* When `metadata` is provided, property names are resolved to predicates
|
|
1815
|
-
* using the model's property metadata. When `metadata` is `null`, property
|
|
1816
|
-
* names are treated as raw predicate URIs.
|
|
1817
|
-
*
|
|
1818
|
-
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
1819
|
-
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
1820
|
-
* runtime query time, not for compile-time getter generation).
|
|
1821
|
-
*/
|
|
1822
|
-
function compileWhereClause(where, metadata) {
|
|
1823
|
-
const conditions = [];
|
|
1824
|
-
for (const [propertyName, condition] of Object.entries(where)) {
|
|
1825
|
-
// Skip special fields that don't apply at compile time
|
|
1826
|
-
if (['id', 'author', 'timestamp'].includes(propertyName))
|
|
1827
|
-
continue;
|
|
1828
|
-
let predicate;
|
|
1829
|
-
let resolveLanguage;
|
|
1830
|
-
if (metadata) {
|
|
1831
|
-
const propMeta = metadata.properties[propertyName];
|
|
1832
|
-
if (propMeta) {
|
|
1833
|
-
predicate = propMeta.predicate;
|
|
1834
|
-
resolveLanguage = propMeta.resolveLanguage;
|
|
1835
|
-
}
|
|
1836
|
-
else {
|
|
1837
|
-
// Property not found in metadata — treat name as raw predicate URI
|
|
1838
|
-
predicate = propertyName;
|
|
1839
|
-
}
|
|
1840
|
-
}
|
|
1841
|
-
else {
|
|
1842
|
-
// No metadata — treat name as raw predicate URI
|
|
1843
|
-
predicate = propertyName;
|
|
1844
|
-
}
|
|
1845
|
-
const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
|
|
1846
|
-
if (cond) {
|
|
1847
|
-
conditions.push(cond);
|
|
1848
|
-
}
|
|
1849
|
-
}
|
|
1850
|
-
return conditions;
|
|
1851
|
-
}
|
|
1852
|
-
|
|
1853
|
-
/**
|
|
1854
|
-
* SHACL shape generation for AD4M model classes.
|
|
1855
|
-
*
|
|
1856
|
-
* Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
|
|
1857
|
-
* from a model's property and relation metadata. The heavy lifting used
|
|
1858
|
-
* to live inside the `@Model` decorator closure — it is extracted here so
|
|
1859
|
-
* decorators.ts stays focused on decorator registration logic.
|
|
1860
|
-
*/
|
|
1861
|
-
/**
|
|
1862
|
-
* Build a SHACL shape for a model class.
|
|
1863
|
-
*
|
|
1864
|
-
* @param subjectName - The model's registered name (from `@Model({ name })`)
|
|
1865
|
-
* @param target - The class constructor (used for prototype access,
|
|
1866
|
-
* inheritance chain, and relation target resolution)
|
|
1867
|
-
* @param properties - Merged property metadata (from `getPropertiesMetadata`)
|
|
1868
|
-
* @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
|
|
1869
|
-
* @param conformanceFilterFn - Injected conformance-filter builder
|
|
1870
|
-
* (avoids circular dependency back into decorators.ts)
|
|
1871
|
-
*/
|
|
1872
|
-
function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
|
|
1873
|
-
const obj = target.prototype;
|
|
1874
|
-
// ── Determine namespace from first property or relation ─────────────
|
|
1875
|
-
let namespace = "ad4m://";
|
|
1876
|
-
const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
|
|
1877
|
-
// Try properties first
|
|
1878
|
-
if (Object.keys(properties).length > 0) {
|
|
1879
|
-
const firstProp = properties[Object.keys(properties)[0]];
|
|
1880
|
-
if (firstProp.through) {
|
|
1881
|
-
const match = firstProp.through.match(/^([^:]+:\/\/)/);
|
|
1882
|
-
if (match) {
|
|
1883
|
-
namespace = match[1];
|
|
1884
|
-
}
|
|
1885
|
-
}
|
|
1886
|
-
}
|
|
1887
|
-
// Fall back to relations if no properties
|
|
1888
|
-
else if (Object.keys(relations).length > 0) {
|
|
1889
|
-
const firstRel = relations[Object.keys(relations)[0]];
|
|
1890
|
-
if (firstRel.predicate) {
|
|
1891
|
-
const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
|
|
1892
|
-
if (match) {
|
|
1893
|
-
namespace = match[1];
|
|
1894
|
-
}
|
|
1895
|
-
}
|
|
1896
|
-
}
|
|
1897
|
-
// ── Create SHACL shape ──────────────────────────────────────────────
|
|
1898
|
-
const shapeUri = `${namespace}${subjectName}Shape`;
|
|
1899
|
-
const targetClass = `${namespace}${subjectName}`;
|
|
1900
|
-
const shape = new SHACLShape(shapeUri, targetClass);
|
|
1901
|
-
// Detect @Model inheritance — if the parent class also has
|
|
1902
|
-
// generateSHACL it is itself a @Model and we reference its shape
|
|
1903
|
-
// via sh:node so SHACL validators can walk the hierarchy.
|
|
1904
|
-
const parentCtor = Object.getPrototypeOf(target);
|
|
1905
|
-
if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
|
|
1906
|
-
const parentSHACL = parentCtor.generateSHACL();
|
|
1907
|
-
if (parentSHACL?.shape?.nodeShapeUri) {
|
|
1908
|
-
shape.addParentShape(parentSHACL.shape.nodeShapeUri);
|
|
1813
|
+
// ── Create SHACL shape ──────────────────────────────────────────────
|
|
1814
|
+
const shapeUri = `${namespace}${subjectName}Shape`;
|
|
1815
|
+
const targetClass = `${namespace}${subjectName}`;
|
|
1816
|
+
const shape = new SHACLShape(shapeUri, targetClass);
|
|
1817
|
+
// Detect @Model inheritance — if the parent class also has
|
|
1818
|
+
// generateSHACL it is itself a @Model and we reference its shape
|
|
1819
|
+
// via sh:node so SHACL validators can walk the hierarchy.
|
|
1820
|
+
const parentCtor = Object.getPrototypeOf(target);
|
|
1821
|
+
if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
|
|
1822
|
+
const parentSHACL = parentCtor.generateSHACL();
|
|
1823
|
+
if (parentSHACL?.shape?.nodeShapeUri) {
|
|
1824
|
+
shape.addParentShape(parentSHACL.shape.nodeShapeUri);
|
|
1909
1825
|
}
|
|
1910
1826
|
}
|
|
1911
1827
|
// ── Constructor / Destructor actions ────────────────────────────────
|
|
@@ -1960,9 +1876,19 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
1960
1876
|
if (propMeta.writable !== undefined) {
|
|
1961
1877
|
propShape.writable = propMeta.writable;
|
|
1962
1878
|
}
|
|
1963
|
-
if (propMeta.resolveLanguage) {
|
|
1879
|
+
if (propMeta.resolveLanguage != null) {
|
|
1964
1880
|
propShape.resolveLanguage = propMeta.resolveLanguage;
|
|
1965
1881
|
}
|
|
1882
|
+
// Explicit getter SPARQL — the executor evaluates this when
|
|
1883
|
+
// hydrating the property, in addition to (or instead of)
|
|
1884
|
+
// reading raw links via `propMeta.through`.
|
|
1885
|
+
if (propMeta.getter) {
|
|
1886
|
+
propShape.getter = propMeta.getter;
|
|
1887
|
+
}
|
|
1888
|
+
// Serializable transform expression (SHACL-AF Node Expression)
|
|
1889
|
+
if (propMeta.transform) {
|
|
1890
|
+
propShape.transform = propMeta.transform;
|
|
1891
|
+
}
|
|
1966
1892
|
// ── Setter actions ──────────────────────────────────────────────
|
|
1967
1893
|
if (propMeta.prologSetter) {
|
|
1968
1894
|
console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
|
|
@@ -2001,63 +1927,82 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2001
1927
|
shape.addProperty(propShape);
|
|
2002
1928
|
}
|
|
2003
1929
|
// ── Convert relations to SHACL property shapes ─────────────────────
|
|
2004
|
-
for (const relName in
|
|
2005
|
-
const relMeta =
|
|
2006
|
-
|
|
1930
|
+
for (const relName in allRelationsMeta) {
|
|
1931
|
+
const relMeta = allRelationsMeta[relName];
|
|
1932
|
+
// Getter-only relations (no `through`) have no real link predicate
|
|
1933
|
+
// but still need a SHACL property entry so the executor can find
|
|
1934
|
+
// the getter expression. Synthesize a deterministic IRI so the
|
|
1935
|
+
// SHACL graph is well-formed; the predicate is never used to match
|
|
1936
|
+
// links because the getter is the sole source of values. Use
|
|
1937
|
+
// slash separators so the result is a valid IRI (colons in the
|
|
1938
|
+
// authority confuse strict SPARQL IRI parsers).
|
|
1939
|
+
if (!relMeta.predicate && !relMeta.getter)
|
|
2007
1940
|
continue;
|
|
1941
|
+
const synthesizedPath = relMeta.predicate
|
|
1942
|
+
|| `ad4m://getter/${subjectName}/${relName}`;
|
|
2008
1943
|
const relShape = {
|
|
2009
1944
|
name: relName,
|
|
2010
|
-
path:
|
|
1945
|
+
path: synthesizedPath,
|
|
2011
1946
|
};
|
|
2012
1947
|
// Relations typically contain IRIs
|
|
2013
1948
|
relShape.nodeKind = 'IRI';
|
|
1949
|
+
// Encode relation kind so the executor can derive direction and
|
|
1950
|
+
// scalar-vs-collection rendering without consulting the JS class.
|
|
1951
|
+
relShape.relationKind = relMeta.kind;
|
|
1952
|
+
// Scalar relations cap at 1.
|
|
1953
|
+
if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
|
|
1954
|
+
relShape.maxCount = 1;
|
|
1955
|
+
}
|
|
1956
|
+
else if (relMeta.maxCount !== undefined) {
|
|
1957
|
+
relShape.maxCount = relMeta.maxCount;
|
|
1958
|
+
}
|
|
1959
|
+
// Encode opt-out of type filtering (default true; only emit when false).
|
|
1960
|
+
if (relMeta.filter === false) {
|
|
1961
|
+
relShape.filter = false;
|
|
1962
|
+
}
|
|
2014
1963
|
// AD4M-specific metadata
|
|
2015
1964
|
if (relMeta.local !== undefined) {
|
|
2016
1965
|
relShape.local = relMeta.local;
|
|
2017
1966
|
}
|
|
2018
|
-
// Adder
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
1967
|
+
// Adder / Remover actions — only meaningful for relations backed
|
|
1968
|
+
// by a real link predicate. Getter-only relations are read-only.
|
|
1969
|
+
if (relMeta.predicate) {
|
|
1970
|
+
relShape.adder = [{
|
|
1971
|
+
action: "addLink",
|
|
1972
|
+
source: "this",
|
|
1973
|
+
predicate: relMeta.predicate,
|
|
1974
|
+
target: "value",
|
|
1975
|
+
...(relMeta.local && { local: true })
|
|
1976
|
+
}];
|
|
1977
|
+
relShape.remover = [{
|
|
1978
|
+
action: "removeLink",
|
|
1979
|
+
source: "this",
|
|
1980
|
+
predicate: relMeta.predicate,
|
|
1981
|
+
target: "value",
|
|
1982
|
+
...(relMeta.local && { local: true })
|
|
1983
|
+
}];
|
|
1984
|
+
}
|
|
2034
1985
|
// ── Build Getter (conformance filter) ───────────────────────────
|
|
2035
1986
|
// Priority chain:
|
|
2036
1987
|
// 1. Explicit getter string → use verbatim
|
|
2037
|
-
// 2.
|
|
2038
|
-
//
|
|
1988
|
+
// 2. target + filter !== false → auto-derive conformance getter
|
|
1989
|
+
// from the shape. Where-clause filtering is applied as a
|
|
1990
|
+
// post-getter pass via `whereFilter` / `wherePredicates`, which
|
|
1991
|
+
// use `parse_literal_value` and so transparently handle
|
|
1992
|
+
// `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
|
|
1993
|
+
// comparisons can't.
|
|
2039
1994
|
if (relMeta.getter) {
|
|
2040
1995
|
relShape.getter = relMeta.getter;
|
|
2041
1996
|
}
|
|
2042
|
-
else if (relMeta.
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
? TargetClass.getModelMetadata?.() ?? null
|
|
2047
|
-
: null;
|
|
2048
|
-
const conditions = compileWhereClause(relMeta.where, targetMetadata);
|
|
2049
|
-
if (conditions.length > 0) {
|
|
2050
|
-
const escapedPredicate = escapeQueryString(relMeta.predicate);
|
|
2051
|
-
relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
catch (e) {
|
|
2055
|
-
// Target metadata may not be available yet
|
|
2056
|
-
}
|
|
2057
|
-
}
|
|
2058
|
-
else if (relMeta.target && relMeta.filter !== false) {
|
|
1997
|
+
else if (relMeta.target
|
|
1998
|
+
&& relMeta.filter !== false
|
|
1999
|
+
&& relMeta.kind !== 'belongsToOne'
|
|
2000
|
+
&& relMeta.kind !== 'belongsToMany') {
|
|
2059
2001
|
// Lazy conformance filter: store deferred reference,
|
|
2060
|
-
// resolve on first access via a getter on relShape
|
|
2002
|
+
// resolve on first access via a getter on relShape.
|
|
2003
|
+
// Skipped for reverse relations (belongsTo*) because the
|
|
2004
|
+
// auto-derived getter assumes forward direction; the executor's
|
|
2005
|
+
// `resolve_reverse_relations` already populates these correctly.
|
|
2061
2006
|
const targetThunk = relMeta.target;
|
|
2062
2007
|
const predicate = relMeta.predicate;
|
|
2063
2008
|
let resolved = false;
|
|
@@ -2094,6 +2039,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2094
2039
|
});
|
|
2095
2040
|
}
|
|
2096
2041
|
// ── sh:class — target shape reference ───────────────────────────
|
|
2042
|
+
// Also emit ad4m:targetClassName so the executor can look up the
|
|
2043
|
+
// target class shape through its in-memory cache by bare name.
|
|
2097
2044
|
if (relMeta.target) {
|
|
2098
2045
|
try {
|
|
2099
2046
|
const TargetClass = relMeta.target();
|
|
@@ -2101,9 +2048,54 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2101
2048
|
if (targetSHACL?.shape?.nodeShapeUri) {
|
|
2102
2049
|
relShape.class = targetSHACL.shape.nodeShapeUri;
|
|
2103
2050
|
}
|
|
2051
|
+
if (targetSHACL?.name) {
|
|
2052
|
+
relShape.targetClassName = targetSHACL.name;
|
|
2053
|
+
}
|
|
2054
|
+
else {
|
|
2055
|
+
const targetProto = TargetClass.prototype;
|
|
2056
|
+
if (targetProto?.className) {
|
|
2057
|
+
relShape.targetClassName = targetProto.className;
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
catch (e) {
|
|
2062
|
+
// Target class resolution failed (typically a circular
|
|
2063
|
+
// decorator dependency). Since the executor no longer
|
|
2064
|
+
// receives target metadata over the wire, dropping the
|
|
2065
|
+
// reference here would turn a transient build-time issue
|
|
2066
|
+
// into a permanent broken-include at query time. Log
|
|
2067
|
+
// loudly so the failure is discoverable.
|
|
2068
|
+
console.warn(`[shacl-gen] Failed to resolve target class for relation `
|
|
2069
|
+
+ `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
// ── Where-clause metadata for post-getter filtering ─────────────
|
|
2073
|
+
// The executor uses these to apply where conditions against the
|
|
2074
|
+
// target class without needing the target's ModelMetadata at query time.
|
|
2075
|
+
if (relMeta.where) {
|
|
2076
|
+
relShape.whereFilter = relMeta.where;
|
|
2077
|
+
try {
|
|
2078
|
+
const TargetClass = relMeta.target?.();
|
|
2079
|
+
const targetMetadata = TargetClass
|
|
2080
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
2081
|
+
: null;
|
|
2082
|
+
if (targetMetadata?.properties) {
|
|
2083
|
+
const predicates = {};
|
|
2084
|
+
for (const propName of Object.keys(relMeta.where)) {
|
|
2085
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
2086
|
+
continue;
|
|
2087
|
+
const propMeta = targetMetadata.properties[propName];
|
|
2088
|
+
if (propMeta?.predicate) {
|
|
2089
|
+
predicates[propName] = propMeta.predicate;
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
if (Object.keys(predicates).length > 0) {
|
|
2093
|
+
relShape.wherePredicates = predicates;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2104
2096
|
}
|
|
2105
2097
|
catch (e) {
|
|
2106
|
-
// Target
|
|
2098
|
+
// Target metadata may not be available yet
|
|
2107
2099
|
}
|
|
2108
2100
|
}
|
|
2109
2101
|
shape.addProperty(relShape);
|
|
@@ -2121,6 +2113,58 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2121
2113
|
};
|
|
2122
2114
|
}
|
|
2123
2115
|
|
|
2116
|
+
function formatList(list) {
|
|
2117
|
+
if (!list?.length) {
|
|
2118
|
+
return "";
|
|
2119
|
+
}
|
|
2120
|
+
if (list.length === 1) {
|
|
2121
|
+
return list.toString();
|
|
2122
|
+
}
|
|
2123
|
+
if (list.length === 2) {
|
|
2124
|
+
return list.join(' and ');
|
|
2125
|
+
}
|
|
2126
|
+
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
2127
|
+
}
|
|
2128
|
+
function capSentence(cap) {
|
|
2129
|
+
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
2130
|
+
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
2131
|
+
const pointers = cap.with.pointers.includes("*")
|
|
2132
|
+
? ["all AD4M data"]
|
|
2133
|
+
: cap.with.pointers;
|
|
2134
|
+
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
2135
|
+
}
|
|
2136
|
+
/**
|
|
2137
|
+
* Escapes a string value for safe use in query strings.
|
|
2138
|
+
*
|
|
2139
|
+
* @description
|
|
2140
|
+
* Prevents SQL injection by properly escaping special characters in string values
|
|
2141
|
+
* that will be interpolated into query strings. This handles the most common
|
|
2142
|
+
* special characters that could break SQL queries or enable injection attacks.
|
|
2143
|
+
*
|
|
2144
|
+
* Single quotes, backslashes, and other special characters are escaped using
|
|
2145
|
+
* backslash notation, which is the standard escaping mechanism for query.
|
|
2146
|
+
*
|
|
2147
|
+
* @param value - The string value to escape
|
|
2148
|
+
* @returns The escaped string safe for query interpolation (without surrounding quotes)
|
|
2149
|
+
*
|
|
2150
|
+
* @example
|
|
2151
|
+
* ```typescript
|
|
2152
|
+
* const userInput = "user's input with 'quotes'";
|
|
2153
|
+
* const escaped = escapeQueryString(userInput);
|
|
2154
|
+
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
2155
|
+
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
2156
|
+
* ```
|
|
2157
|
+
*/
|
|
2158
|
+
function escapeQueryString(value) {
|
|
2159
|
+
return value
|
|
2160
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
2161
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
2162
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
2163
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
2164
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
2165
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
2166
|
+
}
|
|
2167
|
+
|
|
2124
2168
|
/** Registry of property metadata keyed by constructor → { propName → metadata } */
|
|
2125
2169
|
const propertyRegistry = new WeakMap();
|
|
2126
2170
|
/** Registry of relation metadata keyed by constructor → { propName → metadata } */
|
|
@@ -3737,13 +3781,16 @@ class PerspectiveProxy {
|
|
|
3737
3781
|
/**
|
|
3738
3782
|
* Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
|
|
3739
3783
|
*
|
|
3784
|
+
* The executor resolves the model's shape from the perspective's SHACL
|
|
3785
|
+
* triples (written by `addSdna`). Callers no longer ship shape
|
|
3786
|
+
* metadata with the query; the perspective is the source of truth.
|
|
3787
|
+
*
|
|
3740
3788
|
* @param className - The model class name (e.g. "Recipe")
|
|
3741
3789
|
* @param queryJson - Structured query as JSON string
|
|
3742
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
3743
3790
|
* @returns Object with `instances` array and `totalCount`
|
|
3744
3791
|
*/
|
|
3745
|
-
async modelQuery(className, queryJson
|
|
3746
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
3792
|
+
async modelQuery(className, queryJson) {
|
|
3793
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
3747
3794
|
}
|
|
3748
3795
|
/**
|
|
3749
3796
|
* Evaluate property getters for a batch of instances in a single RPC call.
|
|
@@ -3754,12 +3801,11 @@ class PerspectiveProxy {
|
|
|
3754
3801
|
*
|
|
3755
3802
|
* @param className - The model class name (e.g. "Message")
|
|
3756
3803
|
* @param instanceIds - Array of instance base expression URIs
|
|
3757
|
-
* @param shapeJson - Shape metadata JSON from the model class
|
|
3758
3804
|
* @param propertyNames - Optional subset of property names to evaluate
|
|
3759
3805
|
* @returns Map of instance ID → evaluated property values
|
|
3760
3806
|
*/
|
|
3761
|
-
async evaluateGetters(className, instanceIds,
|
|
3762
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds,
|
|
3807
|
+
async evaluateGetters(className, instanceIds, propertyNames) {
|
|
3808
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
|
|
3763
3809
|
}
|
|
3764
3810
|
/**
|
|
3765
3811
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
@@ -3771,11 +3817,10 @@ class PerspectiveProxy {
|
|
|
3771
3817
|
*
|
|
3772
3818
|
* @param className - The model class name
|
|
3773
3819
|
* @param queryJson - JSON-serialized query parameters (same as modelQuery)
|
|
3774
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
3775
3820
|
* @returns Object with `subscriptionId` and initial `result`
|
|
3776
3821
|
*/
|
|
3777
|
-
async modelSubscribe(className, queryJson
|
|
3778
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
3822
|
+
async modelSubscribe(className, queryJson) {
|
|
3823
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
3779
3824
|
}
|
|
3780
3825
|
/**
|
|
3781
3826
|
* Adds a new link to the perspective.
|
|
@@ -5417,22 +5462,21 @@ class PerspectiveClient {
|
|
|
5417
5462
|
}
|
|
5418
5463
|
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
|
|
5419
5464
|
}
|
|
5420
|
-
async modelQuery(uuid, className, queryJson
|
|
5421
|
-
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson
|
|
5465
|
+
async modelQuery(uuid, className, queryJson) {
|
|
5466
|
+
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
|
|
5422
5467
|
return JSON.parse(resultJson);
|
|
5423
5468
|
}
|
|
5424
|
-
async evaluateGetters(uuid, className, instanceIds,
|
|
5469
|
+
async evaluateGetters(uuid, className, instanceIds, propertyNames) {
|
|
5425
5470
|
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
|
|
5426
5471
|
uuid,
|
|
5427
5472
|
class_name: className,
|
|
5428
5473
|
instance_ids: instanceIds,
|
|
5429
|
-
shape_json: shapeJson,
|
|
5430
5474
|
...(propertyNames && { property_names: propertyNames }),
|
|
5431
5475
|
});
|
|
5432
5476
|
return JSON.parse(resultJson);
|
|
5433
5477
|
}
|
|
5434
|
-
async modelSubscribe(uuid, className, queryJson
|
|
5435
|
-
const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson
|
|
5478
|
+
async modelSubscribe(uuid, className, queryJson) {
|
|
5479
|
+
const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
|
|
5436
5480
|
return {
|
|
5437
5481
|
subscriptionId: response.subscription_id,
|
|
5438
5482
|
result: JSON.parse(response.result)
|
|
@@ -13827,7 +13871,7 @@ class AIClient {
|
|
|
13827
13871
|
// Use slice to get only the relevant portion of the underlying ArrayBuffer
|
|
13828
13872
|
// (Float32Array may be a view over a larger buffer)
|
|
13829
13873
|
const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
|
|
13830
|
-
const response = await
|
|
13874
|
+
const response = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
|
|
13831
13875
|
method: 'POST',
|
|
13832
13876
|
headers: {
|
|
13833
13877
|
'Content-Type': 'application/octet-stream',
|
|
@@ -14903,13 +14947,6 @@ class ModelQueryBuilder {
|
|
|
14903
14947
|
this.modelClassName = className;
|
|
14904
14948
|
return this;
|
|
14905
14949
|
}
|
|
14906
|
-
/**
|
|
14907
|
-
* Sets the query engine to use.
|
|
14908
|
-
* @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
|
|
14909
|
-
*/
|
|
14910
|
-
engine(_eng) {
|
|
14911
|
-
return this;
|
|
14912
|
-
}
|
|
14913
14950
|
/**
|
|
14914
14951
|
* Executes the query once and returns the results.
|
|
14915
14952
|
*
|
|
@@ -14991,23 +15028,18 @@ class ModelQueryBuilder {
|
|
|
14991
15028
|
// Clean up any existing subscription
|
|
14992
15029
|
this.dispose();
|
|
14993
15030
|
const ctor = this.ctor;
|
|
14994
|
-
// Build the model query params (className, queryJson
|
|
14995
|
-
|
|
15031
|
+
// Build the model query params (className, queryJson). The executor
|
|
15032
|
+
// resolves the shape from the perspective's SHACL triples.
|
|
15033
|
+
const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
|
|
14996
15034
|
// Register model subscription via Rust — this builds trigger SPARQL internally,
|
|
14997
15035
|
// registers the subscription, and runs the initial query in one call.
|
|
14998
|
-
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson
|
|
15036
|
+
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
|
|
14999
15037
|
// Convert JSON instances to model class instances
|
|
15000
15038
|
const parseResults = (raw) => {
|
|
15001
15039
|
return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
|
|
15002
15040
|
};
|
|
15003
|
-
//
|
|
15004
|
-
|
|
15005
|
-
const resolveAndReturn = async (instances) => {
|
|
15006
|
-
await ctor.resolveNonLiteralProps(this.perspective, instances);
|
|
15007
|
-
return instances;
|
|
15008
|
-
};
|
|
15009
|
-
// Parse initial results (with non-literal resolution)
|
|
15010
|
-
const initialResults = await resolveAndReturn(parseResults(initialModelResult));
|
|
15041
|
+
// Transforms are now applied by the Rust executor during hydration
|
|
15042
|
+
const initialResults = parseResults(initialModelResult);
|
|
15011
15043
|
// Track last emitted result fingerprint to suppress duplicate callbacks
|
|
15012
15044
|
let lastResultFingerprint = null;
|
|
15013
15045
|
const buildFingerprint = (results) => {
|
|
@@ -15020,20 +15052,16 @@ class ModelQueryBuilder {
|
|
|
15020
15052
|
// When Rust re-runs the model query and finds changed results, it pushes them.
|
|
15021
15053
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
|
|
15022
15054
|
try {
|
|
15023
|
-
const
|
|
15024
|
-
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${
|
|
15025
|
-
|
|
15026
|
-
|
|
15027
|
-
|
|
15028
|
-
|
|
15029
|
-
|
|
15030
|
-
|
|
15031
|
-
|
|
15032
|
-
|
|
15033
|
-
callback(results);
|
|
15034
|
-
}).catch((e) => {
|
|
15035
|
-
console.error('Model subscription update resolve error:', e);
|
|
15036
|
-
});
|
|
15055
|
+
const results = parseResults(rawResult);
|
|
15056
|
+
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
|
|
15057
|
+
const fp = buildFingerprint(results);
|
|
15058
|
+
if (fp === lastResultFingerprint) {
|
|
15059
|
+
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
|
|
15060
|
+
return;
|
|
15061
|
+
}
|
|
15062
|
+
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
|
|
15063
|
+
lastResultFingerprint = fp;
|
|
15064
|
+
callback(results);
|
|
15037
15065
|
}
|
|
15038
15066
|
catch (e) {
|
|
15039
15067
|
console.error('Model subscription update parse error:', e);
|
|
@@ -15155,8 +15183,8 @@ class ModelQueryBuilder {
|
|
|
15155
15183
|
// Clean up any existing subscription
|
|
15156
15184
|
this.dispose();
|
|
15157
15185
|
const countParams = { ...this.queryParams, limit: 0 };
|
|
15158
|
-
const { className, queryJson
|
|
15159
|
-
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson
|
|
15186
|
+
const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
|
|
15187
|
+
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
|
|
15160
15188
|
const parseCount = (raw) => {
|
|
15161
15189
|
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
15162
15190
|
return data.totalCount ?? 0;
|
|
@@ -15291,8 +15319,8 @@ class ModelQueryBuilder {
|
|
|
15291
15319
|
const subscriptionParams = { ...(this.queryParams || {}) };
|
|
15292
15320
|
delete subscriptionParams.limit;
|
|
15293
15321
|
delete subscriptionParams.offset;
|
|
15294
|
-
const { className, queryJson
|
|
15295
|
-
const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson
|
|
15322
|
+
const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
|
|
15323
|
+
const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
|
|
15296
15324
|
// Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
|
|
15297
15325
|
const paginatedQuery = {
|
|
15298
15326
|
...(this.queryParams || {}),
|
|
@@ -15389,94 +15417,12 @@ function normalizeValue(value) {
|
|
|
15389
15417
|
}
|
|
15390
15418
|
|
|
15391
15419
|
// ---------------------------------------------------------------------------
|
|
15392
|
-
//
|
|
15420
|
+
// Helpers for Rust-side include resolution
|
|
15393
15421
|
// ---------------------------------------------------------------------------
|
|
15394
15422
|
/**
|
|
15395
|
-
*
|
|
15396
|
-
*
|
|
15397
|
-
*
|
|
15398
|
-
* (e.g. it was synthesised from a SHACL shape at runtime) we still want to
|
|
15399
|
-
* decode the content rather than passing raw `FileData` to callers.
|
|
15400
|
-
*
|
|
15401
|
-
* Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
|
|
15402
|
-
* - `application/json` (default when `file_type` is absent) → JSON.parse
|
|
15403
|
-
* - anything else → raw decoded string
|
|
15404
|
-
*
|
|
15405
|
-
* If `resolved` is not a `FileData` object the value is returned unchanged so
|
|
15406
|
-
* that callers can use this as a safe unconditional fallback.
|
|
15407
|
-
*/
|
|
15408
|
-
function defaultFileDecode(resolved) {
|
|
15409
|
-
if (resolved !== null &&
|
|
15410
|
-
typeof resolved === 'object' &&
|
|
15411
|
-
'data_base64' in resolved) {
|
|
15412
|
-
const fd = resolved;
|
|
15413
|
-
let raw;
|
|
15414
|
-
try {
|
|
15415
|
-
raw = atob(fd.data_base64);
|
|
15416
|
-
}
|
|
15417
|
-
catch {
|
|
15418
|
-
return resolved; // malformed base64 — keep as-is
|
|
15419
|
-
}
|
|
15420
|
-
const isJson = !fd.file_type || fd.file_type === 'application/json';
|
|
15421
|
-
if (isJson) {
|
|
15422
|
-
try {
|
|
15423
|
-
return JSON.parse(raw);
|
|
15424
|
-
}
|
|
15425
|
-
catch {
|
|
15426
|
-
return raw;
|
|
15427
|
-
}
|
|
15428
|
-
}
|
|
15429
|
-
return raw;
|
|
15430
|
-
}
|
|
15431
|
-
return resolved;
|
|
15432
|
-
}
|
|
15433
|
-
// ---------------------------------------------------------------------------
|
|
15434
|
-
// Helpers for Rust-side include resolution
|
|
15435
|
-
// ---------------------------------------------------------------------------
|
|
15436
|
-
/**
|
|
15437
|
-
* Recursively enrich relation metadata in the shape with target class shapes
|
|
15438
|
-
* so the Rust endpoint can resolve includes in-process (no extra GraphQL
|
|
15439
|
-
* round-trips per relation).
|
|
15440
|
-
*/
|
|
15441
|
-
function enrichShapeForIncludes(metadata, include, allRelMeta) {
|
|
15442
|
-
for (const [relName, includeVal] of Object.entries(include)) {
|
|
15443
|
-
if (!includeVal)
|
|
15444
|
-
continue;
|
|
15445
|
-
const meta = allRelMeta[relName];
|
|
15446
|
-
if (!meta?.target)
|
|
15447
|
-
continue;
|
|
15448
|
-
const TargetClass = meta.target();
|
|
15449
|
-
// Deep-copy so we don't mutate the cached metadata
|
|
15450
|
-
const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
|
|
15451
|
-
// Ensure the relation is in metadata.relations (fallback for edge cases)
|
|
15452
|
-
if (!metadata.relations[relName]) {
|
|
15453
|
-
metadata.relations[relName] = {
|
|
15454
|
-
name: relName,
|
|
15455
|
-
predicate: meta.predicate,
|
|
15456
|
-
direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
|
|
15457
|
-
? 'reverse'
|
|
15458
|
-
: 'forward',
|
|
15459
|
-
};
|
|
15460
|
-
}
|
|
15461
|
-
const rel = metadata.relations[relName];
|
|
15462
|
-
rel.kind = meta.kind;
|
|
15463
|
-
rel.maxCount = meta.maxCount;
|
|
15464
|
-
rel.targetShape = targetMeta;
|
|
15465
|
-
rel.targetClassName = targetMeta.className;
|
|
15466
|
-
// Recurse for nested includes
|
|
15467
|
-
const nested = typeof includeVal === 'object' && includeVal !== null
|
|
15468
|
-
? includeVal.include
|
|
15469
|
-
: undefined;
|
|
15470
|
-
if (nested) {
|
|
15471
|
-
const targetRelMeta = getRelationsMetadata(TargetClass);
|
|
15472
|
-
enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
|
|
15473
|
-
}
|
|
15474
|
-
}
|
|
15475
|
-
}
|
|
15476
|
-
/**
|
|
15477
|
-
* Construct a model class instance from a plain JSON object returned by the
|
|
15478
|
-
* Rust endpoint. Recursively converts included relation values (which come
|
|
15479
|
-
* back as plain JSON objects) into proper model class instances.
|
|
15423
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
15424
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
15425
|
+
* back as plain JSON objects) into proper model class instances.
|
|
15480
15426
|
*/
|
|
15481
15427
|
function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
|
|
15482
15428
|
const instance = new ModelClass(perspective, json.id || json.baseExpression);
|
|
@@ -15517,24 +15463,6 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
|
|
|
15517
15463
|
}
|
|
15518
15464
|
instance[key] = value;
|
|
15519
15465
|
}
|
|
15520
|
-
// Apply property transform functions from decorators (only for literal-resolved
|
|
15521
|
-
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
15522
|
-
// asynchronously in executeModelQuery).
|
|
15523
|
-
try {
|
|
15524
|
-
const propsMeta = getPropertiesMetadata(ModelClass);
|
|
15525
|
-
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
15526
|
-
const o = opts;
|
|
15527
|
-
if (typeof o.transform !== 'function' || !(propName in json))
|
|
15528
|
-
continue;
|
|
15529
|
-
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
15530
|
-
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
|
|
15531
|
-
continue;
|
|
15532
|
-
instance[propName] = o.transform(instance[propName]);
|
|
15533
|
-
}
|
|
15534
|
-
}
|
|
15535
|
-
catch (e) {
|
|
15536
|
-
console.debug('jsonToModelInstance: transform metadata unavailable:', e);
|
|
15537
|
-
}
|
|
15538
15466
|
// Recursively convert included relation values to class instances
|
|
15539
15467
|
if (include) {
|
|
15540
15468
|
const relMeta = getRelationsMetadata(ModelClass);
|
|
@@ -15772,8 +15700,8 @@ class Ad4mModel {
|
|
|
15772
15700
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
15773
15701
|
...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
|
|
15774
15702
|
...(options.local !== undefined && { local: options.local }),
|
|
15775
|
-
...(options.
|
|
15776
|
-
...(options.
|
|
15703
|
+
...(options.flag !== undefined && { flag: options.flag }),
|
|
15704
|
+
...(options.transform !== undefined && { transform: options.transform })
|
|
15777
15705
|
};
|
|
15778
15706
|
}
|
|
15779
15707
|
// Extract relations (relations) from WeakMap registry
|
|
@@ -16154,7 +16082,8 @@ class Ad4mModel {
|
|
|
16154
16082
|
}
|
|
16155
16083
|
/**
|
|
16156
16084
|
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
16157
|
-
* Returns the className
|
|
16085
|
+
* Returns the className and queryJson that the Rust executor expects.
|
|
16086
|
+
* Shape resolution happens server-side from the perspective's SHACL triples.
|
|
16158
16087
|
* @internal
|
|
16159
16088
|
*/
|
|
16160
16089
|
static prepareModelQueryParams(query = {}, classNameOverride) {
|
|
@@ -16194,16 +16123,18 @@ class Ad4mModel {
|
|
|
16194
16123
|
if (Object.keys(normalIncludes).length > 0)
|
|
16195
16124
|
queryInput.include = normalIncludes;
|
|
16196
16125
|
if (Object.keys(projections).length > 0) {
|
|
16197
|
-
//
|
|
16126
|
+
// Tag each projection with its target class name so the executor can
|
|
16127
|
+
// resolve the target shape through its in-memory cache when applying
|
|
16128
|
+
// projection where-clause filters.
|
|
16198
16129
|
const allRelMeta = getRelationsMetadata(this);
|
|
16199
16130
|
for (const [, proj] of Object.entries(projections)) {
|
|
16200
16131
|
const relMeta = allRelMeta[proj.from];
|
|
16201
|
-
if (!proj.
|
|
16132
|
+
if (!proj.targetClassName && relMeta?.target) {
|
|
16202
16133
|
try {
|
|
16203
16134
|
const TargetClass = relMeta.target();
|
|
16204
16135
|
const targetMeta = TargetClass.getModelMetadata?.();
|
|
16205
|
-
if (targetMeta) {
|
|
16206
|
-
proj.
|
|
16136
|
+
if (targetMeta?.className) {
|
|
16137
|
+
proj.targetClassName = targetMeta.className;
|
|
16207
16138
|
}
|
|
16208
16139
|
}
|
|
16209
16140
|
catch (e) {
|
|
@@ -16226,64 +16157,12 @@ class Ad4mModel {
|
|
|
16226
16157
|
if (query.count !== undefined)
|
|
16227
16158
|
queryInput.count = query.count;
|
|
16228
16159
|
queryInput.deepQuery = query.deepQuery ?? true;
|
|
16229
|
-
|
|
16230
|
-
|
|
16231
|
-
|
|
16232
|
-
}
|
|
16233
|
-
// Pre-compute conformance getters for Rust-side evaluation.
|
|
16234
|
-
// Where clauses are NOT compiled into getter SPARQL because stored
|
|
16235
|
-
// property values are signed expression envelopes (literal:json:...),
|
|
16236
|
-
// not simple literal:string:X values. Instead, where clauses are
|
|
16237
|
-
// attached as metadata for Rust-side post-evaluation filtering.
|
|
16238
|
-
{
|
|
16239
|
-
const allRelMeta = getRelationsMetadata(this);
|
|
16240
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
16241
|
-
const rel = relMeta;
|
|
16242
|
-
if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
|
|
16243
|
-
continue;
|
|
16244
|
-
const meta = allRelMeta[relName];
|
|
16245
|
-
if (!meta?.target)
|
|
16246
|
-
continue;
|
|
16247
|
-
try {
|
|
16248
|
-
const TargetClass = meta.target();
|
|
16249
|
-
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
16250
|
-
if (filter) {
|
|
16251
|
-
rel.getter = filter.getter;
|
|
16252
|
-
}
|
|
16253
|
-
// Attach where-clause metadata for Rust-side post-getter filtering
|
|
16254
|
-
if (rel.where) {
|
|
16255
|
-
try {
|
|
16256
|
-
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
16257
|
-
if (targetMetadata) {
|
|
16258
|
-
const predicates = {};
|
|
16259
|
-
for (const propName of Object.keys(rel.where)) {
|
|
16260
|
-
if (['id', 'author', 'timestamp'].includes(propName))
|
|
16261
|
-
continue;
|
|
16262
|
-
const propMeta = targetMetadata.properties[propName];
|
|
16263
|
-
if (propMeta?.predicate) {
|
|
16264
|
-
predicates[propName] = propMeta.predicate;
|
|
16265
|
-
}
|
|
16266
|
-
}
|
|
16267
|
-
if (Object.keys(predicates).length > 0) {
|
|
16268
|
-
rel.whereFilter = rel.where;
|
|
16269
|
-
rel.wherePredicates = predicates;
|
|
16270
|
-
}
|
|
16271
|
-
}
|
|
16272
|
-
}
|
|
16273
|
-
catch (e) {
|
|
16274
|
-
console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e);
|
|
16275
|
-
}
|
|
16276
|
-
}
|
|
16277
|
-
}
|
|
16278
|
-
catch (e) {
|
|
16279
|
-
console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e);
|
|
16280
|
-
}
|
|
16281
|
-
}
|
|
16282
|
-
}
|
|
16160
|
+
// Conformance getters, where filters, and target shapes for includes
|
|
16161
|
+
// are all resolved by the executor from the perspective's SHACL triples
|
|
16162
|
+
// — no client-side pre-computation is needed any more.
|
|
16283
16163
|
return {
|
|
16284
16164
|
className,
|
|
16285
16165
|
queryJson: JSON.stringify(queryInput),
|
|
16286
|
-
shapeJson: JSON.stringify(metadata),
|
|
16287
16166
|
metadata,
|
|
16288
16167
|
};
|
|
16289
16168
|
}
|
|
@@ -16299,57 +16178,6 @@ class Ad4mModel {
|
|
|
16299
16178
|
return [];
|
|
16300
16179
|
return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
16301
16180
|
}
|
|
16302
|
-
/**
|
|
16303
|
-
* Resolve non-literal (file-language) properties on an array of already-constructed
|
|
16304
|
-
* model instances. Handles two cases:
|
|
16305
|
-
*
|
|
16306
|
-
* 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
|
|
16307
|
-
* 2. The Rust executor already resolved the expression and returned a `FileData` object
|
|
16308
|
-
* (happens when the perspective backend eagerly fetches file content) → apply transform
|
|
16309
|
-
* (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
|
|
16310
|
-
* synthesised model classes).
|
|
16311
|
-
*
|
|
16312
|
-
* Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
|
|
16313
|
-
* duplicating logic or introducing a circular dependency.
|
|
16314
|
-
* @internal
|
|
16315
|
-
*/
|
|
16316
|
-
static async resolveNonLiteralProps(perspective, instances) {
|
|
16317
|
-
const propsMeta = getPropertiesMetadata(this);
|
|
16318
|
-
const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
|
|
16319
|
-
opts.resolveLanguage !== 'literal');
|
|
16320
|
-
if (resolveProps.length === 0)
|
|
16321
|
-
return;
|
|
16322
|
-
await Promise.all(instances.map(async (inst) => {
|
|
16323
|
-
for (const [propName, opts] of resolveProps) {
|
|
16324
|
-
const val = inst[propName];
|
|
16325
|
-
const transform = opts.transform;
|
|
16326
|
-
const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
|
|
16327
|
-
if (typeof val === 'string' && val && !val.startsWith('literal:')) {
|
|
16328
|
-
// Case 1: raw URI — fetch from language runtime
|
|
16329
|
-
try {
|
|
16330
|
-
const expression = await perspective.getExpression(val);
|
|
16331
|
-
if (expression) {
|
|
16332
|
-
let resolved;
|
|
16333
|
-
try {
|
|
16334
|
-
resolved = JSON.parse(expression.data);
|
|
16335
|
-
}
|
|
16336
|
-
catch {
|
|
16337
|
-
resolved = expression.data;
|
|
16338
|
-
}
|
|
16339
|
-
inst[propName] = applyTransform(resolved);
|
|
16340
|
-
}
|
|
16341
|
-
}
|
|
16342
|
-
catch (e) {
|
|
16343
|
-
console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);
|
|
16344
|
-
}
|
|
16345
|
-
}
|
|
16346
|
-
else if (val !== null && val !== undefined && typeof val === 'object') {
|
|
16347
|
-
// Case 2: already resolved by Rust — apply transform / default decode
|
|
16348
|
-
inst[propName] = applyTransform(val);
|
|
16349
|
-
}
|
|
16350
|
-
}
|
|
16351
|
-
}));
|
|
16352
|
-
}
|
|
16353
16181
|
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
16354
16182
|
/**
|
|
16355
16183
|
* Execute a model query via the executor-side endpoint.
|
|
@@ -16360,20 +16188,15 @@ class Ad4mModel {
|
|
|
16360
16188
|
* @internal
|
|
16361
16189
|
*/
|
|
16362
16190
|
static async executeModelQuery(perspective, query = {}, classNameOverride) {
|
|
16363
|
-
// Delegate
|
|
16364
|
-
//
|
|
16365
|
-
const { className, queryJson
|
|
16366
|
-
const result = await perspective.modelQuery(className, queryJson
|
|
16191
|
+
// Delegate query input building to the shared prepareModelQueryParams
|
|
16192
|
+
// helper. The executor resolves the shape from SHACL server-side.
|
|
16193
|
+
const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
|
|
16194
|
+
const result = await perspective.modelQuery(className, queryJson);
|
|
16367
16195
|
// Convert JSON instances to model class instances, recursively constructing
|
|
16368
16196
|
// class instances for any included relations resolved by Rust.
|
|
16369
16197
|
const instances = result.instances.map((json) => {
|
|
16370
16198
|
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
16371
16199
|
});
|
|
16372
|
-
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
16373
|
-
// value is a content-addressed hash that must be fetched from the language
|
|
16374
|
-
// runtime). The Rust endpoint may return either a raw target URI (string)
|
|
16375
|
-
// or an already-resolved FileData object — both cases are handled here.
|
|
16376
|
-
await this.resolveNonLiteralProps(perspective, instances);
|
|
16377
16200
|
// Take snapshots for dirty tracking (exclude $-prefixed projection keys)
|
|
16378
16201
|
const snapshotRelations = query.include
|
|
16379
16202
|
? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
|
|
@@ -16409,13 +16232,12 @@ class Ad4mModel {
|
|
|
16409
16232
|
* });
|
|
16410
16233
|
* ```
|
|
16411
16234
|
*/
|
|
16412
|
-
static async findAll(perspective, query
|
|
16413
|
-
|
|
16414
|
-
|
|
16415
|
-
if (query.properties && query.properties.length === 0) {
|
|
16235
|
+
static async findAll(perspective, query) {
|
|
16236
|
+
const q = (query ?? {});
|
|
16237
|
+
if (q.properties && q.properties.length === 0) {
|
|
16416
16238
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
16417
16239
|
}
|
|
16418
|
-
const { results } = await this.executeModelQuery(perspective,
|
|
16240
|
+
const { results } = await this.executeModelQuery(perspective, q);
|
|
16419
16241
|
return results;
|
|
16420
16242
|
}
|
|
16421
16243
|
/**
|
|
@@ -16438,10 +16260,8 @@ class Ad4mModel {
|
|
|
16438
16260
|
* }
|
|
16439
16261
|
* ```
|
|
16440
16262
|
*/
|
|
16441
|
-
static async findOne(perspective, query
|
|
16442
|
-
|
|
16443
|
-
_engine) {
|
|
16444
|
-
const limitedQuery = { ...query, limit: 1 };
|
|
16263
|
+
static async findOne(perspective, query) {
|
|
16264
|
+
const limitedQuery = { ...(query ?? {}), limit: 1 };
|
|
16445
16265
|
const results = await this.findAll(perspective, limitedQuery);
|
|
16446
16266
|
return results[0] ?? null;
|
|
16447
16267
|
}
|
|
@@ -16462,10 +16282,9 @@ class Ad4mModel {
|
|
|
16462
16282
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
16463
16283
|
* ```
|
|
16464
16284
|
*/
|
|
16465
|
-
static async findAllAndCount(perspective, query
|
|
16466
|
-
|
|
16467
|
-
|
|
16468
|
-
return await this.executeModelQuery(perspective, query);
|
|
16285
|
+
static async findAllAndCount(perspective, query) {
|
|
16286
|
+
const out = await this.executeModelQuery(perspective, (query ?? {}));
|
|
16287
|
+
return out;
|
|
16469
16288
|
}
|
|
16470
16289
|
/**
|
|
16471
16290
|
* Helper function for pagination with explicit page size and number.
|
|
@@ -16484,12 +16303,10 @@ class Ad4mModel {
|
|
|
16484
16303
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
16485
16304
|
* ```
|
|
16486
16305
|
*/
|
|
16487
|
-
static async paginate(perspective, pageSize, pageNumber, query
|
|
16488
|
-
|
|
16489
|
-
_engine) {
|
|
16490
|
-
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
16306
|
+
static async paginate(perspective, pageSize, pageNumber, query) {
|
|
16307
|
+
const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
16491
16308
|
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
16492
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
16309
|
+
return { results: results, totalCount, pageSize, pageNumber };
|
|
16493
16310
|
}
|
|
16494
16311
|
/**
|
|
16495
16312
|
* Generates a SPARQL COUNT query for the model.
|
|
@@ -16516,8 +16333,8 @@ class Ad4mModel {
|
|
|
16516
16333
|
* });
|
|
16517
16334
|
* ```
|
|
16518
16335
|
*/
|
|
16519
|
-
static async count(perspective, query
|
|
16520
|
-
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
16336
|
+
static async count(perspective, query) {
|
|
16337
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
|
|
16521
16338
|
return totalCount;
|
|
16522
16339
|
}
|
|
16523
16340
|
async setProperty(key, value, batchId) {
|
|
@@ -16828,29 +16645,10 @@ class Ad4mModel {
|
|
|
16828
16645
|
if (instances.length === 0)
|
|
16829
16646
|
return;
|
|
16830
16647
|
const metadata = this.getModelMetadata();
|
|
16831
|
-
// Pre-compute conformance getters so the shape sent to Rust includes them
|
|
16832
|
-
const allRelMeta = getRelationsMetadata(this);
|
|
16833
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
16834
|
-
const rel = relMeta;
|
|
16835
|
-
if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
|
|
16836
|
-
continue;
|
|
16837
|
-
const meta = allRelMeta[relName];
|
|
16838
|
-
if (!meta?.target)
|
|
16839
|
-
continue;
|
|
16840
|
-
try {
|
|
16841
|
-
const TargetClass = meta.target();
|
|
16842
|
-
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
16843
|
-
if (filter)
|
|
16844
|
-
rel.getter = filter.getter;
|
|
16845
|
-
}
|
|
16846
|
-
catch (e) {
|
|
16847
|
-
console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e);
|
|
16848
|
-
}
|
|
16849
|
-
}
|
|
16850
|
-
const shapeJson = JSON.stringify(metadata);
|
|
16851
16648
|
const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
|
|
16852
|
-
//
|
|
16853
|
-
|
|
16649
|
+
// The executor reads getter SPARQL from the perspective's SHACL triples
|
|
16650
|
+
// (written by `addSdna`), so no shape JSON is shipped with the call.
|
|
16651
|
+
const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
|
|
16854
16652
|
// Determine which property names were evaluated for snapshot sync
|
|
16855
16653
|
const evaluatedPropertyNames = [];
|
|
16856
16654
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
@@ -17214,7 +17012,7 @@ class Ad4mModel {
|
|
|
17214
17012
|
* ```
|
|
17215
17013
|
*/
|
|
17216
17014
|
static query(perspective, query) {
|
|
17217
|
-
return new ModelQueryBuilder(perspective, this, query);
|
|
17015
|
+
return new ModelQueryBuilder(perspective, this, (query ?? {}));
|
|
17218
17016
|
}
|
|
17219
17017
|
/**
|
|
17220
17018
|
* Creates an Ad4mModel class from a JSON Schema definition.
|
|
@@ -17414,7 +17212,7 @@ class Ad4mClient {
|
|
|
17414
17212
|
_Ad4mClient_aiClient.set(this, void 0);
|
|
17415
17213
|
__classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
|
|
17416
17214
|
__classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
|
|
17417
|
-
__classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl), "f");
|
|
17215
|
+
__classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
|
|
17418
17216
|
__classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
17419
17217
|
__classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
17420
17218
|
__classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
|
|
@@ -17623,6 +17421,71 @@ class PerspectiveHandle {
|
|
|
17623
17421
|
}
|
|
17624
17422
|
}
|
|
17625
17423
|
|
|
17424
|
+
/**
|
|
17425
|
+
* SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
|
|
17426
|
+
*
|
|
17427
|
+
* AD4M stores non-string property values as URL-encoded `Literal` payloads
|
|
17428
|
+
* (see {@link Literal}). When raw SPARQL queries pull these values out of the
|
|
17429
|
+
* RDF store the bindings are still in encoded form; consumers must decode
|
|
17430
|
+
* before use. The helpers here centralise that decode step so each call site
|
|
17431
|
+
* can pick the variant matching its declared binding type.
|
|
17432
|
+
*
|
|
17433
|
+
* @example
|
|
17434
|
+
* ```ts
|
|
17435
|
+
* interface MessageBinding {
|
|
17436
|
+
* id: string;
|
|
17437
|
+
* timestamp: string; // raw literal — decode with parseLitNumber
|
|
17438
|
+
* body?: string; // raw literal — decode with parseLit
|
|
17439
|
+
* }
|
|
17440
|
+
* const rows = await perspective.querySparql<MessageBinding[]>(query);
|
|
17441
|
+
* const ts = parseLitNumber(rows[0].timestamp); // number
|
|
17442
|
+
* const body = rows[0].body ? parseLit(rows[0].body) : '';
|
|
17443
|
+
* ```
|
|
17444
|
+
*/
|
|
17445
|
+
/** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
|
|
17446
|
+
function parseSparqlCount(result) {
|
|
17447
|
+
if (!result || result.length === 0)
|
|
17448
|
+
return 0;
|
|
17449
|
+
const raw = result[0].count;
|
|
17450
|
+
const n = parseInt(raw, 10);
|
|
17451
|
+
return Number.isNaN(n) ? 0 : n;
|
|
17452
|
+
}
|
|
17453
|
+
/**
|
|
17454
|
+
* Decode a `Literal`-encoded SPARQL binding back to a plain string.
|
|
17455
|
+
*
|
|
17456
|
+
* Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
|
|
17457
|
+
* input. Falls through to the raw value if decoding fails (defensive — the
|
|
17458
|
+
* binding may already be a plain string for unwrapped properties).
|
|
17459
|
+
*/
|
|
17460
|
+
function parseLit(val) {
|
|
17461
|
+
if (val === undefined || val === null || val === '')
|
|
17462
|
+
return '';
|
|
17463
|
+
try {
|
|
17464
|
+
const result = Literal.fromUrl(val).get();
|
|
17465
|
+
if (result && typeof result === 'object') {
|
|
17466
|
+
return result.data ?? JSON.stringify(result);
|
|
17467
|
+
}
|
|
17468
|
+
return String(result);
|
|
17469
|
+
}
|
|
17470
|
+
catch {
|
|
17471
|
+
return val;
|
|
17472
|
+
}
|
|
17473
|
+
}
|
|
17474
|
+
/** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
|
|
17475
|
+
function parseLitNumber(val) {
|
|
17476
|
+
if (val === undefined || val === null || val === '')
|
|
17477
|
+
return 0;
|
|
17478
|
+
const decoded = parseLit(val);
|
|
17479
|
+
const n = Number(decoded);
|
|
17480
|
+
return Number.isNaN(n) ? 0 : n;
|
|
17481
|
+
}
|
|
17482
|
+
/** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
|
|
17483
|
+
function parseLitBoolean(val) {
|
|
17484
|
+
if (val === undefined || val === null || val === '')
|
|
17485
|
+
return false;
|
|
17486
|
+
return parseLit(val) === 'true';
|
|
17487
|
+
}
|
|
17488
|
+
|
|
17626
17489
|
/**
|
|
17627
17490
|
* WakerSubscriptionManager — manages live query subscriptions for the waker.
|
|
17628
17491
|
*
|
|
@@ -17909,6 +17772,195 @@ function isIncludeProjection(val) {
|
|
|
17909
17772
|
return typeof val === 'object' && val !== null && 'from' in val;
|
|
17910
17773
|
}
|
|
17911
17774
|
|
|
17775
|
+
/**
|
|
17776
|
+
* Shared query compilation utilities.
|
|
17777
|
+
*
|
|
17778
|
+
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
17779
|
+
* the compile-time SHACL generator (`decorators.ts`).
|
|
17780
|
+
*
|
|
17781
|
+
* All output uses native SPARQL syntax.
|
|
17782
|
+
*/
|
|
17783
|
+
/**
|
|
17784
|
+
* Format a JavaScript value for embedding in a query expression.
|
|
17785
|
+
*
|
|
17786
|
+
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
17787
|
+
* - Numbers and booleans are passed through as-is
|
|
17788
|
+
* - Arrays are recursed
|
|
17789
|
+
*/
|
|
17790
|
+
function formatQueryValue(value) {
|
|
17791
|
+
if (typeof value === 'string') {
|
|
17792
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
17793
|
+
const escaped = value
|
|
17794
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
17795
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
17796
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
17797
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
17798
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
17799
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
17800
|
+
return `'${escaped}'`;
|
|
17801
|
+
}
|
|
17802
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
17803
|
+
return String(value);
|
|
17804
|
+
}
|
|
17805
|
+
else if (Array.isArray(value)) {
|
|
17806
|
+
return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
|
|
17807
|
+
}
|
|
17808
|
+
else {
|
|
17809
|
+
return String(value);
|
|
17810
|
+
}
|
|
17811
|
+
}
|
|
17812
|
+
/**
|
|
17813
|
+
* Compile a single Where condition for a property into a SPARQL triple pattern
|
|
17814
|
+
* that can be embedded in a getter's WHERE clause.
|
|
17815
|
+
*
|
|
17816
|
+
* The generated pattern operates on `?target` — e.g.:
|
|
17817
|
+
* `?target <pred> <value> .`
|
|
17818
|
+
* `FILTER EXISTS { ?target <pred> ?_v0 }`
|
|
17819
|
+
*
|
|
17820
|
+
* @param predicate - The predicate URI for the property
|
|
17821
|
+
* @param condition - The Where condition value
|
|
17822
|
+
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
17823
|
+
* @returns A single SPARQL condition string
|
|
17824
|
+
*/
|
|
17825
|
+
function buildWhereCondition(predicate, condition, opts) {
|
|
17826
|
+
const escapedPredicate = escapeQueryString(predicate);
|
|
17827
|
+
// For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
|
|
17828
|
+
// For language-resolved properties, we match against the plain URI
|
|
17829
|
+
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
17830
|
+
// For language-resolved properties, values are plain URIs
|
|
17831
|
+
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
17832
|
+
const varSuffix = opts?.varIndex ?? 0;
|
|
17833
|
+
function formatValue(v) {
|
|
17834
|
+
if (typeof v === 'string') {
|
|
17835
|
+
return isLiteral
|
|
17836
|
+
? `<literal:string:${escapeQueryString(v)}>`
|
|
17837
|
+
: `<${escapeQueryString(v)}>`;
|
|
17838
|
+
}
|
|
17839
|
+
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
17840
|
+
return `<literal:string:${v}>`;
|
|
17841
|
+
}
|
|
17842
|
+
/**
|
|
17843
|
+
* For literal properties, generate a FILTER-based match that handles both
|
|
17844
|
+
* the raw value and the literal-encoded value. This mirrors the Rust
|
|
17845
|
+
* `build_projection_where_patterns` approach which uses:
|
|
17846
|
+
* FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
|
|
17847
|
+
* This is more robust than exact IRI matching because it handles edge cases
|
|
17848
|
+
* where the stored format might vary.
|
|
17849
|
+
*/
|
|
17850
|
+
function formatLiteralFilter(varName, v) {
|
|
17851
|
+
const raw = escapeQueryString(String(v));
|
|
17852
|
+
const encoded = encodeURIComponent(String(v))
|
|
17853
|
+
.replace(/!/g, '%21')
|
|
17854
|
+
.replace(/'/g, '%27')
|
|
17855
|
+
.replace(/\(/g, '%28')
|
|
17856
|
+
.replace(/\)/g, '%29')
|
|
17857
|
+
.replace(/\*/g, '%2A');
|
|
17858
|
+
if (typeof v === 'string') {
|
|
17859
|
+
return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
|
|
17860
|
+
}
|
|
17861
|
+
else if (typeof v === 'number') {
|
|
17862
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
|
|
17863
|
+
}
|
|
17864
|
+
else if (typeof v === 'boolean') {
|
|
17865
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
|
|
17866
|
+
}
|
|
17867
|
+
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
17868
|
+
}
|
|
17869
|
+
if (Array.isArray(condition)) {
|
|
17870
|
+
// Array values → FILTER IN
|
|
17871
|
+
if (isLiteral) {
|
|
17872
|
+
const varName = `?_wc${varSuffix}`;
|
|
17873
|
+
const inValues = condition.flatMap(v => {
|
|
17874
|
+
const raw = escapeQueryString(String(v));
|
|
17875
|
+
const encoded = encodeURIComponent(String(v))
|
|
17876
|
+
.replace(/!/g, '%21').replace(/'/g, '%27')
|
|
17877
|
+
.replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
|
|
17878
|
+
return [`"${raw}"`, `"literal:string:${encoded}"`];
|
|
17879
|
+
}).join(', ');
|
|
17880
|
+
return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
|
|
17881
|
+
}
|
|
17882
|
+
const formattedValues = condition.map(formatValue).join(', ');
|
|
17883
|
+
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
17884
|
+
}
|
|
17885
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
17886
|
+
// Operator object
|
|
17887
|
+
const ops = condition;
|
|
17888
|
+
const parts = [];
|
|
17889
|
+
if (ops.not !== undefined) {
|
|
17890
|
+
if (Array.isArray(ops.not)) {
|
|
17891
|
+
const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
|
|
17892
|
+
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
17893
|
+
// so O(N²) behavior is bounded by the number of values for this property.
|
|
17894
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
|
|
17895
|
+
}
|
|
17896
|
+
else {
|
|
17897
|
+
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
17898
|
+
// so O(N²) behavior is bounded by the number of values for this property.
|
|
17899
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
|
|
17900
|
+
}
|
|
17901
|
+
}
|
|
17902
|
+
// Comparison operators — ensure property exists
|
|
17903
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
17904
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
17905
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
17906
|
+
if (hasComparisonOps) {
|
|
17907
|
+
parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
|
|
17908
|
+
}
|
|
17909
|
+
return parts.join(' ');
|
|
17910
|
+
}
|
|
17911
|
+
else {
|
|
17912
|
+
// Simple equality
|
|
17913
|
+
if (isLiteral) {
|
|
17914
|
+
// Use FILTER matching (mirrors Rust build_projection_where_patterns)
|
|
17915
|
+
// to handle both raw values and literal-encoded IRIs robustly.
|
|
17916
|
+
const varName = `?_wc${varSuffix}`;
|
|
17917
|
+
return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
|
|
17918
|
+
}
|
|
17919
|
+
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
17920
|
+
}
|
|
17921
|
+
}
|
|
17922
|
+
/**
|
|
17923
|
+
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
17924
|
+
*
|
|
17925
|
+
* When `metadata` is provided, property names are resolved to predicates
|
|
17926
|
+
* using the model's property metadata. When `metadata` is `null`, property
|
|
17927
|
+
* names are treated as raw predicate URIs.
|
|
17928
|
+
*
|
|
17929
|
+
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
17930
|
+
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
17931
|
+
* runtime query time, not for compile-time getter generation).
|
|
17932
|
+
*/
|
|
17933
|
+
function compileWhereClause(where, metadata) {
|
|
17934
|
+
const conditions = [];
|
|
17935
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
17936
|
+
// Skip special fields that don't apply at compile time
|
|
17937
|
+
if (['id', 'author', 'timestamp'].includes(propertyName))
|
|
17938
|
+
continue;
|
|
17939
|
+
let predicate;
|
|
17940
|
+
let resolveLanguage;
|
|
17941
|
+
if (metadata) {
|
|
17942
|
+
const propMeta = metadata.properties[propertyName];
|
|
17943
|
+
if (propMeta) {
|
|
17944
|
+
predicate = propMeta.predicate;
|
|
17945
|
+
resolveLanguage = propMeta.resolveLanguage;
|
|
17946
|
+
}
|
|
17947
|
+
else {
|
|
17948
|
+
// Property not found in metadata — treat name as raw predicate URI
|
|
17949
|
+
predicate = propertyName;
|
|
17950
|
+
}
|
|
17951
|
+
}
|
|
17952
|
+
else {
|
|
17953
|
+
// No metadata — treat name as raw predicate URI
|
|
17954
|
+
predicate = propertyName;
|
|
17955
|
+
}
|
|
17956
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
|
|
17957
|
+
if (cond) {
|
|
17958
|
+
conditions.push(cond);
|
|
17959
|
+
}
|
|
17960
|
+
}
|
|
17961
|
+
return conditions;
|
|
17962
|
+
}
|
|
17963
|
+
|
|
17912
17964
|
class Neighbourhood {
|
|
17913
17965
|
constructor(linkLanguage, meta) {
|
|
17914
17966
|
this.linkLanguage = linkLanguage;
|
|
@@ -17941,4 +17993,110 @@ class ModelInput {
|
|
|
17941
17993
|
class VoiceActivityParamsInput {
|
|
17942
17994
|
}
|
|
17943
17995
|
|
|
17944
|
-
|
|
17996
|
+
/**
|
|
17997
|
+
* Builder functions for SHACL-AF Node Expressions.
|
|
17998
|
+
*
|
|
17999
|
+
* These functions construct JSON-serializable expression trees for property transforms.
|
|
18000
|
+
* All builders return frozen objects to prevent accidental mutation.
|
|
18001
|
+
*/
|
|
18002
|
+
/**
|
|
18003
|
+
* Identity expression: pass the focus node through unchanged.
|
|
18004
|
+
*/
|
|
18005
|
+
function focus() {
|
|
18006
|
+
return Object.freeze({ type: 'focus' });
|
|
18007
|
+
}
|
|
18008
|
+
/**
|
|
18009
|
+
* Literal constant expression.
|
|
18010
|
+
*/
|
|
18011
|
+
function literal(value) {
|
|
18012
|
+
return Object.freeze({ type: 'literal', value });
|
|
18013
|
+
}
|
|
18014
|
+
/**
|
|
18015
|
+
* Path expression: navigate to a property on the resolved object.
|
|
18016
|
+
* The predicate can be a full IRI (e.g., "file_storage://data_base64")
|
|
18017
|
+
* or a simple property name. The Rust evaluator will strip the namespace.
|
|
18018
|
+
*/
|
|
18019
|
+
function path(predicate) {
|
|
18020
|
+
return Object.freeze({ type: 'path', predicate });
|
|
18021
|
+
}
|
|
18022
|
+
/**
|
|
18023
|
+
* Existence check: returns true if the inner expression is non-null and non-empty.
|
|
18024
|
+
*/
|
|
18025
|
+
function exists(expr) {
|
|
18026
|
+
return Object.freeze({ type: 'exists', expr });
|
|
18027
|
+
}
|
|
18028
|
+
/**
|
|
18029
|
+
* Conditional expression with optional else branch.
|
|
18030
|
+
* Returns a chainable builder that supports `.then()` and `.else()`.
|
|
18031
|
+
*/
|
|
18032
|
+
function ifExpr(cond) {
|
|
18033
|
+
return {
|
|
18034
|
+
then: (thenExpr) => ({
|
|
18035
|
+
else: (elseExpr) => {
|
|
18036
|
+
return Object.freeze({
|
|
18037
|
+
type: 'if',
|
|
18038
|
+
cond,
|
|
18039
|
+
then: thenExpr,
|
|
18040
|
+
...(elseExpr !== undefined && { else: elseExpr }),
|
|
18041
|
+
});
|
|
18042
|
+
},
|
|
18043
|
+
// Allow chaining without explicit else()
|
|
18044
|
+
toExpression: () => Object.freeze({
|
|
18045
|
+
type: 'if',
|
|
18046
|
+
cond,
|
|
18047
|
+
then: thenExpr,
|
|
18048
|
+
}),
|
|
18049
|
+
}),
|
|
18050
|
+
};
|
|
18051
|
+
}
|
|
18052
|
+
/**
|
|
18053
|
+
* String concatenation: joins evaluated arguments as strings.
|
|
18054
|
+
* Null/undefined arguments are skipped.
|
|
18055
|
+
*/
|
|
18056
|
+
function concat(...args) {
|
|
18057
|
+
return Object.freeze({ type: 'concat', args });
|
|
18058
|
+
}
|
|
18059
|
+
/**
|
|
18060
|
+
* Coalesce: returns the first non-null evaluated argument.
|
|
18061
|
+
*/
|
|
18062
|
+
function coalesce(...args) {
|
|
18063
|
+
return Object.freeze({ type: 'coalesce', args });
|
|
18064
|
+
}
|
|
18065
|
+
/**
|
|
18066
|
+
* Function call: invoke a named transform function by IRI.
|
|
18067
|
+
* Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
|
|
18068
|
+
*/
|
|
18069
|
+
function fn(iri, args = []) {
|
|
18070
|
+
return Object.freeze({ type: 'function', iri, args });
|
|
18071
|
+
}
|
|
18072
|
+
|
|
18073
|
+
/**
|
|
18074
|
+
* SHACL-AF Transform DSL — public API
|
|
18075
|
+
*
|
|
18076
|
+
* Re-exports builder functions and provides common built-in transforms.
|
|
18077
|
+
*/
|
|
18078
|
+
/**
|
|
18079
|
+
* Built-in transform: FileData → data: URI
|
|
18080
|
+
*
|
|
18081
|
+
* Converts a file stored via FILE_STORAGE_LANGUAGE into a data: URL.
|
|
18082
|
+
* If the object has a `data_base64` field, returns:
|
|
18083
|
+
* `data:{file_type};base64,{data_base64}`
|
|
18084
|
+
* Otherwise passes through the input unchanged.
|
|
18085
|
+
*
|
|
18086
|
+
* This is the Rust equivalent of the JS `defaultFileDecode` function.
|
|
18087
|
+
*
|
|
18088
|
+
* Usage:
|
|
18089
|
+
* ```typescript
|
|
18090
|
+
* @Property({
|
|
18091
|
+
* through: 'we://image',
|
|
18092
|
+
* resolveLanguage: FILE_STORAGE_LANGUAGE,
|
|
18093
|
+
* transform: fileToDataUri,
|
|
18094
|
+
* })
|
|
18095
|
+
* avatar?: string;
|
|
18096
|
+
* ```
|
|
18097
|
+
*/
|
|
18098
|
+
const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
|
|
18099
|
+
.then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
|
|
18100
|
+
.else(focus());
|
|
18101
|
+
|
|
18102
|
+
export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
|