@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +564 -461
- package/lib/index.js +561 -462
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/src/model/Ad4mModel.d.ts +9 -17
- package/lib/src/model/Ad4mModel.js +34 -148
- package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
- package/lib/src/model/ModelQueryBuilder.js +8 -14
- package/lib/src/model/shacl-gen.js +115 -46
- package/lib/src/model/types.d.ts +138 -3
- package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
- package/lib/src/perspectives/PerspectiveClient.js +5 -6
- package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
- package/lib/src/perspectives/PerspectiveProxy.js +10 -9
- package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
- package/lib/src/perspectives/SparqlBindings.js +65 -0
- package/lib/src/shacl/SHACLShape.d.ts +18 -0
- package/lib/src/shacl/SHACLShape.js +83 -0
- package/package.json +8 -11
- package/src/index.ts +1 -0
- package/src/model/Ad4mModel.test.ts +23 -64
- package/src/model/Ad4mModel.ts +52 -159
- package/src/model/ModelQueryBuilder.ts +17 -23
- package/src/model/relation-filtering.test.ts +46 -39
- package/src/model/shacl-gen.ts +122 -53
- package/src/model/shacl-roundtrip.test.ts +197 -0
- package/src/model/types-typed-query.test.ts +360 -0
- package/src/model/types.ts +194 -3
- package/src/perspectives/PerspectiveClient.ts +6 -8
- package/src/perspectives/PerspectiveProxy.ts +13 -13
- package/src/perspectives/SparqlBindings.ts +79 -0
- package/src/shacl/SHACLShape.test.ts +110 -0
- package/src/shacl/SHACLShape.ts +125 -0
package/lib/index.js
CHANGED
|
@@ -1341,6 +1341,41 @@ class SHACLShape {
|
|
|
1341
1341
|
target: `literal:string:${JSON.stringify(prop.in)}`
|
|
1342
1342
|
});
|
|
1343
1343
|
}
|
|
1344
|
+
if (prop.relationKind) {
|
|
1345
|
+
links.push({
|
|
1346
|
+
source: propShapeId,
|
|
1347
|
+
predicate: "ad4m://relationKind",
|
|
1348
|
+
target: `literal:string:${prop.relationKind}`
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
if (prop.targetClassName) {
|
|
1352
|
+
links.push({
|
|
1353
|
+
source: propShapeId,
|
|
1354
|
+
predicate: "ad4m://targetClassName",
|
|
1355
|
+
target: `literal:string:${prop.targetClassName}`
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
|
|
1359
|
+
links.push({
|
|
1360
|
+
source: propShapeId,
|
|
1361
|
+
predicate: "ad4m://whereFilter",
|
|
1362
|
+
target: `literal:string:${JSON.stringify(prop.whereFilter)}`
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
|
|
1366
|
+
links.push({
|
|
1367
|
+
source: propShapeId,
|
|
1368
|
+
predicate: "ad4m://wherePredicates",
|
|
1369
|
+
target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
if (prop.filter !== undefined) {
|
|
1373
|
+
links.push({
|
|
1374
|
+
source: propShapeId,
|
|
1375
|
+
predicate: "ad4m://filter",
|
|
1376
|
+
target: `literal:${prop.filter}`
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1344
1379
|
}
|
|
1345
1380
|
return links;
|
|
1346
1381
|
}
|
|
@@ -1522,6 +1557,44 @@ class SHACLShape {
|
|
|
1522
1557
|
// Ignore parse errors
|
|
1523
1558
|
}
|
|
1524
1559
|
}
|
|
1560
|
+
const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
|
|
1561
|
+
if (relationKindLink) {
|
|
1562
|
+
const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1563
|
+
if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
|
|
1564
|
+
prop.relationKind = val;
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
|
|
1568
|
+
if (targetClassNameLink) {
|
|
1569
|
+
prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1570
|
+
}
|
|
1571
|
+
const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
|
|
1572
|
+
if (whereFilterLink) {
|
|
1573
|
+
try {
|
|
1574
|
+
const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1575
|
+
prop.whereFilter = JSON.parse(jsonStr);
|
|
1576
|
+
}
|
|
1577
|
+
catch (e) {
|
|
1578
|
+
// Ignore parse errors
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
|
|
1582
|
+
if (wherePredicatesLink) {
|
|
1583
|
+
try {
|
|
1584
|
+
const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
1585
|
+
prop.wherePredicates = JSON.parse(jsonStr);
|
|
1586
|
+
}
|
|
1587
|
+
catch (e) {
|
|
1588
|
+
// Ignore parse errors
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
|
|
1592
|
+
if (filterLink) {
|
|
1593
|
+
let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
1594
|
+
if (val.startsWith('boolean:'))
|
|
1595
|
+
val = val.substring(8);
|
|
1596
|
+
prop.filter = val === 'true';
|
|
1597
|
+
}
|
|
1525
1598
|
shape.addProperty(prop);
|
|
1526
1599
|
}
|
|
1527
1600
|
return shape;
|
|
@@ -1558,6 +1631,11 @@ class SHACLShape {
|
|
|
1558
1631
|
conformance_conditions: p.conformanceConditions,
|
|
1559
1632
|
class: p.class,
|
|
1560
1633
|
in: p.in,
|
|
1634
|
+
relation_kind: p.relationKind,
|
|
1635
|
+
target_class_name: p.targetClassName,
|
|
1636
|
+
where_filter: p.whereFilter,
|
|
1637
|
+
where_predicates: p.wherePredicates,
|
|
1638
|
+
filter: p.filter,
|
|
1561
1639
|
})),
|
|
1562
1640
|
constructor_actions: this.constructor_actions,
|
|
1563
1641
|
destructor_actions: this.destructor_actions,
|
|
@@ -1592,6 +1670,11 @@ class SHACLShape {
|
|
|
1592
1670
|
conformanceConditions: p.conformance_conditions,
|
|
1593
1671
|
class: p.class,
|
|
1594
1672
|
in: p.in,
|
|
1673
|
+
relationKind: p.relation_kind,
|
|
1674
|
+
targetClassName: p.target_class_name,
|
|
1675
|
+
whereFilter: p.where_filter,
|
|
1676
|
+
wherePredicates: p.where_predicates,
|
|
1677
|
+
filter: p.filter,
|
|
1595
1678
|
});
|
|
1596
1679
|
}
|
|
1597
1680
|
if (json.constructor_actions) {
|
|
@@ -1609,247 +1692,6 @@ class SHACLShape {
|
|
|
1609
1692
|
}
|
|
1610
1693
|
}
|
|
1611
1694
|
|
|
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
|
-
/**
|
|
1673
|
-
* Format a JavaScript value for embedding in a query expression.
|
|
1674
|
-
*
|
|
1675
|
-
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
1676
|
-
* - Numbers and booleans are passed through as-is
|
|
1677
|
-
* - Arrays are recursed
|
|
1678
|
-
*/
|
|
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
|
-
/**
|
|
1702
|
-
* Compile a single Where condition for a property into a SPARQL triple pattern
|
|
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 }`
|
|
1708
|
-
*
|
|
1709
|
-
* @param predicate - The predicate URI for the property
|
|
1710
|
-
* @param condition - The Where condition value
|
|
1711
|
-
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
1712
|
-
* @returns A single SPARQL condition string
|
|
1713
|
-
*/
|
|
1714
|
-
function buildWhereCondition(predicate, condition, opts) {
|
|
1715
|
-
const escapedPredicate = escapeQueryString(predicate);
|
|
1716
|
-
// For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
|
|
1717
|
-
// For language-resolved properties, we match against the plain URI
|
|
1718
|
-
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
1719
|
-
// For language-resolved properties, values are plain URIs
|
|
1720
|
-
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
1721
|
-
const varSuffix = opts?.varIndex ?? 0;
|
|
1722
|
-
function formatValue(v) {
|
|
1723
|
-
if (typeof v === 'string') {
|
|
1724
|
-
return isLiteral
|
|
1725
|
-
? `<literal:string:${escapeQueryString(v)}>`
|
|
1726
|
-
: `<${escapeQueryString(v)}>`;
|
|
1727
|
-
}
|
|
1728
|
-
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
1729
|
-
return `<literal:string:${v}>`;
|
|
1730
|
-
}
|
|
1731
|
-
/**
|
|
1732
|
-
* For literal properties, generate a FILTER-based match that handles both
|
|
1733
|
-
* the raw value and the literal-encoded value. This mirrors the Rust
|
|
1734
|
-
* `build_projection_where_patterns` approach which uses:
|
|
1735
|
-
* FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
|
|
1736
|
-
* This is more robust than exact IRI matching because it handles edge cases
|
|
1737
|
-
* where the stored format might vary.
|
|
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}")`;
|
|
1755
|
-
}
|
|
1756
|
-
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
1757
|
-
}
|
|
1758
|
-
if (Array.isArray(condition)) {
|
|
1759
|
-
// Array values → FILTER IN
|
|
1760
|
-
if (isLiteral) {
|
|
1761
|
-
const varName = `?_wc${varSuffix}`;
|
|
1762
|
-
const inValues = condition.flatMap(v => {
|
|
1763
|
-
const raw = escapeQueryString(String(v));
|
|
1764
|
-
const encoded = encodeURIComponent(String(v))
|
|
1765
|
-
.replace(/!/g, '%21').replace(/'/g, '%27')
|
|
1766
|
-
.replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
|
|
1767
|
-
return [`"${raw}"`, `"literal:string:${encoded}"`];
|
|
1768
|
-
}).join(', ');
|
|
1769
|
-
return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
|
|
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
1695
|
/**
|
|
1854
1696
|
* SHACL shape generation for AD4M model classes.
|
|
1855
1697
|
*
|
|
@@ -1873,7 +1715,6 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
1873
1715
|
const obj = target.prototype;
|
|
1874
1716
|
// ── Determine namespace from first property or relation ─────────────
|
|
1875
1717
|
let namespace = "ad4m://";
|
|
1876
|
-
const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
|
|
1877
1718
|
// Try properties first
|
|
1878
1719
|
if (Object.keys(properties).length > 0) {
|
|
1879
1720
|
const firstProp = properties[Object.keys(properties)[0]];
|
|
@@ -1885,8 +1726,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
1885
1726
|
}
|
|
1886
1727
|
}
|
|
1887
1728
|
// Fall back to relations if no properties
|
|
1888
|
-
else if (Object.keys(
|
|
1889
|
-
const firstRel =
|
|
1729
|
+
else if (Object.keys(allRelationsMeta).length > 0) {
|
|
1730
|
+
const firstRel = allRelationsMeta[Object.keys(allRelationsMeta)[0]];
|
|
1890
1731
|
if (firstRel.predicate) {
|
|
1891
1732
|
const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
|
|
1892
1733
|
if (match) {
|
|
@@ -1963,6 +1804,12 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
1963
1804
|
if (propMeta.resolveLanguage) {
|
|
1964
1805
|
propShape.resolveLanguage = propMeta.resolveLanguage;
|
|
1965
1806
|
}
|
|
1807
|
+
// Explicit getter SPARQL — the executor evaluates this when
|
|
1808
|
+
// hydrating the property, in addition to (or instead of)
|
|
1809
|
+
// reading raw links via `propMeta.through`.
|
|
1810
|
+
if (propMeta.getter) {
|
|
1811
|
+
propShape.getter = propMeta.getter;
|
|
1812
|
+
}
|
|
1966
1813
|
// ── Setter actions ──────────────────────────────────────────────
|
|
1967
1814
|
if (propMeta.prologSetter) {
|
|
1968
1815
|
console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
|
|
@@ -2001,63 +1848,82 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2001
1848
|
shape.addProperty(propShape);
|
|
2002
1849
|
}
|
|
2003
1850
|
// ── Convert relations to SHACL property shapes ─────────────────────
|
|
2004
|
-
for (const relName in
|
|
2005
|
-
const relMeta =
|
|
2006
|
-
|
|
1851
|
+
for (const relName in allRelationsMeta) {
|
|
1852
|
+
const relMeta = allRelationsMeta[relName];
|
|
1853
|
+
// Getter-only relations (no `through`) have no real link predicate
|
|
1854
|
+
// but still need a SHACL property entry so the executor can find
|
|
1855
|
+
// the getter expression. Synthesize a deterministic IRI so the
|
|
1856
|
+
// SHACL graph is well-formed; the predicate is never used to match
|
|
1857
|
+
// links because the getter is the sole source of values. Use
|
|
1858
|
+
// slash separators so the result is a valid IRI (colons in the
|
|
1859
|
+
// authority confuse strict SPARQL IRI parsers).
|
|
1860
|
+
if (!relMeta.predicate && !relMeta.getter)
|
|
2007
1861
|
continue;
|
|
1862
|
+
const synthesizedPath = relMeta.predicate
|
|
1863
|
+
|| `ad4m://getter/${subjectName}/${relName}`;
|
|
2008
1864
|
const relShape = {
|
|
2009
1865
|
name: relName,
|
|
2010
|
-
path:
|
|
1866
|
+
path: synthesizedPath,
|
|
2011
1867
|
};
|
|
2012
1868
|
// Relations typically contain IRIs
|
|
2013
1869
|
relShape.nodeKind = 'IRI';
|
|
1870
|
+
// Encode relation kind so the executor can derive direction and
|
|
1871
|
+
// scalar-vs-collection rendering without consulting the JS class.
|
|
1872
|
+
relShape.relationKind = relMeta.kind;
|
|
1873
|
+
// Scalar relations cap at 1.
|
|
1874
|
+
if (relMeta.kind === 'hasOne' || relMeta.kind === 'belongsToOne') {
|
|
1875
|
+
relShape.maxCount = 1;
|
|
1876
|
+
}
|
|
1877
|
+
else if (relMeta.maxCount !== undefined) {
|
|
1878
|
+
relShape.maxCount = relMeta.maxCount;
|
|
1879
|
+
}
|
|
1880
|
+
// Encode opt-out of type filtering (default true; only emit when false).
|
|
1881
|
+
if (relMeta.filter === false) {
|
|
1882
|
+
relShape.filter = false;
|
|
1883
|
+
}
|
|
2014
1884
|
// AD4M-specific metadata
|
|
2015
1885
|
if (relMeta.local !== undefined) {
|
|
2016
1886
|
relShape.local = relMeta.local;
|
|
2017
1887
|
}
|
|
2018
|
-
// Adder
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
1888
|
+
// Adder / Remover actions — only meaningful for relations backed
|
|
1889
|
+
// by a real link predicate. Getter-only relations are read-only.
|
|
1890
|
+
if (relMeta.predicate) {
|
|
1891
|
+
relShape.adder = [{
|
|
1892
|
+
action: "addLink",
|
|
1893
|
+
source: "this",
|
|
1894
|
+
predicate: relMeta.predicate,
|
|
1895
|
+
target: "value",
|
|
1896
|
+
...(relMeta.local && { local: true })
|
|
1897
|
+
}];
|
|
1898
|
+
relShape.remover = [{
|
|
1899
|
+
action: "removeLink",
|
|
1900
|
+
source: "this",
|
|
1901
|
+
predicate: relMeta.predicate,
|
|
1902
|
+
target: "value",
|
|
1903
|
+
...(relMeta.local && { local: true })
|
|
1904
|
+
}];
|
|
1905
|
+
}
|
|
2034
1906
|
// ── Build Getter (conformance filter) ───────────────────────────
|
|
2035
1907
|
// Priority chain:
|
|
2036
1908
|
// 1. Explicit getter string → use verbatim
|
|
2037
|
-
// 2.
|
|
2038
|
-
//
|
|
1909
|
+
// 2. target + filter !== false → auto-derive conformance getter
|
|
1910
|
+
// from the shape. Where-clause filtering is applied as a
|
|
1911
|
+
// post-getter pass via `whereFilter` / `wherePredicates`, which
|
|
1912
|
+
// use `parse_literal_value` and so transparently handle
|
|
1913
|
+
// `literal:json:` envelopes that simple FILTER(STR(?x) = ...)
|
|
1914
|
+
// comparisons can't.
|
|
2039
1915
|
if (relMeta.getter) {
|
|
2040
1916
|
relShape.getter = relMeta.getter;
|
|
2041
1917
|
}
|
|
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) {
|
|
1918
|
+
else if (relMeta.target
|
|
1919
|
+
&& relMeta.filter !== false
|
|
1920
|
+
&& relMeta.kind !== 'belongsToOne'
|
|
1921
|
+
&& relMeta.kind !== 'belongsToMany') {
|
|
2059
1922
|
// Lazy conformance filter: store deferred reference,
|
|
2060
|
-
// resolve on first access via a getter on relShape
|
|
1923
|
+
// resolve on first access via a getter on relShape.
|
|
1924
|
+
// Skipped for reverse relations (belongsTo*) because the
|
|
1925
|
+
// auto-derived getter assumes forward direction; the executor's
|
|
1926
|
+
// `resolve_reverse_relations` already populates these correctly.
|
|
2061
1927
|
const targetThunk = relMeta.target;
|
|
2062
1928
|
const predicate = relMeta.predicate;
|
|
2063
1929
|
let resolved = false;
|
|
@@ -2094,6 +1960,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2094
1960
|
});
|
|
2095
1961
|
}
|
|
2096
1962
|
// ── sh:class — target shape reference ───────────────────────────
|
|
1963
|
+
// Also emit ad4m:targetClassName so the executor can look up the
|
|
1964
|
+
// target class shape through its in-memory cache by bare name.
|
|
2097
1965
|
if (relMeta.target) {
|
|
2098
1966
|
try {
|
|
2099
1967
|
const TargetClass = relMeta.target();
|
|
@@ -2101,9 +1969,54 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2101
1969
|
if (targetSHACL?.shape?.nodeShapeUri) {
|
|
2102
1970
|
relShape.class = targetSHACL.shape.nodeShapeUri;
|
|
2103
1971
|
}
|
|
1972
|
+
if (targetSHACL?.name) {
|
|
1973
|
+
relShape.targetClassName = targetSHACL.name;
|
|
1974
|
+
}
|
|
1975
|
+
else {
|
|
1976
|
+
const targetProto = TargetClass.prototype;
|
|
1977
|
+
if (targetProto?.className) {
|
|
1978
|
+
relShape.targetClassName = targetProto.className;
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
catch (e) {
|
|
1983
|
+
// Target class resolution failed (typically a circular
|
|
1984
|
+
// decorator dependency). Since the executor no longer
|
|
1985
|
+
// receives target metadata over the wire, dropping the
|
|
1986
|
+
// reference here would turn a transient build-time issue
|
|
1987
|
+
// into a permanent broken-include at query time. Log
|
|
1988
|
+
// loudly so the failure is discoverable.
|
|
1989
|
+
console.warn(`[shacl-gen] Failed to resolve target class for relation `
|
|
1990
|
+
+ `"${subjectName}.${relName}": ${e instanceof Error ? e.message : String(e)}`);
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
// ── Where-clause metadata for post-getter filtering ─────────────
|
|
1994
|
+
// The executor uses these to apply where conditions against the
|
|
1995
|
+
// target class without needing the target's ModelMetadata at query time.
|
|
1996
|
+
if (relMeta.where) {
|
|
1997
|
+
relShape.whereFilter = relMeta.where;
|
|
1998
|
+
try {
|
|
1999
|
+
const TargetClass = relMeta.target?.();
|
|
2000
|
+
const targetMetadata = TargetClass
|
|
2001
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
2002
|
+
: null;
|
|
2003
|
+
if (targetMetadata?.properties) {
|
|
2004
|
+
const predicates = {};
|
|
2005
|
+
for (const propName of Object.keys(relMeta.where)) {
|
|
2006
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
2007
|
+
continue;
|
|
2008
|
+
const propMeta = targetMetadata.properties[propName];
|
|
2009
|
+
if (propMeta?.predicate) {
|
|
2010
|
+
predicates[propName] = propMeta.predicate;
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
if (Object.keys(predicates).length > 0) {
|
|
2014
|
+
relShape.wherePredicates = predicates;
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2104
2017
|
}
|
|
2105
2018
|
catch (e) {
|
|
2106
|
-
// Target
|
|
2019
|
+
// Target metadata may not be available yet
|
|
2107
2020
|
}
|
|
2108
2021
|
}
|
|
2109
2022
|
shape.addProperty(relShape);
|
|
@@ -2121,6 +2034,58 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
2121
2034
|
};
|
|
2122
2035
|
}
|
|
2123
2036
|
|
|
2037
|
+
function formatList(list) {
|
|
2038
|
+
if (!list?.length) {
|
|
2039
|
+
return "";
|
|
2040
|
+
}
|
|
2041
|
+
if (list.length === 1) {
|
|
2042
|
+
return list.toString();
|
|
2043
|
+
}
|
|
2044
|
+
if (list.length === 2) {
|
|
2045
|
+
return list.join(' and ');
|
|
2046
|
+
}
|
|
2047
|
+
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
2048
|
+
}
|
|
2049
|
+
function capSentence(cap) {
|
|
2050
|
+
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
2051
|
+
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
2052
|
+
const pointers = cap.with.pointers.includes("*")
|
|
2053
|
+
? ["all AD4M data"]
|
|
2054
|
+
: cap.with.pointers;
|
|
2055
|
+
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
2056
|
+
}
|
|
2057
|
+
/**
|
|
2058
|
+
* Escapes a string value for safe use in query strings.
|
|
2059
|
+
*
|
|
2060
|
+
* @description
|
|
2061
|
+
* Prevents SQL injection by properly escaping special characters in string values
|
|
2062
|
+
* that will be interpolated into query strings. This handles the most common
|
|
2063
|
+
* special characters that could break SQL queries or enable injection attacks.
|
|
2064
|
+
*
|
|
2065
|
+
* Single quotes, backslashes, and other special characters are escaped using
|
|
2066
|
+
* backslash notation, which is the standard escaping mechanism for query.
|
|
2067
|
+
*
|
|
2068
|
+
* @param value - The string value to escape
|
|
2069
|
+
* @returns The escaped string safe for query interpolation (without surrounding quotes)
|
|
2070
|
+
*
|
|
2071
|
+
* @example
|
|
2072
|
+
* ```typescript
|
|
2073
|
+
* const userInput = "user's input with 'quotes'";
|
|
2074
|
+
* const escaped = escapeQueryString(userInput);
|
|
2075
|
+
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
2076
|
+
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
2077
|
+
* ```
|
|
2078
|
+
*/
|
|
2079
|
+
function escapeQueryString(value) {
|
|
2080
|
+
return value
|
|
2081
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
2082
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
2083
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
2084
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
2085
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
2086
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2124
2089
|
/** Registry of property metadata keyed by constructor → { propName → metadata } */
|
|
2125
2090
|
const propertyRegistry = new WeakMap();
|
|
2126
2091
|
/** Registry of relation metadata keyed by constructor → { propName → metadata } */
|
|
@@ -3737,13 +3702,16 @@ class PerspectiveProxy {
|
|
|
3737
3702
|
/**
|
|
3738
3703
|
* Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
|
|
3739
3704
|
*
|
|
3705
|
+
* The executor resolves the model's shape from the perspective's SHACL
|
|
3706
|
+
* triples (written by `addSdna`). Callers no longer ship shape
|
|
3707
|
+
* metadata with the query; the perspective is the source of truth.
|
|
3708
|
+
*
|
|
3740
3709
|
* @param className - The model class name (e.g. "Recipe")
|
|
3741
3710
|
* @param queryJson - Structured query as JSON string
|
|
3742
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
3743
3711
|
* @returns Object with `instances` array and `totalCount`
|
|
3744
3712
|
*/
|
|
3745
|
-
async modelQuery(className, queryJson
|
|
3746
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
3713
|
+
async modelQuery(className, queryJson) {
|
|
3714
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
3747
3715
|
}
|
|
3748
3716
|
/**
|
|
3749
3717
|
* Evaluate property getters for a batch of instances in a single RPC call.
|
|
@@ -3754,12 +3722,11 @@ class PerspectiveProxy {
|
|
|
3754
3722
|
*
|
|
3755
3723
|
* @param className - The model class name (e.g. "Message")
|
|
3756
3724
|
* @param instanceIds - Array of instance base expression URIs
|
|
3757
|
-
* @param shapeJson - Shape metadata JSON from the model class
|
|
3758
3725
|
* @param propertyNames - Optional subset of property names to evaluate
|
|
3759
3726
|
* @returns Map of instance ID → evaluated property values
|
|
3760
3727
|
*/
|
|
3761
|
-
async evaluateGetters(className, instanceIds,
|
|
3762
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds,
|
|
3728
|
+
async evaluateGetters(className, instanceIds, propertyNames) {
|
|
3729
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
|
|
3763
3730
|
}
|
|
3764
3731
|
/**
|
|
3765
3732
|
* Subscribe to model query changes. Builds trigger SPARQL from the model shape
|
|
@@ -3771,11 +3738,10 @@ class PerspectiveProxy {
|
|
|
3771
3738
|
*
|
|
3772
3739
|
* @param className - The model class name
|
|
3773
3740
|
* @param queryJson - JSON-serialized query parameters (same as modelQuery)
|
|
3774
|
-
* @param shapeJson - Optional shape metadata JSON from the model class
|
|
3775
3741
|
* @returns Object with `subscriptionId` and initial `result`
|
|
3776
3742
|
*/
|
|
3777
|
-
async modelSubscribe(className, queryJson
|
|
3778
|
-
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson
|
|
3743
|
+
async modelSubscribe(className, queryJson) {
|
|
3744
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
|
|
3779
3745
|
}
|
|
3780
3746
|
/**
|
|
3781
3747
|
* Adds a new link to the perspective.
|
|
@@ -5417,22 +5383,21 @@ class PerspectiveClient {
|
|
|
5417
5383
|
}
|
|
5418
5384
|
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
|
|
5419
5385
|
}
|
|
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
|
|
5386
|
+
async modelQuery(uuid, className, queryJson) {
|
|
5387
|
+
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
|
|
5422
5388
|
return JSON.parse(resultJson);
|
|
5423
5389
|
}
|
|
5424
|
-
async evaluateGetters(uuid, className, instanceIds,
|
|
5390
|
+
async evaluateGetters(uuid, className, instanceIds, propertyNames) {
|
|
5425
5391
|
const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
|
|
5426
5392
|
uuid,
|
|
5427
5393
|
class_name: className,
|
|
5428
5394
|
instance_ids: instanceIds,
|
|
5429
|
-
shape_json: shapeJson,
|
|
5430
5395
|
...(propertyNames && { property_names: propertyNames }),
|
|
5431
5396
|
});
|
|
5432
5397
|
return JSON.parse(resultJson);
|
|
5433
5398
|
}
|
|
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
|
|
5399
|
+
async modelSubscribe(uuid, className, queryJson) {
|
|
5400
|
+
const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson });
|
|
5436
5401
|
return {
|
|
5437
5402
|
subscriptionId: response.subscription_id,
|
|
5438
5403
|
result: JSON.parse(response.result)
|
|
@@ -14903,13 +14868,6 @@ class ModelQueryBuilder {
|
|
|
14903
14868
|
this.modelClassName = className;
|
|
14904
14869
|
return this;
|
|
14905
14870
|
}
|
|
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
14871
|
/**
|
|
14914
14872
|
* Executes the query once and returns the results.
|
|
14915
14873
|
*
|
|
@@ -14991,11 +14949,12 @@ class ModelQueryBuilder {
|
|
|
14991
14949
|
// Clean up any existing subscription
|
|
14992
14950
|
this.dispose();
|
|
14993
14951
|
const ctor = this.ctor;
|
|
14994
|
-
// Build the model query params (className, queryJson
|
|
14995
|
-
|
|
14952
|
+
// Build the model query params (className, queryJson). The executor
|
|
14953
|
+
// resolves the shape from the perspective's SHACL triples.
|
|
14954
|
+
const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
|
|
14996
14955
|
// Register model subscription via Rust — this builds trigger SPARQL internally,
|
|
14997
14956
|
// registers the subscription, and runs the initial query in one call.
|
|
14998
|
-
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson
|
|
14957
|
+
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
|
|
14999
14958
|
// Convert JSON instances to model class instances
|
|
15000
14959
|
const parseResults = (raw) => {
|
|
15001
14960
|
return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
|
|
@@ -15155,8 +15114,8 @@ class ModelQueryBuilder {
|
|
|
15155
15114
|
// Clean up any existing subscription
|
|
15156
15115
|
this.dispose();
|
|
15157
15116
|
const countParams = { ...this.queryParams, limit: 0 };
|
|
15158
|
-
const { className, queryJson
|
|
15159
|
-
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson
|
|
15117
|
+
const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
|
|
15118
|
+
const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
|
|
15160
15119
|
const parseCount = (raw) => {
|
|
15161
15120
|
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
15162
15121
|
return data.totalCount ?? 0;
|
|
@@ -15291,8 +15250,8 @@ class ModelQueryBuilder {
|
|
|
15291
15250
|
const subscriptionParams = { ...(this.queryParams || {}) };
|
|
15292
15251
|
delete subscriptionParams.limit;
|
|
15293
15252
|
delete subscriptionParams.offset;
|
|
15294
|
-
const { className, queryJson
|
|
15295
|
-
const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson
|
|
15253
|
+
const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
|
|
15254
|
+
const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
|
|
15296
15255
|
// Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
|
|
15297
15256
|
const paginatedQuery = {
|
|
15298
15257
|
...(this.queryParams || {}),
|
|
@@ -15433,46 +15392,6 @@ function defaultFileDecode(resolved) {
|
|
|
15433
15392
|
// ---------------------------------------------------------------------------
|
|
15434
15393
|
// Helpers for Rust-side include resolution
|
|
15435
15394
|
// ---------------------------------------------------------------------------
|
|
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
15395
|
/**
|
|
15477
15396
|
* Construct a model class instance from a plain JSON object returned by the
|
|
15478
15397
|
* Rust endpoint. Recursively converts included relation values (which come
|
|
@@ -16154,7 +16073,8 @@ class Ad4mModel {
|
|
|
16154
16073
|
}
|
|
16155
16074
|
/**
|
|
16156
16075
|
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
16157
|
-
* Returns the className
|
|
16076
|
+
* Returns the className and queryJson that the Rust executor expects.
|
|
16077
|
+
* Shape resolution happens server-side from the perspective's SHACL triples.
|
|
16158
16078
|
* @internal
|
|
16159
16079
|
*/
|
|
16160
16080
|
static prepareModelQueryParams(query = {}, classNameOverride) {
|
|
@@ -16194,16 +16114,18 @@ class Ad4mModel {
|
|
|
16194
16114
|
if (Object.keys(normalIncludes).length > 0)
|
|
16195
16115
|
queryInput.include = normalIncludes;
|
|
16196
16116
|
if (Object.keys(projections).length > 0) {
|
|
16197
|
-
//
|
|
16117
|
+
// Tag each projection with its target class name so the executor can
|
|
16118
|
+
// resolve the target shape through its in-memory cache when applying
|
|
16119
|
+
// projection where-clause filters.
|
|
16198
16120
|
const allRelMeta = getRelationsMetadata(this);
|
|
16199
16121
|
for (const [, proj] of Object.entries(projections)) {
|
|
16200
16122
|
const relMeta = allRelMeta[proj.from];
|
|
16201
|
-
if (!proj.
|
|
16123
|
+
if (!proj.targetClassName && relMeta?.target) {
|
|
16202
16124
|
try {
|
|
16203
16125
|
const TargetClass = relMeta.target();
|
|
16204
16126
|
const targetMeta = TargetClass.getModelMetadata?.();
|
|
16205
|
-
if (targetMeta) {
|
|
16206
|
-
proj.
|
|
16127
|
+
if (targetMeta?.className) {
|
|
16128
|
+
proj.targetClassName = targetMeta.className;
|
|
16207
16129
|
}
|
|
16208
16130
|
}
|
|
16209
16131
|
catch (e) {
|
|
@@ -16226,64 +16148,12 @@ class Ad4mModel {
|
|
|
16226
16148
|
if (query.count !== undefined)
|
|
16227
16149
|
queryInput.count = query.count;
|
|
16228
16150
|
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
|
-
}
|
|
16151
|
+
// Conformance getters, where filters, and target shapes for includes
|
|
16152
|
+
// are all resolved by the executor from the perspective's SHACL triples
|
|
16153
|
+
// — no client-side pre-computation is needed any more.
|
|
16283
16154
|
return {
|
|
16284
16155
|
className,
|
|
16285
16156
|
queryJson: JSON.stringify(queryInput),
|
|
16286
|
-
shapeJson: JSON.stringify(metadata),
|
|
16287
16157
|
metadata,
|
|
16288
16158
|
};
|
|
16289
16159
|
}
|
|
@@ -16360,10 +16230,10 @@ class Ad4mModel {
|
|
|
16360
16230
|
* @internal
|
|
16361
16231
|
*/
|
|
16362
16232
|
static async executeModelQuery(perspective, query = {}, classNameOverride) {
|
|
16363
|
-
// Delegate
|
|
16364
|
-
//
|
|
16365
|
-
const { className, queryJson
|
|
16366
|
-
const result = await perspective.modelQuery(className, queryJson
|
|
16233
|
+
// Delegate query input building to the shared prepareModelQueryParams
|
|
16234
|
+
// helper. The executor resolves the shape from SHACL server-side.
|
|
16235
|
+
const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
|
|
16236
|
+
const result = await perspective.modelQuery(className, queryJson);
|
|
16367
16237
|
// Convert JSON instances to model class instances, recursively constructing
|
|
16368
16238
|
// class instances for any included relations resolved by Rust.
|
|
16369
16239
|
const instances = result.instances.map((json) => {
|
|
@@ -16409,13 +16279,12 @@ class Ad4mModel {
|
|
|
16409
16279
|
* });
|
|
16410
16280
|
* ```
|
|
16411
16281
|
*/
|
|
16412
|
-
static async findAll(perspective, query
|
|
16413
|
-
|
|
16414
|
-
|
|
16415
|
-
if (query.properties && query.properties.length === 0) {
|
|
16282
|
+
static async findAll(perspective, query) {
|
|
16283
|
+
const q = (query ?? {});
|
|
16284
|
+
if (q.properties && q.properties.length === 0) {
|
|
16416
16285
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
16417
16286
|
}
|
|
16418
|
-
const { results } = await this.executeModelQuery(perspective,
|
|
16287
|
+
const { results } = await this.executeModelQuery(perspective, q);
|
|
16419
16288
|
return results;
|
|
16420
16289
|
}
|
|
16421
16290
|
/**
|
|
@@ -16438,10 +16307,8 @@ class Ad4mModel {
|
|
|
16438
16307
|
* }
|
|
16439
16308
|
* ```
|
|
16440
16309
|
*/
|
|
16441
|
-
static async findOne(perspective, query
|
|
16442
|
-
|
|
16443
|
-
_engine) {
|
|
16444
|
-
const limitedQuery = { ...query, limit: 1 };
|
|
16310
|
+
static async findOne(perspective, query) {
|
|
16311
|
+
const limitedQuery = { ...(query ?? {}), limit: 1 };
|
|
16445
16312
|
const results = await this.findAll(perspective, limitedQuery);
|
|
16446
16313
|
return results[0] ?? null;
|
|
16447
16314
|
}
|
|
@@ -16462,10 +16329,9 @@ class Ad4mModel {
|
|
|
16462
16329
|
* console.log(`Showing 10 of ${totalCount} dessert recipes`);
|
|
16463
16330
|
* ```
|
|
16464
16331
|
*/
|
|
16465
|
-
static async findAllAndCount(perspective, query
|
|
16466
|
-
|
|
16467
|
-
|
|
16468
|
-
return await this.executeModelQuery(perspective, query);
|
|
16332
|
+
static async findAllAndCount(perspective, query) {
|
|
16333
|
+
const out = await this.executeModelQuery(perspective, (query ?? {}));
|
|
16334
|
+
return out;
|
|
16469
16335
|
}
|
|
16470
16336
|
/**
|
|
16471
16337
|
* Helper function for pagination with explicit page size and number.
|
|
@@ -16484,12 +16350,10 @@ class Ad4mModel {
|
|
|
16484
16350
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
16485
16351
|
* ```
|
|
16486
16352
|
*/
|
|
16487
|
-
static async paginate(perspective, pageSize, pageNumber, query
|
|
16488
|
-
|
|
16489
|
-
_engine) {
|
|
16490
|
-
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
16353
|
+
static async paginate(perspective, pageSize, pageNumber, query) {
|
|
16354
|
+
const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
16491
16355
|
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
16492
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
16356
|
+
return { results: results, totalCount, pageSize, pageNumber };
|
|
16493
16357
|
}
|
|
16494
16358
|
/**
|
|
16495
16359
|
* Generates a SPARQL COUNT query for the model.
|
|
@@ -16516,8 +16380,8 @@ class Ad4mModel {
|
|
|
16516
16380
|
* });
|
|
16517
16381
|
* ```
|
|
16518
16382
|
*/
|
|
16519
|
-
static async count(perspective, query
|
|
16520
|
-
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
16383
|
+
static async count(perspective, query) {
|
|
16384
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
|
|
16521
16385
|
return totalCount;
|
|
16522
16386
|
}
|
|
16523
16387
|
async setProperty(key, value, batchId) {
|
|
@@ -16828,29 +16692,10 @@ class Ad4mModel {
|
|
|
16828
16692
|
if (instances.length === 0)
|
|
16829
16693
|
return;
|
|
16830
16694
|
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
16695
|
const instanceIds = instances.map(inst => inst.id || inst._baseExpression);
|
|
16852
|
-
//
|
|
16853
|
-
|
|
16696
|
+
// The executor reads getter SPARQL from the perspective's SHACL triples
|
|
16697
|
+
// (written by `addSdna`), so no shape JSON is shipped with the call.
|
|
16698
|
+
const result = await perspective.evaluateGetters(metadata.className, instanceIds, propertyNames);
|
|
16854
16699
|
// Determine which property names were evaluated for snapshot sync
|
|
16855
16700
|
const evaluatedPropertyNames = [];
|
|
16856
16701
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
@@ -17214,7 +17059,7 @@ class Ad4mModel {
|
|
|
17214
17059
|
* ```
|
|
17215
17060
|
*/
|
|
17216
17061
|
static query(perspective, query) {
|
|
17217
|
-
return new ModelQueryBuilder(perspective, this, query);
|
|
17062
|
+
return new ModelQueryBuilder(perspective, this, (query ?? {}));
|
|
17218
17063
|
}
|
|
17219
17064
|
/**
|
|
17220
17065
|
* Creates an Ad4mModel class from a JSON Schema definition.
|
|
@@ -17623,6 +17468,71 @@ class PerspectiveHandle {
|
|
|
17623
17468
|
}
|
|
17624
17469
|
}
|
|
17625
17470
|
|
|
17471
|
+
/**
|
|
17472
|
+
* SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
|
|
17473
|
+
*
|
|
17474
|
+
* AD4M stores non-string property values as URL-encoded `Literal` payloads
|
|
17475
|
+
* (see {@link Literal}). When raw SPARQL queries pull these values out of the
|
|
17476
|
+
* RDF store the bindings are still in encoded form; consumers must decode
|
|
17477
|
+
* before use. The helpers here centralise that decode step so each call site
|
|
17478
|
+
* can pick the variant matching its declared binding type.
|
|
17479
|
+
*
|
|
17480
|
+
* @example
|
|
17481
|
+
* ```ts
|
|
17482
|
+
* interface MessageBinding {
|
|
17483
|
+
* id: string;
|
|
17484
|
+
* timestamp: string; // raw literal — decode with parseLitNumber
|
|
17485
|
+
* body?: string; // raw literal — decode with parseLit
|
|
17486
|
+
* }
|
|
17487
|
+
* const rows = await perspective.querySparql<MessageBinding[]>(query);
|
|
17488
|
+
* const ts = parseLitNumber(rows[0].timestamp); // number
|
|
17489
|
+
* const body = rows[0].body ? parseLit(rows[0].body) : '';
|
|
17490
|
+
* ```
|
|
17491
|
+
*/
|
|
17492
|
+
/** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
|
|
17493
|
+
function parseSparqlCount(result) {
|
|
17494
|
+
if (!result || result.length === 0)
|
|
17495
|
+
return 0;
|
|
17496
|
+
const raw = result[0].count;
|
|
17497
|
+
const n = parseInt(raw, 10);
|
|
17498
|
+
return Number.isNaN(n) ? 0 : n;
|
|
17499
|
+
}
|
|
17500
|
+
/**
|
|
17501
|
+
* Decode a `Literal`-encoded SPARQL binding back to a plain string.
|
|
17502
|
+
*
|
|
17503
|
+
* Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
|
|
17504
|
+
* input. Falls through to the raw value if decoding fails (defensive — the
|
|
17505
|
+
* binding may already be a plain string for unwrapped properties).
|
|
17506
|
+
*/
|
|
17507
|
+
function parseLit(val) {
|
|
17508
|
+
if (val === undefined || val === null || val === '')
|
|
17509
|
+
return '';
|
|
17510
|
+
try {
|
|
17511
|
+
const result = Literal.fromUrl(val).get();
|
|
17512
|
+
if (result && typeof result === 'object') {
|
|
17513
|
+
return result.data ?? JSON.stringify(result);
|
|
17514
|
+
}
|
|
17515
|
+
return String(result);
|
|
17516
|
+
}
|
|
17517
|
+
catch {
|
|
17518
|
+
return val;
|
|
17519
|
+
}
|
|
17520
|
+
}
|
|
17521
|
+
/** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
|
|
17522
|
+
function parseLitNumber(val) {
|
|
17523
|
+
if (val === undefined || val === null || val === '')
|
|
17524
|
+
return 0;
|
|
17525
|
+
const decoded = parseLit(val);
|
|
17526
|
+
const n = Number(decoded);
|
|
17527
|
+
return Number.isNaN(n) ? 0 : n;
|
|
17528
|
+
}
|
|
17529
|
+
/** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
|
|
17530
|
+
function parseLitBoolean(val) {
|
|
17531
|
+
if (val === undefined || val === null || val === '')
|
|
17532
|
+
return false;
|
|
17533
|
+
return parseLit(val) === 'true';
|
|
17534
|
+
}
|
|
17535
|
+
|
|
17626
17536
|
/**
|
|
17627
17537
|
* WakerSubscriptionManager — manages live query subscriptions for the waker.
|
|
17628
17538
|
*
|
|
@@ -17909,6 +17819,195 @@ function isIncludeProjection(val) {
|
|
|
17909
17819
|
return typeof val === 'object' && val !== null && 'from' in val;
|
|
17910
17820
|
}
|
|
17911
17821
|
|
|
17822
|
+
/**
|
|
17823
|
+
* Shared query compilation utilities.
|
|
17824
|
+
*
|
|
17825
|
+
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
17826
|
+
* the compile-time SHACL generator (`decorators.ts`).
|
|
17827
|
+
*
|
|
17828
|
+
* All output uses native SPARQL syntax.
|
|
17829
|
+
*/
|
|
17830
|
+
/**
|
|
17831
|
+
* Format a JavaScript value for embedding in a query expression.
|
|
17832
|
+
*
|
|
17833
|
+
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
17834
|
+
* - Numbers and booleans are passed through as-is
|
|
17835
|
+
* - Arrays are recursed
|
|
17836
|
+
*/
|
|
17837
|
+
function formatQueryValue(value) {
|
|
17838
|
+
if (typeof value === 'string') {
|
|
17839
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
17840
|
+
const escaped = value
|
|
17841
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
17842
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
17843
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
17844
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
17845
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
17846
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
17847
|
+
return `'${escaped}'`;
|
|
17848
|
+
}
|
|
17849
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
17850
|
+
return String(value);
|
|
17851
|
+
}
|
|
17852
|
+
else if (Array.isArray(value)) {
|
|
17853
|
+
return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
|
|
17854
|
+
}
|
|
17855
|
+
else {
|
|
17856
|
+
return String(value);
|
|
17857
|
+
}
|
|
17858
|
+
}
|
|
17859
|
+
/**
|
|
17860
|
+
* Compile a single Where condition for a property into a SPARQL triple pattern
|
|
17861
|
+
* that can be embedded in a getter's WHERE clause.
|
|
17862
|
+
*
|
|
17863
|
+
* The generated pattern operates on `?target` — e.g.:
|
|
17864
|
+
* `?target <pred> <value> .`
|
|
17865
|
+
* `FILTER EXISTS { ?target <pred> ?_v0 }`
|
|
17866
|
+
*
|
|
17867
|
+
* @param predicate - The predicate URI for the property
|
|
17868
|
+
* @param condition - The Where condition value
|
|
17869
|
+
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
17870
|
+
* @returns A single SPARQL condition string
|
|
17871
|
+
*/
|
|
17872
|
+
function buildWhereCondition(predicate, condition, opts) {
|
|
17873
|
+
const escapedPredicate = escapeQueryString(predicate);
|
|
17874
|
+
// For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
|
|
17875
|
+
// For language-resolved properties, we match against the plain URI
|
|
17876
|
+
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
17877
|
+
// For language-resolved properties, values are plain URIs
|
|
17878
|
+
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
17879
|
+
const varSuffix = opts?.varIndex ?? 0;
|
|
17880
|
+
function formatValue(v) {
|
|
17881
|
+
if (typeof v === 'string') {
|
|
17882
|
+
return isLiteral
|
|
17883
|
+
? `<literal:string:${escapeQueryString(v)}>`
|
|
17884
|
+
: `<${escapeQueryString(v)}>`;
|
|
17885
|
+
}
|
|
17886
|
+
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
17887
|
+
return `<literal:string:${v}>`;
|
|
17888
|
+
}
|
|
17889
|
+
/**
|
|
17890
|
+
* For literal properties, generate a FILTER-based match that handles both
|
|
17891
|
+
* the raw value and the literal-encoded value. This mirrors the Rust
|
|
17892
|
+
* `build_projection_where_patterns` approach which uses:
|
|
17893
|
+
* FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
|
|
17894
|
+
* This is more robust than exact IRI matching because it handles edge cases
|
|
17895
|
+
* where the stored format might vary.
|
|
17896
|
+
*/
|
|
17897
|
+
function formatLiteralFilter(varName, v) {
|
|
17898
|
+
const raw = escapeQueryString(String(v));
|
|
17899
|
+
const encoded = encodeURIComponent(String(v))
|
|
17900
|
+
.replace(/!/g, '%21')
|
|
17901
|
+
.replace(/'/g, '%27')
|
|
17902
|
+
.replace(/\(/g, '%28')
|
|
17903
|
+
.replace(/\)/g, '%29')
|
|
17904
|
+
.replace(/\*/g, '%2A');
|
|
17905
|
+
if (typeof v === 'string') {
|
|
17906
|
+
return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
|
|
17907
|
+
}
|
|
17908
|
+
else if (typeof v === 'number') {
|
|
17909
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
|
|
17910
|
+
}
|
|
17911
|
+
else if (typeof v === 'boolean') {
|
|
17912
|
+
return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
|
|
17913
|
+
}
|
|
17914
|
+
return `FILTER(STR(${varName}) = "${raw}")`;
|
|
17915
|
+
}
|
|
17916
|
+
if (Array.isArray(condition)) {
|
|
17917
|
+
// Array values → FILTER IN
|
|
17918
|
+
if (isLiteral) {
|
|
17919
|
+
const varName = `?_wc${varSuffix}`;
|
|
17920
|
+
const inValues = condition.flatMap(v => {
|
|
17921
|
+
const raw = escapeQueryString(String(v));
|
|
17922
|
+
const encoded = encodeURIComponent(String(v))
|
|
17923
|
+
.replace(/!/g, '%21').replace(/'/g, '%27')
|
|
17924
|
+
.replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
|
|
17925
|
+
return [`"${raw}"`, `"literal:string:${encoded}"`];
|
|
17926
|
+
}).join(', ');
|
|
17927
|
+
return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
|
|
17928
|
+
}
|
|
17929
|
+
const formattedValues = condition.map(formatValue).join(', ');
|
|
17930
|
+
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
17931
|
+
}
|
|
17932
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
17933
|
+
// Operator object
|
|
17934
|
+
const ops = condition;
|
|
17935
|
+
const parts = [];
|
|
17936
|
+
if (ops.not !== undefined) {
|
|
17937
|
+
if (Array.isArray(ops.not)) {
|
|
17938
|
+
const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
|
|
17939
|
+
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
17940
|
+
// so O(N²) behavior is bounded by the number of values for this property.
|
|
17941
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
|
|
17942
|
+
}
|
|
17943
|
+
else {
|
|
17944
|
+
// FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,
|
|
17945
|
+
// so O(N²) behavior is bounded by the number of values for this property.
|
|
17946
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
|
|
17947
|
+
}
|
|
17948
|
+
}
|
|
17949
|
+
// Comparison operators — ensure property exists
|
|
17950
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
17951
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
17952
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
17953
|
+
if (hasComparisonOps) {
|
|
17954
|
+
parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
|
|
17955
|
+
}
|
|
17956
|
+
return parts.join(' ');
|
|
17957
|
+
}
|
|
17958
|
+
else {
|
|
17959
|
+
// Simple equality
|
|
17960
|
+
if (isLiteral) {
|
|
17961
|
+
// Use FILTER matching (mirrors Rust build_projection_where_patterns)
|
|
17962
|
+
// to handle both raw values and literal-encoded IRIs robustly.
|
|
17963
|
+
const varName = `?_wc${varSuffix}`;
|
|
17964
|
+
return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
|
|
17965
|
+
}
|
|
17966
|
+
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
17967
|
+
}
|
|
17968
|
+
}
|
|
17969
|
+
/**
|
|
17970
|
+
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
17971
|
+
*
|
|
17972
|
+
* When `metadata` is provided, property names are resolved to predicates
|
|
17973
|
+
* using the model's property metadata. When `metadata` is `null`, property
|
|
17974
|
+
* names are treated as raw predicate URIs.
|
|
17975
|
+
*
|
|
17976
|
+
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
17977
|
+
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
17978
|
+
* runtime query time, not for compile-time getter generation).
|
|
17979
|
+
*/
|
|
17980
|
+
function compileWhereClause(where, metadata) {
|
|
17981
|
+
const conditions = [];
|
|
17982
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
17983
|
+
// Skip special fields that don't apply at compile time
|
|
17984
|
+
if (['id', 'author', 'timestamp'].includes(propertyName))
|
|
17985
|
+
continue;
|
|
17986
|
+
let predicate;
|
|
17987
|
+
let resolveLanguage;
|
|
17988
|
+
if (metadata) {
|
|
17989
|
+
const propMeta = metadata.properties[propertyName];
|
|
17990
|
+
if (propMeta) {
|
|
17991
|
+
predicate = propMeta.predicate;
|
|
17992
|
+
resolveLanguage = propMeta.resolveLanguage;
|
|
17993
|
+
}
|
|
17994
|
+
else {
|
|
17995
|
+
// Property not found in metadata — treat name as raw predicate URI
|
|
17996
|
+
predicate = propertyName;
|
|
17997
|
+
}
|
|
17998
|
+
}
|
|
17999
|
+
else {
|
|
18000
|
+
// No metadata — treat name as raw predicate URI
|
|
18001
|
+
predicate = propertyName;
|
|
18002
|
+
}
|
|
18003
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
|
|
18004
|
+
if (cond) {
|
|
18005
|
+
conditions.push(cond);
|
|
18006
|
+
}
|
|
18007
|
+
}
|
|
18008
|
+
return conditions;
|
|
18009
|
+
}
|
|
18010
|
+
|
|
17912
18011
|
class Neighbourhood {
|
|
17913
18012
|
constructor(linkLanguage, meta) {
|
|
17914
18013
|
this.linkLanguage = linkLanguage;
|
|
@@ -17941,4 +18040,4 @@ class ModelInput {
|
|
|
17941
18040
|
class VoiceActivityParamsInput {
|
|
17942
18041
|
}
|
|
17943
18042
|
|
|
17944
|
-
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, compileWhereClause, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exprRef2String, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
|
|
18043
|
+
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, compileWhereClause, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exprRef2String, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
|