@coasys/ad4m 0.13.0-test-1 → 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.
Files changed (94) hide show
  1. package/lib/index.cjs +1392 -777
  2. package/lib/index.js +1376 -775
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +5 -1
  5. package/lib/src/agent/AgentClient.js +48 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/language/Language.d.ts +41 -3
  8. package/lib/src/model/Ad4mModel.d.ts +28 -28
  9. package/lib/src/model/Ad4mModel.js +129 -101
  10. package/lib/src/model/Ad4mModel.test.js +1543 -535
  11. package/lib/src/model/ModelQueryBuilder.d.ts +48 -34
  12. package/lib/src/model/ModelQueryBuilder.js +163 -78
  13. package/lib/src/model/Subject.js +6 -6
  14. package/lib/src/model/decorators.d.ts +14 -8
  15. package/lib/src/model/decorators.js +41 -14
  16. package/lib/src/model/hydration-batch.d.ts +34 -0
  17. package/lib/src/model/hydration-batch.js +147 -0
  18. package/lib/src/model/hydration.d.ts +3 -3
  19. package/lib/src/model/hydration.js +106 -36
  20. package/lib/src/model/index.d.ts +4 -1
  21. package/lib/src/model/index.js +4 -1
  22. package/lib/src/model/json-schema.js +2 -2
  23. package/lib/src/model/query-cache.d.ts +30 -0
  24. package/lib/src/model/query-cache.js +66 -0
  25. package/lib/src/model/query-cache.test.d.ts +1 -0
  26. package/lib/src/model/query-cache.test.js +43 -0
  27. package/lib/src/model/query-common.d.ts +1 -1
  28. package/lib/src/model/query-common.js +1 -1
  29. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  30. package/lib/src/model/query-sparql-batch.js +260 -0
  31. package/lib/src/model/query-sparql.d.ts +47 -0
  32. package/lib/src/model/query-sparql.js +336 -0
  33. package/lib/src/model/query-utils.d.ts +45 -0
  34. package/lib/src/model/query-utils.js +140 -0
  35. package/lib/src/model/relation-filtering.test.js +15 -15
  36. package/lib/src/model/sdna.js +1 -1
  37. package/lib/src/model/shacl-gen.js +42 -18
  38. package/lib/src/model/subscription-pool.d.ts +39 -0
  39. package/lib/src/model/subscription-pool.js +119 -0
  40. package/lib/src/model/types.d.ts +3 -3
  41. package/lib/src/model/types.js +1 -1
  42. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -17
  43. package/lib/src/perspectives/PerspectiveClient.js +5 -57
  44. package/lib/src/perspectives/PerspectiveProxy.d.ts +51 -30
  45. package/lib/src/perspectives/PerspectiveProxy.js +224 -177
  46. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  47. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  48. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  49. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  50. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  51. package/lib/src/runtime/RuntimeResolver.js +56 -0
  52. package/lib/src/schema.gql +11 -1
  53. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  54. package/lib/src/shacl/SHACLFlow.js +9 -9
  55. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  56. package/lib/src/shacl/SHACLShape.js +38 -38
  57. package/lib/src/typeDefs.js +11 -1
  58. package/lib/src/utils.d.ts +6 -6
  59. package/lib/src/utils.js +6 -6
  60. package/package.json +1 -1
  61. package/src/Literal.test.ts +10 -5
  62. package/src/Literal.ts +6 -5
  63. package/src/agent/AgentClient.ts +53 -1
  64. package/src/expression/ExpressionRef.ts +2 -2
  65. package/src/language/Language.ts +48 -3
  66. package/src/model/Ad4mModel.test.ts +1515 -565
  67. package/src/model/Ad4mModel.ts +142 -102
  68. package/src/model/ModelQueryBuilder.ts +185 -86
  69. package/src/model/Subject.ts +6 -6
  70. package/src/model/decorators.ts +51 -22
  71. package/src/model/hydration-batch.ts +205 -0
  72. package/src/model/hydration.ts +102 -39
  73. package/src/model/index.ts +4 -1
  74. package/src/model/json-schema.ts +2 -2
  75. package/src/model/query-cache.test.ts +54 -0
  76. package/src/model/query-cache.ts +79 -0
  77. package/src/model/query-common.ts +1 -1
  78. package/src/model/query-sparql-batch.ts +301 -0
  79. package/src/model/query-sparql.ts +363 -0
  80. package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
  81. package/src/model/relation-filtering.test.ts +15 -15
  82. package/src/model/sdna.ts +1 -1
  83. package/src/model/shacl-gen.ts +42 -17
  84. package/src/model/subscription-pool.ts +163 -0
  85. package/src/model/types.ts +3 -3
  86. package/src/perspectives/PerspectiveClient.ts +5 -61
  87. package/src/perspectives/PerspectiveProxy.ts +226 -181
  88. package/src/perspectives/PerspectiveResolver.ts +0 -8
  89. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  90. package/src/runtime/RuntimeResolver.ts +43 -0
  91. package/src/shacl/SHACLFlow.ts +9 -9
  92. package/src/shacl/SHACLShape.ts +39 -39
  93. package/src/utils.ts +6 -6
  94. 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://${encoded}`;
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
- // get rid of "literal://"
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 SurrealDB for data queries
4481
+ // Use SPARQL for data queries
4481
4482
  try {
4482
- return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), p);
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 SurrealDB:`, err);
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 SurrealDB for data queries
4520
+ // Use SPARQL for data queries
4520
4521
  try {
4521
- return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getRelationValuesViaSurreal(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), c);
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 SurrealDB:`, err);
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://string:" : undefined);
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://string:${JSON.stringify(this.constructor_actions)}`
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://string:${JSON.stringify(this.destructor_actions)}`
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://${prop.minCount}^^xsd:integer`
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://${prop.maxCount}^^xsd:integer`
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://${prop.pattern}`
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://${prop.minInclusive}`
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://${prop.maxInclusive}`
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://${prop.hasValue}`
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://${prop.local}`
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://${prop.writable}`
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://string:${prop.resolveLanguage}`
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://string:${JSON.stringify(prop.setter)}`
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://string:${JSON.stringify(prop.adder)}`
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://string:${JSON.stringify(prop.remover)}`
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://string:${prop.getter}`
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://string:${JSON.stringify(prop.conformanceConditions)}`
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('literal://string:', '');
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('literal://string:', '');
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://5^^xsd:integer and literal://number:5
5173
- let val = minCountLink.target.replace('literal://', '').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://5^^xsd:integer and literal://number:5
5181
- let val = maxCountLink.target.replace('literal://', '').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('literal://', '');
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://5 and literal://number:5
5193
- let val = minInclusiveLink.target.replace('literal://', '');
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://5 and literal://number:5
5201
- let val = maxInclusiveLink.target.replace('literal://', '');
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('literal://', '');
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://true and literal://boolean:true
5214
- let val = localLink.target.replace('literal://', '');
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://true and literal://boolean:true
5222
- let val = writableLink.target.replace('literal://', '');
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('literal://string:', '');
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('literal://string:', '');
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('literal://string:', '');
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('literal://string:', '');
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('literal://string:', '');
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('literal://string:', '');
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 SurrealQL queries.
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 SurrealQL queries. This handles the most common
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 SurrealQL.
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 SurrealQL interpolation (without surrounding quotes)
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 = escapeSurrealString(userInput);
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 escapeSurrealString(value) {
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 SurrealQL compilation utilities.
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 SurrealQL expression.
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 formatSurrealValue(value) {
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 => formatSurrealValue(v)).join(', ')}]`;
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 SurrealQL
5454
- * graph-traversal sub-expression.
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
- * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
5457
- * style checks that can be used inside a `[WHERE ...]` filter on nodes.
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 SurrealQL condition string
5466
+ * @returns A single SPARQL condition string
5463
5467
  */
5464
5468
  function buildWhereCondition(predicate, condition, opts) {
5465
- const escapedPredicate = escapeSurrealString(predicate);
5466
- const targetField = opts?.resolveLanguage === 'literal'
5467
- ? 'fn::parse_literal(out.uri)'
5468
- : 'out.uri';
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 clause
5471
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
5472
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
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) => formatSurrealValue(v)).join(', ');
5481
- parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
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(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
5499
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
5485
5500
  }
5486
5501
  }
5487
- // Comparison operators — ensure property exists (actual comparison
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(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
5507
+ parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
5495
5508
  }
5496
- return parts.join(' AND ');
5509
+ return parts.join(' ');
5497
5510
  }
5498
5511
  else {
5499
5512
  // Simple equality
5500
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
5513
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
5501
5514
  }
5502
5515
  }
5503
5516
  /**
5504
- * Compile a full `Where` clause to an array of SurrealQL condition strings.
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://string:" : undefined);
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 SurrealQL getter
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 = escapeSurrealString(relMeta.predicate);
5739
- relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
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
- try {
5748
- const TargetClass = relMeta.target();
5749
- const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
5750
- if (filter) {
5751
- relShape.getter = filter.getter;
5752
- relShape.conformanceConditions = filter.conformanceConditions;
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
- catch (e) {
5756
- // Target class may not be available yet — getter will be
5757
- // absent and runtime will fall back to unfiltered get_links
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://string:[]`
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 SurrealQL expression that traverses outgoing links and filters
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 surrealConditions = [];
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
- surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
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
- surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}']) > 0`);
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 escapedPredicate = escapeSurrealString(relationPredicate);
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://string:uninitialized"` sentinel as the initial value
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://string:uninitialized" when required)
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://string:uninitialized" : undefined),
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 SurrealQL.');
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 SurrealDB
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://string:${encodeURIComponent(JSON.stringify(this.flowable))}`
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://string:${encodeURIComponent(JSON.stringify(this.startAction))}`
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://string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
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://string:${encodeURIComponent(JSON.stringify(transition.actions))}`
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('literal://string:', '');
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('literal://string:', '');
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('literal://string:', '');
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('literal://string:', '');
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
- if (this.isSurrealDB) {
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
- if (this.isSurrealDB) {
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
- if (this.isSurrealDB) {
7043
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
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 SurrealQL query against the perspective's link cache.
7258
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
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 - SurrealQL query string (read-only operations only)
7386
+ * @param query - SPARQL query string (read-only operations only)
7265
7387
  * @returns Query results as parsed JSON
7266
7388
  *
7267
- * @example
7268
- * ```typescript
7269
- * // Get all links
7270
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
7271
- *
7272
- * // Filter links by predicate
7273
- * const follows = await perspective.querySurrealDB(
7274
- * "SELECT * FROM link WHERE predicate = 'follows'"
7275
- * );
7389
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
7276
7390
  *
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 querySurrealDB(query) {
7284
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
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
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, batchId);
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://string:shacl://${name}`);
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://string:shacl://${name}`);
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
- // Build a single surreal query that fetches all relevant links
7966
+ // Fetch all links from the shape and its property shapes
7831
7967
  const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
7832
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
7833
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
7834
- const result = await this.querySurrealDB(query);
7835
- const shapeLinks = (result || []).map((r) => ({
7836
- source: r.source,
7837
- predicate: r.predicate,
7838
- target: r.target
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
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
7947
- // Single surreal query to get all flow-related links
7948
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri = '${escapedFlowUri}' OR string::starts_with(in.uri, '${escapedAltPrefix}')`;
7949
- const result = await this.querySurrealDB(query);
7950
- const flowLinks = (result || []).map((r) => ({
7951
- source: r.source,
7952
- predicate: r.predicate,
7953
- target: r.target
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://string:{json}
8063
- const prefix = "literal://string:";
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 escapedExpression = escapeSurrealString(expression);
8120
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
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
- const escapedExpression = escapeSurrealString(expression);
8129
- const escapedPredicate = escapeSurrealString(triple.predicate);
8130
- let checkQuery;
8265
+ let query;
8131
8266
  if (triple.target) {
8132
- // Flag: must match both predicate AND exact target value
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
- // Property: just check predicate exists
8138
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
8139
- }
8140
- const result = await this.querySurrealDB(checkQuery);
8141
- if (!result || result.length === 0) {
8142
- return false;
8270
+ query = new LinkQuery({ source: expression, predicate: triple.predicate });
8143
8271
  }
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 SurrealDB query to find instances based on class metadata.
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
- generateSurrealInstanceQuery(metadata) {
8365
+ async findInstancesByMetadata(metadata) {
8232
8366
  if (metadata.requiredTriples.length === 0) {
8233
- // No required triples - any node with links is an instance
8234
- return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
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
- // Generate WHERE conditions for each required triple (predicate + optional exact target)
8237
- const whereConditions = metadata.requiredTriples.map(triple => {
8238
- const escapedPredicate = escapeSurrealString(triple.predicate);
8239
- if (triple.target) {
8240
- // Flag: must match both predicate AND exact target value
8241
- const escapedTarget = escapeSurrealString(triple.target);
8242
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
8243
- }
8244
- else {
8245
- // Property: just check predicate exists
8246
- return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
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
- }).join(' AND ');
8249
- return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
8399
+ candidates = remaining;
8400
+ }
8401
+ return candidates.map(c => ({ base: c }));
8250
8402
  }
8251
8403
  /**
8252
- * Gets a property value using SurrealDB when Prolog fails.
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 getPropertyValueViaSurreal(baseExpression, className, propertyName) {
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 escapedBaseExpression = escapeSurrealString(baseExpression);
8265
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
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 = result[0].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 SurrealDB when Prolog fails.
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 getRelationValuesViaSurreal(baseExpression, className, relationName) {
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 escapedBaseExpression = escapeSurrealString(baseExpression);
8304
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
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
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
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
- // If condition starts with WHERE, wrap in array length check
8321
- if (condition.trim().startsWith('WHERE')) {
8322
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
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
- const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
8325
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
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 SurrealDB queries.
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 escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
8364
- const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
8365
- const result = await this.querySurrealDB(checkQuery);
8366
- return result.map(r => r.uri);
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, build a query that finds matching expressions
8534
+ // For each required triple, find which expressions match
8369
8535
  const validExpressionSets = [];
8370
8536
  for (const triple of metadata.requiredTriples) {
8371
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
8372
- const escapedPredicate = escapeSurrealString(triple.predicate);
8373
- let checkQuery;
8374
- if (triple.target) {
8375
- // Flag: must match both predicate AND exact target value
8376
- const escapedTarget = escapeSurrealString(triple.target);
8377
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
8378
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
8379
- }
8380
- else {
8381
- // Property: just check predicate exists
8382
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
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
- const result = await this.querySurrealDB(checkQuery);
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 SurrealDB for instances
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 surrealQuery = this.generateSurrealInstanceQuery(metadata);
8443
- const results = await this.querySurrealDB(surrealQuery);
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 SurrealDB for instances
8651
+ // Query SDNA for metadata, then query SPARQL for instances
8489
8652
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8490
8653
  if (metadata) {
8491
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
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
- // Single SurrealDB query to find all classes and their properties/relations
8538
- const query = `SELECT
8539
- in.uri AS shape_source,
8540
- predicate,
8541
- out.uri AS target
8542
- FROM link
8543
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
8544
- const results = await this.querySurrealDB(query);
8545
- if (!results || results.length === 0)
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 SurrealQL query that updates in real-time.
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
- * @param query - SurrealQL query string
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 subscribeSurrealDB(query) {
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
- * Executes a read-only SurrealQL query against a perspective's link cache.
8895
- *
8896
- * Security: Only SELECT, RETURN, and other read-only queries are permitted.
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(perspectiveQuerySurrealDb);
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, _AgentClient_hostingUserInfoChangedCallbacks;
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
@@ -9436,11 +9562,13 @@ class AgentClient {
9436
9562
  _AgentClient_updatedCallbacks.set(this, void 0);
9437
9563
  _AgentClient_agentStatusChangedCallbacks.set(this, void 0);
9438
9564
  _AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);
9565
+ _AgentClient_computeLogUpdatedCallbacks.set(this, void 0);
9439
9566
  __classPrivateFieldSet$7(this, _AgentClient_apolloClient, client, "f");
9440
9567
  __classPrivateFieldSet$7(this, _AgentClient_updatedCallbacks, [], "f");
9441
9568
  __classPrivateFieldSet$7(this, _AgentClient_agentStatusChangedCallbacks, [], "f");
9442
9569
  __classPrivateFieldSet$7(this, _AgentClient_appsChangedCallback, [], "f");
9443
9570
  __classPrivateFieldSet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, [], "f");
9571
+ __classPrivateFieldSet$7(this, _AgentClient_computeLogUpdatedCallbacks, [], "f");
9444
9572
  if (subscribe) {
9445
9573
  this.subscribeAgentUpdated();
9446
9574
  this.subscribeAgentStatusChanged();
@@ -9724,6 +9852,32 @@ class AgentClient {
9724
9852
  error: (e) => console.error(e),
9725
9853
  });
9726
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
+ }
9727
9881
  async requestCapability(authInfo) {
9728
9882
  const { agentRequestCapability } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
9729
9883
  mutation: gql `
@@ -9870,6 +10024,24 @@ class AgentClient {
9870
10024
  }));
9871
10025
  return runtimeHostingUserInfo;
9872
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
+ }
9873
10045
  async setHotWalletAddress(address) {
9874
10046
  const { runtimeSetHotWalletAddress } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
9875
10047
  mutation: gql `mutation runtimeSetHotWalletAddress($address: String!) {
@@ -9892,7 +10064,7 @@ class AgentClient {
9892
10064
  return runtimeRequestPayment;
9893
10065
  }
9894
10066
  }
9895
- _AgentClient_apolloClient = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = 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();
9896
10068
 
9897
10069
  var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
9898
10070
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -18683,11 +18855,11 @@ function exprRef2String(ref) {
18683
18855
  return `${ref.language.address}://${ref.expression}`;
18684
18856
  }
18685
18857
  function parseExprUrl(url) {
18686
- if (url.startsWith("literal://")) {
18858
+ if (url.startsWith("literal:")) {
18687
18859
  const languageRef = new LanguageRef();
18688
18860
  languageRef.address = 'literal';
18689
18861
  languageRef.name = 'literal';
18690
- const content = url.substring(10);
18862
+ const content = url.substring(8);
18691
18863
  return new ExpressionRef(languageRef, content);
18692
18864
  }
18693
18865
  const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
@@ -19008,7 +19180,7 @@ PerspectiveHandle = __decorate$2([
19008
19180
  ], PerspectiveHandle);
19009
19181
 
19010
19182
  /**
19011
- * WakerSubscriptionManager — manages live SurrealDB subscriptions for the waker.
19183
+ * WakerSubscriptionManager — manages live query subscriptions for the waker.
19012
19184
  *
19013
19185
  * Lives in core so it can be imported by both the plugin and integration tests
19014
19186
  * without ESM/CJS import issues.
@@ -19032,7 +19204,7 @@ class WakerSubscriptionManager {
19032
19204
  this.previousSeenMessages = options.previousSeenMessages ?? {};
19033
19205
  }
19034
19206
  /**
19035
- * Create a live SurrealDB subscription.
19207
+ * Create a live SPARQL subscription.
19036
19208
  * If a subscription with the same id already exists, it is disposed first.
19037
19209
  */
19038
19210
  async subscribe(sub) {
@@ -19043,9 +19215,9 @@ class WakerSubscriptionManager {
19043
19215
  }
19044
19216
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
19045
19217
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
19046
- this.logger.info(`[waker] ${sub.id}: SurrealQL query:\n${sub.query}`);
19218
+ this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
19047
19219
  const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
19048
- proxy.isSurrealDB = true;
19220
+ proxy.isSPARQL = true;
19049
19221
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
19050
19222
  // rejects this promise internally when subscribe() fails, and if nobody catches
19051
19223
  // it before the next microtask it crashes the process.
@@ -19078,7 +19250,7 @@ class WakerSubscriptionManager {
19078
19250
  }
19079
19251
  proxy.onResult(async (result) => {
19080
19252
  this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
19081
- // SurrealDB can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
19253
+ // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
19082
19254
  if (!Array.isArray(result)) {
19083
19255
  this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
19084
19256
  return;
@@ -19103,10 +19275,9 @@ class WakerSubscriptionManager {
19103
19275
  for (const msgAddr of newMessages) {
19104
19276
  const parents = [];
19105
19277
  try {
19106
- const escaped = msgAddr.replace(/'/g, "\\'");
19107
- const parentQuery = `SELECT * FROM link WHERE predicate = 'ad4m://has_child' AND target = '${escaped}'`;
19278
+ const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
19108
19279
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
19109
- const parentResult = await this.perspectiveClient.querySurrealDB(sub.perspective, parentQuery);
19280
+ const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
19110
19281
  if (Array.isArray(parentResult)) {
19111
19282
  for (const link of parentResult) {
19112
19283
  if (link && link.source) {
@@ -19305,7 +19476,7 @@ class SmartLiteral {
19305
19476
  _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
19306
19477
 
19307
19478
  /**
19308
- * Shared query helpers used by both the Prolog and SurrealQL query pipelines.
19479
+ * Shared query helpers used by both the Prolog and SPARQL query pipelines.
19309
19480
  */
19310
19481
  /**
19311
19482
  * Resolves the predicate for a parent query.
@@ -19743,14 +19914,14 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
19743
19914
  }
19744
19915
  // Default resolveLanguage to 'literal' for all remaining property types,
19745
19916
  // matching the @Property decorator behaviour. Without this, string values
19746
- // stored as literal:// URLs are returned unparsed.
19917
+ // stored as literal: URLs are returned unparsed.
19747
19918
  if (resolveLanguage === undefined || resolveLanguage === null) {
19748
19919
  resolveLanguage = 'literal';
19749
19920
  }
19750
19921
  // If property is required, ensure it has an initial value
19751
19922
  if (isRequired && !initial) {
19752
19923
  if (isObjectType(propertySchema)) {
19753
- initial = 'literal://json:{}';
19924
+ initial = 'literal:json:{}';
19754
19925
  }
19755
19926
  else {
19756
19927
  initial = "ad4m://undefined";
@@ -19806,250 +19977,433 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
19806
19977
  }
19807
19978
 
19808
19979
  /**
19809
- * SurrealQL query building utilities for Ad4mModel.
19980
+ * SPARQL query building utilities for Ad4mModel.
19810
19981
  *
19811
- * Contains the graph-traversal WHERE clause builder, legacy
19812
- * subquery-based clause builders, SELECT-field builders, and
19813
- * the main `buildSurrealQLQuery()` function that produces a
19814
- * 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.
19815
19984
  *
19816
- * All functions are stateless — model metadata and relation metadata
19817
- * are passed in as parameters instead of accessed via `this`.
19985
+ * All AD4M URIs (source, predicate, target) become RDF IRIs.
19818
19986
  *
19819
19987
  * @module
19820
19988
  */
19821
- // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
19822
19989
  /**
19823
- * Builds WHERE clause filters using SurrealDB graph traversal syntax.
19824
- *
19825
- * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
19826
- * filters that SurrealDB can optimize via graph indexes.
19827
- *
19828
- * @param metadata - Model metadata from `getModelMetadata()`
19829
- * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
19830
- * direction detection)
19831
- * @param where - User-supplied where conditions
19832
- * @returns Combined AND-joined condition string, or empty string
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.
19833
19994
  */
19834
- function buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where) {
19835
- if (!where)
19836
- return '';
19837
- const conditions = [];
19838
- for (const [propertyName, condition] of Object.entries(where)) {
19839
- const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
19840
- if (isSpecial) {
19841
- if (propertyName === 'author' || propertyName === 'timestamp') {
19842
- continue; // Filtered post-query in JS
19843
- }
19844
- const columnName = 'uri';
19845
- if (Array.isArray(condition)) {
19846
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19847
- conditions.push(`${columnName} IN [${formattedValues}]`);
19848
- }
19849
- else if (typeof condition === 'object' && condition !== null) {
19850
- const ops = condition;
19851
- if (ops.not !== undefined) {
19852
- if (Array.isArray(ops.not)) {
19853
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19854
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
19855
- }
19856
- else {
19857
- conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
19858
- }
19859
- }
19860
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
19861
- conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
19862
- }
19863
- if (ops.gt !== undefined) {
19864
- conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
19865
- }
19866
- if (ops.gte !== undefined) {
19867
- conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
19868
- }
19869
- if (ops.lt !== undefined) {
19870
- conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
19871
- }
19872
- if (ops.lte !== undefined) {
19873
- conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
19874
- }
19875
- if (ops.contains !== undefined) {
19876
- conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
19877
- }
19878
- }
19879
- else {
19880
- conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
19881
- }
19882
- }
19883
- else {
19884
- // Regular properties — check relation metadata first for direction
19885
- const relMeta = allRelationsMetadata[propertyName];
19886
- const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
19887
- if (relMeta) {
19888
- const predicate = escapeSurrealString(relMeta.predicate);
19889
- if (Array.isArray(condition)) {
19890
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19891
- if (isBelongs) {
19892
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
19893
- }
19894
- else {
19895
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
19896
- }
19897
- }
19898
- else if (typeof condition === 'object' && condition !== null) {
19899
- const ops = condition;
19900
- if (ops.not !== undefined) {
19901
- if (Array.isArray(ops.not)) {
19902
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19903
- if (isBelongs) {
19904
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
19905
- }
19906
- else {
19907
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
19908
- }
19909
- }
19910
- else {
19911
- if (isBelongs) {
19912
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
19913
- }
19914
- else {
19915
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
19916
- }
19917
- }
19918
- }
19919
- }
19920
- else {
19921
- if (isBelongs) {
19922
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
19923
- }
19924
- else {
19925
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
19926
- }
19927
- }
19928
- continue;
19929
- }
19930
- const propMeta = metadata.properties[propertyName];
19931
- if (!propMeta)
19932
- continue;
19933
- const predicate = escapeSurrealString(propMeta.predicate);
19934
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
19935
- if (Array.isArray(condition)) {
19936
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19937
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
19938
- }
19939
- else if (typeof condition === 'object' && condition !== null) {
19940
- const ops = condition;
19941
- if (ops.not !== undefined) {
19942
- if (Array.isArray(ops.not)) {
19943
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19944
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
19945
- }
19946
- else {
19947
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
19948
- }
19949
- }
19950
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
19951
- ops.lt !== undefined || ops.lte !== undefined ||
19952
- ops.between !== undefined || ops.contains !== undefined;
19953
- if (hasComparisonOps) {
19954
- conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
19955
- }
19956
- }
19957
- else {
19958
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
19959
- }
19960
- }
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)}"`;
19961
20021
  }
19962
- return conditions.join(' AND ');
20022
+ return `"${String(value)}"`;
19963
20023
  }
19964
- // ─── Main Query Builder ─────────────────────────────────────────────────────
19965
20024
  /**
19966
- * Builds a complete SurrealQL query from a Query object and model metadata.
19967
- *
19968
- * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
19969
- * It produces a graph-traversal query that:
19970
- * 1. Filters nodes by required predicates (conformance check)
19971
- * 2. Applies user WHERE conditions
19972
- * 3. Fetches all outgoing links for hydration
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.
19973
20035
  *
19974
- * @param metadata - Model metadata from `getModelMetadata()`
19975
- * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
19976
- * @param query - Query parameters
19977
- * @param modelClass - The model class (for `resolveParentPredicate`)
19978
- * @returns Complete SurrealQL query string
20036
+ * Uses direct triple patterns: ?source ?predicate ?target
20037
+ * with named graph storage and metadata keyed by graph IRI.
19979
20038
  */
19980
- function buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass) {
19981
- const { where } = query;
19982
- // Build graph traversal filters for required predicates
19983
- const graphTraversalFilters = [];
19984
- // Parent filter
20039
+ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
20040
+ const joinPatterns = [];
20041
+ const filterExpressions = [];
20042
+ // Parent filter — direct triple pattern
19985
20043
  if (query.parent) {
19986
20044
  const parentPredicate = resolveParentPredicate(query.parent, modelClass);
19987
- graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
20045
+ joinPatterns.push(`
20046
+ ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
19988
20047
  }
19989
- // Required property filters
20048
+ // Required property JOIN patterns — direct triple patterns
20049
+ let hasConformance = false;
19990
20050
  for (const [, propMeta] of Object.entries(metadata.properties)) {
19991
20051
  if (propMeta.required) {
19992
20052
  if (propMeta.getter)
19993
20053
  continue;
20054
+ hasConformance = true;
19994
20055
  if (propMeta.flag && propMeta.initial) {
19995
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
20056
+ joinPatterns.push(`
20057
+ ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
19996
20058
  }
19997
20059
  else {
19998
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
20060
+ joinPatterns.push(`
20061
+ ?source ${iri(propMeta.predicate)} ?cfTarget_${propMeta.name} .`);
19999
20062
  }
20000
20063
  }
20001
20064
  }
20002
- // Fallback: initial-value filters
20003
- if (graphTraversalFilters.length === 0) {
20065
+ // Fallback: initial-value JOIN patterns
20066
+ if (!hasConformance) {
20004
20067
  for (const [, propMeta] of Object.entries(metadata.properties)) {
20005
20068
  if (propMeta.initial) {
20069
+ hasConformance = true;
20006
20070
  if (propMeta.flag) {
20007
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
20071
+ joinPatterns.push(`
20072
+ ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
20008
20073
  }
20009
20074
  else {
20010
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
20075
+ joinPatterns.push(`
20076
+ ?source ${iri(propMeta.predicate)} ?cfInitTarget_${propMeta.name} .`);
20011
20077
  }
20012
20078
  break;
20013
20079
  }
20014
20080
  }
20015
20081
  }
20016
20082
  // Fallback: open-world structural matching
20017
- if (graphTraversalFilters.length === 0) {
20018
- const structuralPredicates = [];
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 = [];
20019
20087
  for (const [, propMeta] of Object.entries(metadata.properties)) {
20020
20088
  if (propMeta.predicate) {
20021
- structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
20089
+ knownPredicates.push(iri(propMeta.predicate));
20022
20090
  }
20023
20091
  }
20024
20092
  if (metadata.relations) {
20025
20093
  for (const [, relMeta] of Object.entries(metadata.relations)) {
20026
20094
  if (relMeta.predicate) {
20027
- structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
20095
+ knownPredicates.push(iri(relMeta.predicate));
20028
20096
  }
20029
20097
  }
20030
20098
  }
20031
- if (structuralPredicates.length > 0) {
20032
- graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
20099
+ if (knownPredicates.length > 0) {
20100
+ joinPatterns.push(`
20101
+ { SELECT DISTINCT ?source WHERE { ?source ?cf_structPred ?cf_structTarget . FILTER(?cf_structPred IN (${knownPredicates.join(", ")})) } }`);
20033
20102
  }
20034
20103
  }
20035
- // User WHERE clause
20036
- const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
20037
- const whereConditions = [];
20038
- whereConditions.push(...graphTraversalFilters);
20039
- if (userWhereClause) {
20040
- whereConditions.push(userWhereClause);
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.
20172
+ */
20173
+ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
20174
+ if (!where)
20175
+ return { joins: [], filters: [] };
20176
+ const joins = [];
20177
+ const filters = [];
20178
+ for (const [propertyName, condition] of Object.entries(where)) {
20179
+ // 'base' maps to ?source
20180
+ if (propertyName === "base" || propertyName === "id") {
20181
+ if (Array.isArray(condition)) {
20182
+ const formatted = condition.map(v => iri(v)).join(", ");
20183
+ filters.push(`?source IN (${formatted})`);
20184
+ }
20185
+ else if (typeof condition === "object" && condition !== null) {
20186
+ const ops = condition;
20187
+ if (ops.not !== undefined) {
20188
+ if (Array.isArray(ops.not)) {
20189
+ const formatted = ops.not.map(v => iri(v)).join(", ");
20190
+ filters.push(`!(?source IN (${formatted}))`);
20191
+ }
20192
+ else {
20193
+ filters.push(`?source != ${iri(ops.not)}`);
20194
+ }
20195
+ }
20196
+ }
20197
+ else {
20198
+ filters.push(`?source = ${iri(String(condition))}`);
20199
+ }
20200
+ continue;
20201
+ }
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)) {
20225
+ const ops = condition;
20226
+ const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
20227
+ ops.lt !== undefined || ops.lte !== undefined ||
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} .`);
20233
+ }
20234
+ // NOT filters: no SPARQL-level filtering — handled in JS
20235
+ }
20236
+ else {
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
+ }
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))} .`);
20284
+ }
20285
+ }
20286
+ return { joins, filters };
20287
+ }
20288
+
20289
+ /**
20290
+ * Subscription Pool — deduplicates identical SPARQL subscriptions.
20291
+ *
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.
20296
+ *
20297
+ * Key: `perspectiveUUID + sparqlQuery`
20298
+ */
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);
20329
+ }
20330
+ return {
20331
+ initialResult,
20332
+ dispose: () => disposeSubscriber(key, subscriber),
20333
+ };
20334
+ }
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 */ }
20362
+ }
20363
+ }
20364
+ }
20365
+ finally {
20366
+ newEntry.hydrating = false;
20367
+ }
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();
20387
+ }
20388
+ pool.delete(key);
20041
20389
  }
20042
- whereConditions.push(`count(->link) > 0`);
20043
- const fullQuery = `
20044
- SELECT
20045
- id AS source,
20046
- uri AS source_uri,
20047
- ->link AS links
20048
- FROM node
20049
- WHERE ${whereConditions.join(' AND ')}
20050
- FETCH links
20051
- `.trim();
20052
- return fullQuery;
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
+ }
20399
+ }
20400
+ pool.clear();
20401
+ }
20402
+ /**
20403
+ * Get the current pool size (for testing).
20404
+ */
20405
+ function subscriptionPoolSize() {
20406
+ return pool.size;
20053
20407
  }
20054
20408
 
20055
20409
  /**
@@ -20082,7 +20436,7 @@ class ModelQueryBuilder {
20082
20436
  constructor(perspective, ctor, query) {
20083
20437
  this.queryParams = {};
20084
20438
  this.modelClassName = null;
20085
- this.useSurrealDBFlag = true;
20439
+ this.engineFlag = 'sparql';
20086
20440
  this.perspective = perspective;
20087
20441
  this.ctor = ctor;
20088
20442
  if (query)
@@ -20290,32 +20644,10 @@ class ModelQueryBuilder {
20290
20644
  return this;
20291
20645
  }
20292
20646
  /**
20293
- * Enables or disables SurrealDB query path.
20294
- *
20295
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
20296
- * @returns The query builder for chaining
20297
- *
20298
- * @example
20299
- * ```typescript
20300
- * // Use SurrealDB (default)
20301
- * const recipes = await Recipe.query(perspective)
20302
- * .where({ category: "Dessert" })
20303
- * .useSurrealDB(true)
20304
- * .get();
20305
- *
20306
- * // Use Prolog (legacy)
20307
- * const recipesProlog = await Recipe.query(perspective)
20308
- * .where({ category: "Dessert" })
20309
- * .useSurrealDB(false)
20310
- * .get();
20311
- * ```
20312
- *
20313
- * @remarks
20314
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
20315
- * if useSurrealDB(true) is set (default).
20647
+ * Sets the query engine to use.
20316
20648
  */
20317
- useSurrealDB(enabled = true) {
20318
- this.useSurrealDBFlag = enabled;
20649
+ engine(eng) {
20650
+ this.engineFlag = eng;
20319
20651
  return this;
20320
20652
  }
20321
20653
  /**
@@ -20332,10 +20664,8 @@ class ModelQueryBuilder {
20332
20664
  */
20333
20665
  async get() {
20334
20666
  let results;
20335
- if (this.useSurrealDBFlag) {
20336
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20337
- const result = await this.perspective.querySurrealDB(surrealQuery);
20338
- ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
20667
+ if (this.engineFlag === 'sparql') {
20668
+ results = await this.executeSparqlQuery();
20339
20669
  }
20340
20670
  else {
20341
20671
  const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
@@ -20344,6 +20674,29 @@ class ModelQueryBuilder {
20344
20674
  }
20345
20675
  return results;
20346
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
+ }
20347
20700
  /**
20348
20701
  * Returns the first matching instance, or `null` if none match.
20349
20702
  *
@@ -20367,7 +20720,7 @@ class ModelQueryBuilder {
20367
20720
  * Subscribes to the query and receives updates when results change.
20368
20721
  *
20369
20722
  * This method:
20370
- * 1. Creates and initializes a SurrealDB live query subscription (default)
20723
+ * 1. Creates and initializes a SPARQL live query subscription (default)
20371
20724
  * 2. Sets up the callback to process future updates
20372
20725
  * 3. Returns the initial results immediately
20373
20726
  *
@@ -20391,26 +20744,40 @@ class ModelQueryBuilder {
20391
20744
  * ```
20392
20745
  *
20393
20746
  * @remarks
20394
- * By default, this uses SurrealDB live queries for real-time updates.
20395
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
20747
+ * By default, this uses SPARQL live queries for real-time updates.
20748
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20396
20749
  */
20397
20750
  async subscribe(callback) {
20398
20751
  // Clean up any existing subscription
20399
20752
  this.dispose();
20400
20753
  const ctor = this.ctor;
20401
- if (this.useSurrealDBFlag) {
20402
- const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
20403
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20404
- const processResults = async (result) => {
20405
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20406
- callback(results);
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}`;
20407
20764
  };
20408
- this.currentSubscription.onResult(processResults);
20409
- // Process initial result
20410
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20411
- // Also invoke callback with initial results so subscribers see them
20412
- callback(results);
20413
- return results;
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;
20414
20781
  }
20415
20782
  else {
20416
20783
  const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
@@ -20421,11 +20788,26 @@ class ModelQueryBuilder {
20421
20788
  };
20422
20789
  this.currentSubscription.onResult(processResults);
20423
20790
  const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
20424
- // Also invoke callback with initial results so subscribers see them
20425
- callback(results);
20791
+ // Initial results returned via Promise only — callback is for subsequent updates
20426
20792
  return results;
20427
20793
  }
20428
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
+ }
20429
20811
  /**
20430
20812
  * Gets the total count of matching entities.
20431
20813
  *
@@ -20439,13 +20821,10 @@ class ModelQueryBuilder {
20439
20821
  * ```
20440
20822
  */
20441
20823
  async count() {
20442
- if (this.useSurrealDBFlag) {
20443
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20444
- const result = await this.perspective.querySurrealDB(surrealQuery);
20445
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
20446
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
20447
- // This ensures count() returns the same number as get().length
20448
- 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);
20449
20828
  return totalCount;
20450
20829
  }
20451
20830
  else {
@@ -20454,11 +20833,25 @@ class ModelQueryBuilder {
20454
20833
  return result?.[0]?.TotalCount || 0;
20455
20834
  }
20456
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
+ }
20457
20850
  /**
20458
20851
  * Subscribes to count updates for matching entities.
20459
20852
  *
20460
20853
  * This method:
20461
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
20854
+ * 1. Creates and initializes a SPARQL live query subscription for the count (default)
20462
20855
  * 2. Sets up the callback to process future count updates
20463
20856
  * 3. Returns the initial count immediately
20464
20857
  *
@@ -20482,22 +20875,22 @@ class ModelQueryBuilder {
20482
20875
  * ```
20483
20876
  *
20484
20877
  * @remarks
20485
- * By default, this uses SurrealDB live queries for real-time updates.
20486
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
20878
+ * By default, this uses SPARQL live queries for real-time updates.
20879
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20487
20880
  */
20488
20881
  async countSubscribe(callback) {
20489
20882
  // Clean up any existing subscription
20490
20883
  this.dispose();
20491
- if (this.useSurrealDBFlag) {
20492
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20493
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20884
+ if (this.engineFlag === 'sparql') {
20885
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20886
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20494
20887
  const processResults = async (result) => {
20495
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20888
+ const { totalCount } = await this.processSparqlResult(result);
20496
20889
  callback(totalCount);
20497
20890
  };
20498
20891
  this.currentSubscription.onResult(processResults);
20499
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20500
- callback(totalCount);
20892
+ const { totalCount } = await this.processSparqlResult(this.currentSubscription.result);
20893
+ // Initial count returned via Promise — callback for updates only
20501
20894
  return totalCount;
20502
20895
  }
20503
20896
  else {
@@ -20509,10 +20902,26 @@ class ModelQueryBuilder {
20509
20902
  };
20510
20903
  this.currentSubscription.onResult(processResults);
20511
20904
  const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
20512
- callback(initialCount);
20905
+ // Initial count returned via Promise — callback for subsequent updates only
20513
20906
  return initialCount;
20514
20907
  }
20515
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
+ }
20516
20925
  /**
20517
20926
  * Gets a page of results with pagination metadata.
20518
20927
  *
@@ -20530,10 +20939,10 @@ class ModelQueryBuilder {
20530
20939
  */
20531
20940
  async paginate(pageSize, pageNumber) {
20532
20941
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20533
- if (this.useSurrealDBFlag) {
20534
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20535
- const result = await this.perspective.querySurrealDB(surrealQuery);
20536
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
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);
20537
20946
  return { results, totalCount, pageSize, pageNumber };
20538
20947
  }
20539
20948
  else {
@@ -20543,11 +20952,25 @@ class ModelQueryBuilder {
20543
20952
  return { results, totalCount, pageSize, pageNumber };
20544
20953
  }
20545
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
+ }
20546
20969
  /**
20547
20970
  * Subscribes to paginated results updates.
20548
20971
  *
20549
20972
  * This method:
20550
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
20973
+ * 1. Creates and initializes a SPARQL live query subscription for the paginated results (default)
20551
20974
  * 2. Sets up the callback to process future page updates
20552
20975
  * 3. Returns the initial page immediately
20553
20976
  *
@@ -20573,24 +20996,24 @@ class ModelQueryBuilder {
20573
20996
  * ```
20574
20997
  *
20575
20998
  * @remarks
20576
- * By default, this uses SurrealDB live queries for real-time updates.
20577
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
20999
+ * By default, this uses SPARQL live queries for real-time updates.
21000
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20578
21001
  */
20579
21002
  async paginateSubscribe(pageSize, pageNumber, callback) {
20580
21003
  // Clean up any existing subscription
20581
21004
  this.dispose();
20582
21005
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20583
- if (this.useSurrealDBFlag) {
20584
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20585
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
21006
+ if (this.engineFlag === 'sparql') {
21007
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
21008
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20586
21009
  const processResults = async (result) => {
20587
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
21010
+ const { results, totalCount } = await this.processSparqlResult(result, paginationQuery);
20588
21011
  callback({ results, totalCount, pageSize, pageNumber });
20589
21012
  };
20590
21013
  this.currentSubscription.onResult(processResults);
20591
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
21014
+ const { results, totalCount } = await this.processSparqlResult(this.currentSubscription.result, paginationQuery);
20592
21015
  const initialPage = { results, totalCount, pageSize, pageNumber };
20593
- callback(initialPage);
21016
+ // Initial page returned via Promise — callback for subsequent updates only
20594
21017
  return initialPage;
20595
21018
  }
20596
21019
  else {
@@ -20603,17 +21026,31 @@ class ModelQueryBuilder {
20603
21026
  this.currentSubscription.onResult(processResults);
20604
21027
  const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
20605
21028
  const initialPrologPage = { results, totalCount, pageSize, pageNumber };
20606
- callback(initialPrologPage);
21029
+ // Initial page returned via Promise — callback for subsequent updates only
20607
21030
  return initialPrologPage;
20608
21031
  }
20609
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
+ }
20610
21047
  }
20611
21048
 
20612
21049
  /**
20613
21050
  * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
20614
21051
  *
20615
21052
  * Pure / stateless functions that populate Ad4mModel instances from
20616
- * raw link arrays, Prolog tuples, or SurrealDB rows. None of these
21053
+ * raw link arrays, Prolog tuples, or query results. None of these
20617
21054
  * functions depend on the `Ad4mModel` class at runtime — they accept
20618
21055
  * the instance, metadata, or perspective as explicit parameters.
20619
21056
  */
@@ -20708,7 +21145,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
20708
21145
  if (propMeta.resolveLanguage != null &&
20709
21146
  propMeta.resolveLanguage !== 'literal' &&
20710
21147
  typeof target === 'string' &&
20711
- !target.startsWith('literal://')) {
21148
+ !target.startsWith('literal:')) {
20712
21149
  try {
20713
21150
  const expression = await perspective.getExpression(target);
20714
21151
  if (expression) {
@@ -20727,7 +21164,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
20727
21164
  // Literal URI parsing
20728
21165
  else if (propMeta.resolveLanguage === 'literal' &&
20729
21166
  typeof target === 'string' &&
20730
- target.startsWith('literal://')) {
21167
+ target.startsWith('literal:')) {
20731
21168
  try {
20732
21169
  const parsed = Literal.fromUrl(target).get();
20733
21170
  value = parsed.data !== undefined ? parsed.data : parsed;
@@ -20959,10 +21396,10 @@ async function assignValuesToInstance(perspective, instance, values) {
20959
21396
  Object.assign(instance, writableProps);
20960
21397
  }
20961
21398
  // ──────────────────────────────────────────────────────────
20962
- // SurrealQL custom getter evaluation
21399
+ // SPARQL custom getter evaluation
20963
21400
  // ──────────────────────────────────────────────────────────
20964
21401
  /**
20965
- * Builds a SurrealQL conformance getter for a relation whose `target` model
21402
+ * Builds a SPARQL conformance getter for a relation whose `target` model
20966
21403
  * is known but no explicit `getter` string was supplied.
20967
21404
  *
20968
21405
  * The generated getter traverses outgoing links matching the relation's
@@ -20974,7 +21411,7 @@ async function assignValuesToInstance(perspective, instance, values) {
20974
21411
  *
20975
21412
  * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
20976
21413
  * @param targetClass - The target model class (result of calling the `target()` thunk)
20977
- * @returns A SurrealQL expression string, or `undefined` if no conformance
21414
+ * @returns A SPARQL expression string, or `undefined` if no conformance
20978
21415
  * conditions could be derived from the target model.
20979
21416
  */
20980
21417
  function buildConformanceGetter(relationPredicate, targetClass) {
@@ -20993,7 +21430,7 @@ function buildConformanceGetter(relationPredicate, targetClass) {
20993
21430
  * getter is auto-generated from the target model's metadata (unless `filter: false`).
20994
21431
  */
20995
21432
  async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
20996
- const safeBaseExpression = formatSurrealValue(instance.id);
21433
+ `<${instance.id}>`;
20997
21434
  // Build projection filter — when requestedProperties is active, only
20998
21435
  // evaluate getters for fields that are requested (or included).
20999
21436
  const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
@@ -21004,12 +21441,28 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21004
21441
  continue;
21005
21442
  if (propMeta.getter) {
21006
21443
  try {
21007
- // Replace 'Base' placeholder with actual base expression
21008
- const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
21009
- // Query from node table to have graph traversal context
21010
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
21011
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
21012
- instance[propName] = result[0].value;
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)}`);
21013
21466
  }
21014
21467
  }
21015
21468
  catch (error) {
@@ -21025,12 +21478,11 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21025
21478
  const meta = relMeta;
21026
21479
  // Determine the getter to execute:
21027
21480
  // 1. Explicit `getter` always wins
21028
- // 2. `where` clause → compile DSL to SurrealQL getter
21029
- // 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
21030
21482
  // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
21031
- // because buildConformanceGetter traverses outgoing links (->link) which is
21032
- // wrong for reverse relations. Their values are already populated by the
21033
- // reverse link lookup in instancesFromSurrealResult / getData.
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.
21034
21486
  let getter = meta.getter;
21035
21487
  if (!getter && meta.where && meta.direction !== 'reverse') {
21036
21488
  try {
@@ -21038,14 +21490,35 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21038
21490
  const targetMetadata = TargetClass
21039
21491
  ? TargetClass.getModelMetadata?.() ?? null
21040
21492
  : null;
21041
- const conditions = compileWhereClause(meta.where, targetMetadata);
21042
- if (conditions.length > 0) {
21043
- const escapedPred = escapeSurrealString(meta.predicate);
21044
- getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
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;
21045
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
21046
21519
  }
21047
21520
  catch (e) {
21048
- // Target metadata may not be available yet
21521
+ console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
21049
21522
  }
21050
21523
  }
21051
21524
  if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
@@ -21062,23 +21535,57 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21062
21535
  }
21063
21536
  if (getter) {
21064
21537
  try {
21065
- // Replace 'Base' placeholder with actual base expression
21066
- const query = getter.replace(/Base/g, safeBaseExpression);
21067
- const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
21068
- // Query from node table to have graph traversal context
21069
- const result = await perspective.querySurrealDB(fullQuery);
21070
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
21071
- // Filter out 'None' from relation results
21072
- const value = result[0].value;
21073
- instance[relName] = Array.isArray(value)
21074
- ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
21075
- : value;
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)}`);
21076
21554
  }
21077
21555
  }
21078
21556
  catch (error) {
21079
21557
  console.warn(`Failed to evaluate getter for ${relName}:`, error);
21080
21558
  }
21081
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
+ }
21082
21589
  }
21083
21590
  }
21084
21591
  /**
@@ -21593,7 +22100,7 @@ class Ad4mModel {
21593
22100
  * const recipe = new Recipe(perspective);
21594
22101
  *
21595
22102
  * // Create with specific base expression
21596
- * const recipe = new Recipe(perspective, "literal://...");
22103
+ * const recipe = new Recipe(perspective, "literal:...");
21597
22104
  * ```
21598
22105
  */
21599
22106
  constructor(perspective, baseExpression) {
@@ -21820,19 +22327,13 @@ class Ad4mModel {
21820
22327
  }
21821
22328
  async getData(opts) {
21822
22329
  // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
21823
- // Use SurrealDB for data queries
22330
+ // Use SPARQL for data queries
21824
22331
  try {
21825
22332
  const ctor = this.constructor;
21826
22333
  const metadata = ctor.getModelMetadata();
21827
22334
  // Query for all links from this specific node (base expression)
21828
- const safeBaseExpression = formatSurrealValue(this._baseExpression);
21829
- const linksQuery = `
21830
- SELECT id, predicate, out.uri AS target, author, timestamp
21831
- FROM link
21832
- WHERE in.uri = ${safeBaseExpression}
21833
- ORDER BY timestamp ASC
21834
- `;
21835
- const links = await this._perspective.querySurrealDB(linksQuery);
22335
+ const linksQuery = buildSPARQLGetDataQuery(this._baseExpression);
22336
+ const links = await this._perspective.querySparql(linksQuery);
21836
22337
  if (links && links.length > 0) {
21837
22338
  // Core hydration: properties (latest-wins), relations, timestamps/author
21838
22339
  const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
@@ -21857,7 +22358,7 @@ class Ad4mModel {
21857
22358
  this[relName] = sourceIds;
21858
22359
  }
21859
22360
  }
21860
- // Evaluate SurrealQL getters
22361
+ // Evaluate SPARQL getters
21861
22362
  const getterOpts = opts?.properties || opts?.include
21862
22363
  ? { requestedProperties: opts?.properties, include: opts?.include }
21863
22364
  : undefined;
@@ -21868,7 +22369,7 @@ class Ad4mModel {
21868
22369
  }
21869
22370
  }
21870
22371
  catch (e) {
21871
- console.error(`SurrealDB getData also failed for ${this._baseExpression}:`, e);
22372
+ console.error(`SPARQL getData also failed for ${this._baseExpression}:`, e);
21872
22373
  }
21873
22374
  this.takeSnapshot();
21874
22375
  return this;
@@ -21898,13 +22399,13 @@ class Ad4mModel {
21898
22399
  return fullQuery;
21899
22400
  }
21900
22401
  /**
21901
- * Generates a SurrealQL query from a Query object.
22402
+ * Generates a SPARQL query from a Query object.
21902
22403
  *
21903
22404
  * @description
21904
- * This method translates high-level query parameters into a SurrealQL query string
21905
- * that can be executed against the SurrealDB backend. Unlike Prolog queries which
21906
- * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
21907
- * stored in SurrealDB.
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.
21908
22409
  *
21909
22410
  * The generated query uses a CTE (Common Table Expression) pattern:
21910
22411
  * 1. First, identify candidate base expressions by filtering links based on where conditions
@@ -21912,7 +22413,7 @@ class Ad4mModel {
21912
22413
  * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
21913
22414
  *
21914
22415
  * Key architectural notes:
21915
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
22416
+ * - SPARQL stores only raw links (source, predicate, target, author, timestamp)
21916
22417
  * - No SDNA knowledge at the database level
21917
22418
  * - Properties are resolved via subqueries that look for links with specific predicates
21918
22419
  * - Relations are similar but return multiple values instead of one
@@ -21920,11 +22421,11 @@ class Ad4mModel {
21920
22421
  *
21921
22422
  * @param perspective - The perspective to query (used for metadata extraction)
21922
22423
  * @param query - Query parameters (where, order, limit, offset, properties, relations)
21923
- * @returns Complete SurrealQL query string ready for execution
22424
+ * @returns Complete SPARQL query string ready for execution
21924
22425
  *
21925
22426
  * @example
21926
22427
  * ```typescript
21927
- * const query = Recipe.queryToSurrealQL(perspective, {
22428
+ * const query = Recipe.queryToSPARQL(perspective, {
21928
22429
  * where: { name: "Pasta", rating: { gt: 4 } },
21929
22430
  * order: { timestamp: "DESC" },
21930
22431
  * limit: 10
@@ -21933,10 +22434,10 @@ class Ad4mModel {
21933
22434
  * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
21934
22435
  * ```
21935
22436
  */
21936
- static async queryToSurrealQL(perspective, query) {
22437
+ static async queryToSPARQL(perspective, query) {
21937
22438
  const metadata = this.getModelMetadata();
21938
22439
  const allRelMeta = getRelationsMetadata(this);
21939
- return buildSurrealQLQuery(metadata, allRelMeta, query, this);
22440
+ return buildSPARQLQuery(metadata, allRelMeta, query, this);
21940
22441
  }
21941
22442
  static async instancesFromPrologResult(perspective, query, result) {
21942
22443
  if (!result?.[0]?.AllInstances)
@@ -21981,16 +22482,16 @@ class Ad4mModel {
21981
22482
  return { results: instances, totalCount: result[0].TotalCount };
21982
22483
  }
21983
22484
  /**
21984
- * Converts SurrealDB query results to Ad4mModel instances.
22485
+ * Converts SPARQL query results to Ad4mModel instances.
21985
22486
  *
21986
22487
  * @param perspective - The perspective context
21987
22488
  * @param query - The query parameters used
21988
- * @param result - Array of result objects from SurrealDB
22489
+ * @param result - Array of result objects from SPARQL
21989
22490
  * @returns Promise resolving to results with total count
21990
22491
  *
21991
22492
  * @internal
21992
22493
  */
21993
- static async instancesFromSurrealResult(perspective, query, result) {
22494
+ static async instancesFromQueryResult(perspective, query, result) {
21994
22495
  if (!result || result.length === 0)
21995
22496
  return { results: [], totalCount: 0 };
21996
22497
  const metadata = this.getModelMetadata();
@@ -22011,33 +22512,25 @@ class Ad4mModel {
22011
22512
  }
22012
22513
  const links = row.links || [];
22013
22514
  const instance = new this(perspective, base);
22014
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
22015
- await hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
22016
- // When specific properties are requested, delete unrequested properties
22017
- // so they return undefined instead of their constructor defaults (e.g. 0, [])
22018
- if (requestedProperties.length > 0) {
22019
- const requested = new Set(requestedProperties);
22020
- for (const propName of Object.keys(metadata.properties)) {
22021
- if (!requested.has(propName)) {
22022
- delete instance[propName];
22023
- }
22024
- }
22025
- for (const relName of Object.keys(metadata.relations)) {
22026
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
22027
- delete instance[relName];
22028
- }
22029
- }
22030
- // Also strip metadata fields unless explicitly requested
22031
- for (const metaField of ['author', 'createdAt', 'updatedAt']) {
22032
- if (!requested.has(metaField)) {
22033
- 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);
22034
22523
  }
22035
22524
  }
22036
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.
22037
22530
  instances.push(instance);
22038
22531
  }
22039
22532
  catch (error) {
22040
- console.error(`Failed to process SurrealDB instance ${base}:`, error);
22533
+ console.error(`Failed to process SPARQL instance ${base}:`, error);
22041
22534
  }
22042
22535
  }
22043
22536
  // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
@@ -22070,17 +22563,19 @@ class Ad4mModel {
22070
22563
  for (const instance of instances) {
22071
22564
  await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
22072
22565
  }
22073
- // Filter by where conditions that couldn't be filtered in SQL
22566
+ // Filter by where conditions that couldn't be filtered in SPARQL
22074
22567
  // This includes:
22075
22568
  // - author/timestamp (computed from grouped links)
22076
22569
  // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
22077
- // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
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
22078
22573
  let filteredInstances = instances;
22079
22574
  if (query.where) {
22080
22575
  filteredInstances = instances.filter(instance => {
22081
22576
  for (const [propertyName, condition] of Object.entries(query.where)) {
22082
- // Skip 'base' as it's filtered in SQL
22083
- if (propertyName === 'base')
22577
+ // Skip 'base'/'id' as it's filtered in SPARQL
22578
+ if (propertyName === 'base' || propertyName === 'id')
22084
22579
  continue;
22085
22580
  // For author and timestamp, always filter in JS
22086
22581
  if (propertyName === 'author' || propertyName === 'timestamp') {
@@ -22089,19 +22584,20 @@ class Ad4mModel {
22089
22584
  }
22090
22585
  continue;
22091
22586
  }
22092
- // For regular properties, only filter comparison operators in JS
22093
- // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
22094
- if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
22095
- const ops = condition;
22096
- // Check if any comparison operators are present
22097
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
22098
- ops.lt !== undefined || ops.lte !== undefined ||
22099
- ops.between !== undefined || ops.contains !== undefined;
22100
- if (hasComparisonOps) {
22101
- if (!matchesCondition(instance[propertyName], condition)) {
22102
- return false;
22103
- }
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;
22104
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;
22105
22601
  }
22106
22602
  }
22107
22603
  return true;
@@ -22153,6 +22649,28 @@ class Ad4mModel {
22153
22649
  const end = query.limit ? start + query.limit : undefined;
22154
22650
  paginatedInstances = filteredInstances.slice(start, end);
22155
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
+ }
22156
22674
  // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
22157
22675
  if (query.include && paginatedInstances.length > 0) {
22158
22676
  await hydrateRelations(this, paginatedInstances, perspective, query.include);
@@ -22177,15 +22695,15 @@ class Ad4mModel {
22177
22695
  *
22178
22696
  * @param perspective - The perspective to search in
22179
22697
  * @param query - Optional query parameters to filter results
22180
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22698
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22181
22699
  * @returns Array of matching models
22182
22700
  *
22183
22701
  * @example
22184
22702
  * ```typescript
22185
- * // Get all recipes (uses SurrealDB by default)
22703
+ * // Get all recipes (uses SPARQL by default)
22186
22704
  * const allRecipes = await Recipe.findAll(perspective);
22187
22705
  *
22188
- * // Get recipes with specific criteria (uses SurrealDB)
22706
+ * // Get recipes with specific criteria (uses SPARQL)
22189
22707
  * const recipes = await Recipe.findAll(perspective, {
22190
22708
  * where: {
22191
22709
  * name: "Pasta",
@@ -22199,14 +22717,23 @@ class Ad4mModel {
22199
22717
  * const recipesProlog = await Recipe.findAll(perspective, {}, false);
22200
22718
  * ```
22201
22719
  */
22202
- static async findAll(perspective, query = {}, useSurrealDB = true) {
22720
+ static async findAll(perspective, query = {}, engine = 'sparql') {
22203
22721
  if (query.properties && query.properties.length === 0) {
22204
22722
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
22205
22723
  }
22206
- if (useSurrealDB) {
22207
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22208
- const result = await perspective.querySurrealDB(surrealQuery);
22209
- const { results } = await this.instancesFromSurrealResult(perspective, query, result);
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);
22210
22737
  return results;
22211
22738
  }
22212
22739
  else {
@@ -22223,7 +22750,7 @@ class Ad4mModel {
22223
22750
  *
22224
22751
  * @param perspective - The perspective to search in
22225
22752
  * @param query - Optional query parameters to filter results
22226
- * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
22753
+ * @param useSPARQL - Whether to use SPARQL (default: true) or Prolog (legacy)
22227
22754
  * @returns The first matching instance, or `null`
22228
22755
  *
22229
22756
  * @example
@@ -22236,9 +22763,9 @@ class Ad4mModel {
22236
22763
  * }
22237
22764
  * ```
22238
22765
  */
22239
- static async findOne(perspective, query = {}, useSurrealDB = true) {
22766
+ static async findOne(perspective, query = {}, engine = 'sparql') {
22240
22767
  const limitedQuery = { ...query, limit: 1 };
22241
- const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
22768
+ const results = await this.findAll(perspective, limitedQuery, engine);
22242
22769
  return results[0] ?? null;
22243
22770
  }
22244
22771
  /**
@@ -22246,7 +22773,7 @@ class Ad4mModel {
22246
22773
  *
22247
22774
  * @param perspective - The perspective to search in
22248
22775
  * @param query - Optional query parameters to filter results
22249
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22776
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22250
22777
  * @returns Object containing results array and total count
22251
22778
  *
22252
22779
  * @example
@@ -22261,11 +22788,15 @@ class Ad4mModel {
22261
22788
  * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
22262
22789
  * ```
22263
22790
  */
22264
- static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
22265
- if (useSurrealDB) {
22266
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22267
- const result = await perspective.querySurrealDB(surrealQuery);
22268
- return await this.instancesFromSurrealResult(perspective, query, result);
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);
22269
22800
  }
22270
22801
  else {
22271
22802
  const prologQuery = await this.queryToProlog(perspective, query);
@@ -22280,7 +22811,7 @@ class Ad4mModel {
22280
22811
  * @param pageSize - Number of items per page
22281
22812
  * @param pageNumber - Which page to retrieve (1-based)
22282
22813
  * @param query - Optional additional query parameters
22283
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22814
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22284
22815
  * @returns Paginated results with metadata
22285
22816
  *
22286
22817
  * @example
@@ -22294,12 +22825,16 @@ class Ad4mModel {
22294
22825
  * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
22295
22826
  * ```
22296
22827
  */
22297
- static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
22828
+ static async paginate(perspective, pageSize, pageNumber, query, engine = 'sparql') {
22298
22829
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
22299
- if (useSurrealDB) {
22300
- const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
22301
- const result = await perspective.querySurrealDB(surrealQuery);
22302
- const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
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);
22303
22838
  return { results, totalCount, pageSize, pageNumber };
22304
22839
  }
22305
22840
  else {
@@ -22328,28 +22863,28 @@ class Ad4mModel {
22328
22863
  return fullQuery;
22329
22864
  }
22330
22865
  /**
22331
- * Generates a SurrealQL COUNT query for the model.
22866
+ * Generates a SPARQL COUNT query for the model.
22332
22867
  *
22333
22868
  * @param perspective - The perspective context
22334
22869
  * @param query - Query parameters to filter the count
22335
- * @returns SurrealQL COUNT query string
22870
+ * @returns SPARQL COUNT query string
22336
22871
  *
22337
22872
  * @private
22338
22873
  */
22339
- static async countQueryToSurrealQL(perspective, query) {
22874
+ static async countQueryToSPARQL(perspective, query) {
22340
22875
  // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
22341
22876
  // We'll count the number of rows returned (one row per source)
22342
22877
  const countQuery = { ...query };
22343
22878
  delete countQuery.limit;
22344
22879
  delete countQuery.offset;
22345
- return await this.queryToSurrealQL(perspective, countQuery);
22880
+ return await this.queryToSPARQL(perspective, countQuery);
22346
22881
  }
22347
22882
  /**
22348
22883
  * Gets a count of all matching instances.
22349
22884
  *
22350
22885
  * @param perspective - The perspective to search in
22351
22886
  * @param query - Optional query parameters to filter results
22352
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22887
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22353
22888
  * @returns Total count of matching entities
22354
22889
  *
22355
22890
  * @example
@@ -22363,14 +22898,15 @@ class Ad4mModel {
22363
22898
  * const countProlog = await Recipe.count(perspective, {}, false);
22364
22899
  * ```
22365
22900
  */
22366
- static async count(perspective, query = {}, useSurrealDB = true) {
22367
- if (useSurrealDB) {
22368
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22369
- const result = await perspective.querySurrealDB(surrealQuery);
22370
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
22371
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
22372
- // This ensures count() returns the same number as findAll().length
22373
- const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
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);
22374
22910
  return totalCount;
22375
22911
  }
22376
22912
  else {
@@ -22388,7 +22924,7 @@ class Ad4mModel {
22388
22924
  const actions = this.generatePropertySetterAction(key, metadata);
22389
22925
  // Get resolve language from metadata (replaces Prolog query)
22390
22926
  let resolveLanguage = metadata.resolveLanguage;
22391
- // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
22927
+ // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
22392
22928
  if (value === undefined || value === null || value === "") {
22393
22929
  return;
22394
22930
  }
@@ -23255,6 +23791,16 @@ input CapabilityInput {
23255
23791
  with: ResourceInput!
23256
23792
  }
23257
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
+
23258
23804
  scalar DateTime
23259
23805
 
23260
23806
  type EntanglementProof {
@@ -23663,9 +24209,9 @@ type Query {
23663
24209
  perspective(uuid: String!): PerspectiveHandle
23664
24210
  perspectiveQueryLinks(query: LinkQuery!, uuid: String!): [LinkExpression!]
23665
24211
  perspectiveQueryProlog(query: String!, uuid: String!): String!
23666
- perspectiveQuerySurrealDB(query: String!, uuid: String!): String!
23667
24212
  perspectiveSnapshot(uuid: String!): Perspective
23668
24213
  perspectives: [PerspectiveHandle!]!
24214
+ runtimeComputeLog(limit: Float, since: String, userEmail: String): [ComputeLogEntry!]!
23669
24215
  runtimeFreeHostingEnabled: Boolean!
23670
24216
  runtimeFriendStatus(did: String!): PerspectiveExpression
23671
24217
  runtimeFriends: [String!]!
@@ -24140,6 +24686,49 @@ PaymentRequestResult = __decorate([
24140
24686
  ObjectType(),
24141
24687
  __metadata("design:paramtypes", [Boolean, String])
24142
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);
24143
24732
  /**
24144
24733
  * Resolver classes are used here to define the GraphQL schema
24145
24734
  * (through the type-graphql annotations)
@@ -24360,6 +24949,9 @@ let RuntimeResolver = class RuntimeResolver {
24360
24949
  runtimeHostingUserInfo() {
24361
24950
  return new HostingUserInfo("test@example.com", "100000000", null, false);
24362
24951
  }
24952
+ runtimeComputeLog(since, limit, userEmail) {
24953
+ return [];
24954
+ }
24363
24955
  runtimeSetHotWalletAddress(address) {
24364
24956
  return true;
24365
24957
  }
@@ -24742,6 +25334,15 @@ __decorate([
24742
25334
  __metadata("design:paramtypes", []),
24743
25335
  __metadata("design:returntype", HostingUserInfo)
24744
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);
24745
25346
  __decorate([
24746
25347
  Mutation(),
24747
25348
  __param(0, Arg()),
@@ -24829,4 +25430,4 @@ RuntimeResolver = __decorate([
24829
25430
  Resolver()
24830
25431
  ], RuntimeResolver);
24831
25432
 
24832
- 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, buildGraphTraversalWhereClause, buildLimitQuery, buildModelFromJSONSchema, buildOffsetQuery, buildOrderQuery, buildParentQuery, buildPropertiesQuery, buildSDNA, buildSHACL, buildSurrealQLQuery, buildWhereQuery, capSentence, determineNamespace, determinePredicate, escapeSurrealString, evaluateCustomGettersForInstance, exprRef2String, formatList, generatePrologFacts, getDefaultValueForType, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hydrateFromLinks, hydratePropertyValue, hydrateRelations, isArrayType, isExpression, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, matchesCondition, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, resolveParentPredicate, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
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 };