@coasys/ad4m 0.12.1-dev → 0.13.0-test-2
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 +1469 -781
- package/lib/index.js +1453 -779
- package/lib/src/Literal.js +6 -5
- package/lib/src/agent/AgentClient.d.ts +8 -1
- package/lib/src/agent/AgentClient.js +73 -2
- package/lib/src/expression/ExpressionRef.js +2 -2
- package/lib/src/language/Language.d.ts +41 -3
- package/lib/src/model/Ad4mModel.d.ts +28 -28
- package/lib/src/model/Ad4mModel.js +129 -101
- package/lib/src/model/Ad4mModel.test.js +1543 -535
- package/lib/src/model/ModelQueryBuilder.d.ts +48 -34
- package/lib/src/model/ModelQueryBuilder.js +163 -78
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/decorators.d.ts +14 -8
- package/lib/src/model/decorators.js +41 -14
- package/lib/src/model/hydration-batch.d.ts +34 -0
- package/lib/src/model/hydration-batch.js +147 -0
- package/lib/src/model/hydration.d.ts +3 -3
- package/lib/src/model/hydration.js +106 -36
- package/lib/src/model/index.d.ts +4 -1
- package/lib/src/model/index.js +4 -1
- package/lib/src/model/json-schema.js +2 -2
- package/lib/src/model/query-cache.d.ts +30 -0
- package/lib/src/model/query-cache.js +66 -0
- package/lib/src/model/query-cache.test.d.ts +1 -0
- package/lib/src/model/query-cache.test.js +43 -0
- package/lib/src/model/query-common.d.ts +1 -1
- package/lib/src/model/query-common.js +1 -1
- package/lib/src/model/query-sparql-batch.d.ts +17 -0
- package/lib/src/model/query-sparql-batch.js +260 -0
- package/lib/src/model/query-sparql.d.ts +47 -0
- package/lib/src/model/query-sparql.js +336 -0
- package/lib/src/model/query-utils.d.ts +45 -0
- package/lib/src/model/query-utils.js +140 -0
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/sdna.js +1 -1
- package/lib/src/model/shacl-gen.js +42 -18
- package/lib/src/model/subscription-pool.d.ts +39 -0
- package/lib/src/model/subscription-pool.js +119 -0
- package/lib/src/model/types.d.ts +3 -3
- package/lib/src/model/types.js +1 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -17
- package/lib/src/perspectives/PerspectiveClient.js +5 -57
- package/lib/src/perspectives/PerspectiveProxy.d.ts +51 -30
- package/lib/src/perspectives/PerspectiveProxy.js +224 -177
- package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveResolver.js +0 -11
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
- package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
- package/lib/src/runtime/RuntimeClient.d.ts +2 -0
- package/lib/src/runtime/RuntimeClient.js +17 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
- package/lib/src/runtime/RuntimeResolver.js +84 -0
- package/lib/src/schema.gql +14 -1
- package/lib/src/shacl/SHACLFlow.d.ts +1 -1
- package/lib/src/shacl/SHACLFlow.js +9 -9
- package/lib/src/shacl/SHACLShape.d.ts +1 -1
- package/lib/src/shacl/SHACLShape.js +38 -38
- package/lib/src/typeDefs.js +14 -1
- package/lib/src/utils.d.ts +6 -6
- package/lib/src/utils.js +6 -6
- package/package.json +1 -1
- package/src/Literal.test.ts +10 -5
- package/src/Literal.ts +6 -5
- package/src/agent/AgentClient.ts +81 -1
- package/src/expression/ExpressionRef.ts +2 -2
- package/src/language/Language.ts +48 -3
- package/src/model/Ad4mModel.test.ts +1515 -565
- package/src/model/Ad4mModel.ts +142 -102
- package/src/model/ModelQueryBuilder.ts +185 -86
- package/src/model/Subject.ts +6 -6
- package/src/model/decorators.ts +51 -22
- package/src/model/hydration-batch.ts +205 -0
- package/src/model/hydration.ts +102 -39
- package/src/model/index.ts +4 -1
- package/src/model/json-schema.ts +2 -2
- package/src/model/query-cache.test.ts +54 -0
- package/src/model/query-cache.ts +79 -0
- package/src/model/query-common.ts +1 -1
- package/src/model/query-sparql-batch.ts +301 -0
- package/src/model/query-sparql.ts +363 -0
- package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
- package/src/model/relation-filtering.test.ts +15 -15
- package/src/model/sdna.ts +1 -1
- package/src/model/shacl-gen.ts +42 -17
- package/src/model/subscription-pool.ts +163 -0
- package/src/model/types.ts +3 -3
- package/src/perspectives/PerspectiveClient.ts +5 -61
- package/src/perspectives/PerspectiveProxy.ts +226 -181
- package/src/perspectives/PerspectiveResolver.ts +0 -8
- package/src/perspectives/WakerSubscriptionManager.ts +8 -9
- package/src/runtime/RuntimeClient.ts +19 -0
- package/src/runtime/RuntimeResolver.ts +58 -0
- package/src/shacl/SHACLFlow.ts +9 -9
- package/src/shacl/SHACLShape.ts +39 -39
- package/src/utils.ts +6 -6
- package/src/model/query-surreal.ts +0 -280
package/lib/index.js
CHANGED
|
@@ -4306,8 +4306,10 @@ class Literal {
|
|
|
4306
4306
|
_Literal_url.set(this, void 0);
|
|
4307
4307
|
}
|
|
4308
4308
|
static fromUrl(url) {
|
|
4309
|
-
if (!url || !url.startsWith("literal
|
|
4309
|
+
if (!url || !url.startsWith("literal:"))
|
|
4310
4310
|
throw new Error("Can't create Literal from non-literal URL");
|
|
4311
|
+
if (url.startsWith("literal://"))
|
|
4312
|
+
throw new Error("literal:// format is no longer supported. Use literal: instead.");
|
|
4311
4313
|
const l = new Literal();
|
|
4312
4314
|
__classPrivateFieldSet$b(l, _Literal_url, url, "f");
|
|
4313
4315
|
return l;
|
|
@@ -4337,17 +4339,16 @@ class Literal {
|
|
|
4337
4339
|
encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$b(this, _Literal_literal, "f")))}`;
|
|
4338
4340
|
break;
|
|
4339
4341
|
}
|
|
4340
|
-
return `literal
|
|
4342
|
+
return `literal:${encoded}`;
|
|
4341
4343
|
}
|
|
4342
4344
|
get() {
|
|
4343
4345
|
if (__classPrivateFieldGet$b(this, _Literal_literal, "f"))
|
|
4344
4346
|
return __classPrivateFieldGet$b(this, _Literal_literal, "f");
|
|
4345
4347
|
if (!__classPrivateFieldGet$b(this, _Literal_url, "f"))
|
|
4346
4348
|
throw new Error("Can't render empty Literal");
|
|
4347
|
-
if (!__classPrivateFieldGet$b(this, _Literal_url, "f").startsWith("literal
|
|
4349
|
+
if (!__classPrivateFieldGet$b(this, _Literal_url, "f").startsWith("literal:"))
|
|
4348
4350
|
throw new Error("Can't render Literal from non-literal URL");
|
|
4349
|
-
|
|
4350
|
-
const body = __classPrivateFieldGet$b(this, _Literal_url, "f").substring(10);
|
|
4351
|
+
const body = __classPrivateFieldGet$b(this, _Literal_url, "f").substring(8);
|
|
4351
4352
|
if (body.startsWith("string:")) {
|
|
4352
4353
|
return decodeURIComponent(body.substring(7));
|
|
4353
4354
|
}
|
|
@@ -4477,12 +4478,12 @@ class Subject {
|
|
|
4477
4478
|
Object.defineProperty(this, p, {
|
|
4478
4479
|
configurable: true,
|
|
4479
4480
|
get: async () => {
|
|
4480
|
-
// Use
|
|
4481
|
+
// Use SPARQL for data queries
|
|
4481
4482
|
try {
|
|
4482
|
-
return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").
|
|
4483
|
+
return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getPropertyValueViaSparql(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), p);
|
|
4483
4484
|
}
|
|
4484
4485
|
catch (err) {
|
|
4485
|
-
console.warn(`Failed to get property ${p} via
|
|
4486
|
+
console.warn(`Failed to get property ${p} via SPARQL:`, err);
|
|
4486
4487
|
return undefined;
|
|
4487
4488
|
}
|
|
4488
4489
|
}
|
|
@@ -4516,12 +4517,12 @@ class Subject {
|
|
|
4516
4517
|
Object.defineProperty(this, c, {
|
|
4517
4518
|
configurable: true,
|
|
4518
4519
|
get: async () => {
|
|
4519
|
-
// Use
|
|
4520
|
+
// Use SPARQL for data queries
|
|
4520
4521
|
try {
|
|
4521
|
-
return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").
|
|
4522
|
+
return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getRelationValuesViaSparql(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), c);
|
|
4522
4523
|
}
|
|
4523
4524
|
catch (err) {
|
|
4524
|
-
console.warn(`Failed to get relation ${c} via
|
|
4525
|
+
console.warn(`Failed to get relation ${c} via SPARQL:`, err);
|
|
4525
4526
|
return [];
|
|
4526
4527
|
}
|
|
4527
4528
|
}
|
|
@@ -4659,7 +4660,7 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
|
|
|
4659
4660
|
// Optional properties (required: false) are excluded — they should
|
|
4660
4661
|
// remain unset (undefined) until explicitly assigned.
|
|
4661
4662
|
const effectiveInitial = initial
|
|
4662
|
-
?? (required && writable && !flag && through ? "literal
|
|
4663
|
+
?? (required && writable && !flag && through ? "literal:string:" : undefined);
|
|
4663
4664
|
if (effectiveInitial) {
|
|
4664
4665
|
constructorActions.push({
|
|
4665
4666
|
action: "addLink",
|
|
@@ -4945,7 +4946,7 @@ class SHACLShape {
|
|
|
4945
4946
|
links.push({
|
|
4946
4947
|
source: this.nodeShapeUri,
|
|
4947
4948
|
predicate: "ad4m://constructor",
|
|
4948
|
-
target: `literal
|
|
4949
|
+
target: `literal:string:${JSON.stringify(this.constructor_actions)}`
|
|
4949
4950
|
});
|
|
4950
4951
|
}
|
|
4951
4952
|
// Destructor actions — same rationale as constructor.
|
|
@@ -4953,7 +4954,7 @@ class SHACLShape {
|
|
|
4953
4954
|
links.push({
|
|
4954
4955
|
source: this.nodeShapeUri,
|
|
4955
4956
|
predicate: "ad4m://destructor",
|
|
4956
|
-
target: `literal
|
|
4957
|
+
target: `literal:string:${JSON.stringify(this.destructor_actions)}`
|
|
4957
4958
|
});
|
|
4958
4959
|
}
|
|
4959
4960
|
// Property shapes (each gets a named URI: {namespace}/{ClassName}.{propertyName})
|
|
@@ -5003,42 +5004,42 @@ class SHACLShape {
|
|
|
5003
5004
|
links.push({
|
|
5004
5005
|
source: propShapeId,
|
|
5005
5006
|
predicate: "sh://minCount",
|
|
5006
|
-
target: `literal
|
|
5007
|
+
target: `literal:${prop.minCount}^^xsd:integer`
|
|
5007
5008
|
});
|
|
5008
5009
|
}
|
|
5009
5010
|
if (prop.maxCount !== undefined) {
|
|
5010
5011
|
links.push({
|
|
5011
5012
|
source: propShapeId,
|
|
5012
5013
|
predicate: "sh://maxCount",
|
|
5013
|
-
target: `literal
|
|
5014
|
+
target: `literal:${prop.maxCount}^^xsd:integer`
|
|
5014
5015
|
});
|
|
5015
5016
|
}
|
|
5016
5017
|
if (prop.pattern) {
|
|
5017
5018
|
links.push({
|
|
5018
5019
|
source: propShapeId,
|
|
5019
5020
|
predicate: "sh://pattern",
|
|
5020
|
-
target: `literal
|
|
5021
|
+
target: `literal:${prop.pattern}`
|
|
5021
5022
|
});
|
|
5022
5023
|
}
|
|
5023
5024
|
if (prop.minInclusive !== undefined) {
|
|
5024
5025
|
links.push({
|
|
5025
5026
|
source: propShapeId,
|
|
5026
5027
|
predicate: "sh://minInclusive",
|
|
5027
|
-
target: `literal
|
|
5028
|
+
target: `literal:${prop.minInclusive}`
|
|
5028
5029
|
});
|
|
5029
5030
|
}
|
|
5030
5031
|
if (prop.maxInclusive !== undefined) {
|
|
5031
5032
|
links.push({
|
|
5032
5033
|
source: propShapeId,
|
|
5033
5034
|
predicate: "sh://maxInclusive",
|
|
5034
|
-
target: `literal
|
|
5035
|
+
target: `literal:${prop.maxInclusive}`
|
|
5035
5036
|
});
|
|
5036
5037
|
}
|
|
5037
5038
|
if (prop.hasValue) {
|
|
5038
5039
|
links.push({
|
|
5039
5040
|
source: propShapeId,
|
|
5040
5041
|
predicate: "sh://hasValue",
|
|
5041
|
-
target: `literal
|
|
5042
|
+
target: `literal:${prop.hasValue}`
|
|
5042
5043
|
});
|
|
5043
5044
|
}
|
|
5044
5045
|
// AD4M-specific metadata
|
|
@@ -5046,21 +5047,21 @@ class SHACLShape {
|
|
|
5046
5047
|
links.push({
|
|
5047
5048
|
source: propShapeId,
|
|
5048
5049
|
predicate: "ad4m://local",
|
|
5049
|
-
target: `literal
|
|
5050
|
+
target: `literal:${prop.local}`
|
|
5050
5051
|
});
|
|
5051
5052
|
}
|
|
5052
5053
|
if (prop.writable !== undefined) {
|
|
5053
5054
|
links.push({
|
|
5054
5055
|
source: propShapeId,
|
|
5055
5056
|
predicate: "ad4m://writable",
|
|
5056
|
-
target: `literal
|
|
5057
|
+
target: `literal:${prop.writable}`
|
|
5057
5058
|
});
|
|
5058
5059
|
}
|
|
5059
5060
|
if (prop.resolveLanguage) {
|
|
5060
5061
|
links.push({
|
|
5061
5062
|
source: propShapeId,
|
|
5062
5063
|
predicate: "ad4m://resolveLanguage",
|
|
5063
|
-
target: `literal
|
|
5064
|
+
target: `literal:string:${prop.resolveLanguage}`
|
|
5064
5065
|
});
|
|
5065
5066
|
}
|
|
5066
5067
|
// AD4M-specific actions
|
|
@@ -5068,35 +5069,35 @@ class SHACLShape {
|
|
|
5068
5069
|
links.push({
|
|
5069
5070
|
source: propShapeId,
|
|
5070
5071
|
predicate: "ad4m://setter",
|
|
5071
|
-
target: `literal
|
|
5072
|
+
target: `literal:string:${JSON.stringify(prop.setter)}`
|
|
5072
5073
|
});
|
|
5073
5074
|
}
|
|
5074
5075
|
if (prop.adder && prop.adder.length > 0) {
|
|
5075
5076
|
links.push({
|
|
5076
5077
|
source: propShapeId,
|
|
5077
5078
|
predicate: "ad4m://adder",
|
|
5078
|
-
target: `literal
|
|
5079
|
+
target: `literal:string:${JSON.stringify(prop.adder)}`
|
|
5079
5080
|
});
|
|
5080
5081
|
}
|
|
5081
5082
|
if (prop.remover && prop.remover.length > 0) {
|
|
5082
5083
|
links.push({
|
|
5083
5084
|
source: propShapeId,
|
|
5084
5085
|
predicate: "ad4m://remover",
|
|
5085
|
-
target: `literal
|
|
5086
|
+
target: `literal:string:${JSON.stringify(prop.remover)}`
|
|
5086
5087
|
});
|
|
5087
5088
|
}
|
|
5088
5089
|
if (prop.getter) {
|
|
5089
5090
|
links.push({
|
|
5090
5091
|
source: propShapeId,
|
|
5091
5092
|
predicate: "ad4m://getter",
|
|
5092
|
-
target: `literal
|
|
5093
|
+
target: `literal:string:${prop.getter}`
|
|
5093
5094
|
});
|
|
5094
5095
|
}
|
|
5095
5096
|
if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {
|
|
5096
5097
|
links.push({
|
|
5097
5098
|
source: propShapeId,
|
|
5098
5099
|
predicate: "ad4m://conformanceConditions",
|
|
5099
|
-
target: `literal
|
|
5100
|
+
target: `literal:string:${JSON.stringify(prop.conformanceConditions)}`
|
|
5100
5101
|
});
|
|
5101
5102
|
}
|
|
5102
5103
|
if (prop.class) {
|
|
@@ -5120,7 +5121,7 @@ class SHACLShape {
|
|
|
5120
5121
|
const constructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://constructor");
|
|
5121
5122
|
if (constructorLink) {
|
|
5122
5123
|
try {
|
|
5123
|
-
const jsonStr = constructorLink.target.replace(
|
|
5124
|
+
const jsonStr = constructorLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5124
5125
|
shape.constructor_actions = JSON.parse(jsonStr);
|
|
5125
5126
|
}
|
|
5126
5127
|
catch (e) {
|
|
@@ -5131,7 +5132,7 @@ class SHACLShape {
|
|
|
5131
5132
|
const destructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://destructor");
|
|
5132
5133
|
if (destructorLink) {
|
|
5133
5134
|
try {
|
|
5134
|
-
const jsonStr = destructorLink.target.replace(
|
|
5135
|
+
const jsonStr = destructorLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5135
5136
|
shape.destructor_actions = JSON.parse(jsonStr);
|
|
5136
5137
|
}
|
|
5137
5138
|
catch (e) {
|
|
@@ -5169,70 +5170,70 @@ class SHACLShape {
|
|
|
5169
5170
|
}
|
|
5170
5171
|
const minCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minCount");
|
|
5171
5172
|
if (minCountLink) {
|
|
5172
|
-
// Handle both formats: literal
|
|
5173
|
-
let val = minCountLink.target.replace(
|
|
5173
|
+
// Handle both formats: literal:5^^xsd:integer and literal:number:5
|
|
5174
|
+
let val = minCountLink.target.replace(/^literal:\/\/|^literal:/, '').replace(/\^\^.*$/, '');
|
|
5174
5175
|
if (val.startsWith('number:'))
|
|
5175
5176
|
val = val.substring(7);
|
|
5176
5177
|
prop.minCount = parseInt(val);
|
|
5177
5178
|
}
|
|
5178
5179
|
const maxCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxCount");
|
|
5179
5180
|
if (maxCountLink) {
|
|
5180
|
-
// Handle both formats: literal
|
|
5181
|
-
let val = maxCountLink.target.replace(
|
|
5181
|
+
// Handle both formats: literal:5^^xsd:integer and literal:number:5
|
|
5182
|
+
let val = maxCountLink.target.replace(/^literal:\/\/|^literal:/, '').replace(/\^\^.*$/, '');
|
|
5182
5183
|
if (val.startsWith('number:'))
|
|
5183
5184
|
val = val.substring(7);
|
|
5184
5185
|
prop.maxCount = parseInt(val);
|
|
5185
5186
|
}
|
|
5186
5187
|
const patternLink = links.find(l => l.source === propShapeId && l.predicate === "sh://pattern");
|
|
5187
5188
|
if (patternLink) {
|
|
5188
|
-
prop.pattern = patternLink.target.replace(
|
|
5189
|
+
prop.pattern = patternLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
5189
5190
|
}
|
|
5190
5191
|
const minInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minInclusive");
|
|
5191
5192
|
if (minInclusiveLink) {
|
|
5192
|
-
// Handle both formats: literal
|
|
5193
|
-
let val = minInclusiveLink.target.replace(
|
|
5193
|
+
// Handle both formats: literal:5 and literal:number:5
|
|
5194
|
+
let val = minInclusiveLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
5194
5195
|
if (val.startsWith('number:'))
|
|
5195
5196
|
val = val.substring(7);
|
|
5196
5197
|
prop.minInclusive = parseFloat(val);
|
|
5197
5198
|
}
|
|
5198
5199
|
const maxInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxInclusive");
|
|
5199
5200
|
if (maxInclusiveLink) {
|
|
5200
|
-
// Handle both formats: literal
|
|
5201
|
-
let val = maxInclusiveLink.target.replace(
|
|
5201
|
+
// Handle both formats: literal:5 and literal:number:5
|
|
5202
|
+
let val = maxInclusiveLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
5202
5203
|
if (val.startsWith('number:'))
|
|
5203
5204
|
val = val.substring(7);
|
|
5204
5205
|
prop.maxInclusive = parseFloat(val);
|
|
5205
5206
|
}
|
|
5206
5207
|
const hasValueLink = links.find(l => l.source === propShapeId && l.predicate === "sh://hasValue");
|
|
5207
5208
|
if (hasValueLink) {
|
|
5208
|
-
prop.hasValue = hasValueLink.target.replace(
|
|
5209
|
+
prop.hasValue = hasValueLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
5209
5210
|
}
|
|
5210
5211
|
// AD4M-specific
|
|
5211
5212
|
const localLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://local");
|
|
5212
5213
|
if (localLink) {
|
|
5213
|
-
// Handle both formats: literal
|
|
5214
|
-
let val = localLink.target.replace(
|
|
5214
|
+
// Handle both formats: literal:true and literal:boolean:true
|
|
5215
|
+
let val = localLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
5215
5216
|
if (val.startsWith('boolean:'))
|
|
5216
5217
|
val = val.substring(8);
|
|
5217
5218
|
prop.local = val === 'true';
|
|
5218
5219
|
}
|
|
5219
5220
|
const writableLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://writable");
|
|
5220
5221
|
if (writableLink) {
|
|
5221
|
-
// Handle both formats: literal
|
|
5222
|
-
let val = writableLink.target.replace(
|
|
5222
|
+
// Handle both formats: literal:true and literal:boolean:true
|
|
5223
|
+
let val = writableLink.target.replace(/^literal:\/\/|^literal:/, '');
|
|
5223
5224
|
if (val.startsWith('boolean:'))
|
|
5224
5225
|
val = val.substring(8);
|
|
5225
5226
|
prop.writable = val === 'true';
|
|
5226
5227
|
}
|
|
5227
5228
|
const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://resolveLanguage");
|
|
5228
5229
|
if (resolveLangLink) {
|
|
5229
|
-
prop.resolveLanguage = resolveLangLink.target.replace(
|
|
5230
|
+
prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5230
5231
|
}
|
|
5231
5232
|
// Parse action arrays
|
|
5232
5233
|
const setterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://setter");
|
|
5233
5234
|
if (setterLink) {
|
|
5234
5235
|
try {
|
|
5235
|
-
const jsonStr = setterLink.target.replace(
|
|
5236
|
+
const jsonStr = setterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5236
5237
|
prop.setter = JSON.parse(jsonStr);
|
|
5237
5238
|
}
|
|
5238
5239
|
catch (e) {
|
|
@@ -5242,7 +5243,7 @@ class SHACLShape {
|
|
|
5242
5243
|
const adderLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://adder");
|
|
5243
5244
|
if (adderLink) {
|
|
5244
5245
|
try {
|
|
5245
|
-
const jsonStr = adderLink.target.replace(
|
|
5246
|
+
const jsonStr = adderLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5246
5247
|
prop.adder = JSON.parse(jsonStr);
|
|
5247
5248
|
}
|
|
5248
5249
|
catch (e) {
|
|
@@ -5252,7 +5253,7 @@ class SHACLShape {
|
|
|
5252
5253
|
const removerLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://remover");
|
|
5253
5254
|
if (removerLink) {
|
|
5254
5255
|
try {
|
|
5255
|
-
const jsonStr = removerLink.target.replace(
|
|
5256
|
+
const jsonStr = removerLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5256
5257
|
prop.remover = JSON.parse(jsonStr);
|
|
5257
5258
|
}
|
|
5258
5259
|
catch (e) {
|
|
@@ -5261,12 +5262,12 @@ class SHACLShape {
|
|
|
5261
5262
|
}
|
|
5262
5263
|
const getterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://getter");
|
|
5263
5264
|
if (getterLink) {
|
|
5264
|
-
prop.getter = getterLink.target.replace(
|
|
5265
|
+
prop.getter = getterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5265
5266
|
}
|
|
5266
5267
|
const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://conformanceConditions");
|
|
5267
5268
|
if (conditionsLink) {
|
|
5268
5269
|
try {
|
|
5269
|
-
const jsonStr = conditionsLink.target.replace(
|
|
5270
|
+
const jsonStr = conditionsLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
5270
5271
|
prop.conformanceConditions = JSON.parse(jsonStr);
|
|
5271
5272
|
}
|
|
5272
5273
|
catch (e) {
|
|
@@ -5383,28 +5384,28 @@ function capSentence(cap) {
|
|
|
5383
5384
|
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
5384
5385
|
}
|
|
5385
5386
|
/**
|
|
5386
|
-
* Escapes a string value for safe use in
|
|
5387
|
+
* Escapes a string value for safe use in query strings.
|
|
5387
5388
|
*
|
|
5388
5389
|
* @description
|
|
5389
5390
|
* Prevents SQL injection by properly escaping special characters in string values
|
|
5390
|
-
* that will be interpolated into
|
|
5391
|
+
* that will be interpolated into query strings. This handles the most common
|
|
5391
5392
|
* special characters that could break SQL queries or enable injection attacks.
|
|
5392
5393
|
*
|
|
5393
5394
|
* Single quotes, backslashes, and other special characters are escaped using
|
|
5394
|
-
* backslash notation, which is the standard escaping mechanism for
|
|
5395
|
+
* backslash notation, which is the standard escaping mechanism for query.
|
|
5395
5396
|
*
|
|
5396
5397
|
* @param value - The string value to escape
|
|
5397
|
-
* @returns The escaped string safe for
|
|
5398
|
+
* @returns The escaped string safe for query interpolation (without surrounding quotes)
|
|
5398
5399
|
*
|
|
5399
5400
|
* @example
|
|
5400
5401
|
* ```typescript
|
|
5401
5402
|
* const userInput = "user's input with 'quotes'";
|
|
5402
|
-
* const escaped =
|
|
5403
|
+
* const escaped = escapeQueryString(userInput);
|
|
5403
5404
|
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
5404
5405
|
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
5405
5406
|
* ```
|
|
5406
5407
|
*/
|
|
5407
|
-
function
|
|
5408
|
+
function escapeQueryString(value) {
|
|
5408
5409
|
return value
|
|
5409
5410
|
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
5410
5411
|
.replace(/'/g, "\\'") // Single quote -> \'
|
|
@@ -5415,19 +5416,21 @@ function escapeSurrealString(value) {
|
|
|
5415
5416
|
}
|
|
5416
5417
|
|
|
5417
5418
|
/**
|
|
5418
|
-
* Shared
|
|
5419
|
+
* Shared query compilation utilities.
|
|
5419
5420
|
*
|
|
5420
5421
|
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
5421
5422
|
* the compile-time SHACL generator (`decorators.ts`).
|
|
5423
|
+
*
|
|
5424
|
+
* All output uses native SPARQL syntax.
|
|
5422
5425
|
*/
|
|
5423
5426
|
/**
|
|
5424
|
-
* Format a JavaScript value for embedding in a
|
|
5427
|
+
* Format a JavaScript value for embedding in a query expression.
|
|
5425
5428
|
*
|
|
5426
5429
|
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
5427
5430
|
* - Numbers and booleans are passed through as-is
|
|
5428
5431
|
* - Arrays are recursed
|
|
5429
5432
|
*/
|
|
5430
|
-
function
|
|
5433
|
+
function formatQueryValue(value) {
|
|
5431
5434
|
if (typeof value === 'string') {
|
|
5432
5435
|
// Escape backslashes first, then single quotes and other special characters
|
|
5433
5436
|
const escaped = value
|
|
@@ -5443,33 +5446,45 @@ function formatSurrealValue(value) {
|
|
|
5443
5446
|
return String(value);
|
|
5444
5447
|
}
|
|
5445
5448
|
else if (Array.isArray(value)) {
|
|
5446
|
-
return `[${value.map(v =>
|
|
5449
|
+
return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
|
|
5447
5450
|
}
|
|
5448
5451
|
else {
|
|
5449
5452
|
return String(value);
|
|
5450
5453
|
}
|
|
5451
5454
|
}
|
|
5452
5455
|
/**
|
|
5453
|
-
* Compile a single Where condition for a property into a
|
|
5454
|
-
*
|
|
5456
|
+
* Compile a single Where condition for a property into a SPARQL triple pattern
|
|
5457
|
+
* that can be embedded in a getter's WHERE clause.
|
|
5455
5458
|
*
|
|
5456
|
-
*
|
|
5457
|
-
*
|
|
5459
|
+
* The generated pattern operates on `?target` — e.g.:
|
|
5460
|
+
* `?target <pred> <value> .`
|
|
5461
|
+
* `FILTER EXISTS { ?target <pred> ?_v0 }`
|
|
5458
5462
|
*
|
|
5459
5463
|
* @param predicate - The predicate URI for the property
|
|
5460
5464
|
* @param condition - The Where condition value
|
|
5461
5465
|
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
5462
|
-
* @returns A single
|
|
5466
|
+
* @returns A single SPARQL condition string
|
|
5463
5467
|
*/
|
|
5464
5468
|
function buildWhereCondition(predicate, condition, opts) {
|
|
5465
|
-
const escapedPredicate =
|
|
5466
|
-
|
|
5467
|
-
|
|
5468
|
-
|
|
5469
|
+
const escapedPredicate = escapeQueryString(predicate);
|
|
5470
|
+
// For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
|
|
5471
|
+
// For language-resolved properties, we match against the plain URI
|
|
5472
|
+
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
5473
|
+
// For language-resolved properties, values are plain URIs
|
|
5474
|
+
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
5475
|
+
function formatValue(v) {
|
|
5476
|
+
if (typeof v === 'string') {
|
|
5477
|
+
return isLiteral
|
|
5478
|
+
? `<literal:string:${escapeQueryString(v)}>`
|
|
5479
|
+
: `<${escapeQueryString(v)}>`;
|
|
5480
|
+
}
|
|
5481
|
+
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
5482
|
+
return `<literal:string:${v}>`;
|
|
5483
|
+
}
|
|
5469
5484
|
if (Array.isArray(condition)) {
|
|
5470
|
-
// Array values → IN
|
|
5471
|
-
const formattedValues = condition.map(
|
|
5472
|
-
return `
|
|
5485
|
+
// Array values → FILTER IN
|
|
5486
|
+
const formattedValues = condition.map(formatValue).join(', ');
|
|
5487
|
+
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
5473
5488
|
}
|
|
5474
5489
|
else if (typeof condition === 'object' && condition !== null) {
|
|
5475
5490
|
// Operator object
|
|
@@ -5477,31 +5492,29 @@ function buildWhereCondition(predicate, condition, opts) {
|
|
|
5477
5492
|
const parts = [];
|
|
5478
5493
|
if (ops.not !== undefined) {
|
|
5479
5494
|
if (Array.isArray(ops.not)) {
|
|
5480
|
-
const formattedValues = ops.not.map((v) =>
|
|
5481
|
-
parts.push(`
|
|
5495
|
+
const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
|
|
5496
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
|
|
5482
5497
|
}
|
|
5483
5498
|
else {
|
|
5484
|
-
parts.push(`
|
|
5499
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
|
|
5485
5500
|
}
|
|
5486
5501
|
}
|
|
5487
|
-
// Comparison operators — ensure property exists
|
|
5488
|
-
// may be post-filtered in JS at runtime, but the SurrealQL condition
|
|
5489
|
-
// is valid for compile-time getter generation too).
|
|
5502
|
+
// Comparison operators — ensure property exists
|
|
5490
5503
|
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
5491
5504
|
ops.lt !== undefined || ops.lte !== undefined ||
|
|
5492
5505
|
ops.between !== undefined || ops.contains !== undefined;
|
|
5493
5506
|
if (hasComparisonOps) {
|
|
5494
|
-
parts.push(`
|
|
5507
|
+
parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
|
|
5495
5508
|
}
|
|
5496
|
-
return parts.join('
|
|
5509
|
+
return parts.join(' ');
|
|
5497
5510
|
}
|
|
5498
5511
|
else {
|
|
5499
5512
|
// Simple equality
|
|
5500
|
-
return
|
|
5513
|
+
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
5501
5514
|
}
|
|
5502
5515
|
}
|
|
5503
5516
|
/**
|
|
5504
|
-
* Compile a full `Where` clause to an array of
|
|
5517
|
+
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
5505
5518
|
*
|
|
5506
5519
|
* When `metadata` is provided, property names are resolved to predicates
|
|
5507
5520
|
* using the model's property metadata. When `metadata` is `null`, property
|
|
@@ -5671,7 +5684,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
5671
5684
|
// ── Constructor / Destructor entries ────────────────────────────
|
|
5672
5685
|
const effectiveInitial = propMeta.initial
|
|
5673
5686
|
?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
|
|
5674
|
-
? "literal
|
|
5687
|
+
? "literal:string:" : undefined);
|
|
5675
5688
|
if (effectiveInitial) {
|
|
5676
5689
|
constructorActions.push({
|
|
5677
5690
|
action: "addLink",
|
|
@@ -5722,7 +5735,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
5722
5735
|
// ── Build Getter (conformance filter) ───────────────────────────
|
|
5723
5736
|
// Priority chain:
|
|
5724
5737
|
// 1. Explicit getter string → use verbatim
|
|
5725
|
-
// 2. `where` clause → compile DSL to
|
|
5738
|
+
// 2. `where` clause → compile DSL to SPARQL getter
|
|
5726
5739
|
// 3. target + filter !== false → auto-derive from shape
|
|
5727
5740
|
if (relMeta.getter) {
|
|
5728
5741
|
relShape.getter = relMeta.getter;
|
|
@@ -5735,8 +5748,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
5735
5748
|
: null;
|
|
5736
5749
|
const conditions = compileWhereClause(relMeta.where, targetMetadata);
|
|
5737
5750
|
if (conditions.length > 0) {
|
|
5738
|
-
const escapedPredicate =
|
|
5739
|
-
relShape.getter = `
|
|
5751
|
+
const escapedPredicate = escapeQueryString(relMeta.predicate);
|
|
5752
|
+
relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
5740
5753
|
}
|
|
5741
5754
|
}
|
|
5742
5755
|
catch (e) {
|
|
@@ -5744,18 +5757,42 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
5744
5757
|
}
|
|
5745
5758
|
}
|
|
5746
5759
|
else if (relMeta.target && relMeta.filter !== false) {
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5760
|
+
// Lazy conformance filter: store deferred reference,
|
|
5761
|
+
// resolve on first access via a getter on relShape
|
|
5762
|
+
const targetThunk = relMeta.target;
|
|
5763
|
+
const predicate = relMeta.predicate;
|
|
5764
|
+
let resolved = false;
|
|
5765
|
+
let cachedGetter;
|
|
5766
|
+
let cachedConditions;
|
|
5767
|
+
const resolveFilter = () => {
|
|
5768
|
+
if (resolved)
|
|
5769
|
+
return;
|
|
5770
|
+
resolved = true;
|
|
5771
|
+
try {
|
|
5772
|
+
const TargetClass = targetThunk();
|
|
5773
|
+
const filter = conformanceFilterFn(predicate, TargetClass);
|
|
5774
|
+
if (filter) {
|
|
5775
|
+
cachedGetter = filter.getter;
|
|
5776
|
+
cachedConditions = filter.conformanceConditions;
|
|
5777
|
+
}
|
|
5753
5778
|
}
|
|
5754
|
-
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
5758
|
-
|
|
5779
|
+
catch (e) {
|
|
5780
|
+
// Target class may not be available yet
|
|
5781
|
+
}
|
|
5782
|
+
};
|
|
5783
|
+
// Define lazy getters that resolve on first access
|
|
5784
|
+
Object.defineProperty(relShape, 'getter', {
|
|
5785
|
+
get() { resolveFilter(); return cachedGetter; },
|
|
5786
|
+
set(v) { resolved = true; cachedGetter = v; },
|
|
5787
|
+
enumerable: true,
|
|
5788
|
+
configurable: true,
|
|
5789
|
+
});
|
|
5790
|
+
Object.defineProperty(relShape, 'conformanceConditions', {
|
|
5791
|
+
get() { resolveFilter(); return cachedConditions; },
|
|
5792
|
+
set(v) { resolved = true; cachedConditions = v; },
|
|
5793
|
+
enumerable: true,
|
|
5794
|
+
configurable: true,
|
|
5795
|
+
});
|
|
5759
5796
|
}
|
|
5760
5797
|
// ── sh:class — target shape reference ───────────────────────────
|
|
5761
5798
|
if (relMeta.target) {
|
|
@@ -5773,7 +5810,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
5773
5810
|
shape.addProperty(relShape);
|
|
5774
5811
|
}
|
|
5775
5812
|
// Always set constructor and destructor actions on the shape, even
|
|
5776
|
-
// when empty. An empty array serialises to `literal
|
|
5813
|
+
// when empty. An empty array serialises to `literal:string:[]`
|
|
5777
5814
|
// which the Rust executor parses as a valid (no-op) command list,
|
|
5778
5815
|
// avoiding "No SHACL constructor found" errors for models whose
|
|
5779
5816
|
// properties are all optional and have no @Flag.
|
|
@@ -5789,11 +5826,21 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
|
|
|
5789
5826
|
const propertyRegistry = new WeakMap();
|
|
5790
5827
|
/** Registry of relation metadata keyed by constructor → { propName → metadata } */
|
|
5791
5828
|
const relationRegistry = new WeakMap();
|
|
5829
|
+
/** Memoisation cache for getPropertiesMetadata — avoids repeated prototype-chain walks */
|
|
5830
|
+
const propertiesMetadataCache = new WeakMap();
|
|
5831
|
+
/** Memoisation cache for getRelationsMetadata — avoids repeated prototype-chain walks */
|
|
5832
|
+
const relationsMetadataCache = new WeakMap();
|
|
5833
|
+
/** Memoisation cache for generateSHACL — avoids recomputing SHACL shapes */
|
|
5834
|
+
const shaclCache = new WeakMap();
|
|
5792
5835
|
/**
|
|
5793
5836
|
* Retrieve property metadata for a given class constructor.
|
|
5794
5837
|
* Walks the prototype chain so subclass decorators compose with parent decorators.
|
|
5838
|
+
* Results are memoised per class constructor.
|
|
5795
5839
|
*/
|
|
5796
5840
|
function getPropertiesMetadata(ctor) {
|
|
5841
|
+
const cached = propertiesMetadataCache.get(ctor);
|
|
5842
|
+
if (cached)
|
|
5843
|
+
return cached;
|
|
5797
5844
|
const result = {};
|
|
5798
5845
|
const chain = [];
|
|
5799
5846
|
let current = ctor;
|
|
@@ -5806,13 +5853,18 @@ function getPropertiesMetadata(ctor) {
|
|
|
5806
5853
|
if (meta)
|
|
5807
5854
|
Object.assign(result, meta);
|
|
5808
5855
|
}
|
|
5856
|
+
propertiesMetadataCache.set(ctor, result);
|
|
5809
5857
|
return result;
|
|
5810
5858
|
}
|
|
5811
5859
|
/**
|
|
5812
5860
|
* Retrieve relation metadata for a given class constructor.
|
|
5813
5861
|
* Walks the prototype chain so subclass decorators compose with parent decorators.
|
|
5862
|
+
* Results are memoised per class constructor.
|
|
5814
5863
|
*/
|
|
5815
5864
|
function getRelationsMetadata(ctor) {
|
|
5865
|
+
const cached = relationsMetadataCache.get(ctor);
|
|
5866
|
+
if (cached)
|
|
5867
|
+
return cached;
|
|
5816
5868
|
const result = {};
|
|
5817
5869
|
const chain = [];
|
|
5818
5870
|
let current = ctor;
|
|
@@ -5825,6 +5877,18 @@ function getRelationsMetadata(ctor) {
|
|
|
5825
5877
|
if (meta)
|
|
5826
5878
|
Object.assign(result, meta);
|
|
5827
5879
|
}
|
|
5880
|
+
relationsMetadataCache.set(ctor, result);
|
|
5881
|
+
return result;
|
|
5882
|
+
}
|
|
5883
|
+
/**
|
|
5884
|
+
* Get or compute memoised SHACL for a class. Used by @Model decorator.
|
|
5885
|
+
*/
|
|
5886
|
+
function getMemoizedSHACL(target, compute) {
|
|
5887
|
+
const cached = shaclCache.get(target);
|
|
5888
|
+
if (cached)
|
|
5889
|
+
return cached;
|
|
5890
|
+
const result = compute();
|
|
5891
|
+
shaclCache.set(target, result);
|
|
5828
5892
|
return result;
|
|
5829
5893
|
}
|
|
5830
5894
|
/**
|
|
@@ -5850,7 +5914,7 @@ function setRelationRegistryEntry(ctor, relName, meta) {
|
|
|
5850
5914
|
*
|
|
5851
5915
|
* Inspects the target class's property metadata to derive:
|
|
5852
5916
|
* - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
|
|
5853
|
-
* - `getter`: Pre-computed
|
|
5917
|
+
* - `getter`: Pre-computed graph traversal expression that traverses outgoing links and filters
|
|
5854
5918
|
* target nodes to only those conforming to the target shape.
|
|
5855
5919
|
*
|
|
5856
5920
|
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
@@ -5861,7 +5925,8 @@ function buildConformanceFilter(relationPredicate, targetClass) {
|
|
|
5861
5925
|
try {
|
|
5862
5926
|
const targetProps = getPropertiesMetadata(targetClass);
|
|
5863
5927
|
const conditions = [];
|
|
5864
|
-
const
|
|
5928
|
+
const sparqlConditions = [];
|
|
5929
|
+
let varIdx = 0;
|
|
5865
5930
|
// 1. Flags — check predicate + value
|
|
5866
5931
|
for (const [_propName, propMeta] of Object.entries(targetProps)) {
|
|
5867
5932
|
if (propMeta.flag && propMeta.initial && propMeta.through) {
|
|
@@ -5870,7 +5935,7 @@ function buildConformanceFilter(relationPredicate, targetClass) {
|
|
|
5870
5935
|
predicate: propMeta.through,
|
|
5871
5936
|
value: propMeta.initial,
|
|
5872
5937
|
});
|
|
5873
|
-
|
|
5938
|
+
sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> <${escapeQueryString(propMeta.initial)}> .`);
|
|
5874
5939
|
}
|
|
5875
5940
|
}
|
|
5876
5941
|
// 2. Required (non-flag) properties — check predicate exists
|
|
@@ -5881,14 +5946,13 @@ function buildConformanceFilter(relationPredicate, targetClass) {
|
|
|
5881
5946
|
type: 'required',
|
|
5882
5947
|
predicate: propMeta.through,
|
|
5883
5948
|
});
|
|
5884
|
-
|
|
5949
|
+
sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> ?_v${varIdx++} .`);
|
|
5885
5950
|
}
|
|
5886
5951
|
}
|
|
5887
5952
|
if (conditions.length === 0) {
|
|
5888
5953
|
return undefined;
|
|
5889
5954
|
}
|
|
5890
|
-
const
|
|
5891
|
-
const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
|
|
5955
|
+
const getter = `SELECT ?target WHERE { <Base> <${escapeQueryString(relationPredicate)}> ?target . ${sparqlConditions.join(' ')} }`;
|
|
5892
5956
|
return { getter, conformanceConditions: conditions };
|
|
5893
5957
|
}
|
|
5894
5958
|
catch (e) {
|
|
@@ -5909,8 +5973,8 @@ function applyPropertyMetadata(opts) {
|
|
|
5909
5973
|
if (opts.required && !opts.initial) {
|
|
5910
5974
|
throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
|
|
5911
5975
|
}
|
|
5912
|
-
if (!opts.through && !opts.prologGetter) {
|
|
5913
|
-
throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
|
|
5976
|
+
if (!opts.through && !opts.prologGetter && !opts.getter) {
|
|
5977
|
+
throw new Error("SubjectProperty requires either 'through' or 'prologGetter' or 'getter' option");
|
|
5914
5978
|
}
|
|
5915
5979
|
// Write to WeakMap registry (keyed by constructor)
|
|
5916
5980
|
const ctor = target.constructor;
|
|
@@ -6095,7 +6159,7 @@ function Model(opts) {
|
|
|
6095
6159
|
return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
|
|
6096
6160
|
};
|
|
6097
6161
|
target.generateSHACL = function () {
|
|
6098
|
-
return buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter);
|
|
6162
|
+
return getMemoizedSHACL(target, () => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter));
|
|
6099
6163
|
};
|
|
6100
6164
|
Object.defineProperty(target, 'type', { configurable: true });
|
|
6101
6165
|
};
|
|
@@ -6118,7 +6182,7 @@ function Model(opts) {
|
|
|
6118
6182
|
* Properties are optional by default. When a model instance is created without
|
|
6119
6183
|
* providing a value for an optional property, no link is added to the graph.
|
|
6120
6184
|
* Set `required: true` explicitly when a property must always be present (this
|
|
6121
|
-
* also adds a `"literal
|
|
6185
|
+
* also adds a `"literal:string:uninitialized"` sentinel as the initial value
|
|
6122
6186
|
* so that the SDNA constructor creates a placeholder link).
|
|
6123
6187
|
*
|
|
6124
6188
|
* @example
|
|
@@ -6157,7 +6221,7 @@ function Model(opts) {
|
|
|
6157
6221
|
* @param {PropertyOptions} opts - Property configuration
|
|
6158
6222
|
* @param {string} opts.through - The predicate URI for the property
|
|
6159
6223
|
* @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
|
|
6160
|
-
* @param {string} [opts.initial] - Initial value (defaults to "literal
|
|
6224
|
+
* @param {string} [opts.initial] - Initial value (defaults to "literal:string:uninitialized" when required)
|
|
6161
6225
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
6162
6226
|
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
6163
6227
|
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
@@ -6170,7 +6234,7 @@ function Property(opts) {
|
|
|
6170
6234
|
required,
|
|
6171
6235
|
readOnly: opts.readOnly ?? false,
|
|
6172
6236
|
resolveLanguage: opts.resolveLanguage ?? "literal",
|
|
6173
|
-
initial: opts.initial ?? (required ? "literal
|
|
6237
|
+
initial: opts.initial ?? (required ? "literal:string:uninitialized" : undefined),
|
|
6174
6238
|
});
|
|
6175
6239
|
}
|
|
6176
6240
|
/**
|
|
@@ -6259,7 +6323,7 @@ function resolveRelationArgs(first, second) {
|
|
|
6259
6323
|
}
|
|
6260
6324
|
if (opts.where) {
|
|
6261
6325
|
throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
|
|
6262
|
-
'Use `where` for DSL-based filtering, or `getter` for raw
|
|
6326
|
+
'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');
|
|
6263
6327
|
}
|
|
6264
6328
|
return opts;
|
|
6265
6329
|
}
|
|
@@ -6402,6 +6466,73 @@ function BelongsToMany(first, second) {
|
|
|
6402
6466
|
};
|
|
6403
6467
|
}
|
|
6404
6468
|
|
|
6469
|
+
/**
|
|
6470
|
+
* Query Result TTL Cache
|
|
6471
|
+
*
|
|
6472
|
+
* Short-lived cache (200ms TTL) for SPARQL query results.
|
|
6473
|
+
* Prevents redundant queries during rapid render cycles where
|
|
6474
|
+
* multiple components issue the same query within milliseconds.
|
|
6475
|
+
*
|
|
6476
|
+
* Key: `perspectiveUUID + queryText`
|
|
6477
|
+
*/
|
|
6478
|
+
const cache = new Map();
|
|
6479
|
+
const DEFAULT_TTL_MS = 200;
|
|
6480
|
+
function makeKey$1(perspectiveUUID, queryText) {
|
|
6481
|
+
return `${perspectiveUUID}:${queryText}`;
|
|
6482
|
+
}
|
|
6483
|
+
/**
|
|
6484
|
+
* Get a cached query result if it exists and hasn't expired.
|
|
6485
|
+
*/
|
|
6486
|
+
function getCachedResult(perspectiveUUID, queryText) {
|
|
6487
|
+
const key = makeKey$1(perspectiveUUID, queryText);
|
|
6488
|
+
const entry = cache.get(key);
|
|
6489
|
+
if (!entry)
|
|
6490
|
+
return undefined;
|
|
6491
|
+
if (Date.now() > entry.expiry) {
|
|
6492
|
+
cache.delete(key);
|
|
6493
|
+
return undefined;
|
|
6494
|
+
}
|
|
6495
|
+
return entry.result;
|
|
6496
|
+
}
|
|
6497
|
+
/**
|
|
6498
|
+
* Store a query result in the cache with TTL.
|
|
6499
|
+
*/
|
|
6500
|
+
function setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {
|
|
6501
|
+
// Lazy eviction of expired entries
|
|
6502
|
+
const now = Date.now();
|
|
6503
|
+
for (const [key, entry] of cache) {
|
|
6504
|
+
if (now > entry.expiry) {
|
|
6505
|
+
cache.delete(key);
|
|
6506
|
+
}
|
|
6507
|
+
}
|
|
6508
|
+
const cacheKey = makeKey$1(perspectiveUUID, queryText);
|
|
6509
|
+
cache.set(cacheKey, { result, expiry: now + ttlMs });
|
|
6510
|
+
}
|
|
6511
|
+
/**
|
|
6512
|
+
* Invalidate all cache entries for a given perspective.
|
|
6513
|
+
* Called after write operations to ensure stale data isn't served.
|
|
6514
|
+
*/
|
|
6515
|
+
function invalidatePerspectiveCache(perspectiveUUID) {
|
|
6516
|
+
const prefix = perspectiveUUID + ':';
|
|
6517
|
+
for (const [key] of cache) {
|
|
6518
|
+
if (key.startsWith(prefix)) {
|
|
6519
|
+
cache.delete(key);
|
|
6520
|
+
}
|
|
6521
|
+
}
|
|
6522
|
+
}
|
|
6523
|
+
/**
|
|
6524
|
+
* Clear all cache entries (useful for testing).
|
|
6525
|
+
*/
|
|
6526
|
+
function clearQueryCache() {
|
|
6527
|
+
cache.clear();
|
|
6528
|
+
}
|
|
6529
|
+
/**
|
|
6530
|
+
* Get the current size of the cache (useful for testing).
|
|
6531
|
+
*/
|
|
6532
|
+
function queryCacheSize() {
|
|
6533
|
+
return cache.size;
|
|
6534
|
+
}
|
|
6535
|
+
|
|
6405
6536
|
/**
|
|
6406
6537
|
* SHACL Flow - represents a state machine for AD4M expressions
|
|
6407
6538
|
*
|
|
@@ -6517,7 +6648,7 @@ class SHACLFlow {
|
|
|
6517
6648
|
}
|
|
6518
6649
|
/**
|
|
6519
6650
|
* Serialize the flow to AD4M links
|
|
6520
|
-
* These links can be stored in a perspective and queried via
|
|
6651
|
+
* These links can be stored in a perspective and queried via SPARQL
|
|
6521
6652
|
*
|
|
6522
6653
|
* @returns Array of Link objects representing the flow
|
|
6523
6654
|
*/
|
|
@@ -6548,7 +6679,7 @@ class SHACLFlow {
|
|
|
6548
6679
|
links.push({
|
|
6549
6680
|
source: flowUri,
|
|
6550
6681
|
predicate: "ad4m://flowable",
|
|
6551
|
-
target: `literal
|
|
6682
|
+
target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
|
|
6552
6683
|
});
|
|
6553
6684
|
}
|
|
6554
6685
|
// Start action
|
|
@@ -6556,7 +6687,7 @@ class SHACLFlow {
|
|
|
6556
6687
|
links.push({
|
|
6557
6688
|
source: flowUri,
|
|
6558
6689
|
predicate: "ad4m://startAction",
|
|
6559
|
-
target: `literal
|
|
6690
|
+
target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
|
|
6560
6691
|
});
|
|
6561
6692
|
}
|
|
6562
6693
|
// States
|
|
@@ -6590,7 +6721,7 @@ class SHACLFlow {
|
|
|
6590
6721
|
links.push({
|
|
6591
6722
|
source: stateUri,
|
|
6592
6723
|
predicate: "ad4m://stateCheck",
|
|
6593
|
-
target: `literal
|
|
6724
|
+
target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
|
|
6594
6725
|
});
|
|
6595
6726
|
}
|
|
6596
6727
|
// Transitions
|
|
@@ -6632,7 +6763,7 @@ class SHACLFlow {
|
|
|
6632
6763
|
links.push({
|
|
6633
6764
|
source: transitionUri,
|
|
6634
6765
|
predicate: "ad4m://transitionActions",
|
|
6635
|
-
target: `literal
|
|
6766
|
+
target: `literal:string:${encodeURIComponent(JSON.stringify(transition.actions))}`
|
|
6636
6767
|
});
|
|
6637
6768
|
}
|
|
6638
6769
|
return links;
|
|
@@ -6664,7 +6795,7 @@ class SHACLFlow {
|
|
|
6664
6795
|
}
|
|
6665
6796
|
else {
|
|
6666
6797
|
try {
|
|
6667
|
-
const jsonStr = flowableLink.target.replace(
|
|
6798
|
+
const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
6668
6799
|
flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
|
|
6669
6800
|
}
|
|
6670
6801
|
catch {
|
|
@@ -6676,7 +6807,7 @@ class SHACLFlow {
|
|
|
6676
6807
|
const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
|
|
6677
6808
|
if (startActionLink) {
|
|
6678
6809
|
try {
|
|
6679
|
-
const jsonStr = startActionLink.target.replace(
|
|
6810
|
+
const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
6680
6811
|
flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
|
|
6681
6812
|
}
|
|
6682
6813
|
catch {
|
|
@@ -6702,7 +6833,7 @@ class SHACLFlow {
|
|
|
6702
6833
|
let stateCheck = { predicate: "", target: "" };
|
|
6703
6834
|
if (checkLink) {
|
|
6704
6835
|
try {
|
|
6705
|
-
const jsonStr = checkLink.target.replace(
|
|
6836
|
+
const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
6706
6837
|
stateCheck = JSON.parse(decodeURIComponent(jsonStr));
|
|
6707
6838
|
}
|
|
6708
6839
|
catch {
|
|
@@ -6731,7 +6862,7 @@ class SHACLFlow {
|
|
|
6731
6862
|
let actions = [];
|
|
6732
6863
|
if (actionsLink) {
|
|
6733
6864
|
try {
|
|
6734
|
-
const jsonStr = actionsLink.target.replace(
|
|
6865
|
+
const jsonStr = actionsLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
|
|
6735
6866
|
actions = JSON.parse(decodeURIComponent(jsonStr));
|
|
6736
6867
|
}
|
|
6737
6868
|
catch {
|
|
@@ -6783,7 +6914,7 @@ var __classPrivateFieldGet$9 = (undefined && undefined.__classPrivateFieldGet) |
|
|
|
6783
6914
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
6784
6915
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
6785
6916
|
};
|
|
6786
|
-
var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
|
|
6917
|
+
var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
|
|
6787
6918
|
/** Proxy object for a subscribed Prolog query that provides real-time updates
|
|
6788
6919
|
*
|
|
6789
6920
|
* This class handles:
|
|
@@ -6838,7 +6969,6 @@ class QuerySubscriptionProxy {
|
|
|
6838
6969
|
_QuerySubscriptionProxy_initReject.set(this, void 0);
|
|
6839
6970
|
_QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
|
|
6840
6971
|
_QuerySubscriptionProxy_query.set(this, void 0);
|
|
6841
|
-
this.isSurrealDB = false;
|
|
6842
6972
|
__classPrivateFieldSet$9(this, _QuerySubscriptionProxy_uuid, uuid, "f");
|
|
6843
6973
|
__classPrivateFieldSet$9(this, _QuerySubscriptionProxy_query, query, "f");
|
|
6844
6974
|
__classPrivateFieldSet$9(this, _QuerySubscriptionProxy_client, client, "f");
|
|
@@ -6869,12 +6999,7 @@ class QuerySubscriptionProxy {
|
|
|
6869
6999
|
try {
|
|
6870
7000
|
// Initialize the query subscription
|
|
6871
7001
|
let initialResult;
|
|
6872
|
-
|
|
6873
|
-
initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
|
|
6874
|
-
}
|
|
6875
|
-
else {
|
|
6876
|
-
initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
|
|
6877
|
-
}
|
|
7002
|
+
initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
|
|
6878
7003
|
__classPrivateFieldSet$9(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
|
|
6879
7004
|
// Process the initial result immediately for fast UX
|
|
6880
7005
|
if (initialResult.result) {
|
|
@@ -6927,12 +7052,7 @@ class QuerySubscriptionProxy {
|
|
|
6927
7052
|
if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_disposed, "f"))
|
|
6928
7053
|
return;
|
|
6929
7054
|
try {
|
|
6930
|
-
|
|
6931
|
-
await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
|
|
6932
|
-
}
|
|
6933
|
-
else {
|
|
6934
|
-
await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
|
|
6935
|
-
}
|
|
7055
|
+
await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
|
|
6936
7056
|
}
|
|
6937
7057
|
catch (e) {
|
|
6938
7058
|
console.error('Error in keepalive:', e);
|
|
@@ -7039,14 +7159,8 @@ class QuerySubscriptionProxy {
|
|
|
7039
7159
|
}
|
|
7040
7160
|
// Tell the backend to dispose of the subscription
|
|
7041
7161
|
if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
|
|
7042
|
-
|
|
7043
|
-
|
|
7044
|
-
.catch(e => console.error('Error disposing surreal query subscription:', e));
|
|
7045
|
-
}
|
|
7046
|
-
else {
|
|
7047
|
-
__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
|
|
7048
|
-
.catch(e => console.error('Error disposing query subscription:', e));
|
|
7049
|
-
}
|
|
7162
|
+
__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
|
|
7163
|
+
.catch(e => console.error('Error disposing query subscription:', e));
|
|
7050
7164
|
}
|
|
7051
7165
|
}
|
|
7052
7166
|
}
|
|
@@ -7111,6 +7225,12 @@ class PerspectiveProxy {
|
|
|
7111
7225
|
_PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);
|
|
7112
7226
|
_PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
|
|
7113
7227
|
_PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
|
|
7228
|
+
_PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()
|
|
7229
|
+
/**
|
|
7230
|
+
* Creates a new PerspectiveProxy instance.
|
|
7231
|
+
* Note: Don't create this directly, use ad4m.perspective.add() instead.
|
|
7232
|
+
*/
|
|
7233
|
+
);
|
|
7114
7234
|
__classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
|
|
7115
7235
|
__classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
|
|
7116
7236
|
__classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
|
|
@@ -7201,7 +7321,9 @@ class PerspectiveProxy {
|
|
|
7201
7321
|
* @param batchId - Optional batch ID to group this operation with others
|
|
7202
7322
|
*/
|
|
7203
7323
|
async executeAction(actions, expression, parameters, batchId) {
|
|
7204
|
-
|
|
7324
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
|
|
7325
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7326
|
+
return result;
|
|
7205
7327
|
}
|
|
7206
7328
|
/**
|
|
7207
7329
|
* Retrieves links from the perspective that match the given query.
|
|
@@ -7254,34 +7376,28 @@ class PerspectiveProxy {
|
|
|
7254
7376
|
return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
7255
7377
|
}
|
|
7256
7378
|
/**
|
|
7257
|
-
* Executes a
|
|
7258
|
-
* This allows powerful SQL-like queries on the link data stored in
|
|
7379
|
+
* Executes a SPARQL query against the perspective's link cache.
|
|
7380
|
+
* This allows powerful SQL-like queries on the link data stored in SPARQL.
|
|
7259
7381
|
*
|
|
7260
7382
|
* **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
|
|
7261
7383
|
* Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
|
|
7262
7384
|
* blocked for security reasons. Use the perspective's add/remove methods to modify links.
|
|
7263
7385
|
*
|
|
7264
|
-
* @param query -
|
|
7386
|
+
* @param query - SPARQL query string (read-only operations only)
|
|
7265
7387
|
* @returns Query results as parsed JSON
|
|
7266
7388
|
*
|
|
7267
|
-
*
|
|
7268
|
-
* ```typescript
|
|
7269
|
-
* // Get all links
|
|
7270
|
-
* const links = await perspective.querySurrealDB('SELECT * FROM link');
|
|
7389
|
+
* Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
|
|
7271
7390
|
*
|
|
7272
|
-
*
|
|
7273
|
-
*
|
|
7274
|
-
* "SELECT * FROM link WHERE predicate = 'follows'"
|
|
7275
|
-
* );
|
|
7276
|
-
*
|
|
7277
|
-
* // Complex aggregation query
|
|
7278
|
-
* const stats = await perspective.querySurrealDB(
|
|
7279
|
-
* "SELECT predicate, count() as total FROM link GROUP BY predicate"
|
|
7280
|
-
* );
|
|
7281
|
-
* ```
|
|
7391
|
+
* @param query - SPARQL query string
|
|
7392
|
+
* @returns Query results as parsed JSON
|
|
7282
7393
|
*/
|
|
7283
|
-
async
|
|
7284
|
-
|
|
7394
|
+
async querySparql(query) {
|
|
7395
|
+
const cached = getCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
7396
|
+
if (cached !== undefined)
|
|
7397
|
+
return cached;
|
|
7398
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
7399
|
+
setCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query, result);
|
|
7400
|
+
return result;
|
|
7285
7401
|
}
|
|
7286
7402
|
/**
|
|
7287
7403
|
* Adds a new link to the perspective.
|
|
@@ -7309,7 +7425,9 @@ class PerspectiveProxy {
|
|
|
7309
7425
|
* ```
|
|
7310
7426
|
*/
|
|
7311
7427
|
async add(link, status = 'shared', batchId) {
|
|
7312
|
-
|
|
7428
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
|
|
7429
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7430
|
+
return result;
|
|
7313
7431
|
}
|
|
7314
7432
|
/**
|
|
7315
7433
|
* Adds multiple links to the perspective in a single operation.
|
|
@@ -7321,7 +7439,9 @@ class PerspectiveProxy {
|
|
|
7321
7439
|
* @returns Array of created LinkExpressions
|
|
7322
7440
|
*/
|
|
7323
7441
|
async addLinks(links, status = 'shared', batchId) {
|
|
7324
|
-
|
|
7442
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
|
|
7443
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7444
|
+
return result;
|
|
7325
7445
|
}
|
|
7326
7446
|
/**
|
|
7327
7447
|
* Removes multiple links from the perspective.
|
|
@@ -7331,7 +7451,9 @@ class PerspectiveProxy {
|
|
|
7331
7451
|
* @returns Array of removed LinkExpressions
|
|
7332
7452
|
*/
|
|
7333
7453
|
async removeLinks(links, batchId) {
|
|
7334
|
-
|
|
7454
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
|
|
7455
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7456
|
+
return result;
|
|
7335
7457
|
}
|
|
7336
7458
|
/**
|
|
7337
7459
|
* Applies a set of link mutations (adds and removes) in a single operation.
|
|
@@ -7342,7 +7464,9 @@ class PerspectiveProxy {
|
|
|
7342
7464
|
* @returns Object containing results of the mutations
|
|
7343
7465
|
*/
|
|
7344
7466
|
async linkMutations(mutations, status = 'shared') {
|
|
7345
|
-
|
|
7467
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
|
|
7468
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7469
|
+
return result;
|
|
7346
7470
|
}
|
|
7347
7471
|
/**
|
|
7348
7472
|
* Adds a pre-signed LinkExpression to the perspective.
|
|
@@ -7363,7 +7487,9 @@ class PerspectiveProxy {
|
|
|
7363
7487
|
* @param batchId - Optional batch ID to group this operation with others
|
|
7364
7488
|
*/
|
|
7365
7489
|
async update(oldLink, newLink, batchId) {
|
|
7366
|
-
|
|
7490
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
|
|
7491
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7492
|
+
return result;
|
|
7367
7493
|
}
|
|
7368
7494
|
/**
|
|
7369
7495
|
* Removes a link from the perspective.
|
|
@@ -7372,7 +7498,9 @@ class PerspectiveProxy {
|
|
|
7372
7498
|
* @param batchId - Optional batch ID to group this operation with others
|
|
7373
7499
|
*/
|
|
7374
7500
|
async remove(link, batchId) {
|
|
7375
|
-
|
|
7501
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
|
|
7502
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7503
|
+
return result;
|
|
7376
7504
|
}
|
|
7377
7505
|
/** Creates a new batch for grouping operations */
|
|
7378
7506
|
async createBatch() {
|
|
@@ -7380,7 +7508,9 @@ class PerspectiveProxy {
|
|
|
7380
7508
|
}
|
|
7381
7509
|
/** Commits a batch of operations */
|
|
7382
7510
|
async commitBatch(batchId) {
|
|
7383
|
-
|
|
7511
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, batchId);
|
|
7512
|
+
invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
7513
|
+
return result;
|
|
7384
7514
|
}
|
|
7385
7515
|
/**
|
|
7386
7516
|
* Retrieves and renders an Expression referenced in this perspective.
|
|
@@ -7755,6 +7885,13 @@ class PerspectiveProxy {
|
|
|
7755
7885
|
async addSdna(name, sdnaCode, sdnaType, shaclJson) {
|
|
7756
7886
|
return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
|
|
7757
7887
|
}
|
|
7888
|
+
/**
|
|
7889
|
+
* Adds a subject class to the perspective.
|
|
7890
|
+
* Alias for addSdna() with sdnaType='subject_class'.
|
|
7891
|
+
*/
|
|
7892
|
+
async addSubjectClass(name, shaclJson) {
|
|
7893
|
+
return this.addSdna(name, '', 'subject_class', shaclJson);
|
|
7894
|
+
}
|
|
7758
7895
|
/**
|
|
7759
7896
|
* **Recommended way to add SDNA schemas.**
|
|
7760
7897
|
*
|
|
@@ -7786,7 +7923,7 @@ class PerspectiveProxy {
|
|
|
7786
7923
|
// Serialize shape to links
|
|
7787
7924
|
const shapeLinks = shape.toLinks();
|
|
7788
7925
|
// Create name -> shape mapping links
|
|
7789
|
-
const nameMapping = Literal.fromUrl(`literal
|
|
7926
|
+
const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
|
|
7790
7927
|
const allLinks = [
|
|
7791
7928
|
...shapeLinks.map(l => new Link({
|
|
7792
7929
|
source: l.source,
|
|
@@ -7812,7 +7949,7 @@ class PerspectiveProxy {
|
|
|
7812
7949
|
*/
|
|
7813
7950
|
async getShacl(name) {
|
|
7814
7951
|
// Find the shape URI from the name mapping
|
|
7815
|
-
const nameMapping = Literal.fromUrl(`literal
|
|
7952
|
+
const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
|
|
7816
7953
|
const shapeUriLinks = await this.get(new LinkQuery({
|
|
7817
7954
|
source: nameMapping.toUrl(),
|
|
7818
7955
|
predicate: "ad4m://shacl_shape_uri"
|
|
@@ -7821,22 +7958,25 @@ class PerspectiveProxy {
|
|
|
7821
7958
|
return null;
|
|
7822
7959
|
}
|
|
7823
7960
|
const shapeUri = shapeUriLinks[0].data.target;
|
|
7824
|
-
escapeSurrealString(shapeUri);
|
|
7825
7961
|
// First get property shape URIs so we can query everything in one go
|
|
7826
7962
|
const propertyLinks = await this.get(new LinkQuery({
|
|
7827
7963
|
source: shapeUri,
|
|
7828
7964
|
predicate: "sh://property"
|
|
7829
7965
|
}));
|
|
7830
|
-
//
|
|
7966
|
+
// Fetch all links from the shape and its property shapes
|
|
7831
7967
|
const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
|
|
7832
|
-
const
|
|
7833
|
-
const
|
|
7834
|
-
|
|
7835
|
-
|
|
7836
|
-
|
|
7837
|
-
|
|
7838
|
-
|
|
7839
|
-
|
|
7968
|
+
const allLinks = [];
|
|
7969
|
+
for (const uri of sourceUris) {
|
|
7970
|
+
const links = await this.get(new LinkQuery({ source: uri }));
|
|
7971
|
+
for (const l of links) {
|
|
7972
|
+
allLinks.push({
|
|
7973
|
+
source: l.data.source,
|
|
7974
|
+
predicate: l.data.predicate,
|
|
7975
|
+
target: l.data.target
|
|
7976
|
+
});
|
|
7977
|
+
}
|
|
7978
|
+
}
|
|
7979
|
+
const shapeLinks = allLinks;
|
|
7840
7980
|
return SHACLShape.fromLinks(shapeLinks, shapeUri);
|
|
7841
7981
|
}
|
|
7842
7982
|
/**
|
|
@@ -7938,19 +8078,20 @@ class PerspectiveProxy {
|
|
|
7938
8078
|
return null;
|
|
7939
8079
|
}
|
|
7940
8080
|
const flowUri = flowUriLinks[0].data.target;
|
|
7941
|
-
const escapedFlowUri = escapeSurrealString(flowUri);
|
|
7942
8081
|
// Compute alternate prefix for state/transition URIs
|
|
7943
8082
|
const alternatePrefix = flowUri.endsWith('Flow')
|
|
7944
8083
|
? flowUri.slice(0, -4) + '.'
|
|
7945
8084
|
: flowUri + '.';
|
|
7946
|
-
|
|
7947
|
-
|
|
7948
|
-
|
|
7949
|
-
|
|
7950
|
-
|
|
7951
|
-
|
|
7952
|
-
|
|
7953
|
-
|
|
8085
|
+
// Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
|
|
8086
|
+
const sparqlQuery = `SELECT ?s ?p ?o WHERE {
|
|
8087
|
+
?s ?p ?o .
|
|
8088
|
+
FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
|
|
8089
|
+
}`;
|
|
8090
|
+
const sparqlResult = await this.querySparql(sparqlQuery);
|
|
8091
|
+
const flowLinks = (sparqlResult || []).map((r) => ({
|
|
8092
|
+
source: r.s,
|
|
8093
|
+
predicate: r.p,
|
|
8094
|
+
target: r.o
|
|
7954
8095
|
}));
|
|
7955
8096
|
return SHACLFlow.fromLinks(flowLinks, flowUri);
|
|
7956
8097
|
}
|
|
@@ -8059,8 +8200,8 @@ class PerspectiveProxy {
|
|
|
8059
8200
|
const links = await this.get(new LinkQuery({ predicate }));
|
|
8060
8201
|
for (const link of links) {
|
|
8061
8202
|
if (shapePattern.test(link.data.source)) {
|
|
8062
|
-
// Parse actions from literal
|
|
8063
|
-
const prefix = "literal
|
|
8203
|
+
// Parse actions from literal:string:{json}
|
|
8204
|
+
const prefix = "literal:string:";
|
|
8064
8205
|
if (link.data.target.startsWith(prefix)) {
|
|
8065
8206
|
const jsonStr = link.data.target.slice(prefix.length);
|
|
8066
8207
|
// Decode URL-encoded JSON if needed, with fallback for raw % characters
|
|
@@ -8116,35 +8257,20 @@ class PerspectiveProxy {
|
|
|
8116
8257
|
}
|
|
8117
8258
|
// If no required triples, any expression with links is an instance
|
|
8118
8259
|
if (metadata.requiredTriples.length === 0) {
|
|
8119
|
-
const
|
|
8120
|
-
|
|
8121
|
-
const result = await this.querySurrealDB(checkQuery);
|
|
8122
|
-
const count = result[0]?.count ?? 0;
|
|
8123
|
-
const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
|
|
8124
|
-
return countValue > 0;
|
|
8260
|
+
const links = await this.get(new LinkQuery({ source: expression }));
|
|
8261
|
+
return links.length > 0;
|
|
8125
8262
|
}
|
|
8126
8263
|
// Check if the expression has all required triples (predicate + optional exact target)
|
|
8127
8264
|
for (const triple of metadata.requiredTriples) {
|
|
8128
|
-
|
|
8129
|
-
const escapedPredicate = escapeSurrealString(triple.predicate);
|
|
8130
|
-
let checkQuery;
|
|
8265
|
+
let query;
|
|
8131
8266
|
if (triple.target) {
|
|
8132
|
-
|
|
8133
|
-
const escapedTarget = escapeSurrealString(triple.target);
|
|
8134
|
-
checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
|
|
8267
|
+
query = new LinkQuery({ source: expression, predicate: triple.predicate, target: triple.target });
|
|
8135
8268
|
}
|
|
8136
8269
|
else {
|
|
8137
|
-
|
|
8138
|
-
checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
|
|
8270
|
+
query = new LinkQuery({ source: expression, predicate: triple.predicate });
|
|
8139
8271
|
}
|
|
8140
|
-
const
|
|
8141
|
-
if (!
|
|
8142
|
-
return false;
|
|
8143
|
-
}
|
|
8144
|
-
const count = result[0]?.count ?? 0;
|
|
8145
|
-
// Handle potential object response like {Int: 0}
|
|
8146
|
-
const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
|
|
8147
|
-
if (countValue === 0) {
|
|
8272
|
+
const links = await this.get(query);
|
|
8273
|
+
if (!links || links.length === 0) {
|
|
8148
8274
|
return false;
|
|
8149
8275
|
}
|
|
8150
8276
|
}
|
|
@@ -8172,6 +8298,10 @@ class PerspectiveProxy {
|
|
|
8172
8298
|
* Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
|
|
8173
8299
|
* Retrieves the SHACL shape and extracts metadata for instance queries.
|
|
8174
8300
|
*/
|
|
8301
|
+
async getSubjectClassMetadata(className) {
|
|
8302
|
+
return this.getSubjectClassMetadataFromSDNA(className);
|
|
8303
|
+
}
|
|
8304
|
+
/** @deprecated Use getSubjectClassMetadata() */
|
|
8175
8305
|
async getSubjectClassMetadataFromSDNA(className) {
|
|
8176
8306
|
try {
|
|
8177
8307
|
// Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
|
|
@@ -8226,33 +8356,55 @@ class PerspectiveProxy {
|
|
|
8226
8356
|
}
|
|
8227
8357
|
}
|
|
8228
8358
|
/**
|
|
8229
|
-
* Generates a
|
|
8359
|
+
* Generates a SPARQL query to find instances based on class metadata.
|
|
8360
|
+
*/
|
|
8361
|
+
/**
|
|
8362
|
+
* Finds all instances matching subject class metadata by querying links.
|
|
8363
|
+
* Returns base URIs of matching instances.
|
|
8230
8364
|
*/
|
|
8231
|
-
|
|
8365
|
+
async findInstancesByMetadata(metadata) {
|
|
8232
8366
|
if (metadata.requiredTriples.length === 0) {
|
|
8233
|
-
// No required triples -
|
|
8234
|
-
|
|
8367
|
+
// No required triples - return all unique sources that have any link
|
|
8368
|
+
const allLinks = await this.get(new LinkQuery({}));
|
|
8369
|
+
const sources = new Set(allLinks.map(l => l.data.source));
|
|
8370
|
+
return Array.from(sources).map(s => ({ base: s }));
|
|
8235
8371
|
}
|
|
8236
|
-
//
|
|
8237
|
-
const
|
|
8238
|
-
|
|
8239
|
-
|
|
8240
|
-
|
|
8241
|
-
|
|
8242
|
-
|
|
8243
|
-
}
|
|
8244
|
-
|
|
8245
|
-
|
|
8246
|
-
|
|
8372
|
+
// Use first required triple to get candidate set, then filter by rest
|
|
8373
|
+
const first = metadata.requiredTriples[0];
|
|
8374
|
+
let query;
|
|
8375
|
+
if (first.target) {
|
|
8376
|
+
query = new LinkQuery({ predicate: first.predicate, target: first.target });
|
|
8377
|
+
}
|
|
8378
|
+
else {
|
|
8379
|
+
query = new LinkQuery({ predicate: first.predicate });
|
|
8380
|
+
}
|
|
8381
|
+
const candidateLinks = await this.get(query);
|
|
8382
|
+
let candidates = [...new Set(candidateLinks.map(l => l.data.source))];
|
|
8383
|
+
// Filter by remaining required triples
|
|
8384
|
+
for (let i = 1; i < metadata.requiredTriples.length; i++) {
|
|
8385
|
+
const triple = metadata.requiredTriples[i];
|
|
8386
|
+
const remaining = [];
|
|
8387
|
+
for (const expr of candidates) {
|
|
8388
|
+
let q;
|
|
8389
|
+
if (triple.target) {
|
|
8390
|
+
q = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
|
|
8391
|
+
}
|
|
8392
|
+
else {
|
|
8393
|
+
q = new LinkQuery({ source: expr, predicate: triple.predicate });
|
|
8394
|
+
}
|
|
8395
|
+
const links = await this.get(q);
|
|
8396
|
+
if (links.length > 0)
|
|
8397
|
+
remaining.push(expr);
|
|
8247
8398
|
}
|
|
8248
|
-
|
|
8249
|
-
|
|
8399
|
+
candidates = remaining;
|
|
8400
|
+
}
|
|
8401
|
+
return candidates.map(c => ({ base: c }));
|
|
8250
8402
|
}
|
|
8251
8403
|
/**
|
|
8252
|
-
* Gets a property value using
|
|
8404
|
+
* Gets a property value using SPARQL when Prolog fails.
|
|
8253
8405
|
* This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
|
|
8254
8406
|
*/
|
|
8255
|
-
async
|
|
8407
|
+
async getPropertyValueViaSparql(baseExpression, className, propertyName) {
|
|
8256
8408
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
8257
8409
|
if (!metadata) {
|
|
8258
8410
|
return undefined;
|
|
@@ -8261,14 +8413,11 @@ class PerspectiveProxy {
|
|
|
8261
8413
|
if (!propMeta) {
|
|
8262
8414
|
return undefined;
|
|
8263
8415
|
}
|
|
8264
|
-
const
|
|
8265
|
-
|
|
8266
|
-
const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
|
|
8267
|
-
const result = await this.querySurrealDB(query);
|
|
8268
|
-
if (!result || result.length === 0) {
|
|
8416
|
+
const links = await this.get(new LinkQuery({ source: baseExpression, predicate: propMeta.predicate }));
|
|
8417
|
+
if (!links || links.length === 0) {
|
|
8269
8418
|
return undefined;
|
|
8270
8419
|
}
|
|
8271
|
-
const value =
|
|
8420
|
+
const value = links[0].data.target;
|
|
8272
8421
|
// Handle expression resolution if needed
|
|
8273
8422
|
if (propMeta.resolveLanguage && value) {
|
|
8274
8423
|
try {
|
|
@@ -8287,11 +8436,11 @@ class PerspectiveProxy {
|
|
|
8287
8436
|
return value;
|
|
8288
8437
|
}
|
|
8289
8438
|
/**
|
|
8290
|
-
* Gets relation values using
|
|
8439
|
+
* Gets relation values using SPARQL when Prolog fails.
|
|
8291
8440
|
* This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
|
|
8292
8441
|
* Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
|
|
8293
8442
|
*/
|
|
8294
|
-
async
|
|
8443
|
+
async getRelationValuesViaSparql(baseExpression, className, relationName) {
|
|
8295
8444
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
8296
8445
|
if (!metadata) {
|
|
8297
8446
|
return [];
|
|
@@ -8300,14 +8449,13 @@ class PerspectiveProxy {
|
|
|
8300
8449
|
if (!relMeta) {
|
|
8301
8450
|
return [];
|
|
8302
8451
|
}
|
|
8303
|
-
const
|
|
8304
|
-
|
|
8305
|
-
const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
|
|
8306
|
-
const result = await this.querySurrealDB(query);
|
|
8307
|
-
if (!result || result.length === 0) {
|
|
8452
|
+
const links = await this.get(new LinkQuery({ source: baseExpression, predicate: relMeta.predicate }));
|
|
8453
|
+
if (!links || links.length === 0) {
|
|
8308
8454
|
return [];
|
|
8309
8455
|
}
|
|
8310
|
-
|
|
8456
|
+
// Sort by timestamp ascending
|
|
8457
|
+
links.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
|
|
8458
|
+
let values = links.map(l => l.data.target).filter(v => v !== "" && v !== '');
|
|
8311
8459
|
// Apply condition filtering if present
|
|
8312
8460
|
if (relMeta.condition && values.length > 0) {
|
|
8313
8461
|
try {
|
|
@@ -8317,13 +8465,28 @@ class PerspectiveProxy {
|
|
|
8317
8465
|
.replace(/\$perspective/g, `'${this.uuid}'`)
|
|
8318
8466
|
.replace(/\$base/g, `'${baseExpression}'`)
|
|
8319
8467
|
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
8320
|
-
//
|
|
8321
|
-
|
|
8322
|
-
|
|
8468
|
+
// Parse condition to extract link query parameters
|
|
8469
|
+
// Conditions typically look like: WHERE in.uri = 'X' AND predicate = 'Y' AND out.uri = 'Z'
|
|
8470
|
+
// or: array::len(SELECT * FROM link WHERE ...) > 0
|
|
8471
|
+
// Convert to queryLinks calls
|
|
8472
|
+
const sourceMatch = condition.match(/in\.uri\s*=\s*'([^']+)'/);
|
|
8473
|
+
const predicateMatch = condition.match(/predicate\s*=\s*'([^']+)'/);
|
|
8474
|
+
const targetMatch = condition.match(/out\.uri\s*=\s*'([^']+)'/);
|
|
8475
|
+
if (sourceMatch || predicateMatch || targetMatch) {
|
|
8476
|
+
const linkQuery = {};
|
|
8477
|
+
if (sourceMatch)
|
|
8478
|
+
linkQuery.source = sourceMatch[1];
|
|
8479
|
+
if (predicateMatch)
|
|
8480
|
+
linkQuery.predicate = predicateMatch[1];
|
|
8481
|
+
if (targetMatch)
|
|
8482
|
+
linkQuery.target = targetMatch[1];
|
|
8483
|
+
const matchingLinks = await this.get(new LinkQuery(linkQuery));
|
|
8484
|
+
if (matchingLinks.length > 0) {
|
|
8485
|
+
filteredValues.push(value);
|
|
8486
|
+
}
|
|
8323
8487
|
}
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
if (isTrue) {
|
|
8488
|
+
else {
|
|
8489
|
+
// Can't parse condition, include by default
|
|
8327
8490
|
filteredValues.push(value);
|
|
8328
8491
|
}
|
|
8329
8492
|
}
|
|
@@ -8351,7 +8514,7 @@ class PerspectiveProxy {
|
|
|
8351
8514
|
return values;
|
|
8352
8515
|
}
|
|
8353
8516
|
/**
|
|
8354
|
-
* Batch-checks multiple expressions against subject class metadata using a single or limited
|
|
8517
|
+
* Batch-checks multiple expressions against subject class metadata using a single or limited SPARQL queries.
|
|
8355
8518
|
* This avoids N+1 query problems by checking all values at once.
|
|
8356
8519
|
*/
|
|
8357
8520
|
async batchCheckSubjectInstances(expressions, metadata) {
|
|
@@ -8360,30 +8523,31 @@ class PerspectiveProxy {
|
|
|
8360
8523
|
}
|
|
8361
8524
|
// If no required triples, check which expressions have any links
|
|
8362
8525
|
if (metadata.requiredTriples.length === 0) {
|
|
8363
|
-
const
|
|
8364
|
-
const
|
|
8365
|
-
|
|
8366
|
-
|
|
8526
|
+
const results = [];
|
|
8527
|
+
for (const expr of expressions) {
|
|
8528
|
+
const links = await this.get(new LinkQuery({ source: expr }));
|
|
8529
|
+
if (links.length > 0)
|
|
8530
|
+
results.push(expr);
|
|
8531
|
+
}
|
|
8532
|
+
return results;
|
|
8367
8533
|
}
|
|
8368
|
-
// For each required triple,
|
|
8534
|
+
// For each required triple, find which expressions match
|
|
8369
8535
|
const validExpressionSets = [];
|
|
8370
8536
|
for (const triple of metadata.requiredTriples) {
|
|
8371
|
-
const
|
|
8372
|
-
const
|
|
8373
|
-
|
|
8374
|
-
|
|
8375
|
-
|
|
8376
|
-
|
|
8377
|
-
|
|
8378
|
-
|
|
8379
|
-
|
|
8380
|
-
|
|
8381
|
-
|
|
8382
|
-
|
|
8383
|
-
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
|
|
8537
|
+
const matchingExprs = new Set();
|
|
8538
|
+
for (const expr of expressions) {
|
|
8539
|
+
let query;
|
|
8540
|
+
if (triple.target) {
|
|
8541
|
+
query = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
|
|
8542
|
+
}
|
|
8543
|
+
else {
|
|
8544
|
+
query = new LinkQuery({ source: expr, predicate: triple.predicate });
|
|
8545
|
+
}
|
|
8546
|
+
const links = await this.get(query);
|
|
8547
|
+
if (links.length > 0)
|
|
8548
|
+
matchingExprs.add(expr);
|
|
8384
8549
|
}
|
|
8385
|
-
|
|
8386
|
-
validExpressionSets.push(new Set(result.map(r => r.uri)));
|
|
8550
|
+
validExpressionSets.push(matchingExprs);
|
|
8387
8551
|
}
|
|
8388
8552
|
// Find intersection: expressions that passed ALL required triple checks
|
|
8389
8553
|
if (validExpressionSets.length === 0) {
|
|
@@ -8435,13 +8599,12 @@ class PerspectiveProxy {
|
|
|
8435
8599
|
let instances = [];
|
|
8436
8600
|
for (let className of classes) {
|
|
8437
8601
|
//console.log(`getAllSubjectInstances: Processing class ${className}`);
|
|
8438
|
-
// Query SDNA for metadata, then query
|
|
8602
|
+
// Query SDNA for metadata, then query SPARQL for instances
|
|
8439
8603
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
8440
8604
|
//console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
|
|
8441
8605
|
if (metadata) {
|
|
8442
|
-
const
|
|
8443
|
-
|
|
8444
|
-
// console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
|
|
8606
|
+
const results = await this.findInstancesByMetadata(metadata);
|
|
8607
|
+
// console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);
|
|
8445
8608
|
for (const result of results || []) {
|
|
8446
8609
|
//console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
|
|
8447
8610
|
try {
|
|
@@ -8485,11 +8648,10 @@ class PerspectiveProxy {
|
|
|
8485
8648
|
}
|
|
8486
8649
|
let instances = [];
|
|
8487
8650
|
for (let className of classes) {
|
|
8488
|
-
// Query SDNA for metadata, then query
|
|
8651
|
+
// Query SDNA for metadata, then query SPARQL for instances
|
|
8489
8652
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
8490
8653
|
if (metadata) {
|
|
8491
|
-
const
|
|
8492
|
-
const results = await this.querySurrealDB(surrealQuery);
|
|
8654
|
+
const results = await this.findInstancesByMetadata(metadata);
|
|
8493
8655
|
for (const result of results || []) {
|
|
8494
8656
|
try {
|
|
8495
8657
|
let subject = new Subject(this, result.base, className);
|
|
@@ -8534,15 +8696,16 @@ class PerspectiveProxy {
|
|
|
8534
8696
|
if (properties.length === 0 && relations.length === 0) {
|
|
8535
8697
|
return null;
|
|
8536
8698
|
}
|
|
8537
|
-
//
|
|
8538
|
-
const
|
|
8539
|
-
|
|
8540
|
-
|
|
8541
|
-
|
|
8542
|
-
|
|
8543
|
-
|
|
8544
|
-
|
|
8545
|
-
|
|
8699
|
+
// Query links for class shapes using queryLinks
|
|
8700
|
+
const typeLinks = await this.get(new LinkQuery({ predicate: 'rdf://type', target: 'ad4m://SubjectClass' }));
|
|
8701
|
+
const propLinks = await this.get(new LinkQuery({ predicate: 'sh://property' }));
|
|
8702
|
+
const collLinks = await this.get(new LinkQuery({ predicate: 'sh://collection' }));
|
|
8703
|
+
const results = [
|
|
8704
|
+
...typeLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
|
|
8705
|
+
...propLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
|
|
8706
|
+
...collLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
|
|
8707
|
+
];
|
|
8708
|
+
if (results.length === 0)
|
|
8546
8709
|
return null;
|
|
8547
8710
|
// Build a map of className -> { properties, relations }
|
|
8548
8711
|
const classShapes = new Map();
|
|
@@ -8640,8 +8803,15 @@ class PerspectiveProxy {
|
|
|
8640
8803
|
* static generateSDNA() function and adds it to the perspective's SDNA.
|
|
8641
8804
|
*/
|
|
8642
8805
|
async ensureSDNASubjectClass(jsClass) {
|
|
8806
|
+
return this.ensureSubjectClass(jsClass);
|
|
8807
|
+
}
|
|
8808
|
+
/** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
|
|
8809
|
+
async ensureSubjectClass(jsClass) {
|
|
8643
8810
|
// Get the class name from the JS class
|
|
8644
8811
|
const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
|
|
8812
|
+
// Skip if already registered for this perspective instance
|
|
8813
|
+
if (__classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
|
|
8814
|
+
return;
|
|
8645
8815
|
// Note: Duplicate checking is handled on the Rust side in add_sdna
|
|
8646
8816
|
// Generate SHACL SDNA (Prolog-free)
|
|
8647
8817
|
if (!jsClass.generateSHACL) {
|
|
@@ -8654,6 +8824,14 @@ class PerspectiveProxy {
|
|
|
8654
8824
|
// Pass SHACL JSON to backend (Prolog-free)
|
|
8655
8825
|
// Backend stores SHACL links directly
|
|
8656
8826
|
await this.addSdna(className, '', 'subject_class', shaclJson);
|
|
8827
|
+
// Mark as registered for this perspective instance
|
|
8828
|
+
__classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(className);
|
|
8829
|
+
}
|
|
8830
|
+
/** Clear the per-instance ensured subject class cache.
|
|
8831
|
+
* Call this after wiping a perspective's links so that
|
|
8832
|
+
* subsequent register() calls re-add SHACL definitions. */
|
|
8833
|
+
clearEnsuredSubjectClasses() {
|
|
8834
|
+
__classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").clear();
|
|
8657
8835
|
}
|
|
8658
8836
|
getNeighbourhoodProxy() {
|
|
8659
8837
|
return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
|
|
@@ -8723,7 +8901,7 @@ class PerspectiveProxy {
|
|
|
8723
8901
|
return subscriptionProxy;
|
|
8724
8902
|
}
|
|
8725
8903
|
/**
|
|
8726
|
-
* Creates a subscription for a
|
|
8904
|
+
* Creates a subscription for a SPARQL query that updates in real-time.
|
|
8727
8905
|
*
|
|
8728
8906
|
* This method:
|
|
8729
8907
|
* 1. Creates the subscription on the Rust side
|
|
@@ -8738,12 +8916,12 @@ class PerspectiveProxy {
|
|
|
8738
8916
|
* when dispose() is called. Make sure to call dispose() when you're done to
|
|
8739
8917
|
* prevent memory leaks and ensure proper cleanup of resources.
|
|
8740
8918
|
*
|
|
8741
|
-
|
|
8919
|
+
/** Subscribe to a query with live updates via the SPARQL subscription endpoint.
|
|
8920
|
+
* @param query - Query string
|
|
8742
8921
|
* @returns Initialized QuerySubscriptionProxy instance
|
|
8743
8922
|
*/
|
|
8744
|
-
async
|
|
8923
|
+
async subscribeQuery(query) {
|
|
8745
8924
|
const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f"));
|
|
8746
|
-
subscriptionProxy.isSurrealDB = true;
|
|
8747
8925
|
// Start the subscription on the Rust side first to get the real subscription ID
|
|
8748
8926
|
await subscriptionProxy.subscribe();
|
|
8749
8927
|
// Wait for the initial result
|
|
@@ -8751,7 +8929,7 @@ class PerspectiveProxy {
|
|
|
8751
8929
|
return subscriptionProxy;
|
|
8752
8930
|
}
|
|
8753
8931
|
}
|
|
8754
|
-
_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
|
|
8932
|
+
_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();
|
|
8755
8933
|
|
|
8756
8934
|
var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
8757
8935
|
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
@@ -8890,23 +9068,14 @@ class PerspectiveClient {
|
|
|
8890
9068
|
}));
|
|
8891
9069
|
return JSON.parse(perspectiveQueryProlog);
|
|
8892
9070
|
}
|
|
8893
|
-
|
|
8894
|
-
|
|
8895
|
-
|
|
8896
|
-
|
|
8897
|
-
* Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
|
|
8898
|
-
*
|
|
8899
|
-
* Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
|
|
8900
|
-
* as generated from Rust method "perspective_query_surreal_db"
|
|
8901
|
-
*/
|
|
8902
|
-
async querySurrealDB(uuid, query) {
|
|
8903
|
-
const { perspectiveQuerySurrealDb } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").query({
|
|
8904
|
-
query: gql `query perspectiveQuerySurrealDb($uuid: String!, $query: String!) {
|
|
8905
|
-
perspectiveQuerySurrealDb(uuid: $uuid, query: $query)
|
|
9071
|
+
async querySparql(uuid, query) {
|
|
9072
|
+
const { perspectiveQuerySparql } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").query({
|
|
9073
|
+
query: gql `query perspectiveQuerySparql($uuid: String!, $query: String!) {
|
|
9074
|
+
perspectiveQuerySparql(uuid: $uuid, query: $query)
|
|
8906
9075
|
}`,
|
|
8907
9076
|
variables: { uuid, query }
|
|
8908
9077
|
}));
|
|
8909
|
-
return JSON.parse(
|
|
9078
|
+
return JSON.parse(perspectiveQuerySparql);
|
|
8910
9079
|
}
|
|
8911
9080
|
async subscribeQuery(uuid, query) {
|
|
8912
9081
|
const { perspectiveSubscribeQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
@@ -8933,49 +9102,6 @@ class PerspectiveClient {
|
|
|
8933
9102
|
}
|
|
8934
9103
|
return { subscriptionId, result: finalResult, isInit };
|
|
8935
9104
|
}
|
|
8936
|
-
async perspectiveSubscribeSurrealQuery(uuid, query) {
|
|
8937
|
-
const { perspectiveSubscribeSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
8938
|
-
mutation: gql `mutation perspectiveSubscribeSurrealQuery($uuid: String!, $query: String!) {
|
|
8939
|
-
perspectiveSubscribeSurrealQuery(uuid: $uuid, query: $query) {
|
|
8940
|
-
subscriptionId
|
|
8941
|
-
result
|
|
8942
|
-
}
|
|
8943
|
-
}`,
|
|
8944
|
-
variables: { uuid, query }
|
|
8945
|
-
}));
|
|
8946
|
-
const { subscriptionId, result } = perspectiveSubscribeSurrealQuery;
|
|
8947
|
-
let finalResult = result;
|
|
8948
|
-
let isInit = false;
|
|
8949
|
-
if (finalResult.startsWith("#init#")) {
|
|
8950
|
-
finalResult = finalResult.substring(6);
|
|
8951
|
-
isInit = true;
|
|
8952
|
-
}
|
|
8953
|
-
try {
|
|
8954
|
-
finalResult = JSON.parse(finalResult);
|
|
8955
|
-
}
|
|
8956
|
-
catch (e) {
|
|
8957
|
-
console.error('Error parsing perspectiveSubscribeSurrealQuery result:', e);
|
|
8958
|
-
}
|
|
8959
|
-
return { subscriptionId, result: finalResult, isInit };
|
|
8960
|
-
}
|
|
8961
|
-
async perspectiveKeepAliveSurrealQuery(uuid, subscriptionId) {
|
|
8962
|
-
const { perspectiveKeepAliveSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
8963
|
-
mutation: gql `mutation perspectiveKeepAliveSurrealQuery($uuid: String!, $subscriptionId: String!) {
|
|
8964
|
-
perspectiveKeepAliveSurrealQuery(uuid: $uuid, subscriptionId: $subscriptionId)
|
|
8965
|
-
}`,
|
|
8966
|
-
variables: { uuid, subscriptionId }
|
|
8967
|
-
}));
|
|
8968
|
-
return perspectiveKeepAliveSurrealQuery;
|
|
8969
|
-
}
|
|
8970
|
-
async perspectiveDisposeSurrealQuerySubscription(uuid, subscriptionId) {
|
|
8971
|
-
const { perspectiveDisposeSurrealQuerySubscription } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
|
|
8972
|
-
mutation: gql `mutation perspectiveDisposeSurrealQuerySubscription($uuid: String!, $subscriptionId: String!) {
|
|
8973
|
-
perspectiveDisposeSurrealQuerySubscription(uuid: $uuid, subscriptionId: $subscriptionId)
|
|
8974
|
-
}`,
|
|
8975
|
-
variables: { uuid, subscriptionId }
|
|
8976
|
-
}));
|
|
8977
|
-
return perspectiveDisposeSurrealQuerySubscription;
|
|
8978
|
-
}
|
|
8979
9105
|
subscribeToQueryUpdates(subscriptionId, onData) {
|
|
8980
9106
|
const subscription = __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").subscribe({
|
|
8981
9107
|
query: gql `
|
|
@@ -9372,7 +9498,7 @@ var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) |
|
|
|
9372
9498
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
9373
9499
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
9374
9500
|
};
|
|
9375
|
-
var _AgentClient_apolloClient, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks;
|
|
9501
|
+
var _AgentClient_apolloClient, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks;
|
|
9376
9502
|
const AGENT_SUBITEMS = `
|
|
9377
9503
|
did
|
|
9378
9504
|
directMessageLanguage
|
|
@@ -9435,10 +9561,14 @@ class AgentClient {
|
|
|
9435
9561
|
_AgentClient_appsChangedCallback.set(this, void 0);
|
|
9436
9562
|
_AgentClient_updatedCallbacks.set(this, void 0);
|
|
9437
9563
|
_AgentClient_agentStatusChangedCallbacks.set(this, void 0);
|
|
9564
|
+
_AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);
|
|
9565
|
+
_AgentClient_computeLogUpdatedCallbacks.set(this, void 0);
|
|
9438
9566
|
__classPrivateFieldSet$7(this, _AgentClient_apolloClient, client, "f");
|
|
9439
9567
|
__classPrivateFieldSet$7(this, _AgentClient_updatedCallbacks, [], "f");
|
|
9440
9568
|
__classPrivateFieldSet$7(this, _AgentClient_agentStatusChangedCallbacks, [], "f");
|
|
9441
9569
|
__classPrivateFieldSet$7(this, _AgentClient_appsChangedCallback, [], "f");
|
|
9570
|
+
__classPrivateFieldSet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, [], "f");
|
|
9571
|
+
__classPrivateFieldSet$7(this, _AgentClient_computeLogUpdatedCallbacks, [], "f");
|
|
9442
9572
|
if (subscribe) {
|
|
9443
9573
|
this.subscribeAgentUpdated();
|
|
9444
9574
|
this.subscribeAgentStatusChanged();
|
|
@@ -9699,6 +9829,55 @@ class AgentClient {
|
|
|
9699
9829
|
error: (e) => console.error(e),
|
|
9700
9830
|
});
|
|
9701
9831
|
}
|
|
9832
|
+
addHostingUserInfoChangedListener(listener) {
|
|
9833
|
+
__classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, "f").push(listener);
|
|
9834
|
+
}
|
|
9835
|
+
subscribeHostingUserInfoChanged() {
|
|
9836
|
+
__classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f")
|
|
9837
|
+
.subscribe({
|
|
9838
|
+
query: gql `subscription {
|
|
9839
|
+
runtimeHostingUserInfoChanged {
|
|
9840
|
+
email
|
|
9841
|
+
remainingCredits
|
|
9842
|
+
hotWalletAddress
|
|
9843
|
+
freeAccess
|
|
9844
|
+
}
|
|
9845
|
+
}`,
|
|
9846
|
+
})
|
|
9847
|
+
.subscribe({
|
|
9848
|
+
next: (result) => {
|
|
9849
|
+
const info = result.data.runtimeHostingUserInfoChanged;
|
|
9850
|
+
__classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, "f").forEach((cb) => cb(info));
|
|
9851
|
+
},
|
|
9852
|
+
error: (e) => console.error(e),
|
|
9853
|
+
});
|
|
9854
|
+
}
|
|
9855
|
+
addComputeLogUpdatedListener(listener) {
|
|
9856
|
+
__classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, "f").push(listener);
|
|
9857
|
+
}
|
|
9858
|
+
subscribeComputeLogUpdated() {
|
|
9859
|
+
__classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f")
|
|
9860
|
+
.subscribe({
|
|
9861
|
+
query: gql `subscription {
|
|
9862
|
+
runtimeComputeLogUpdated {
|
|
9863
|
+
id
|
|
9864
|
+
userEmail
|
|
9865
|
+
timestamp
|
|
9866
|
+
operation
|
|
9867
|
+
summary
|
|
9868
|
+
cost
|
|
9869
|
+
creditsAfter
|
|
9870
|
+
}
|
|
9871
|
+
}`,
|
|
9872
|
+
})
|
|
9873
|
+
.subscribe({
|
|
9874
|
+
next: (result) => {
|
|
9875
|
+
const entry = result.data.runtimeComputeLogUpdated;
|
|
9876
|
+
__classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, "f").forEach((cb) => cb(entry));
|
|
9877
|
+
},
|
|
9878
|
+
error: (e) => console.error(e),
|
|
9879
|
+
});
|
|
9880
|
+
}
|
|
9702
9881
|
async requestCapability(authInfo) {
|
|
9703
9882
|
const { agentRequestCapability } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
|
|
9704
9883
|
mutation: gql `
|
|
@@ -9845,6 +10024,24 @@ class AgentClient {
|
|
|
9845
10024
|
}));
|
|
9846
10025
|
return runtimeHostingUserInfo;
|
|
9847
10026
|
}
|
|
10027
|
+
async computeLog(since, limit, userEmail) {
|
|
10028
|
+
const { runtimeComputeLog } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").query({
|
|
10029
|
+
query: gql `query runtimeComputeLog($since: String, $limit: Int, $userEmail: String) {
|
|
10030
|
+
runtimeComputeLog(since: $since, limit: $limit, userEmail: $userEmail) {
|
|
10031
|
+
id
|
|
10032
|
+
userEmail
|
|
10033
|
+
timestamp
|
|
10034
|
+
operation
|
|
10035
|
+
summary
|
|
10036
|
+
cost
|
|
10037
|
+
creditsAfter
|
|
10038
|
+
}
|
|
10039
|
+
}`,
|
|
10040
|
+
variables: { since, limit, userEmail },
|
|
10041
|
+
fetchPolicy: 'network-only',
|
|
10042
|
+
}));
|
|
10043
|
+
return runtimeComputeLog;
|
|
10044
|
+
}
|
|
9848
10045
|
async setHotWalletAddress(address) {
|
|
9849
10046
|
const { runtimeSetHotWalletAddress } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
|
|
9850
10047
|
mutation: gql `mutation runtimeSetHotWalletAddress($address: String!) {
|
|
@@ -9867,7 +10064,7 @@ class AgentClient {
|
|
|
9867
10064
|
return runtimeRequestPayment;
|
|
9868
10065
|
}
|
|
9869
10066
|
}
|
|
9870
|
-
_AgentClient_apolloClient = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap();
|
|
10067
|
+
_AgentClient_apolloClient = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap();
|
|
9871
10068
|
|
|
9872
10069
|
var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
9873
10070
|
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
@@ -10658,6 +10855,23 @@ class RuntimeClient {
|
|
|
10658
10855
|
}));
|
|
10659
10856
|
return runtimeSetMultiUserEnabled;
|
|
10660
10857
|
}
|
|
10858
|
+
async freeHostingEnabled() {
|
|
10859
|
+
const { runtimeFreeHostingEnabled } = unwrapApolloResult(await __classPrivateFieldGet$4(this, _RuntimeClient_apolloClient, "f").query({
|
|
10860
|
+
query: gql `query runtimeFreeHostingEnabled {
|
|
10861
|
+
runtimeFreeHostingEnabled
|
|
10862
|
+
}`
|
|
10863
|
+
}));
|
|
10864
|
+
return runtimeFreeHostingEnabled;
|
|
10865
|
+
}
|
|
10866
|
+
async setFreeHostingEnabled(enabled) {
|
|
10867
|
+
const { runtimeSetFreeHostingEnabled } = unwrapApolloResult(await __classPrivateFieldGet$4(this, _RuntimeClient_apolloClient, "f").mutate({
|
|
10868
|
+
mutation: gql `mutation runtimeSetFreeHostingEnabled($enabled: Boolean!) {
|
|
10869
|
+
runtimeSetFreeHostingEnabled(enabled: $enabled)
|
|
10870
|
+
}`,
|
|
10871
|
+
variables: { enabled }
|
|
10872
|
+
}));
|
|
10873
|
+
return runtimeSetFreeHostingEnabled;
|
|
10874
|
+
}
|
|
10661
10875
|
async listUsers() {
|
|
10662
10876
|
const { runtimeListUsers } = unwrapApolloResult(await __classPrivateFieldGet$4(this, _RuntimeClient_apolloClient, "f").query({
|
|
10663
10877
|
query: gql `query runtimeListUsers {
|
|
@@ -18641,11 +18855,11 @@ function exprRef2String(ref) {
|
|
|
18641
18855
|
return `${ref.language.address}://${ref.expression}`;
|
|
18642
18856
|
}
|
|
18643
18857
|
function parseExprUrl(url) {
|
|
18644
|
-
if (url.startsWith("literal
|
|
18858
|
+
if (url.startsWith("literal:")) {
|
|
18645
18859
|
const languageRef = new LanguageRef();
|
|
18646
18860
|
languageRef.address = 'literal';
|
|
18647
18861
|
languageRef.name = 'literal';
|
|
18648
|
-
const content = url.substring(
|
|
18862
|
+
const content = url.substring(8);
|
|
18649
18863
|
return new ExpressionRef(languageRef, content);
|
|
18650
18864
|
}
|
|
18651
18865
|
const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
|
|
@@ -18966,7 +19180,7 @@ PerspectiveHandle = __decorate$2([
|
|
|
18966
19180
|
], PerspectiveHandle);
|
|
18967
19181
|
|
|
18968
19182
|
/**
|
|
18969
|
-
* WakerSubscriptionManager — manages live
|
|
19183
|
+
* WakerSubscriptionManager — manages live query subscriptions for the waker.
|
|
18970
19184
|
*
|
|
18971
19185
|
* Lives in core so it can be imported by both the plugin and integration tests
|
|
18972
19186
|
* without ESM/CJS import issues.
|
|
@@ -18990,7 +19204,7 @@ class WakerSubscriptionManager {
|
|
|
18990
19204
|
this.previousSeenMessages = options.previousSeenMessages ?? {};
|
|
18991
19205
|
}
|
|
18992
19206
|
/**
|
|
18993
|
-
* Create a live
|
|
19207
|
+
* Create a live SPARQL subscription.
|
|
18994
19208
|
* If a subscription with the same id already exists, it is disposed first.
|
|
18995
19209
|
*/
|
|
18996
19210
|
async subscribe(sub) {
|
|
@@ -19001,9 +19215,9 @@ class WakerSubscriptionManager {
|
|
|
19001
19215
|
}
|
|
19002
19216
|
const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
|
|
19003
19217
|
this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
|
|
19004
|
-
this.logger.info(`[waker] ${sub.id}:
|
|
19218
|
+
this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
|
|
19005
19219
|
const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
|
|
19006
|
-
proxy.
|
|
19220
|
+
proxy.isSPARQL = true;
|
|
19007
19221
|
// Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
|
|
19008
19222
|
// rejects this promise internally when subscribe() fails, and if nobody catches
|
|
19009
19223
|
// it before the next microtask it crashes the process.
|
|
@@ -19036,7 +19250,7 @@ class WakerSubscriptionManager {
|
|
|
19036
19250
|
}
|
|
19037
19251
|
proxy.onResult(async (result) => {
|
|
19038
19252
|
this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
|
|
19039
|
-
//
|
|
19253
|
+
// Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
|
|
19040
19254
|
if (!Array.isArray(result)) {
|
|
19041
19255
|
this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
|
|
19042
19256
|
return;
|
|
@@ -19061,10 +19275,9 @@ class WakerSubscriptionManager {
|
|
|
19061
19275
|
for (const msgAddr of newMessages) {
|
|
19062
19276
|
const parents = [];
|
|
19063
19277
|
try {
|
|
19064
|
-
const
|
|
19065
|
-
const parentQuery = `SELECT * FROM link WHERE predicate = 'ad4m://has_child' AND target = '${escaped}'`;
|
|
19278
|
+
const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
|
|
19066
19279
|
this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
|
|
19067
|
-
const parentResult = await this.perspectiveClient.
|
|
19280
|
+
const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
|
|
19068
19281
|
if (Array.isArray(parentResult)) {
|
|
19069
19282
|
for (const link of parentResult) {
|
|
19070
19283
|
if (link && link.source) {
|
|
@@ -19263,7 +19476,7 @@ class SmartLiteral {
|
|
|
19263
19476
|
_SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
|
|
19264
19477
|
|
|
19265
19478
|
/**
|
|
19266
|
-
* Shared query helpers used by both the Prolog and
|
|
19479
|
+
* Shared query helpers used by both the Prolog and SPARQL query pipelines.
|
|
19267
19480
|
*/
|
|
19268
19481
|
/**
|
|
19269
19482
|
* Resolves the predicate for a parent query.
|
|
@@ -19701,14 +19914,14 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
|
|
|
19701
19914
|
}
|
|
19702
19915
|
// Default resolveLanguage to 'literal' for all remaining property types,
|
|
19703
19916
|
// matching the @Property decorator behaviour. Without this, string values
|
|
19704
|
-
// stored as literal
|
|
19917
|
+
// stored as literal: URLs are returned unparsed.
|
|
19705
19918
|
if (resolveLanguage === undefined || resolveLanguage === null) {
|
|
19706
19919
|
resolveLanguage = 'literal';
|
|
19707
19920
|
}
|
|
19708
19921
|
// If property is required, ensure it has an initial value
|
|
19709
19922
|
if (isRequired && !initial) {
|
|
19710
19923
|
if (isObjectType(propertySchema)) {
|
|
19711
|
-
initial = 'literal
|
|
19924
|
+
initial = 'literal:json:{}';
|
|
19712
19925
|
}
|
|
19713
19926
|
else {
|
|
19714
19927
|
initial = "ad4m://undefined";
|
|
@@ -19764,250 +19977,433 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
|
|
|
19764
19977
|
}
|
|
19765
19978
|
|
|
19766
19979
|
/**
|
|
19767
|
-
*
|
|
19980
|
+
* SPARQL query building utilities for Ad4mModel.
|
|
19768
19981
|
*
|
|
19769
|
-
*
|
|
19770
|
-
*
|
|
19771
|
-
* the main `buildSurrealQLQuery()` function that produces a
|
|
19772
|
-
* complete SurrealQL query string from a `Query` object.
|
|
19982
|
+
* Uses the direct triple + named graph storage model where each AD4M link
|
|
19983
|
+
* is stored in a named graph (keyed by link hash) with metadata in the default graph.
|
|
19773
19984
|
*
|
|
19774
|
-
* All
|
|
19775
|
-
* are passed in as parameters instead of accessed via `this`.
|
|
19985
|
+
* All AD4M URIs (source, predicate, target) become RDF IRIs.
|
|
19776
19986
|
*
|
|
19777
19987
|
* @module
|
|
19778
19988
|
*/
|
|
19779
|
-
// ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
|
|
19780
19989
|
/**
|
|
19781
|
-
*
|
|
19782
|
-
*
|
|
19783
|
-
*
|
|
19784
|
-
*
|
|
19990
|
+
* Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).
|
|
19991
|
+
* Properties with resolveLanguage === "literal" AND properties without resolveLanguage
|
|
19992
|
+
* both store values as literal: URIs. Only properties with a non-literal resolveLanguage
|
|
19993
|
+
* (e.g. file storage) or flag properties store raw URIs.
|
|
19994
|
+
*/
|
|
19995
|
+
function isLiteralStoredProperty(propMeta) {
|
|
19996
|
+
if (propMeta.flag)
|
|
19997
|
+
return false;
|
|
19998
|
+
// If resolveLanguage is set to something other than "literal", it's a language expression URI
|
|
19999
|
+
if (propMeta.resolveLanguage && propMeta.resolveLanguage !== "literal")
|
|
20000
|
+
return false;
|
|
20001
|
+
// Everything else (resolveLanguage === "literal" or undefined) stores as literal: URIs
|
|
20002
|
+
return true;
|
|
20003
|
+
}
|
|
20004
|
+
/**
|
|
20005
|
+
* Escape a string for use as a SPARQL string literal.
|
|
20006
|
+
*/
|
|
20007
|
+
function escapeSPARQL(value) {
|
|
20008
|
+
return value
|
|
20009
|
+
.replace(/\\/g, "\\\\")
|
|
20010
|
+
.replace(/"/g, '\\"')
|
|
20011
|
+
.replace(/\n/g, "\\n")
|
|
20012
|
+
.replace(/\r/g, "\\r")
|
|
20013
|
+
.replace(/\t/g, "\\t");
|
|
20014
|
+
}
|
|
20015
|
+
/**
|
|
20016
|
+
* Format a value as a SPARQL string literal (double-quoted).
|
|
20017
|
+
*/
|
|
20018
|
+
function formatSPARQLValue(value) {
|
|
20019
|
+
if (typeof value === "string") {
|
|
20020
|
+
return `"${escapeSPARQL(value)}"`;
|
|
20021
|
+
}
|
|
20022
|
+
return `"${String(value)}"`;
|
|
20023
|
+
}
|
|
20024
|
+
/**
|
|
20025
|
+
* Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
|
|
20026
|
+
* All AD4M link source/predicate/target values become IRIs in angle brackets.
|
|
20027
|
+
* The Rust SPARQL service transparently transforms these to valid IRI format.
|
|
20028
|
+
*/
|
|
20029
|
+
function iri(value) {
|
|
20030
|
+
return `<${value}>`;
|
|
20031
|
+
}
|
|
20032
|
+
/**
|
|
20033
|
+
* Build a SPARQL query that returns all links belonging to instances of
|
|
20034
|
+
* the given model class, optionally filtered by `where` conditions.
|
|
19785
20035
|
*
|
|
19786
|
-
*
|
|
19787
|
-
*
|
|
19788
|
-
|
|
19789
|
-
|
|
19790
|
-
|
|
20036
|
+
* Uses direct triple patterns: ?source ?predicate ?target
|
|
20037
|
+
* with named graph storage and metadata keyed by graph IRI.
|
|
20038
|
+
*/
|
|
20039
|
+
function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
|
|
20040
|
+
const joinPatterns = [];
|
|
20041
|
+
const filterExpressions = [];
|
|
20042
|
+
// Parent filter — direct triple pattern
|
|
20043
|
+
if (query.parent) {
|
|
20044
|
+
const parentPredicate = resolveParentPredicate(query.parent, modelClass);
|
|
20045
|
+
joinPatterns.push(`
|
|
20046
|
+
${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
|
|
20047
|
+
}
|
|
20048
|
+
// Required property JOIN patterns — direct triple patterns
|
|
20049
|
+
let hasConformance = false;
|
|
20050
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
20051
|
+
if (propMeta.required) {
|
|
20052
|
+
if (propMeta.getter)
|
|
20053
|
+
continue;
|
|
20054
|
+
hasConformance = true;
|
|
20055
|
+
if (propMeta.flag && propMeta.initial) {
|
|
20056
|
+
joinPatterns.push(`
|
|
20057
|
+
?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
|
|
20058
|
+
}
|
|
20059
|
+
else {
|
|
20060
|
+
joinPatterns.push(`
|
|
20061
|
+
?source ${iri(propMeta.predicate)} ?cfTarget_${propMeta.name} .`);
|
|
20062
|
+
}
|
|
20063
|
+
}
|
|
20064
|
+
}
|
|
20065
|
+
// Fallback: initial-value JOIN patterns
|
|
20066
|
+
if (!hasConformance) {
|
|
20067
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
20068
|
+
if (propMeta.initial) {
|
|
20069
|
+
hasConformance = true;
|
|
20070
|
+
if (propMeta.flag) {
|
|
20071
|
+
joinPatterns.push(`
|
|
20072
|
+
?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
|
|
20073
|
+
}
|
|
20074
|
+
else {
|
|
20075
|
+
joinPatterns.push(`
|
|
20076
|
+
?source ${iri(propMeta.predicate)} ?cfInitTarget_${propMeta.name} .`);
|
|
20077
|
+
}
|
|
20078
|
+
break;
|
|
20079
|
+
}
|
|
20080
|
+
}
|
|
20081
|
+
}
|
|
20082
|
+
// Fallback: open-world structural matching
|
|
20083
|
+
// Use a subquery with DISTINCT to avoid row multiplication when the main
|
|
20084
|
+
// ?source ?predicate ?target pattern cross-joins with multiple structural matches.
|
|
20085
|
+
if (!hasConformance && joinPatterns.length === 0) {
|
|
20086
|
+
const knownPredicates = [];
|
|
20087
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
20088
|
+
if (propMeta.predicate) {
|
|
20089
|
+
knownPredicates.push(iri(propMeta.predicate));
|
|
20090
|
+
}
|
|
20091
|
+
}
|
|
20092
|
+
if (metadata.relations) {
|
|
20093
|
+
for (const [, relMeta] of Object.entries(metadata.relations)) {
|
|
20094
|
+
if (relMeta.predicate) {
|
|
20095
|
+
knownPredicates.push(iri(relMeta.predicate));
|
|
20096
|
+
}
|
|
20097
|
+
}
|
|
20098
|
+
}
|
|
20099
|
+
if (knownPredicates.length > 0) {
|
|
20100
|
+
joinPatterns.push(`
|
|
20101
|
+
{ SELECT DISTINCT ?source WHERE { ?source ?cf_structPred ?cf_structTarget . FILTER(?cf_structPred IN (${knownPredicates.join(", ")})) } }`);
|
|
20102
|
+
}
|
|
20103
|
+
}
|
|
20104
|
+
// Build WHERE clause filters from user query
|
|
20105
|
+
const { joins: userJoins, filters: userFilters } = buildSPARQLWhereFilters(metadata, allRelationsMetadata, query.where);
|
|
20106
|
+
joinPatterns.push(...userJoins);
|
|
20107
|
+
filterExpressions.push(...userFilters);
|
|
20108
|
+
// Main triple pattern — fetches all links for matched sources
|
|
20109
|
+
// The direct triple in named graph: GRAPH ?linkGraph { ?source ?predicate ?target }
|
|
20110
|
+
// FILTER(isIRI(?source)) excludes non-IRI subjects
|
|
20111
|
+
const joinClause = joinPatterns.join("\n");
|
|
20112
|
+
const filterClause = filterExpressions.length > 0
|
|
20113
|
+
? `FILTER(\n ${filterExpressions.join(" &&\n ")}\n )`
|
|
20114
|
+
: "";
|
|
20115
|
+
return `
|
|
20116
|
+
SELECT ?source ?predicate ?target ?author ?timestamp WHERE {${joinClause}
|
|
20117
|
+
GRAPH ?linkGraph { ?source ?predicate ?target . }
|
|
20118
|
+
FILTER(isIRI(?source) && isIRI(?predicate))
|
|
20119
|
+
?linkGraph <ad4m://ontology/author> ?author .
|
|
20120
|
+
?linkGraph <ad4m://ontology/timestamp> ?timestamp .
|
|
20121
|
+
${filterClause}
|
|
20122
|
+
}
|
|
20123
|
+
${buildSPARQLOrderLimitOffset()}
|
|
20124
|
+
`.trim();
|
|
20125
|
+
}
|
|
20126
|
+
/**
|
|
20127
|
+
* Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
|
|
20128
|
+
*/
|
|
20129
|
+
function buildSPARQLOrderLimitOffset(_metadata, _query) {
|
|
20130
|
+
return "";
|
|
20131
|
+
}
|
|
20132
|
+
/**
|
|
20133
|
+
* Build a SPARQL query to fetch all links for a single instance.
|
|
20134
|
+
*/
|
|
20135
|
+
function buildSPARQLGetDataQuery(baseExpression) {
|
|
20136
|
+
return `
|
|
20137
|
+
SELECT ?source ?predicate ?target ?author ?timestamp WHERE {
|
|
20138
|
+
GRAPH ?linkGraph { ${iri(baseExpression)} ?predicate ?target . }
|
|
20139
|
+
FILTER(isIRI(?predicate))
|
|
20140
|
+
BIND(${iri(baseExpression)} AS ?source)
|
|
20141
|
+
?linkGraph <ad4m://ontology/author> ?author .
|
|
20142
|
+
?linkGraph <ad4m://ontology/timestamp> ?timestamp .
|
|
20143
|
+
}
|
|
20144
|
+
`.trim();
|
|
20145
|
+
}
|
|
20146
|
+
/**
|
|
20147
|
+
* Group flat SPARQL link rows into the same shape that SPARQL returned:
|
|
20148
|
+
* `{ source_uri: string, links: Array<{predicate, target, author, timestamp}> }`
|
|
20149
|
+
*/
|
|
20150
|
+
function groupSPARQLResults(rows) {
|
|
20151
|
+
const grouped = new Map();
|
|
20152
|
+
for (const row of rows) {
|
|
20153
|
+
const key = row.source;
|
|
20154
|
+
if (!grouped.has(key)) {
|
|
20155
|
+
grouped.set(key, []);
|
|
20156
|
+
}
|
|
20157
|
+
grouped.get(key).push({
|
|
20158
|
+
predicate: row.predicate,
|
|
20159
|
+
target: row.target,
|
|
20160
|
+
author: row.author,
|
|
20161
|
+
timestamp: row.timestamp,
|
|
20162
|
+
});
|
|
20163
|
+
}
|
|
20164
|
+
return Array.from(grouped.entries()).map(([source_uri, links]) => ({
|
|
20165
|
+
source_uri,
|
|
20166
|
+
links,
|
|
20167
|
+
}));
|
|
20168
|
+
}
|
|
20169
|
+
/**
|
|
20170
|
+
* Build SPARQL FILTER expressions from user `where` conditions.
|
|
20171
|
+
* Uses direct triple patterns instead of link-node reification.
|
|
19791
20172
|
*/
|
|
19792
|
-
function
|
|
20173
|
+
function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
|
|
19793
20174
|
if (!where)
|
|
19794
|
-
return
|
|
19795
|
-
const
|
|
20175
|
+
return { joins: [], filters: [] };
|
|
20176
|
+
const joins = [];
|
|
20177
|
+
const filters = [];
|
|
19796
20178
|
for (const [propertyName, condition] of Object.entries(where)) {
|
|
19797
|
-
|
|
19798
|
-
if (
|
|
19799
|
-
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
19800
|
-
continue; // Filtered post-query in JS
|
|
19801
|
-
}
|
|
19802
|
-
const columnName = 'uri';
|
|
20179
|
+
// 'base' maps to ?source
|
|
20180
|
+
if (propertyName === "base" || propertyName === "id") {
|
|
19803
20181
|
if (Array.isArray(condition)) {
|
|
19804
|
-
const
|
|
19805
|
-
|
|
20182
|
+
const formatted = condition.map(v => iri(v)).join(", ");
|
|
20183
|
+
filters.push(`?source IN (${formatted})`);
|
|
19806
20184
|
}
|
|
19807
|
-
else if (typeof condition ===
|
|
20185
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
19808
20186
|
const ops = condition;
|
|
19809
20187
|
if (ops.not !== undefined) {
|
|
19810
20188
|
if (Array.isArray(ops.not)) {
|
|
19811
|
-
const
|
|
19812
|
-
|
|
20189
|
+
const formatted = ops.not.map(v => iri(v)).join(", ");
|
|
20190
|
+
filters.push(`!(?source IN (${formatted}))`);
|
|
19813
20191
|
}
|
|
19814
20192
|
else {
|
|
19815
|
-
|
|
20193
|
+
filters.push(`?source != ${iri(ops.not)}`);
|
|
19816
20194
|
}
|
|
19817
20195
|
}
|
|
19818
|
-
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
19819
|
-
conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
|
|
19820
|
-
}
|
|
19821
|
-
if (ops.gt !== undefined) {
|
|
19822
|
-
conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
|
|
19823
|
-
}
|
|
19824
|
-
if (ops.gte !== undefined) {
|
|
19825
|
-
conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
|
|
19826
|
-
}
|
|
19827
|
-
if (ops.lt !== undefined) {
|
|
19828
|
-
conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
|
|
19829
|
-
}
|
|
19830
|
-
if (ops.lte !== undefined) {
|
|
19831
|
-
conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
|
|
19832
|
-
}
|
|
19833
|
-
if (ops.contains !== undefined) {
|
|
19834
|
-
conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
|
|
19835
|
-
}
|
|
19836
20196
|
}
|
|
19837
20197
|
else {
|
|
19838
|
-
|
|
20198
|
+
filters.push(`?source = ${iri(String(condition))}`);
|
|
19839
20199
|
}
|
|
20200
|
+
continue;
|
|
19840
20201
|
}
|
|
19841
|
-
|
|
19842
|
-
|
|
19843
|
-
|
|
19844
|
-
|
|
19845
|
-
|
|
19846
|
-
|
|
19847
|
-
|
|
19848
|
-
|
|
19849
|
-
|
|
19850
|
-
|
|
19851
|
-
|
|
19852
|
-
|
|
19853
|
-
|
|
19854
|
-
|
|
19855
|
-
|
|
19856
|
-
|
|
19857
|
-
|
|
19858
|
-
|
|
19859
|
-
|
|
19860
|
-
|
|
19861
|
-
|
|
19862
|
-
|
|
19863
|
-
|
|
19864
|
-
else {
|
|
19865
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
|
|
19866
|
-
}
|
|
19867
|
-
}
|
|
19868
|
-
else {
|
|
19869
|
-
if (isBelongs) {
|
|
19870
|
-
conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
19871
|
-
}
|
|
19872
|
-
else {
|
|
19873
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
19874
|
-
}
|
|
19875
|
-
}
|
|
19876
|
-
}
|
|
19877
|
-
}
|
|
19878
|
-
else {
|
|
19879
|
-
if (isBelongs) {
|
|
19880
|
-
conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
|
|
19881
|
-
}
|
|
19882
|
-
else {
|
|
19883
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
|
|
19884
|
-
}
|
|
19885
|
-
}
|
|
19886
|
-
continue;
|
|
19887
|
-
}
|
|
19888
|
-
const propMeta = metadata.properties[propertyName];
|
|
19889
|
-
if (!propMeta)
|
|
19890
|
-
continue;
|
|
19891
|
-
const predicate = escapeSurrealString(propMeta.predicate);
|
|
19892
|
-
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
|
|
19893
|
-
if (Array.isArray(condition)) {
|
|
19894
|
-
const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
|
|
19895
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
|
|
19896
|
-
}
|
|
19897
|
-
else if (typeof condition === 'object' && condition !== null) {
|
|
20202
|
+
if (propertyName === "author" || propertyName === "timestamp") {
|
|
20203
|
+
continue;
|
|
20204
|
+
}
|
|
20205
|
+
const propMeta = metadata.properties[propertyName];
|
|
20206
|
+
if (!propMeta)
|
|
20207
|
+
continue;
|
|
20208
|
+
// Skip reverse relations (belongsToOne / belongsToMany) — these are registered as
|
|
20209
|
+
// read-only properties but the link direction is reversed (target→source, not source→target).
|
|
20210
|
+
// Adding a forward join pattern would match nothing. These are filtered in JS post-filter.
|
|
20211
|
+
const relMeta = _allRelationsMetadata[propertyName];
|
|
20212
|
+
if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {
|
|
20213
|
+
continue;
|
|
20214
|
+
}
|
|
20215
|
+
// Determine if this property stores values as literal: IRIs
|
|
20216
|
+
const useParseLiteral = isLiteralStoredProperty(propMeta);
|
|
20217
|
+
// For literal-stored properties, skip SPARQL-level FILTER expressions entirely.
|
|
20218
|
+
// The parse_literal custom function is unreliable across oxigraph versions and
|
|
20219
|
+
// environments. All property-level where filtering is done in JS post-filter
|
|
20220
|
+
// (instancesFromQueryResult) after hydration resolves values to JS primitives.
|
|
20221
|
+
// We only add a JOIN pattern to ensure the property exists (conformance check).
|
|
20222
|
+
if (useParseLiteral) {
|
|
20223
|
+
// Just ensure the property exists — no value filtering in SPARQL
|
|
20224
|
+
if (typeof condition === "object" && condition !== null && !Array.isArray(condition)) {
|
|
19898
20225
|
const ops = condition;
|
|
19899
|
-
|
|
19900
|
-
if (Array.isArray(ops.not)) {
|
|
19901
|
-
const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
|
|
19902
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
19903
|
-
}
|
|
19904
|
-
else {
|
|
19905
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
19906
|
-
}
|
|
19907
|
-
}
|
|
19908
|
-
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
20226
|
+
const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
19909
20227
|
ops.lt !== undefined || ops.lte !== undefined ||
|
|
19910
|
-
ops.between !== undefined || ops.contains !== undefined
|
|
19911
|
-
|
|
19912
|
-
|
|
20228
|
+
ops.between !== undefined || ops.contains !== undefined ||
|
|
20229
|
+
ops.not !== undefined;
|
|
20230
|
+
if (hasCompOps) {
|
|
20231
|
+
joins.push(`
|
|
20232
|
+
?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
|
|
19913
20233
|
}
|
|
20234
|
+
// NOT filters: no SPARQL-level filtering — handled in JS
|
|
19914
20235
|
}
|
|
19915
20236
|
else {
|
|
19916
|
-
|
|
20237
|
+
// Simple equality or IN — add join for conformance.
|
|
20238
|
+
// NOTE: push-down FILTER with fn::parse_literal was attempted but removed because
|
|
20239
|
+
// Oxigraph's query parser rejects the fn:: custom function syntax at parse time
|
|
20240
|
+
// (custom functions are only available at execution time). All literal property
|
|
20241
|
+
// filtering is done in JS post-filter after hydration resolves values.
|
|
20242
|
+
joins.push(`
|
|
20243
|
+
?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
|
|
20244
|
+
}
|
|
20245
|
+
}
|
|
20246
|
+
else if (Array.isArray(condition)) {
|
|
20247
|
+
const formatted = condition.map(v => iri(v)).join(", ");
|
|
20248
|
+
joins.push(`
|
|
20249
|
+
?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
|
|
20250
|
+
filters.push(`?wTarget_${propertyName} IN (${formatted})`);
|
|
20251
|
+
}
|
|
20252
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
20253
|
+
const ops = condition;
|
|
20254
|
+
if (ops.not !== undefined) {
|
|
20255
|
+
if (Array.isArray(ops.not)) {
|
|
20256
|
+
const formatted = ops.not.map(v => iri(v)).join(", ");
|
|
20257
|
+
filters.push(`
|
|
20258
|
+
NOT EXISTS {
|
|
20259
|
+
?source ${iri(propMeta.predicate)} ?wTarget_not_${propertyName} .
|
|
20260
|
+
FILTER(?wTarget_not_${propertyName} IN (${formatted}))
|
|
20261
|
+
}
|
|
20262
|
+
`);
|
|
20263
|
+
}
|
|
20264
|
+
else {
|
|
20265
|
+
filters.push(`
|
|
20266
|
+
NOT EXISTS {
|
|
20267
|
+
?source ${iri(propMeta.predicate)} ${iri(ops.not)} .
|
|
20268
|
+
}
|
|
20269
|
+
`);
|
|
20270
|
+
}
|
|
19917
20271
|
}
|
|
20272
|
+
const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
20273
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
20274
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
20275
|
+
if (hasCompOps) {
|
|
20276
|
+
joins.push(`
|
|
20277
|
+
?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
|
|
20278
|
+
}
|
|
20279
|
+
}
|
|
20280
|
+
else {
|
|
20281
|
+
// Simple equality — non-literal property, use exact IRI match
|
|
20282
|
+
joins.push(`
|
|
20283
|
+
?source ${iri(propMeta.predicate)} ${iri(String(condition))} .`);
|
|
19918
20284
|
}
|
|
19919
20285
|
}
|
|
19920
|
-
return
|
|
20286
|
+
return { joins, filters };
|
|
19921
20287
|
}
|
|
19922
|
-
|
|
20288
|
+
|
|
19923
20289
|
/**
|
|
19924
|
-
*
|
|
20290
|
+
* Subscription Pool — deduplicates identical SPARQL subscriptions.
|
|
19925
20291
|
*
|
|
19926
|
-
*
|
|
19927
|
-
*
|
|
19928
|
-
*
|
|
19929
|
-
*
|
|
19930
|
-
* 3. Fetches all outgoing links for hydration
|
|
20292
|
+
* When multiple UI components subscribe to the same SPARQL query on the same
|
|
20293
|
+
* perspective, the pool shares a single `subscribeQuery()` call and distributes
|
|
20294
|
+
* results to all registered callbacks. Hydration happens once per result set,
|
|
20295
|
+
* then is shared across all subscribers.
|
|
19931
20296
|
*
|
|
19932
|
-
*
|
|
19933
|
-
* @param allRelationsMetadata - Full relation registry (for belongs-to detection)
|
|
19934
|
-
* @param query - Query parameters
|
|
19935
|
-
* @param modelClass - The model class (for `resolveParentPredicate`)
|
|
19936
|
-
* @returns Complete SurrealQL query string
|
|
20297
|
+
* Key: `perspectiveUUID + sparqlQuery`
|
|
19937
20298
|
*/
|
|
19938
|
-
|
|
19939
|
-
|
|
19940
|
-
|
|
19941
|
-
|
|
19942
|
-
|
|
19943
|
-
|
|
19944
|
-
|
|
19945
|
-
|
|
19946
|
-
|
|
19947
|
-
|
|
19948
|
-
|
|
19949
|
-
|
|
19950
|
-
|
|
19951
|
-
|
|
19952
|
-
|
|
19953
|
-
|
|
19954
|
-
|
|
19955
|
-
|
|
19956
|
-
|
|
19957
|
-
|
|
20299
|
+
const pool = new Map();
|
|
20300
|
+
function makeKey(perspectiveUUID, sparqlQuery) {
|
|
20301
|
+
return `${perspectiveUUID}::${sparqlQuery}`;
|
|
20302
|
+
}
|
|
20303
|
+
/**
|
|
20304
|
+
* Subscribe to a SPARQL query, sharing the underlying subscription
|
|
20305
|
+
* with any other subscribers using the same perspective + query.
|
|
20306
|
+
*
|
|
20307
|
+
* @param perspective - The perspective proxy
|
|
20308
|
+
* @param sparqlQuery - The SPARQL query text
|
|
20309
|
+
* @param hydrate - Async function that takes raw SPARQL results and returns hydrated results
|
|
20310
|
+
* @param onResult - Callback for subsequent result updates (hydrated)
|
|
20311
|
+
* @returns PooledSubscription with initial result and dispose function
|
|
20312
|
+
*/
|
|
20313
|
+
async function pooledSubscribe(perspective, sparqlQuery, hydrate, onResult) {
|
|
20314
|
+
const uuid = perspective.uuid || perspective.handle?.uuid || '';
|
|
20315
|
+
const key = makeKey(uuid, sparqlQuery);
|
|
20316
|
+
const entry = pool.get(key);
|
|
20317
|
+
const subscriber = { onResult, hydrate };
|
|
20318
|
+
if (entry) {
|
|
20319
|
+
// Join existing subscription
|
|
20320
|
+
entry.callbacks.add(subscriber);
|
|
20321
|
+
entry.refCount++;
|
|
20322
|
+
// Hydrate latest result for this new subscriber
|
|
20323
|
+
let initialResult;
|
|
20324
|
+
if (entry.latestHydrated !== undefined) {
|
|
20325
|
+
initialResult = entry.latestHydrated;
|
|
20326
|
+
}
|
|
20327
|
+
else if (entry.latestRaw !== undefined) {
|
|
20328
|
+
initialResult = await hydrate(entry.latestRaw);
|
|
19958
20329
|
}
|
|
20330
|
+
return {
|
|
20331
|
+
initialResult,
|
|
20332
|
+
dispose: () => disposeSubscriber(key, subscriber),
|
|
20333
|
+
};
|
|
19959
20334
|
}
|
|
19960
|
-
//
|
|
19961
|
-
|
|
19962
|
-
|
|
19963
|
-
|
|
19964
|
-
|
|
19965
|
-
|
|
19966
|
-
|
|
19967
|
-
|
|
19968
|
-
|
|
20335
|
+
// Create new subscription
|
|
20336
|
+
const subscription = await perspective.subscribeQuery(sparqlQuery);
|
|
20337
|
+
const newEntry = {
|
|
20338
|
+
subscription,
|
|
20339
|
+
callbacks: new Set([subscriber]),
|
|
20340
|
+
latestRaw: subscription.result,
|
|
20341
|
+
latestHydrated: undefined,
|
|
20342
|
+
hydrating: false,
|
|
20343
|
+
refCount: 1,
|
|
20344
|
+
};
|
|
20345
|
+
pool.set(key, newEntry);
|
|
20346
|
+
// Set up shared result handler
|
|
20347
|
+
subscription.onResult(async (rawResult) => {
|
|
20348
|
+
newEntry.latestRaw = rawResult;
|
|
20349
|
+
newEntry.hydrating = true;
|
|
20350
|
+
try {
|
|
20351
|
+
// Hydrate ONCE using the first subscriber's hydrate function
|
|
20352
|
+
const firstSub = newEntry.callbacks.values().next().value;
|
|
20353
|
+
if (firstSub) {
|
|
20354
|
+
const hydrated = await firstSub.hydrate(rawResult);
|
|
20355
|
+
newEntry.latestHydrated = hydrated;
|
|
20356
|
+
// Distribute to all callbacks
|
|
20357
|
+
for (const cb of newEntry.callbacks) {
|
|
20358
|
+
try {
|
|
20359
|
+
cb.onResult(hydrated);
|
|
20360
|
+
}
|
|
20361
|
+
catch (e) { /* subscriber error */ }
|
|
19969
20362
|
}
|
|
19970
|
-
break;
|
|
19971
20363
|
}
|
|
19972
20364
|
}
|
|
19973
|
-
|
|
19974
|
-
|
|
19975
|
-
if (graphTraversalFilters.length === 0) {
|
|
19976
|
-
const structuralPredicates = [];
|
|
19977
|
-
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
19978
|
-
if (propMeta.predicate) {
|
|
19979
|
-
structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
|
|
19980
|
-
}
|
|
20365
|
+
finally {
|
|
20366
|
+
newEntry.hydrating = false;
|
|
19981
20367
|
}
|
|
19982
|
-
|
|
19983
|
-
|
|
19984
|
-
|
|
19985
|
-
|
|
19986
|
-
|
|
19987
|
-
|
|
19988
|
-
|
|
19989
|
-
|
|
19990
|
-
|
|
20368
|
+
});
|
|
20369
|
+
// Hydrate initial result
|
|
20370
|
+
const initialResult = await hydrate(subscription.result);
|
|
20371
|
+
newEntry.latestHydrated = initialResult;
|
|
20372
|
+
return {
|
|
20373
|
+
initialResult,
|
|
20374
|
+
dispose: () => disposeSubscriber(key, subscriber),
|
|
20375
|
+
};
|
|
20376
|
+
}
|
|
20377
|
+
function disposeSubscriber(key, subscriber) {
|
|
20378
|
+
const entry = pool.get(key);
|
|
20379
|
+
if (!entry)
|
|
20380
|
+
return;
|
|
20381
|
+
entry.callbacks.delete(subscriber);
|
|
20382
|
+
entry.refCount--;
|
|
20383
|
+
if (entry.refCount <= 0) {
|
|
20384
|
+
// Last subscriber — tear down the underlying subscription
|
|
20385
|
+
if (entry.subscription?.dispose) {
|
|
20386
|
+
entry.subscription.dispose();
|
|
19991
20387
|
}
|
|
20388
|
+
pool.delete(key);
|
|
19992
20389
|
}
|
|
19993
|
-
|
|
19994
|
-
|
|
19995
|
-
|
|
19996
|
-
|
|
19997
|
-
|
|
19998
|
-
|
|
20390
|
+
}
|
|
20391
|
+
/**
|
|
20392
|
+
* Clear the entire pool (for testing).
|
|
20393
|
+
*/
|
|
20394
|
+
function clearSubscriptionPool() {
|
|
20395
|
+
for (const entry of pool.values()) {
|
|
20396
|
+
if (entry.subscription?.dispose) {
|
|
20397
|
+
entry.subscription.dispose();
|
|
20398
|
+
}
|
|
19999
20399
|
}
|
|
20000
|
-
|
|
20001
|
-
|
|
20002
|
-
|
|
20003
|
-
|
|
20004
|
-
|
|
20005
|
-
|
|
20006
|
-
|
|
20007
|
-
WHERE ${whereConditions.join(' AND ')}
|
|
20008
|
-
FETCH links
|
|
20009
|
-
`.trim();
|
|
20010
|
-
return fullQuery;
|
|
20400
|
+
pool.clear();
|
|
20401
|
+
}
|
|
20402
|
+
/**
|
|
20403
|
+
* Get the current pool size (for testing).
|
|
20404
|
+
*/
|
|
20405
|
+
function subscriptionPoolSize() {
|
|
20406
|
+
return pool.size;
|
|
20011
20407
|
}
|
|
20012
20408
|
|
|
20013
20409
|
/**
|
|
@@ -20040,7 +20436,7 @@ class ModelQueryBuilder {
|
|
|
20040
20436
|
constructor(perspective, ctor, query) {
|
|
20041
20437
|
this.queryParams = {};
|
|
20042
20438
|
this.modelClassName = null;
|
|
20043
|
-
this.
|
|
20439
|
+
this.engineFlag = 'sparql';
|
|
20044
20440
|
this.perspective = perspective;
|
|
20045
20441
|
this.ctor = ctor;
|
|
20046
20442
|
if (query)
|
|
@@ -20248,32 +20644,10 @@ class ModelQueryBuilder {
|
|
|
20248
20644
|
return this;
|
|
20249
20645
|
}
|
|
20250
20646
|
/**
|
|
20251
|
-
*
|
|
20252
|
-
*
|
|
20253
|
-
* @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
|
|
20254
|
-
* @returns The query builder for chaining
|
|
20255
|
-
*
|
|
20256
|
-
* @example
|
|
20257
|
-
* ```typescript
|
|
20258
|
-
* // Use SurrealDB (default)
|
|
20259
|
-
* const recipes = await Recipe.query(perspective)
|
|
20260
|
-
* .where({ category: "Dessert" })
|
|
20261
|
-
* .useSurrealDB(true)
|
|
20262
|
-
* .get();
|
|
20263
|
-
*
|
|
20264
|
-
* // Use Prolog (legacy)
|
|
20265
|
-
* const recipesProlog = await Recipe.query(perspective)
|
|
20266
|
-
* .where({ category: "Dessert" })
|
|
20267
|
-
* .useSurrealDB(false)
|
|
20268
|
-
* .get();
|
|
20269
|
-
* ```
|
|
20270
|
-
*
|
|
20271
|
-
* @remarks
|
|
20272
|
-
* Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
|
|
20273
|
-
* if useSurrealDB(true) is set (default).
|
|
20647
|
+
* Sets the query engine to use.
|
|
20274
20648
|
*/
|
|
20275
|
-
|
|
20276
|
-
this.
|
|
20649
|
+
engine(eng) {
|
|
20650
|
+
this.engineFlag = eng;
|
|
20277
20651
|
return this;
|
|
20278
20652
|
}
|
|
20279
20653
|
/**
|
|
@@ -20290,10 +20664,8 @@ class ModelQueryBuilder {
|
|
|
20290
20664
|
*/
|
|
20291
20665
|
async get() {
|
|
20292
20666
|
let results;
|
|
20293
|
-
if (this.
|
|
20294
|
-
|
|
20295
|
-
const result = await this.perspective.querySurrealDB(surrealQuery);
|
|
20296
|
-
({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
|
|
20667
|
+
if (this.engineFlag === 'sparql') {
|
|
20668
|
+
results = await this.executeSparqlQuery();
|
|
20297
20669
|
}
|
|
20298
20670
|
else {
|
|
20299
20671
|
const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
@@ -20302,6 +20674,29 @@ class ModelQueryBuilder {
|
|
|
20302
20674
|
}
|
|
20303
20675
|
return results;
|
|
20304
20676
|
}
|
|
20677
|
+
/**
|
|
20678
|
+
* Executes the query once using SPARQL and returns the results.
|
|
20679
|
+
*/
|
|
20680
|
+
async getSparql() {
|
|
20681
|
+
return this.executeSparqlQuery();
|
|
20682
|
+
}
|
|
20683
|
+
/**
|
|
20684
|
+
* Shared SPARQL query execution logic used by both get() and getSparql().
|
|
20685
|
+
*/
|
|
20686
|
+
async executeSparqlQuery() {
|
|
20687
|
+
const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
|
|
20688
|
+
const rawResult = await this.perspective.querySparql(sparqlQuery);
|
|
20689
|
+
const { results } = await this.processSparqlResult(rawResult);
|
|
20690
|
+
return results;
|
|
20691
|
+
}
|
|
20692
|
+
/**
|
|
20693
|
+
* Groups raw SPARQL results and hydrates them into model instances.
|
|
20694
|
+
* Centralises the repeated groupSPARQLResults → instancesFromQueryResult pipeline.
|
|
20695
|
+
*/
|
|
20696
|
+
async processSparqlResult(rawResult, queryOverride) {
|
|
20697
|
+
const grouped = groupSPARQLResults(Array.isArray(rawResult) ? rawResult : []);
|
|
20698
|
+
return await this.ctor.instancesFromQueryResult(this.perspective, queryOverride || this.queryParams, grouped);
|
|
20699
|
+
}
|
|
20305
20700
|
/**
|
|
20306
20701
|
* Returns the first matching instance, or `null` if none match.
|
|
20307
20702
|
*
|
|
@@ -20325,7 +20720,7 @@ class ModelQueryBuilder {
|
|
|
20325
20720
|
* Subscribes to the query and receives updates when results change.
|
|
20326
20721
|
*
|
|
20327
20722
|
* This method:
|
|
20328
|
-
* 1. Creates and initializes a
|
|
20723
|
+
* 1. Creates and initializes a SPARQL live query subscription (default)
|
|
20329
20724
|
* 2. Sets up the callback to process future updates
|
|
20330
20725
|
* 3. Returns the initial results immediately
|
|
20331
20726
|
*
|
|
@@ -20349,26 +20744,40 @@ class ModelQueryBuilder {
|
|
|
20349
20744
|
* ```
|
|
20350
20745
|
*
|
|
20351
20746
|
* @remarks
|
|
20352
|
-
* By default, this uses
|
|
20353
|
-
* Prolog subscriptions remain available via `.
|
|
20747
|
+
* By default, this uses SPARQL live queries for real-time updates.
|
|
20748
|
+
* Prolog subscriptions remain available via `.useSPARQL(false)`.
|
|
20354
20749
|
*/
|
|
20355
20750
|
async subscribe(callback) {
|
|
20356
20751
|
// Clean up any existing subscription
|
|
20357
20752
|
this.dispose();
|
|
20358
20753
|
const ctor = this.ctor;
|
|
20359
|
-
if (this.
|
|
20360
|
-
const
|
|
20361
|
-
|
|
20362
|
-
|
|
20363
|
-
|
|
20364
|
-
|
|
20754
|
+
if (this.engineFlag === 'sparql') {
|
|
20755
|
+
const sparqlQuery = await ctor.queryToSPARQL(this.perspective, this.queryParams);
|
|
20756
|
+
// Track last emitted result fingerprint to suppress duplicate callbacks
|
|
20757
|
+
let lastResultFingerprint = null;
|
|
20758
|
+
const buildFingerprint = (results) => {
|
|
20759
|
+
if (results.length === 0)
|
|
20760
|
+
return '0:';
|
|
20761
|
+
const ids = results.map((r) => r.id || '').sort().join(',');
|
|
20762
|
+
const ts = results.map((r) => r.updatedAt || r.timestamp || '').join(',');
|
|
20763
|
+
return `${results.length}:${ids}:${ts}`;
|
|
20365
20764
|
};
|
|
20366
|
-
|
|
20367
|
-
|
|
20368
|
-
|
|
20369
|
-
|
|
20370
|
-
|
|
20371
|
-
|
|
20765
|
+
const hydrate = async (rawResult) => {
|
|
20766
|
+
const { results } = await this.processSparqlResult(rawResult);
|
|
20767
|
+
return results;
|
|
20768
|
+
};
|
|
20769
|
+
const pooled = await pooledSubscribe(this.perspective, sparqlQuery, hydrate, (hydratedResults) => {
|
|
20770
|
+
const fp = buildFingerprint(hydratedResults);
|
|
20771
|
+
if (fp === lastResultFingerprint)
|
|
20772
|
+
return;
|
|
20773
|
+
lastResultFingerprint = fp;
|
|
20774
|
+
callback(hydratedResults);
|
|
20775
|
+
});
|
|
20776
|
+
// Store dispose function as subscription
|
|
20777
|
+
this.currentSubscription = { dispose: pooled.dispose };
|
|
20778
|
+
const initialResults = pooled.initialResult;
|
|
20779
|
+
lastResultFingerprint = buildFingerprint(initialResults);
|
|
20780
|
+
return initialResults;
|
|
20372
20781
|
}
|
|
20373
20782
|
else {
|
|
20374
20783
|
const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
|
|
@@ -20379,11 +20788,26 @@ class ModelQueryBuilder {
|
|
|
20379
20788
|
};
|
|
20380
20789
|
this.currentSubscription.onResult(processResults);
|
|
20381
20790
|
const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
|
|
20382
|
-
//
|
|
20383
|
-
callback(results);
|
|
20791
|
+
// Initial results returned via Promise only — callback is for subsequent updates
|
|
20384
20792
|
return results;
|
|
20385
20793
|
}
|
|
20386
20794
|
}
|
|
20795
|
+
/**
|
|
20796
|
+
* Subscribes to the query and receives updates using SPARQL.
|
|
20797
|
+
*/
|
|
20798
|
+
async subscribeSparql(callback) {
|
|
20799
|
+
this.dispose();
|
|
20800
|
+
const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
|
|
20801
|
+
this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
|
|
20802
|
+
const processResults = async (result) => {
|
|
20803
|
+
const { results } = await this.processSparqlResult(result);
|
|
20804
|
+
callback(results);
|
|
20805
|
+
};
|
|
20806
|
+
this.currentSubscription.onResult(processResults);
|
|
20807
|
+
const { results } = await this.processSparqlResult(this.currentSubscription.result);
|
|
20808
|
+
// Initial results returned via Promise only — callback is for subsequent updates
|
|
20809
|
+
return results;
|
|
20810
|
+
}
|
|
20387
20811
|
/**
|
|
20388
20812
|
* Gets the total count of matching entities.
|
|
20389
20813
|
*
|
|
@@ -20397,13 +20821,10 @@ class ModelQueryBuilder {
|
|
|
20397
20821
|
* ```
|
|
20398
20822
|
*/
|
|
20399
20823
|
async count() {
|
|
20400
|
-
if (this.
|
|
20401
|
-
const
|
|
20402
|
-
const
|
|
20403
|
-
|
|
20404
|
-
// (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
|
|
20405
|
-
// This ensures count() returns the same number as get().length
|
|
20406
|
-
const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
|
|
20824
|
+
if (this.engineFlag === 'sparql') {
|
|
20825
|
+
const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
|
|
20826
|
+
const rawResult = await this.perspective.querySparql(sparqlQuery);
|
|
20827
|
+
const { totalCount } = await this.processSparqlResult(rawResult);
|
|
20407
20828
|
return totalCount;
|
|
20408
20829
|
}
|
|
20409
20830
|
else {
|
|
@@ -20412,11 +20833,25 @@ class ModelQueryBuilder {
|
|
|
20412
20833
|
return result?.[0]?.TotalCount || 0;
|
|
20413
20834
|
}
|
|
20414
20835
|
}
|
|
20836
|
+
/**
|
|
20837
|
+
* Gets the total count of matching entities using SPARQL.
|
|
20838
|
+
* Delegates to count() with SPARQL engine forced.
|
|
20839
|
+
*/
|
|
20840
|
+
async countSparql() {
|
|
20841
|
+
const prev = this.engineFlag;
|
|
20842
|
+
this.engineFlag = 'sparql';
|
|
20843
|
+
try {
|
|
20844
|
+
return await this.count();
|
|
20845
|
+
}
|
|
20846
|
+
finally {
|
|
20847
|
+
this.engineFlag = prev;
|
|
20848
|
+
}
|
|
20849
|
+
}
|
|
20415
20850
|
/**
|
|
20416
20851
|
* Subscribes to count updates for matching entities.
|
|
20417
20852
|
*
|
|
20418
20853
|
* This method:
|
|
20419
|
-
* 1. Creates and initializes a
|
|
20854
|
+
* 1. Creates and initializes a SPARQL live query subscription for the count (default)
|
|
20420
20855
|
* 2. Sets up the callback to process future count updates
|
|
20421
20856
|
* 3. Returns the initial count immediately
|
|
20422
20857
|
*
|
|
@@ -20440,22 +20875,22 @@ class ModelQueryBuilder {
|
|
|
20440
20875
|
* ```
|
|
20441
20876
|
*
|
|
20442
20877
|
* @remarks
|
|
20443
|
-
* By default, this uses
|
|
20444
|
-
* Prolog subscriptions remain available via `.
|
|
20878
|
+
* By default, this uses SPARQL live queries for real-time updates.
|
|
20879
|
+
* Prolog subscriptions remain available via `.useSPARQL(false)`.
|
|
20445
20880
|
*/
|
|
20446
20881
|
async countSubscribe(callback) {
|
|
20447
20882
|
// Clean up any existing subscription
|
|
20448
20883
|
this.dispose();
|
|
20449
|
-
if (this.
|
|
20450
|
-
const
|
|
20451
|
-
this.currentSubscription = await this.perspective.
|
|
20884
|
+
if (this.engineFlag === 'sparql') {
|
|
20885
|
+
const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
|
|
20886
|
+
this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
|
|
20452
20887
|
const processResults = async (result) => {
|
|
20453
|
-
const { totalCount } = await this.
|
|
20888
|
+
const { totalCount } = await this.processSparqlResult(result);
|
|
20454
20889
|
callback(totalCount);
|
|
20455
20890
|
};
|
|
20456
20891
|
this.currentSubscription.onResult(processResults);
|
|
20457
|
-
const { totalCount } = await this.
|
|
20458
|
-
callback
|
|
20892
|
+
const { totalCount } = await this.processSparqlResult(this.currentSubscription.result);
|
|
20893
|
+
// Initial count returned via Promise — callback for updates only
|
|
20459
20894
|
return totalCount;
|
|
20460
20895
|
}
|
|
20461
20896
|
else {
|
|
@@ -20467,10 +20902,26 @@ class ModelQueryBuilder {
|
|
|
20467
20902
|
};
|
|
20468
20903
|
this.currentSubscription.onResult(processResults);
|
|
20469
20904
|
const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
|
|
20470
|
-
callback
|
|
20905
|
+
// Initial count returned via Promise — callback for subsequent updates only
|
|
20471
20906
|
return initialCount;
|
|
20472
20907
|
}
|
|
20473
20908
|
}
|
|
20909
|
+
/**
|
|
20910
|
+
* Subscribes to count updates using SPARQL.
|
|
20911
|
+
*/
|
|
20912
|
+
async countSubscribeSparql(callback) {
|
|
20913
|
+
this.dispose();
|
|
20914
|
+
const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
|
|
20915
|
+
this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
|
|
20916
|
+
const processResults = async (result) => {
|
|
20917
|
+
const { totalCount } = await this.processSparqlResult(result);
|
|
20918
|
+
callback(totalCount);
|
|
20919
|
+
};
|
|
20920
|
+
this.currentSubscription.onResult(processResults);
|
|
20921
|
+
const { totalCount } = await this.processSparqlResult(this.currentSubscription.result);
|
|
20922
|
+
// Initial count returned via Promise — callback for updates only
|
|
20923
|
+
return totalCount;
|
|
20924
|
+
}
|
|
20474
20925
|
/**
|
|
20475
20926
|
* Gets a page of results with pagination metadata.
|
|
20476
20927
|
*
|
|
@@ -20488,10 +20939,10 @@ class ModelQueryBuilder {
|
|
|
20488
20939
|
*/
|
|
20489
20940
|
async paginate(pageSize, pageNumber) {
|
|
20490
20941
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
20491
|
-
if (this.
|
|
20492
|
-
const
|
|
20493
|
-
const result = await this.perspective.
|
|
20494
|
-
const { results, totalCount } =
|
|
20942
|
+
if (this.engineFlag === 'sparql') {
|
|
20943
|
+
const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
|
|
20944
|
+
const result = await this.perspective.querySparql(sparqlQuery);
|
|
20945
|
+
const { results, totalCount } = await this.processSparqlResult(result, paginationQuery);
|
|
20495
20946
|
return { results, totalCount, pageSize, pageNumber };
|
|
20496
20947
|
}
|
|
20497
20948
|
else {
|
|
@@ -20501,11 +20952,25 @@ class ModelQueryBuilder {
|
|
|
20501
20952
|
return { results, totalCount, pageSize, pageNumber };
|
|
20502
20953
|
}
|
|
20503
20954
|
}
|
|
20955
|
+
/**
|
|
20956
|
+
* Gets a page of results using SPARQL.
|
|
20957
|
+
* Delegates to paginate() with SPARQL engine forced.
|
|
20958
|
+
*/
|
|
20959
|
+
async paginateSparql(pageSize, pageNumber) {
|
|
20960
|
+
const prev = this.engineFlag;
|
|
20961
|
+
this.engineFlag = 'sparql';
|
|
20962
|
+
try {
|
|
20963
|
+
return await this.paginate(pageSize, pageNumber);
|
|
20964
|
+
}
|
|
20965
|
+
finally {
|
|
20966
|
+
this.engineFlag = prev;
|
|
20967
|
+
}
|
|
20968
|
+
}
|
|
20504
20969
|
/**
|
|
20505
20970
|
* Subscribes to paginated results updates.
|
|
20506
20971
|
*
|
|
20507
20972
|
* This method:
|
|
20508
|
-
* 1. Creates and initializes a
|
|
20973
|
+
* 1. Creates and initializes a SPARQL live query subscription for the paginated results (default)
|
|
20509
20974
|
* 2. Sets up the callback to process future page updates
|
|
20510
20975
|
* 3. Returns the initial page immediately
|
|
20511
20976
|
*
|
|
@@ -20531,24 +20996,24 @@ class ModelQueryBuilder {
|
|
|
20531
20996
|
* ```
|
|
20532
20997
|
*
|
|
20533
20998
|
* @remarks
|
|
20534
|
-
* By default, this uses
|
|
20535
|
-
* Prolog subscriptions remain available via `.
|
|
20999
|
+
* By default, this uses SPARQL live queries for real-time updates.
|
|
21000
|
+
* Prolog subscriptions remain available via `.useSPARQL(false)`.
|
|
20536
21001
|
*/
|
|
20537
21002
|
async paginateSubscribe(pageSize, pageNumber, callback) {
|
|
20538
21003
|
// Clean up any existing subscription
|
|
20539
21004
|
this.dispose();
|
|
20540
21005
|
const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
20541
|
-
if (this.
|
|
20542
|
-
const
|
|
20543
|
-
this.currentSubscription = await this.perspective.
|
|
21006
|
+
if (this.engineFlag === 'sparql') {
|
|
21007
|
+
const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
|
|
21008
|
+
this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
|
|
20544
21009
|
const processResults = async (result) => {
|
|
20545
|
-
const { results, totalCount } =
|
|
21010
|
+
const { results, totalCount } = await this.processSparqlResult(result, paginationQuery);
|
|
20546
21011
|
callback({ results, totalCount, pageSize, pageNumber });
|
|
20547
21012
|
};
|
|
20548
21013
|
this.currentSubscription.onResult(processResults);
|
|
20549
|
-
const { results, totalCount } =
|
|
21014
|
+
const { results, totalCount } = await this.processSparqlResult(this.currentSubscription.result, paginationQuery);
|
|
20550
21015
|
const initialPage = { results, totalCount, pageSize, pageNumber };
|
|
20551
|
-
callback
|
|
21016
|
+
// Initial page returned via Promise — callback for subsequent updates only
|
|
20552
21017
|
return initialPage;
|
|
20553
21018
|
}
|
|
20554
21019
|
else {
|
|
@@ -20561,17 +21026,31 @@ class ModelQueryBuilder {
|
|
|
20561
21026
|
this.currentSubscription.onResult(processResults);
|
|
20562
21027
|
const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
|
|
20563
21028
|
const initialPrologPage = { results, totalCount, pageSize, pageNumber };
|
|
20564
|
-
callback
|
|
21029
|
+
// Initial page returned via Promise — callback for subsequent updates only
|
|
20565
21030
|
return initialPrologPage;
|
|
20566
21031
|
}
|
|
20567
21032
|
}
|
|
21033
|
+
/**
|
|
21034
|
+
* Subscribes to paginated results updates using SPARQL.
|
|
21035
|
+
* Delegates to paginateSubscribe() with SPARQL engine forced.
|
|
21036
|
+
*/
|
|
21037
|
+
async paginateSubscribeSparql(pageSize, pageNumber, callback) {
|
|
21038
|
+
const prev = this.engineFlag;
|
|
21039
|
+
this.engineFlag = 'sparql';
|
|
21040
|
+
try {
|
|
21041
|
+
return await this.paginateSubscribe(pageSize, pageNumber, callback);
|
|
21042
|
+
}
|
|
21043
|
+
finally {
|
|
21044
|
+
this.engineFlag = prev;
|
|
21045
|
+
}
|
|
21046
|
+
}
|
|
20568
21047
|
}
|
|
20569
21048
|
|
|
20570
21049
|
/**
|
|
20571
21050
|
* hydration.ts — Instance hydration helpers extracted from Ad4mModel.
|
|
20572
21051
|
*
|
|
20573
21052
|
* Pure / stateless functions that populate Ad4mModel instances from
|
|
20574
|
-
* raw link arrays, Prolog tuples, or
|
|
21053
|
+
* raw link arrays, Prolog tuples, or query results. None of these
|
|
20575
21054
|
* functions depend on the `Ad4mModel` class at runtime — they accept
|
|
20576
21055
|
* the instance, metadata, or perspective as explicit parameters.
|
|
20577
21056
|
*/
|
|
@@ -20666,7 +21145,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
|
|
|
20666
21145
|
if (propMeta.resolveLanguage != null &&
|
|
20667
21146
|
propMeta.resolveLanguage !== 'literal' &&
|
|
20668
21147
|
typeof target === 'string' &&
|
|
20669
|
-
!target.startsWith('literal
|
|
21148
|
+
!target.startsWith('literal:')) {
|
|
20670
21149
|
try {
|
|
20671
21150
|
const expression = await perspective.getExpression(target);
|
|
20672
21151
|
if (expression) {
|
|
@@ -20685,7 +21164,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
|
|
|
20685
21164
|
// Literal URI parsing
|
|
20686
21165
|
else if (propMeta.resolveLanguage === 'literal' &&
|
|
20687
21166
|
typeof target === 'string' &&
|
|
20688
|
-
target.startsWith('literal
|
|
21167
|
+
target.startsWith('literal:')) {
|
|
20689
21168
|
try {
|
|
20690
21169
|
const parsed = Literal.fromUrl(target).get();
|
|
20691
21170
|
value = parsed.data !== undefined ? parsed.data : parsed;
|
|
@@ -20917,10 +21396,10 @@ async function assignValuesToInstance(perspective, instance, values) {
|
|
|
20917
21396
|
Object.assign(instance, writableProps);
|
|
20918
21397
|
}
|
|
20919
21398
|
// ──────────────────────────────────────────────────────────
|
|
20920
|
-
//
|
|
21399
|
+
// SPARQL custom getter evaluation
|
|
20921
21400
|
// ──────────────────────────────────────────────────────────
|
|
20922
21401
|
/**
|
|
20923
|
-
* Builds a
|
|
21402
|
+
* Builds a SPARQL conformance getter for a relation whose `target` model
|
|
20924
21403
|
* is known but no explicit `getter` string was supplied.
|
|
20925
21404
|
*
|
|
20926
21405
|
* The generated getter traverses outgoing links matching the relation's
|
|
@@ -20932,7 +21411,7 @@ async function assignValuesToInstance(perspective, instance, values) {
|
|
|
20932
21411
|
*
|
|
20933
21412
|
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
20934
21413
|
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
20935
|
-
* @returns A
|
|
21414
|
+
* @returns A SPARQL expression string, or `undefined` if no conformance
|
|
20936
21415
|
* conditions could be derived from the target model.
|
|
20937
21416
|
*/
|
|
20938
21417
|
function buildConformanceGetter(relationPredicate, targetClass) {
|
|
@@ -20951,7 +21430,7 @@ function buildConformanceGetter(relationPredicate, targetClass) {
|
|
|
20951
21430
|
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
20952
21431
|
*/
|
|
20953
21432
|
async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
|
|
20954
|
-
|
|
21433
|
+
`<${instance.id}>`;
|
|
20955
21434
|
// Build projection filter — when requestedProperties is active, only
|
|
20956
21435
|
// evaluate getters for fields that are requested (or included).
|
|
20957
21436
|
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
@@ -20962,12 +21441,28 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
|
|
|
20962
21441
|
continue;
|
|
20963
21442
|
if (propMeta.getter) {
|
|
20964
21443
|
try {
|
|
20965
|
-
|
|
20966
|
-
const
|
|
20967
|
-
//
|
|
20968
|
-
const
|
|
20969
|
-
if (
|
|
20970
|
-
|
|
21444
|
+
const rawGetter = propMeta.getter;
|
|
21445
|
+
const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
|
|
21446
|
+
// If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
|
|
21447
|
+
const trimmed = getterWithBase.trim().toUpperCase();
|
|
21448
|
+
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
21449
|
+
const result = await perspective.querySparql(getterWithBase);
|
|
21450
|
+
if (trimmed.startsWith('ASK')) {
|
|
21451
|
+
instance[propName] = result === true || result === 'true';
|
|
21452
|
+
}
|
|
21453
|
+
else if (result && result.length > 0) {
|
|
21454
|
+
// Get first binding's first value
|
|
21455
|
+
const firstRow = result[0];
|
|
21456
|
+
const firstKey = Object.keys(firstRow)[0];
|
|
21457
|
+
const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
|
|
21458
|
+
if (val !== undefined && val !== null && val !== 'None' && val !== '') {
|
|
21459
|
+
instance[propName] = val;
|
|
21460
|
+
}
|
|
21461
|
+
}
|
|
21462
|
+
}
|
|
21463
|
+
else {
|
|
21464
|
+
// Legacy SurrealDB-style getter — no longer supported
|
|
21465
|
+
console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
|
|
20971
21466
|
}
|
|
20972
21467
|
}
|
|
20973
21468
|
catch (error) {
|
|
@@ -20983,12 +21478,11 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
|
|
|
20983
21478
|
const meta = relMeta;
|
|
20984
21479
|
// Determine the getter to execute:
|
|
20985
21480
|
// 1. Explicit `getter` always wins
|
|
20986
|
-
// 2. `
|
|
20987
|
-
// 3. If `target` is set and `filter !== false`, auto-generate from target metadata
|
|
21481
|
+
// 2. If `target` is set and `filter !== false`, auto-generate conformance getter
|
|
20988
21482
|
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
20989
|
-
// because buildConformanceGetter traverses outgoing links
|
|
20990
|
-
//
|
|
20991
|
-
//
|
|
21483
|
+
// because buildConformanceGetter traverses outgoing links which is wrong for
|
|
21484
|
+
// reverse relations. Their values are already populated by the reverse link
|
|
21485
|
+
// lookup in instancesFromQueryResult / getData.
|
|
20992
21486
|
let getter = meta.getter;
|
|
20993
21487
|
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
20994
21488
|
try {
|
|
@@ -20996,14 +21490,35 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
|
|
|
20996
21490
|
const targetMetadata = TargetClass
|
|
20997
21491
|
? TargetClass.getModelMetadata?.() ?? null
|
|
20998
21492
|
: null;
|
|
20999
|
-
|
|
21000
|
-
|
|
21001
|
-
|
|
21002
|
-
|
|
21493
|
+
// Check if all where conditions can be SPARQL-filtered.
|
|
21494
|
+
// literal-resolved properties store signed expressions (literal:json:{…}),
|
|
21495
|
+
// not raw literal:string: IRIs, so SPARQL exact-match fails for them.
|
|
21496
|
+
let allSparqlFilterable = true;
|
|
21497
|
+
if (targetMetadata) {
|
|
21498
|
+
for (const propName of Object.keys(meta.where)) {
|
|
21499
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
21500
|
+
continue;
|
|
21501
|
+
const propMeta = targetMetadata.properties[propName];
|
|
21502
|
+
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
21503
|
+
allSparqlFilterable = false;
|
|
21504
|
+
break;
|
|
21505
|
+
}
|
|
21506
|
+
}
|
|
21507
|
+
}
|
|
21508
|
+
else {
|
|
21509
|
+
allSparqlFilterable = false;
|
|
21003
21510
|
}
|
|
21511
|
+
if (allSparqlFilterable) {
|
|
21512
|
+
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
21513
|
+
if (conditions.length > 0) {
|
|
21514
|
+
const escapedPredicate = escapeQueryString(meta.predicate);
|
|
21515
|
+
getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
|
|
21516
|
+
}
|
|
21517
|
+
}
|
|
21518
|
+
// If not filterable, fall through to buildConformanceGetter + JS post-filter below
|
|
21004
21519
|
}
|
|
21005
21520
|
catch (e) {
|
|
21006
|
-
|
|
21521
|
+
console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
|
|
21007
21522
|
}
|
|
21008
21523
|
}
|
|
21009
21524
|
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
@@ -21020,23 +21535,57 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
|
|
|
21020
21535
|
}
|
|
21021
21536
|
if (getter) {
|
|
21022
21537
|
try {
|
|
21023
|
-
|
|
21024
|
-
const
|
|
21025
|
-
|
|
21026
|
-
|
|
21027
|
-
|
|
21028
|
-
|
|
21029
|
-
|
|
21030
|
-
|
|
21031
|
-
|
|
21032
|
-
|
|
21033
|
-
|
|
21538
|
+
const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
|
|
21539
|
+
const trimmed = getterWithBase.trim().toUpperCase();
|
|
21540
|
+
if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
|
|
21541
|
+
// Native SPARQL getter — execute directly
|
|
21542
|
+
const result = await perspective.querySparql(getterWithBase);
|
|
21543
|
+
if (result && result.length > 0) {
|
|
21544
|
+
const values = result.map((r) => {
|
|
21545
|
+
const firstKey = Object.keys(r)[0];
|
|
21546
|
+
return r[firstKey]?.value ?? r[firstKey];
|
|
21547
|
+
}).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
21548
|
+
instance[relName] = values;
|
|
21549
|
+
}
|
|
21550
|
+
}
|
|
21551
|
+
else {
|
|
21552
|
+
// Legacy SurrealDB-style getter — no longer supported
|
|
21553
|
+
console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
|
|
21034
21554
|
}
|
|
21035
21555
|
}
|
|
21036
21556
|
catch (error) {
|
|
21037
21557
|
console.warn(`Failed to evaluate getter for ${relName}:`, error);
|
|
21038
21558
|
}
|
|
21039
21559
|
}
|
|
21560
|
+
// JS post-filter for where conditions that couldn't be SPARQL-filtered
|
|
21561
|
+
// (e.g. literal-resolved properties storing signed expressions)
|
|
21562
|
+
const currentValues = instance[relName];
|
|
21563
|
+
if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
|
|
21564
|
+
const TargetClass = meta.target?.();
|
|
21565
|
+
if (TargetClass) {
|
|
21566
|
+
const filtered = [];
|
|
21567
|
+
for (const targetId of currentValues) {
|
|
21568
|
+
try {
|
|
21569
|
+
const inst = new TargetClass(perspective, targetId);
|
|
21570
|
+
await inst.get();
|
|
21571
|
+
let matches = true;
|
|
21572
|
+
for (const [prop, expected] of Object.entries(meta.where)) {
|
|
21573
|
+
if (inst[prop] !== expected) {
|
|
21574
|
+
matches = false;
|
|
21575
|
+
break;
|
|
21576
|
+
}
|
|
21577
|
+
}
|
|
21578
|
+
if (matches)
|
|
21579
|
+
filtered.push(targetId);
|
|
21580
|
+
}
|
|
21581
|
+
catch {
|
|
21582
|
+
// If we can't hydrate, keep the value (conservative)
|
|
21583
|
+
filtered.push(targetId);
|
|
21584
|
+
}
|
|
21585
|
+
}
|
|
21586
|
+
instance[relName] = filtered;
|
|
21587
|
+
}
|
|
21588
|
+
}
|
|
21040
21589
|
}
|
|
21041
21590
|
}
|
|
21042
21591
|
/**
|
|
@@ -21551,7 +22100,7 @@ class Ad4mModel {
|
|
|
21551
22100
|
* const recipe = new Recipe(perspective);
|
|
21552
22101
|
*
|
|
21553
22102
|
* // Create with specific base expression
|
|
21554
|
-
* const recipe = new Recipe(perspective, "literal
|
|
22103
|
+
* const recipe = new Recipe(perspective, "literal:...");
|
|
21555
22104
|
* ```
|
|
21556
22105
|
*/
|
|
21557
22106
|
constructor(perspective, baseExpression) {
|
|
@@ -21778,19 +22327,13 @@ class Ad4mModel {
|
|
|
21778
22327
|
}
|
|
21779
22328
|
async getData(opts) {
|
|
21780
22329
|
// Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
|
|
21781
|
-
// Use
|
|
22330
|
+
// Use SPARQL for data queries
|
|
21782
22331
|
try {
|
|
21783
22332
|
const ctor = this.constructor;
|
|
21784
22333
|
const metadata = ctor.getModelMetadata();
|
|
21785
22334
|
// Query for all links from this specific node (base expression)
|
|
21786
|
-
const
|
|
21787
|
-
const
|
|
21788
|
-
SELECT id, predicate, out.uri AS target, author, timestamp
|
|
21789
|
-
FROM link
|
|
21790
|
-
WHERE in.uri = ${safeBaseExpression}
|
|
21791
|
-
ORDER BY timestamp ASC
|
|
21792
|
-
`;
|
|
21793
|
-
const links = await this._perspective.querySurrealDB(linksQuery);
|
|
22335
|
+
const linksQuery = buildSPARQLGetDataQuery(this._baseExpression);
|
|
22336
|
+
const links = await this._perspective.querySparql(linksQuery);
|
|
21794
22337
|
if (links && links.length > 0) {
|
|
21795
22338
|
// Core hydration: properties (latest-wins), relations, timestamps/author
|
|
21796
22339
|
const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
|
|
@@ -21815,7 +22358,7 @@ class Ad4mModel {
|
|
|
21815
22358
|
this[relName] = sourceIds;
|
|
21816
22359
|
}
|
|
21817
22360
|
}
|
|
21818
|
-
// Evaluate
|
|
22361
|
+
// Evaluate SPARQL getters
|
|
21819
22362
|
const getterOpts = opts?.properties || opts?.include
|
|
21820
22363
|
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
21821
22364
|
: undefined;
|
|
@@ -21826,7 +22369,7 @@ class Ad4mModel {
|
|
|
21826
22369
|
}
|
|
21827
22370
|
}
|
|
21828
22371
|
catch (e) {
|
|
21829
|
-
console.error(`
|
|
22372
|
+
console.error(`SPARQL getData also failed for ${this._baseExpression}:`, e);
|
|
21830
22373
|
}
|
|
21831
22374
|
this.takeSnapshot();
|
|
21832
22375
|
return this;
|
|
@@ -21856,13 +22399,13 @@ class Ad4mModel {
|
|
|
21856
22399
|
return fullQuery;
|
|
21857
22400
|
}
|
|
21858
22401
|
/**
|
|
21859
|
-
* Generates a
|
|
22402
|
+
* Generates a SPARQL query from a Query object.
|
|
21860
22403
|
*
|
|
21861
22404
|
* @description
|
|
21862
|
-
* This method translates high-level query parameters into a
|
|
21863
|
-
* that can be executed against the
|
|
21864
|
-
* operate on SDNA-aware predicates,
|
|
21865
|
-
* stored in
|
|
22405
|
+
* This method translates high-level query parameters into a SPARQL query string
|
|
22406
|
+
* that can be executed against the SPARQL backend. Unlike Prolog queries which
|
|
22407
|
+
* operate on SDNA-aware predicates, SPARQL queries operate directly on raw links
|
|
22408
|
+
* stored in SPARQL.
|
|
21866
22409
|
*
|
|
21867
22410
|
* The generated query uses a CTE (Common Table Expression) pattern:
|
|
21868
22411
|
* 1. First, identify candidate base expressions by filtering links based on where conditions
|
|
@@ -21870,7 +22413,7 @@ class Ad4mModel {
|
|
|
21870
22413
|
* 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
|
|
21871
22414
|
*
|
|
21872
22415
|
* Key architectural notes:
|
|
21873
|
-
* -
|
|
22416
|
+
* - SPARQL stores only raw links (source, predicate, target, author, timestamp)
|
|
21874
22417
|
* - No SDNA knowledge at the database level
|
|
21875
22418
|
* - Properties are resolved via subqueries that look for links with specific predicates
|
|
21876
22419
|
* - Relations are similar but return multiple values instead of one
|
|
@@ -21878,11 +22421,11 @@ class Ad4mModel {
|
|
|
21878
22421
|
*
|
|
21879
22422
|
* @param perspective - The perspective to query (used for metadata extraction)
|
|
21880
22423
|
* @param query - Query parameters (where, order, limit, offset, properties, relations)
|
|
21881
|
-
* @returns Complete
|
|
22424
|
+
* @returns Complete SPARQL query string ready for execution
|
|
21882
22425
|
*
|
|
21883
22426
|
* @example
|
|
21884
22427
|
* ```typescript
|
|
21885
|
-
* const query = Recipe.
|
|
22428
|
+
* const query = Recipe.queryToSPARQL(perspective, {
|
|
21886
22429
|
* where: { name: "Pasta", rating: { gt: 4 } },
|
|
21887
22430
|
* order: { timestamp: "DESC" },
|
|
21888
22431
|
* limit: 10
|
|
@@ -21891,10 +22434,10 @@ class Ad4mModel {
|
|
|
21891
22434
|
* // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
|
|
21892
22435
|
* ```
|
|
21893
22436
|
*/
|
|
21894
|
-
static async
|
|
22437
|
+
static async queryToSPARQL(perspective, query) {
|
|
21895
22438
|
const metadata = this.getModelMetadata();
|
|
21896
22439
|
const allRelMeta = getRelationsMetadata(this);
|
|
21897
|
-
return
|
|
22440
|
+
return buildSPARQLQuery(metadata, allRelMeta, query, this);
|
|
21898
22441
|
}
|
|
21899
22442
|
static async instancesFromPrologResult(perspective, query, result) {
|
|
21900
22443
|
if (!result?.[0]?.AllInstances)
|
|
@@ -21939,16 +22482,16 @@ class Ad4mModel {
|
|
|
21939
22482
|
return { results: instances, totalCount: result[0].TotalCount };
|
|
21940
22483
|
}
|
|
21941
22484
|
/**
|
|
21942
|
-
* Converts
|
|
22485
|
+
* Converts SPARQL query results to Ad4mModel instances.
|
|
21943
22486
|
*
|
|
21944
22487
|
* @param perspective - The perspective context
|
|
21945
22488
|
* @param query - The query parameters used
|
|
21946
|
-
* @param result - Array of result objects from
|
|
22489
|
+
* @param result - Array of result objects from SPARQL
|
|
21947
22490
|
* @returns Promise resolving to results with total count
|
|
21948
22491
|
*
|
|
21949
22492
|
* @internal
|
|
21950
22493
|
*/
|
|
21951
|
-
static async
|
|
22494
|
+
static async instancesFromQueryResult(perspective, query, result) {
|
|
21952
22495
|
if (!result || result.length === 0)
|
|
21953
22496
|
return { results: [], totalCount: 0 };
|
|
21954
22497
|
const metadata = this.getModelMetadata();
|
|
@@ -21969,33 +22512,25 @@ class Ad4mModel {
|
|
|
21969
22512
|
}
|
|
21970
22513
|
const links = row.links || [];
|
|
21971
22514
|
const instance = new this(perspective, base);
|
|
21972
|
-
// Core hydration via unified helper (pass requestedProperties for sparse fieldset)
|
|
21973
|
-
|
|
21974
|
-
//
|
|
21975
|
-
|
|
21976
|
-
if (
|
|
21977
|
-
const
|
|
21978
|
-
|
|
21979
|
-
|
|
21980
|
-
delete instance[propName];
|
|
21981
|
-
}
|
|
21982
|
-
}
|
|
21983
|
-
for (const relName of Object.keys(metadata.relations)) {
|
|
21984
|
-
if (!requested.has(relName) && !(query.include && relName in query.include)) {
|
|
21985
|
-
delete instance[relName];
|
|
21986
|
-
}
|
|
21987
|
-
}
|
|
21988
|
-
// Also strip metadata fields unless explicitly requested
|
|
21989
|
-
for (const metaField of ['author', 'createdAt', 'updatedAt']) {
|
|
21990
|
-
if (!requested.has(metaField)) {
|
|
21991
|
-
delete instance[metaField];
|
|
22515
|
+
// Core hydration via unified helper (pass requestedProperties for sparse fieldset).
|
|
22516
|
+
// Also hydrate any properties referenced in `where` so the JS post-filter can match them,
|
|
22517
|
+
// even if they're not in the user's `properties` projection.
|
|
22518
|
+
let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
|
|
22519
|
+
if (hydrationProps && query.where) {
|
|
22520
|
+
for (const key of Object.keys(query.where)) {
|
|
22521
|
+
if (!hydrationProps.includes(key)) {
|
|
22522
|
+
hydrationProps.push(key);
|
|
21992
22523
|
}
|
|
21993
22524
|
}
|
|
21994
22525
|
}
|
|
22526
|
+
await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
|
|
22527
|
+
// NOTE: Property deletion for sparse fieldsets is deferred until AFTER
|
|
22528
|
+
// where-filtering so that where conditions can reference any property,
|
|
22529
|
+
// even ones not in the `properties` projection.
|
|
21995
22530
|
instances.push(instance);
|
|
21996
22531
|
}
|
|
21997
22532
|
catch (error) {
|
|
21998
|
-
console.error(`Failed to process
|
|
22533
|
+
console.error(`Failed to process SPARQL instance ${base}:`, error);
|
|
21999
22534
|
}
|
|
22000
22535
|
}
|
|
22001
22536
|
// Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
|
|
@@ -22028,17 +22563,19 @@ class Ad4mModel {
|
|
|
22028
22563
|
for (const instance of instances) {
|
|
22029
22564
|
await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
|
|
22030
22565
|
}
|
|
22031
|
-
// Filter by where conditions that couldn't be filtered in
|
|
22566
|
+
// Filter by where conditions that couldn't be filtered in SPARQL
|
|
22032
22567
|
// This includes:
|
|
22033
22568
|
// - author/timestamp (computed from grouped links)
|
|
22034
22569
|
// - Properties with comparison operators (gt, gte, lt, lte, between, contains)
|
|
22035
|
-
// because fn::parse_literal() comparisons in
|
|
22570
|
+
// because fn::parse_literal() comparisons in SPARQL subqueries don't work reliably
|
|
22571
|
+
// - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
|
|
22572
|
+
// which require reverse-link resolution before filtering
|
|
22036
22573
|
let filteredInstances = instances;
|
|
22037
22574
|
if (query.where) {
|
|
22038
22575
|
filteredInstances = instances.filter(instance => {
|
|
22039
22576
|
for (const [propertyName, condition] of Object.entries(query.where)) {
|
|
22040
|
-
// Skip 'base' as it's filtered in
|
|
22041
|
-
if (propertyName === 'base')
|
|
22577
|
+
// Skip 'base'/'id' as it's filtered in SPARQL
|
|
22578
|
+
if (propertyName === 'base' || propertyName === 'id')
|
|
22042
22579
|
continue;
|
|
22043
22580
|
// For author and timestamp, always filter in JS
|
|
22044
22581
|
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
@@ -22047,19 +22584,20 @@ class Ad4mModel {
|
|
|
22047
22584
|
}
|
|
22048
22585
|
continue;
|
|
22049
22586
|
}
|
|
22050
|
-
//
|
|
22051
|
-
|
|
22052
|
-
if (
|
|
22053
|
-
|
|
22054
|
-
|
|
22055
|
-
|
|
22056
|
-
ops.lt !== undefined || ops.lte !== undefined ||
|
|
22057
|
-
ops.between !== undefined || ops.contains !== undefined;
|
|
22058
|
-
if (hasComparisonOps) {
|
|
22059
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
22060
|
-
return false;
|
|
22061
|
-
}
|
|
22587
|
+
// Check if this is a relation field (not in properties metadata)
|
|
22588
|
+
const isPropField = propertyName in metadata.properties;
|
|
22589
|
+
if (!isPropField) {
|
|
22590
|
+
// Relation-based where — filter in JS against the populated field
|
|
22591
|
+
if (!matchesCondition(instance[propertyName], condition)) {
|
|
22592
|
+
return false;
|
|
22062
22593
|
}
|
|
22594
|
+
continue;
|
|
22595
|
+
}
|
|
22596
|
+
// Filter ALL property conditions in JS (equality, NOT, IN, comparison operators).
|
|
22597
|
+
// SPARQL-level filtering with parse_literal is unreliable across environments,
|
|
22598
|
+
// so we do all property filtering here after hydration resolves values.
|
|
22599
|
+
if (!matchesCondition(instance[propertyName], condition)) {
|
|
22600
|
+
return false;
|
|
22063
22601
|
}
|
|
22064
22602
|
}
|
|
22065
22603
|
return true;
|
|
@@ -22111,6 +22649,28 @@ class Ad4mModel {
|
|
|
22111
22649
|
const end = query.limit ? start + query.limit : undefined;
|
|
22112
22650
|
paginatedInstances = filteredInstances.slice(start, end);
|
|
22113
22651
|
}
|
|
22652
|
+
// Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
|
|
22653
|
+
// This must happen AFTER where-filtering so conditions can reference any property.
|
|
22654
|
+
if (requestedProperties.length > 0) {
|
|
22655
|
+
const requested = new Set(requestedProperties);
|
|
22656
|
+
for (const inst of paginatedInstances) {
|
|
22657
|
+
for (const propName of Object.keys(metadata.properties)) {
|
|
22658
|
+
if (!requested.has(propName)) {
|
|
22659
|
+
delete inst[propName];
|
|
22660
|
+
}
|
|
22661
|
+
}
|
|
22662
|
+
for (const relName of Object.keys(metadata.relations)) {
|
|
22663
|
+
if (!requested.has(relName) && !(query.include && relName in query.include)) {
|
|
22664
|
+
delete inst[relName];
|
|
22665
|
+
}
|
|
22666
|
+
}
|
|
22667
|
+
for (const metaField of ['author', 'createdAt', 'updatedAt']) {
|
|
22668
|
+
if (!requested.has(metaField)) {
|
|
22669
|
+
delete inst[metaField];
|
|
22670
|
+
}
|
|
22671
|
+
}
|
|
22672
|
+
}
|
|
22673
|
+
}
|
|
22114
22674
|
// Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
|
|
22115
22675
|
if (query.include && paginatedInstances.length > 0) {
|
|
22116
22676
|
await hydrateRelations(this, paginatedInstances, perspective, query.include);
|
|
@@ -22135,15 +22695,15 @@ class Ad4mModel {
|
|
|
22135
22695
|
*
|
|
22136
22696
|
* @param perspective - The perspective to search in
|
|
22137
22697
|
* @param query - Optional query parameters to filter results
|
|
22138
|
-
* @param
|
|
22698
|
+
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
22139
22699
|
* @returns Array of matching models
|
|
22140
22700
|
*
|
|
22141
22701
|
* @example
|
|
22142
22702
|
* ```typescript
|
|
22143
|
-
* // Get all recipes (uses
|
|
22703
|
+
* // Get all recipes (uses SPARQL by default)
|
|
22144
22704
|
* const allRecipes = await Recipe.findAll(perspective);
|
|
22145
22705
|
*
|
|
22146
|
-
* // Get recipes with specific criteria (uses
|
|
22706
|
+
* // Get recipes with specific criteria (uses SPARQL)
|
|
22147
22707
|
* const recipes = await Recipe.findAll(perspective, {
|
|
22148
22708
|
* where: {
|
|
22149
22709
|
* name: "Pasta",
|
|
@@ -22157,14 +22717,23 @@ class Ad4mModel {
|
|
|
22157
22717
|
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
22158
22718
|
* ```
|
|
22159
22719
|
*/
|
|
22160
|
-
static async findAll(perspective, query = {},
|
|
22720
|
+
static async findAll(perspective, query = {}, engine = 'sparql') {
|
|
22161
22721
|
if (query.properties && query.properties.length === 0) {
|
|
22162
22722
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
22163
22723
|
}
|
|
22164
|
-
|
|
22165
|
-
|
|
22166
|
-
|
|
22167
|
-
|
|
22724
|
+
// Backward compatibility: boolean maps to sparql (true) or prolog (false)
|
|
22725
|
+
const resolvedEngine = typeof engine === 'boolean'
|
|
22726
|
+
? (engine ? 'sparql' : 'prolog')
|
|
22727
|
+
: engine;
|
|
22728
|
+
if (resolvedEngine === 'sparql') {
|
|
22729
|
+
// Always use the regular SPARQL path + JS-level hydrateRelations for includes.
|
|
22730
|
+
// The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
|
|
22731
|
+
// non-conforming node filtering, and parse_literal compatibility.
|
|
22732
|
+
// hydrateRelations handles all of these correctly via per-relation findAll calls.
|
|
22733
|
+
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
22734
|
+
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
22735
|
+
const grouped = groupSPARQLResults(rawResult);
|
|
22736
|
+
const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
|
|
22168
22737
|
return results;
|
|
22169
22738
|
}
|
|
22170
22739
|
else {
|
|
@@ -22181,7 +22750,7 @@ class Ad4mModel {
|
|
|
22181
22750
|
*
|
|
22182
22751
|
* @param perspective - The perspective to search in
|
|
22183
22752
|
* @param query - Optional query parameters to filter results
|
|
22184
|
-
* @param
|
|
22753
|
+
* @param useSPARQL - Whether to use SPARQL (default: true) or Prolog (legacy)
|
|
22185
22754
|
* @returns The first matching instance, or `null`
|
|
22186
22755
|
*
|
|
22187
22756
|
* @example
|
|
@@ -22194,9 +22763,9 @@ class Ad4mModel {
|
|
|
22194
22763
|
* }
|
|
22195
22764
|
* ```
|
|
22196
22765
|
*/
|
|
22197
|
-
static async findOne(perspective, query = {},
|
|
22766
|
+
static async findOne(perspective, query = {}, engine = 'sparql') {
|
|
22198
22767
|
const limitedQuery = { ...query, limit: 1 };
|
|
22199
|
-
const results = await this.findAll(perspective, limitedQuery,
|
|
22768
|
+
const results = await this.findAll(perspective, limitedQuery, engine);
|
|
22200
22769
|
return results[0] ?? null;
|
|
22201
22770
|
}
|
|
22202
22771
|
/**
|
|
@@ -22204,7 +22773,7 @@ class Ad4mModel {
|
|
|
22204
22773
|
*
|
|
22205
22774
|
* @param perspective - The perspective to search in
|
|
22206
22775
|
* @param query - Optional query parameters to filter results
|
|
22207
|
-
* @param
|
|
22776
|
+
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
22208
22777
|
* @returns Object containing results array and total count
|
|
22209
22778
|
*
|
|
22210
22779
|
* @example
|
|
@@ -22219,11 +22788,15 @@ class Ad4mModel {
|
|
|
22219
22788
|
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
22220
22789
|
* ```
|
|
22221
22790
|
*/
|
|
22222
|
-
static async findAllAndCount(perspective, query = {},
|
|
22223
|
-
|
|
22224
|
-
|
|
22225
|
-
|
|
22226
|
-
|
|
22791
|
+
static async findAllAndCount(perspective, query = {}, engine = 'sparql') {
|
|
22792
|
+
const resolvedEngine = typeof engine === 'boolean'
|
|
22793
|
+
? (engine ? 'sparql' : 'prolog')
|
|
22794
|
+
: engine;
|
|
22795
|
+
if (resolvedEngine === 'sparql') {
|
|
22796
|
+
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
22797
|
+
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
22798
|
+
const grouped = groupSPARQLResults(rawResult);
|
|
22799
|
+
return await this.instancesFromQueryResult(perspective, query, grouped);
|
|
22227
22800
|
}
|
|
22228
22801
|
else {
|
|
22229
22802
|
const prologQuery = await this.queryToProlog(perspective, query);
|
|
@@ -22238,7 +22811,7 @@ class Ad4mModel {
|
|
|
22238
22811
|
* @param pageSize - Number of items per page
|
|
22239
22812
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
22240
22813
|
* @param query - Optional additional query parameters
|
|
22241
|
-
* @param
|
|
22814
|
+
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
22242
22815
|
* @returns Paginated results with metadata
|
|
22243
22816
|
*
|
|
22244
22817
|
* @example
|
|
@@ -22252,12 +22825,16 @@ class Ad4mModel {
|
|
|
22252
22825
|
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
22253
22826
|
* ```
|
|
22254
22827
|
*/
|
|
22255
|
-
static async paginate(perspective, pageSize, pageNumber, query,
|
|
22828
|
+
static async paginate(perspective, pageSize, pageNumber, query, engine = 'sparql') {
|
|
22256
22829
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
22257
|
-
|
|
22258
|
-
|
|
22259
|
-
|
|
22260
|
-
|
|
22830
|
+
const resolvedEngine = typeof engine === 'boolean'
|
|
22831
|
+
? (engine ? 'sparql' : 'prolog')
|
|
22832
|
+
: engine;
|
|
22833
|
+
if (resolvedEngine === 'sparql') {
|
|
22834
|
+
const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
|
|
22835
|
+
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
22836
|
+
const grouped = groupSPARQLResults(rawResult);
|
|
22837
|
+
const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped);
|
|
22261
22838
|
return { results, totalCount, pageSize, pageNumber };
|
|
22262
22839
|
}
|
|
22263
22840
|
else {
|
|
@@ -22286,28 +22863,28 @@ class Ad4mModel {
|
|
|
22286
22863
|
return fullQuery;
|
|
22287
22864
|
}
|
|
22288
22865
|
/**
|
|
22289
|
-
* Generates a
|
|
22866
|
+
* Generates a SPARQL COUNT query for the model.
|
|
22290
22867
|
*
|
|
22291
22868
|
* @param perspective - The perspective context
|
|
22292
22869
|
* @param query - Query parameters to filter the count
|
|
22293
|
-
* @returns
|
|
22870
|
+
* @returns SPARQL COUNT query string
|
|
22294
22871
|
*
|
|
22295
22872
|
* @private
|
|
22296
22873
|
*/
|
|
22297
|
-
static async
|
|
22874
|
+
static async countQueryToSPARQL(perspective, query) {
|
|
22298
22875
|
// Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
|
|
22299
22876
|
// We'll count the number of rows returned (one row per source)
|
|
22300
22877
|
const countQuery = { ...query };
|
|
22301
22878
|
delete countQuery.limit;
|
|
22302
22879
|
delete countQuery.offset;
|
|
22303
|
-
return await this.
|
|
22880
|
+
return await this.queryToSPARQL(perspective, countQuery);
|
|
22304
22881
|
}
|
|
22305
22882
|
/**
|
|
22306
22883
|
* Gets a count of all matching instances.
|
|
22307
22884
|
*
|
|
22308
22885
|
* @param perspective - The perspective to search in
|
|
22309
22886
|
* @param query - Optional query parameters to filter results
|
|
22310
|
-
* @param
|
|
22887
|
+
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
22311
22888
|
* @returns Total count of matching entities
|
|
22312
22889
|
*
|
|
22313
22890
|
* @example
|
|
@@ -22321,14 +22898,15 @@ class Ad4mModel {
|
|
|
22321
22898
|
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
22322
22899
|
* ```
|
|
22323
22900
|
*/
|
|
22324
|
-
static async count(perspective, query = {},
|
|
22325
|
-
|
|
22326
|
-
|
|
22327
|
-
|
|
22328
|
-
|
|
22329
|
-
|
|
22330
|
-
|
|
22331
|
-
const
|
|
22901
|
+
static async count(perspective, query = {}, engine = 'sparql') {
|
|
22902
|
+
const resolvedEngine = typeof engine === 'boolean'
|
|
22903
|
+
? (engine ? 'sparql' : 'prolog')
|
|
22904
|
+
: engine;
|
|
22905
|
+
if (resolvedEngine === 'sparql') {
|
|
22906
|
+
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
22907
|
+
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
22908
|
+
const grouped = groupSPARQLResults(rawResult);
|
|
22909
|
+
const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped);
|
|
22332
22910
|
return totalCount;
|
|
22333
22911
|
}
|
|
22334
22912
|
else {
|
|
@@ -22346,7 +22924,7 @@ class Ad4mModel {
|
|
|
22346
22924
|
const actions = this.generatePropertySetterAction(key, metadata);
|
|
22347
22925
|
// Get resolve language from metadata (replaces Prolog query)
|
|
22348
22926
|
let resolveLanguage = metadata.resolveLanguage;
|
|
22349
|
-
// Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal
|
|
22927
|
+
// Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
|
|
22350
22928
|
if (value === undefined || value === null || value === "") {
|
|
22351
22929
|
return;
|
|
22352
22930
|
}
|
|
@@ -23213,6 +23791,16 @@ input CapabilityInput {
|
|
|
23213
23791
|
with: ResourceInput!
|
|
23214
23792
|
}
|
|
23215
23793
|
|
|
23794
|
+
type ComputeLogEntry {
|
|
23795
|
+
cost: Float!
|
|
23796
|
+
creditsAfter: Float!
|
|
23797
|
+
id: Float!
|
|
23798
|
+
operation: String!
|
|
23799
|
+
summary: String
|
|
23800
|
+
timestamp: String!
|
|
23801
|
+
userEmail: String!
|
|
23802
|
+
}
|
|
23803
|
+
|
|
23216
23804
|
scalar DateTime
|
|
23217
23805
|
|
|
23218
23806
|
type EntanglementProof {
|
|
@@ -23509,6 +24097,7 @@ type Mutation {
|
|
|
23509
24097
|
runtimeRequestPayment(amountHOT: String!): PaymentRequestResult!
|
|
23510
24098
|
runtimeRestartHolochain: Boolean!
|
|
23511
24099
|
runtimeSendHot(amount: String!, recipient: String!): PaymentRequestResult!
|
|
24100
|
+
runtimeSetFreeHostingEnabled(enabled: Boolean!): Boolean!
|
|
23512
24101
|
runtimeSetHotWalletAddress(address: String!): Boolean!
|
|
23513
24102
|
runtimeSetMultiUserEnabled(enabled: Boolean!): Boolean!
|
|
23514
24103
|
runtimeSetStatus(status: PerspectiveInput!): Boolean!
|
|
@@ -23620,9 +24209,10 @@ type Query {
|
|
|
23620
24209
|
perspective(uuid: String!): PerspectiveHandle
|
|
23621
24210
|
perspectiveQueryLinks(query: LinkQuery!, uuid: String!): [LinkExpression!]
|
|
23622
24211
|
perspectiveQueryProlog(query: String!, uuid: String!): String!
|
|
23623
|
-
perspectiveQuerySurrealDB(query: String!, uuid: String!): String!
|
|
23624
24212
|
perspectiveSnapshot(uuid: String!): Perspective
|
|
23625
24213
|
perspectives: [PerspectiveHandle!]!
|
|
24214
|
+
runtimeComputeLog(limit: Float, since: String, userEmail: String): [ComputeLogEntry!]!
|
|
24215
|
+
runtimeFreeHostingEnabled: Boolean!
|
|
23626
24216
|
runtimeFriendStatus(did: String!): PerspectiveExpression
|
|
23627
24217
|
runtimeFriends: [String!]!
|
|
23628
24218
|
runtimeGetNetworkMetrics: String!
|
|
@@ -23638,6 +24228,7 @@ type Query {
|
|
|
23638
24228
|
runtimeMessageOutbox(filter: String): [SentMessage!]!
|
|
23639
24229
|
runtimeMultiUserEnabled: Boolean!
|
|
23640
24230
|
runtimeNotifications: [Notification!]!
|
|
24231
|
+
runtimeUnytAgentKey: String!
|
|
23641
24232
|
runtimeUnytVersionInfo: String!
|
|
23642
24233
|
runtimeVerifyStringSignedByDid(data: String!, did: String!, didSigningKeyId: String!, signedData: String!): Boolean!
|
|
23643
24234
|
}
|
|
@@ -24095,6 +24686,49 @@ PaymentRequestResult = __decorate([
|
|
|
24095
24686
|
ObjectType(),
|
|
24096
24687
|
__metadata("design:paramtypes", [Boolean, String])
|
|
24097
24688
|
], PaymentRequestResult);
|
|
24689
|
+
let ComputeLogEntry = class ComputeLogEntry {
|
|
24690
|
+
constructor(id, userEmail, timestamp, operation, cost, creditsAfter, summary) {
|
|
24691
|
+
this.id = id;
|
|
24692
|
+
this.userEmail = userEmail;
|
|
24693
|
+
this.timestamp = timestamp;
|
|
24694
|
+
this.operation = operation;
|
|
24695
|
+
this.cost = cost;
|
|
24696
|
+
this.creditsAfter = creditsAfter;
|
|
24697
|
+
this.summary = summary;
|
|
24698
|
+
}
|
|
24699
|
+
};
|
|
24700
|
+
__decorate([
|
|
24701
|
+
Field(),
|
|
24702
|
+
__metadata("design:type", Number)
|
|
24703
|
+
], ComputeLogEntry.prototype, "id", void 0);
|
|
24704
|
+
__decorate([
|
|
24705
|
+
Field(),
|
|
24706
|
+
__metadata("design:type", String)
|
|
24707
|
+
], ComputeLogEntry.prototype, "userEmail", void 0);
|
|
24708
|
+
__decorate([
|
|
24709
|
+
Field(),
|
|
24710
|
+
__metadata("design:type", String)
|
|
24711
|
+
], ComputeLogEntry.prototype, "timestamp", void 0);
|
|
24712
|
+
__decorate([
|
|
24713
|
+
Field(),
|
|
24714
|
+
__metadata("design:type", String)
|
|
24715
|
+
], ComputeLogEntry.prototype, "operation", void 0);
|
|
24716
|
+
__decorate([
|
|
24717
|
+
Field(),
|
|
24718
|
+
__metadata("design:type", String)
|
|
24719
|
+
], ComputeLogEntry.prototype, "summary", void 0);
|
|
24720
|
+
__decorate([
|
|
24721
|
+
Field(),
|
|
24722
|
+
__metadata("design:type", Number)
|
|
24723
|
+
], ComputeLogEntry.prototype, "cost", void 0);
|
|
24724
|
+
__decorate([
|
|
24725
|
+
Field(),
|
|
24726
|
+
__metadata("design:type", Number)
|
|
24727
|
+
], ComputeLogEntry.prototype, "creditsAfter", void 0);
|
|
24728
|
+
ComputeLogEntry = __decorate([
|
|
24729
|
+
ObjectType(),
|
|
24730
|
+
__metadata("design:paramtypes", [Number, String, String, String, Number, Number, String])
|
|
24731
|
+
], ComputeLogEntry);
|
|
24098
24732
|
/**
|
|
24099
24733
|
* Resolver classes are used here to define the GraphQL schema
|
|
24100
24734
|
* (through the type-graphql annotations)
|
|
@@ -24250,6 +24884,12 @@ let RuntimeResolver = class RuntimeResolver {
|
|
|
24250
24884
|
runtimeSetMultiUserEnabled(enabled) {
|
|
24251
24885
|
return enabled;
|
|
24252
24886
|
}
|
|
24887
|
+
runtimeFreeHostingEnabled() {
|
|
24888
|
+
return true;
|
|
24889
|
+
}
|
|
24890
|
+
runtimeSetFreeHostingEnabled(enabled) {
|
|
24891
|
+
return enabled;
|
|
24892
|
+
}
|
|
24253
24893
|
runtimeListUsers() {
|
|
24254
24894
|
return [{
|
|
24255
24895
|
email: "test@example.com",
|
|
@@ -24309,6 +24949,9 @@ let RuntimeResolver = class RuntimeResolver {
|
|
|
24309
24949
|
runtimeHostingUserInfo() {
|
|
24310
24950
|
return new HostingUserInfo("test@example.com", "100000000", null, false);
|
|
24311
24951
|
}
|
|
24952
|
+
runtimeComputeLog(since, limit, userEmail) {
|
|
24953
|
+
return [];
|
|
24954
|
+
}
|
|
24312
24955
|
runtimeSetHotWalletAddress(address) {
|
|
24313
24956
|
return true;
|
|
24314
24957
|
}
|
|
@@ -24339,6 +24982,9 @@ let RuntimeResolver = class RuntimeResolver {
|
|
|
24339
24982
|
runtimeHotAgentPubkey() {
|
|
24340
24983
|
return "";
|
|
24341
24984
|
}
|
|
24985
|
+
runtimeUnytAgentKey() {
|
|
24986
|
+
return "";
|
|
24987
|
+
}
|
|
24342
24988
|
runtimeUnytVersionInfo() {
|
|
24343
24989
|
return "";
|
|
24344
24990
|
}
|
|
@@ -24588,6 +25234,19 @@ __decorate([
|
|
|
24588
25234
|
__metadata("design:paramtypes", [Boolean]),
|
|
24589
25235
|
__metadata("design:returntype", Boolean)
|
|
24590
25236
|
], RuntimeResolver.prototype, "runtimeSetMultiUserEnabled", null);
|
|
25237
|
+
__decorate([
|
|
25238
|
+
Query(),
|
|
25239
|
+
__metadata("design:type", Function),
|
|
25240
|
+
__metadata("design:paramtypes", []),
|
|
25241
|
+
__metadata("design:returntype", Boolean)
|
|
25242
|
+
], RuntimeResolver.prototype, "runtimeFreeHostingEnabled", null);
|
|
25243
|
+
__decorate([
|
|
25244
|
+
Mutation(),
|
|
25245
|
+
__param(0, Arg()),
|
|
25246
|
+
__metadata("design:type", Function),
|
|
25247
|
+
__metadata("design:paramtypes", [Boolean]),
|
|
25248
|
+
__metadata("design:returntype", Boolean)
|
|
25249
|
+
], RuntimeResolver.prototype, "runtimeSetFreeHostingEnabled", null);
|
|
24591
25250
|
__decorate([
|
|
24592
25251
|
Query(),
|
|
24593
25252
|
__metadata("design:type", Function),
|
|
@@ -24675,6 +25334,15 @@ __decorate([
|
|
|
24675
25334
|
__metadata("design:paramtypes", []),
|
|
24676
25335
|
__metadata("design:returntype", HostingUserInfo)
|
|
24677
25336
|
], RuntimeResolver.prototype, "runtimeHostingUserInfo", null);
|
|
25337
|
+
__decorate([
|
|
25338
|
+
Query(),
|
|
25339
|
+
__param(0, Arg()),
|
|
25340
|
+
__param(1, Arg()),
|
|
25341
|
+
__param(2, Arg()),
|
|
25342
|
+
__metadata("design:type", Function),
|
|
25343
|
+
__metadata("design:paramtypes", [String, Number, String]),
|
|
25344
|
+
__metadata("design:returntype", Array)
|
|
25345
|
+
], RuntimeResolver.prototype, "runtimeComputeLog", null);
|
|
24678
25346
|
__decorate([
|
|
24679
25347
|
Mutation(),
|
|
24680
25348
|
__param(0, Arg()),
|
|
@@ -24746,6 +25414,12 @@ __decorate([
|
|
|
24746
25414
|
__metadata("design:paramtypes", []),
|
|
24747
25415
|
__metadata("design:returntype", String)
|
|
24748
25416
|
], RuntimeResolver.prototype, "runtimeHotAgentPubkey", null);
|
|
25417
|
+
__decorate([
|
|
25418
|
+
Query(),
|
|
25419
|
+
__metadata("design:type", Function),
|
|
25420
|
+
__metadata("design:paramtypes", []),
|
|
25421
|
+
__metadata("design:returntype", String)
|
|
25422
|
+
], RuntimeResolver.prototype, "runtimeUnytAgentKey", null);
|
|
24749
25423
|
__decorate([
|
|
24750
25424
|
Query(),
|
|
24751
25425
|
__metadata("design:type", Function),
|
|
@@ -24756,4 +25430,4 @@ RuntimeResolver = __decorate([
|
|
|
24756
25430
|
Resolver()
|
|
24757
25431
|
], RuntimeResolver);
|
|
24758
25432
|
|
|
24759
|
-
export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, Model, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, WakerSubscriptionManager, assignValuesToInstance, buildAuthorAndTimestampQuery, buildConformanceFilter, buildConformanceGetter, buildCountQuery,
|
|
25433
|
+
export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, Model, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, WakerSubscriptionManager, assignValuesToInstance, buildAuthorAndTimestampQuery, buildConformanceFilter, buildConformanceGetter, buildCountQuery, buildLimitQuery, buildModelFromJSONSchema, buildOffsetQuery, buildOrderQuery, buildParentQuery, buildPropertiesQuery, buildSDNA, buildSHACL, buildSPARQLGetDataQuery, buildSPARQLQuery, buildWhereCondition, buildWhereQuery, capSentence, clearQueryCache, clearSubscriptionPool, compileWhereClause, determineNamespace, determinePredicate, escapeQueryString, evaluateCustomGettersForInstance, exprRef2String, formatList, formatQueryValue, formatSPARQLValue, generatePrologFacts, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, groupSPARQLResults, hydrateFromLinks, hydratePropertyValue, hydrateRelations, invalidatePerspectiveCache, isArrayType, isExpression, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, matchesCondition, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, pooledSubscribe, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, subscriptionPoolSize, typeDefsString };
|