@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.cjs CHANGED
@@ -4310,8 +4310,10 @@ class Literal {
4310
4310
  _Literal_url.set(this, void 0);
4311
4311
  }
4312
4312
  static fromUrl(url) {
4313
- if (!url || !url.startsWith("literal://"))
4313
+ if (!url || !url.startsWith("literal:"))
4314
4314
  throw new Error("Can't create Literal from non-literal URL");
4315
+ if (url.startsWith("literal://"))
4316
+ throw new Error("literal:// format is no longer supported. Use literal: instead.");
4315
4317
  const l = new Literal();
4316
4318
  __classPrivateFieldSet$b(l, _Literal_url, url, "f");
4317
4319
  return l;
@@ -4341,17 +4343,16 @@ class Literal {
4341
4343
  encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$b(this, _Literal_literal, "f")))}`;
4342
4344
  break;
4343
4345
  }
4344
- return `literal://${encoded}`;
4346
+ return `literal:${encoded}`;
4345
4347
  }
4346
4348
  get() {
4347
4349
  if (__classPrivateFieldGet$b(this, _Literal_literal, "f"))
4348
4350
  return __classPrivateFieldGet$b(this, _Literal_literal, "f");
4349
4351
  if (!__classPrivateFieldGet$b(this, _Literal_url, "f"))
4350
4352
  throw new Error("Can't render empty Literal");
4351
- if (!__classPrivateFieldGet$b(this, _Literal_url, "f").startsWith("literal://"))
4353
+ if (!__classPrivateFieldGet$b(this, _Literal_url, "f").startsWith("literal:"))
4352
4354
  throw new Error("Can't render Literal from non-literal URL");
4353
- // get rid of "literal://"
4354
- const body = __classPrivateFieldGet$b(this, _Literal_url, "f").substring(10);
4355
+ const body = __classPrivateFieldGet$b(this, _Literal_url, "f").substring(8);
4355
4356
  if (body.startsWith("string:")) {
4356
4357
  return decodeURIComponent(body.substring(7));
4357
4358
  }
@@ -4481,12 +4482,12 @@ class Subject {
4481
4482
  Object.defineProperty(this, p, {
4482
4483
  configurable: true,
4483
4484
  get: async () => {
4484
- // Use SurrealDB for data queries
4485
+ // Use SPARQL for data queries
4485
4486
  try {
4486
- return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), p);
4487
+ return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getPropertyValueViaSparql(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), p);
4487
4488
  }
4488
4489
  catch (err) {
4489
- console.warn(`Failed to get property ${p} via SurrealDB:`, err);
4490
+ console.warn(`Failed to get property ${p} via SPARQL:`, err);
4490
4491
  return undefined;
4491
4492
  }
4492
4493
  }
@@ -4520,12 +4521,12 @@ class Subject {
4520
4521
  Object.defineProperty(this, c, {
4521
4522
  configurable: true,
4522
4523
  get: async () => {
4523
- // Use SurrealDB for data queries
4524
+ // Use SPARQL for data queries
4524
4525
  try {
4525
- return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getRelationValuesViaSurreal(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), c);
4526
+ return await __classPrivateFieldGet$a(this, _Subject_perspective, "f").getRelationValuesViaSparql(__classPrivateFieldGet$a(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$a(this, _Subject_subjectClassName, "f"), c);
4526
4527
  }
4527
4528
  catch (err) {
4528
- console.warn(`Failed to get relation ${c} via SurrealDB:`, err);
4529
+ console.warn(`Failed to get relation ${c} via SPARQL:`, err);
4529
4530
  return [];
4530
4531
  }
4531
4532
  }
@@ -4663,7 +4664,7 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
4663
4664
  // Optional properties (required: false) are excluded — they should
4664
4665
  // remain unset (undefined) until explicitly assigned.
4665
4666
  const effectiveInitial = initial
4666
- ?? (required && writable && !flag && through ? "literal://string:" : undefined);
4667
+ ?? (required && writable && !flag && through ? "literal:string:" : undefined);
4667
4668
  if (effectiveInitial) {
4668
4669
  constructorActions.push({
4669
4670
  action: "addLink",
@@ -4949,7 +4950,7 @@ class SHACLShape {
4949
4950
  links.push({
4950
4951
  source: this.nodeShapeUri,
4951
4952
  predicate: "ad4m://constructor",
4952
- target: `literal://string:${JSON.stringify(this.constructor_actions)}`
4953
+ target: `literal:string:${JSON.stringify(this.constructor_actions)}`
4953
4954
  });
4954
4955
  }
4955
4956
  // Destructor actions — same rationale as constructor.
@@ -4957,7 +4958,7 @@ class SHACLShape {
4957
4958
  links.push({
4958
4959
  source: this.nodeShapeUri,
4959
4960
  predicate: "ad4m://destructor",
4960
- target: `literal://string:${JSON.stringify(this.destructor_actions)}`
4961
+ target: `literal:string:${JSON.stringify(this.destructor_actions)}`
4961
4962
  });
4962
4963
  }
4963
4964
  // Property shapes (each gets a named URI: {namespace}/{ClassName}.{propertyName})
@@ -5007,42 +5008,42 @@ class SHACLShape {
5007
5008
  links.push({
5008
5009
  source: propShapeId,
5009
5010
  predicate: "sh://minCount",
5010
- target: `literal://${prop.minCount}^^xsd:integer`
5011
+ target: `literal:${prop.minCount}^^xsd:integer`
5011
5012
  });
5012
5013
  }
5013
5014
  if (prop.maxCount !== undefined) {
5014
5015
  links.push({
5015
5016
  source: propShapeId,
5016
5017
  predicate: "sh://maxCount",
5017
- target: `literal://${prop.maxCount}^^xsd:integer`
5018
+ target: `literal:${prop.maxCount}^^xsd:integer`
5018
5019
  });
5019
5020
  }
5020
5021
  if (prop.pattern) {
5021
5022
  links.push({
5022
5023
  source: propShapeId,
5023
5024
  predicate: "sh://pattern",
5024
- target: `literal://${prop.pattern}`
5025
+ target: `literal:${prop.pattern}`
5025
5026
  });
5026
5027
  }
5027
5028
  if (prop.minInclusive !== undefined) {
5028
5029
  links.push({
5029
5030
  source: propShapeId,
5030
5031
  predicate: "sh://minInclusive",
5031
- target: `literal://${prop.minInclusive}`
5032
+ target: `literal:${prop.minInclusive}`
5032
5033
  });
5033
5034
  }
5034
5035
  if (prop.maxInclusive !== undefined) {
5035
5036
  links.push({
5036
5037
  source: propShapeId,
5037
5038
  predicate: "sh://maxInclusive",
5038
- target: `literal://${prop.maxInclusive}`
5039
+ target: `literal:${prop.maxInclusive}`
5039
5040
  });
5040
5041
  }
5041
5042
  if (prop.hasValue) {
5042
5043
  links.push({
5043
5044
  source: propShapeId,
5044
5045
  predicate: "sh://hasValue",
5045
- target: `literal://${prop.hasValue}`
5046
+ target: `literal:${prop.hasValue}`
5046
5047
  });
5047
5048
  }
5048
5049
  // AD4M-specific metadata
@@ -5050,21 +5051,21 @@ class SHACLShape {
5050
5051
  links.push({
5051
5052
  source: propShapeId,
5052
5053
  predicate: "ad4m://local",
5053
- target: `literal://${prop.local}`
5054
+ target: `literal:${prop.local}`
5054
5055
  });
5055
5056
  }
5056
5057
  if (prop.writable !== undefined) {
5057
5058
  links.push({
5058
5059
  source: propShapeId,
5059
5060
  predicate: "ad4m://writable",
5060
- target: `literal://${prop.writable}`
5061
+ target: `literal:${prop.writable}`
5061
5062
  });
5062
5063
  }
5063
5064
  if (prop.resolveLanguage) {
5064
5065
  links.push({
5065
5066
  source: propShapeId,
5066
5067
  predicate: "ad4m://resolveLanguage",
5067
- target: `literal://string:${prop.resolveLanguage}`
5068
+ target: `literal:string:${prop.resolveLanguage}`
5068
5069
  });
5069
5070
  }
5070
5071
  // AD4M-specific actions
@@ -5072,35 +5073,35 @@ class SHACLShape {
5072
5073
  links.push({
5073
5074
  source: propShapeId,
5074
5075
  predicate: "ad4m://setter",
5075
- target: `literal://string:${JSON.stringify(prop.setter)}`
5076
+ target: `literal:string:${JSON.stringify(prop.setter)}`
5076
5077
  });
5077
5078
  }
5078
5079
  if (prop.adder && prop.adder.length > 0) {
5079
5080
  links.push({
5080
5081
  source: propShapeId,
5081
5082
  predicate: "ad4m://adder",
5082
- target: `literal://string:${JSON.stringify(prop.adder)}`
5083
+ target: `literal:string:${JSON.stringify(prop.adder)}`
5083
5084
  });
5084
5085
  }
5085
5086
  if (prop.remover && prop.remover.length > 0) {
5086
5087
  links.push({
5087
5088
  source: propShapeId,
5088
5089
  predicate: "ad4m://remover",
5089
- target: `literal://string:${JSON.stringify(prop.remover)}`
5090
+ target: `literal:string:${JSON.stringify(prop.remover)}`
5090
5091
  });
5091
5092
  }
5092
5093
  if (prop.getter) {
5093
5094
  links.push({
5094
5095
  source: propShapeId,
5095
5096
  predicate: "ad4m://getter",
5096
- target: `literal://string:${prop.getter}`
5097
+ target: `literal:string:${prop.getter}`
5097
5098
  });
5098
5099
  }
5099
5100
  if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {
5100
5101
  links.push({
5101
5102
  source: propShapeId,
5102
5103
  predicate: "ad4m://conformanceConditions",
5103
- target: `literal://string:${JSON.stringify(prop.conformanceConditions)}`
5104
+ target: `literal:string:${JSON.stringify(prop.conformanceConditions)}`
5104
5105
  });
5105
5106
  }
5106
5107
  if (prop.class) {
@@ -5124,7 +5125,7 @@ class SHACLShape {
5124
5125
  const constructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://constructor");
5125
5126
  if (constructorLink) {
5126
5127
  try {
5127
- const jsonStr = constructorLink.target.replace('literal://string:', '');
5128
+ const jsonStr = constructorLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5128
5129
  shape.constructor_actions = JSON.parse(jsonStr);
5129
5130
  }
5130
5131
  catch (e) {
@@ -5135,7 +5136,7 @@ class SHACLShape {
5135
5136
  const destructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://destructor");
5136
5137
  if (destructorLink) {
5137
5138
  try {
5138
- const jsonStr = destructorLink.target.replace('literal://string:', '');
5139
+ const jsonStr = destructorLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5139
5140
  shape.destructor_actions = JSON.parse(jsonStr);
5140
5141
  }
5141
5142
  catch (e) {
@@ -5173,70 +5174,70 @@ class SHACLShape {
5173
5174
  }
5174
5175
  const minCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minCount");
5175
5176
  if (minCountLink) {
5176
- // Handle both formats: literal://5^^xsd:integer and literal://number:5
5177
- let val = minCountLink.target.replace('literal://', '').replace(/\^\^.*$/, '');
5177
+ // Handle both formats: literal:5^^xsd:integer and literal:number:5
5178
+ let val = minCountLink.target.replace(/^literal:\/\/|^literal:/, '').replace(/\^\^.*$/, '');
5178
5179
  if (val.startsWith('number:'))
5179
5180
  val = val.substring(7);
5180
5181
  prop.minCount = parseInt(val);
5181
5182
  }
5182
5183
  const maxCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxCount");
5183
5184
  if (maxCountLink) {
5184
- // Handle both formats: literal://5^^xsd:integer and literal://number:5
5185
- let val = maxCountLink.target.replace('literal://', '').replace(/\^\^.*$/, '');
5185
+ // Handle both formats: literal:5^^xsd:integer and literal:number:5
5186
+ let val = maxCountLink.target.replace(/^literal:\/\/|^literal:/, '').replace(/\^\^.*$/, '');
5186
5187
  if (val.startsWith('number:'))
5187
5188
  val = val.substring(7);
5188
5189
  prop.maxCount = parseInt(val);
5189
5190
  }
5190
5191
  const patternLink = links.find(l => l.source === propShapeId && l.predicate === "sh://pattern");
5191
5192
  if (patternLink) {
5192
- prop.pattern = patternLink.target.replace('literal://', '');
5193
+ prop.pattern = patternLink.target.replace(/^literal:\/\/|^literal:/, '');
5193
5194
  }
5194
5195
  const minInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minInclusive");
5195
5196
  if (minInclusiveLink) {
5196
- // Handle both formats: literal://5 and literal://number:5
5197
- let val = minInclusiveLink.target.replace('literal://', '');
5197
+ // Handle both formats: literal:5 and literal:number:5
5198
+ let val = minInclusiveLink.target.replace(/^literal:\/\/|^literal:/, '');
5198
5199
  if (val.startsWith('number:'))
5199
5200
  val = val.substring(7);
5200
5201
  prop.minInclusive = parseFloat(val);
5201
5202
  }
5202
5203
  const maxInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxInclusive");
5203
5204
  if (maxInclusiveLink) {
5204
- // Handle both formats: literal://5 and literal://number:5
5205
- let val = maxInclusiveLink.target.replace('literal://', '');
5205
+ // Handle both formats: literal:5 and literal:number:5
5206
+ let val = maxInclusiveLink.target.replace(/^literal:\/\/|^literal:/, '');
5206
5207
  if (val.startsWith('number:'))
5207
5208
  val = val.substring(7);
5208
5209
  prop.maxInclusive = parseFloat(val);
5209
5210
  }
5210
5211
  const hasValueLink = links.find(l => l.source === propShapeId && l.predicate === "sh://hasValue");
5211
5212
  if (hasValueLink) {
5212
- prop.hasValue = hasValueLink.target.replace('literal://', '');
5213
+ prop.hasValue = hasValueLink.target.replace(/^literal:\/\/|^literal:/, '');
5213
5214
  }
5214
5215
  // AD4M-specific
5215
5216
  const localLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://local");
5216
5217
  if (localLink) {
5217
- // Handle both formats: literal://true and literal://boolean:true
5218
- let val = localLink.target.replace('literal://', '');
5218
+ // Handle both formats: literal:true and literal:boolean:true
5219
+ let val = localLink.target.replace(/^literal:\/\/|^literal:/, '');
5219
5220
  if (val.startsWith('boolean:'))
5220
5221
  val = val.substring(8);
5221
5222
  prop.local = val === 'true';
5222
5223
  }
5223
5224
  const writableLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://writable");
5224
5225
  if (writableLink) {
5225
- // Handle both formats: literal://true and literal://boolean:true
5226
- let val = writableLink.target.replace('literal://', '');
5226
+ // Handle both formats: literal:true and literal:boolean:true
5227
+ let val = writableLink.target.replace(/^literal:\/\/|^literal:/, '');
5227
5228
  if (val.startsWith('boolean:'))
5228
5229
  val = val.substring(8);
5229
5230
  prop.writable = val === 'true';
5230
5231
  }
5231
5232
  const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://resolveLanguage");
5232
5233
  if (resolveLangLink) {
5233
- prop.resolveLanguage = resolveLangLink.target.replace('literal://string:', '');
5234
+ prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5234
5235
  }
5235
5236
  // Parse action arrays
5236
5237
  const setterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://setter");
5237
5238
  if (setterLink) {
5238
5239
  try {
5239
- const jsonStr = setterLink.target.replace('literal://string:', '');
5240
+ const jsonStr = setterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5240
5241
  prop.setter = JSON.parse(jsonStr);
5241
5242
  }
5242
5243
  catch (e) {
@@ -5246,7 +5247,7 @@ class SHACLShape {
5246
5247
  const adderLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://adder");
5247
5248
  if (adderLink) {
5248
5249
  try {
5249
- const jsonStr = adderLink.target.replace('literal://string:', '');
5250
+ const jsonStr = adderLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5250
5251
  prop.adder = JSON.parse(jsonStr);
5251
5252
  }
5252
5253
  catch (e) {
@@ -5256,7 +5257,7 @@ class SHACLShape {
5256
5257
  const removerLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://remover");
5257
5258
  if (removerLink) {
5258
5259
  try {
5259
- const jsonStr = removerLink.target.replace('literal://string:', '');
5260
+ const jsonStr = removerLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5260
5261
  prop.remover = JSON.parse(jsonStr);
5261
5262
  }
5262
5263
  catch (e) {
@@ -5265,12 +5266,12 @@ class SHACLShape {
5265
5266
  }
5266
5267
  const getterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://getter");
5267
5268
  if (getterLink) {
5268
- prop.getter = getterLink.target.replace('literal://string:', '');
5269
+ prop.getter = getterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5269
5270
  }
5270
5271
  const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://conformanceConditions");
5271
5272
  if (conditionsLink) {
5272
5273
  try {
5273
- const jsonStr = conditionsLink.target.replace('literal://string:', '');
5274
+ const jsonStr = conditionsLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
5274
5275
  prop.conformanceConditions = JSON.parse(jsonStr);
5275
5276
  }
5276
5277
  catch (e) {
@@ -5387,28 +5388,28 @@ function capSentence(cap) {
5387
5388
  return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
5388
5389
  }
5389
5390
  /**
5390
- * Escapes a string value for safe use in SurrealQL queries.
5391
+ * Escapes a string value for safe use in query strings.
5391
5392
  *
5392
5393
  * @description
5393
5394
  * Prevents SQL injection by properly escaping special characters in string values
5394
- * that will be interpolated into SurrealQL queries. This handles the most common
5395
+ * that will be interpolated into query strings. This handles the most common
5395
5396
  * special characters that could break SQL queries or enable injection attacks.
5396
5397
  *
5397
5398
  * Single quotes, backslashes, and other special characters are escaped using
5398
- * backslash notation, which is the standard escaping mechanism for SurrealQL.
5399
+ * backslash notation, which is the standard escaping mechanism for query.
5399
5400
  *
5400
5401
  * @param value - The string value to escape
5401
- * @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
5402
+ * @returns The escaped string safe for query interpolation (without surrounding quotes)
5402
5403
  *
5403
5404
  * @example
5404
5405
  * ```typescript
5405
5406
  * const userInput = "user's input with 'quotes'";
5406
- * const escaped = escapeSurrealString(userInput);
5407
+ * const escaped = escapeQueryString(userInput);
5407
5408
  * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
5408
5409
  * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
5409
5410
  * ```
5410
5411
  */
5411
- function escapeSurrealString(value) {
5412
+ function escapeQueryString(value) {
5412
5413
  return value
5413
5414
  .replace(/\\/g, '\\\\') // Backslash -> \\
5414
5415
  .replace(/'/g, "\\'") // Single quote -> \'
@@ -5419,19 +5420,21 @@ function escapeSurrealString(value) {
5419
5420
  }
5420
5421
 
5421
5422
  /**
5422
- * Shared SurrealQL compilation utilities.
5423
+ * Shared query compilation utilities.
5423
5424
  *
5424
5425
  * These functions are used by both the runtime query builder (`Ad4mModel`) and
5425
5426
  * the compile-time SHACL generator (`decorators.ts`).
5427
+ *
5428
+ * All output uses native SPARQL syntax.
5426
5429
  */
5427
5430
  /**
5428
- * Format a JavaScript value for embedding in a SurrealQL expression.
5431
+ * Format a JavaScript value for embedding in a query expression.
5429
5432
  *
5430
5433
  * - Strings are single-quoted with backslash / quote / newline escaping
5431
5434
  * - Numbers and booleans are passed through as-is
5432
5435
  * - Arrays are recursed
5433
5436
  */
5434
- function formatSurrealValue(value) {
5437
+ function formatQueryValue(value) {
5435
5438
  if (typeof value === 'string') {
5436
5439
  // Escape backslashes first, then single quotes and other special characters
5437
5440
  const escaped = value
@@ -5447,33 +5450,45 @@ function formatSurrealValue(value) {
5447
5450
  return String(value);
5448
5451
  }
5449
5452
  else if (Array.isArray(value)) {
5450
- return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
5453
+ return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
5451
5454
  }
5452
5455
  else {
5453
5456
  return String(value);
5454
5457
  }
5455
5458
  }
5456
5459
  /**
5457
- * Compile a single Where condition for a property into a SurrealQL
5458
- * graph-traversal sub-expression.
5460
+ * Compile a single Where condition for a property into a SPARQL triple pattern
5461
+ * that can be embedded in a getter's WHERE clause.
5459
5462
  *
5460
- * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
5461
- * style checks that can be used inside a `[WHERE ...]` filter on nodes.
5463
+ * The generated pattern operates on `?target` — e.g.:
5464
+ * `?target <pred> <value> .`
5465
+ * `FILTER EXISTS { ?target <pred> ?_v0 }`
5462
5466
  *
5463
5467
  * @param predicate - The predicate URI for the property
5464
5468
  * @param condition - The Where condition value
5465
5469
  * @param opts - Optional settings (e.g. `resolveLanguage`)
5466
- * @returns A single SurrealQL condition string
5470
+ * @returns A single SPARQL condition string
5467
5471
  */
5468
5472
  function buildWhereCondition(predicate, condition, opts) {
5469
- const escapedPredicate = escapeSurrealString(predicate);
5470
- const targetField = opts?.resolveLanguage === 'literal'
5471
- ? 'fn::parse_literal(out.uri)'
5472
- : 'out.uri';
5473
+ const escapedPredicate = escapeQueryString(predicate);
5474
+ // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
5475
+ // For language-resolved properties, we match against the plain URI
5476
+ // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
5477
+ // For language-resolved properties, values are plain URIs
5478
+ const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
5479
+ function formatValue(v) {
5480
+ if (typeof v === 'string') {
5481
+ return isLiteral
5482
+ ? `<literal:string:${escapeQueryString(v)}>`
5483
+ : `<${escapeQueryString(v)}>`;
5484
+ }
5485
+ // Numbers/booleans — also stored as literal:string: in AD4M
5486
+ return `<literal:string:${v}>`;
5487
+ }
5473
5488
  if (Array.isArray(condition)) {
5474
- // Array values → IN clause
5475
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
5476
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
5489
+ // Array values → FILTER IN
5490
+ const formattedValues = condition.map(formatValue).join(', ');
5491
+ return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
5477
5492
  }
5478
5493
  else if (typeof condition === 'object' && condition !== null) {
5479
5494
  // Operator object
@@ -5481,31 +5496,29 @@ function buildWhereCondition(predicate, condition, opts) {
5481
5496
  const parts = [];
5482
5497
  if (ops.not !== undefined) {
5483
5498
  if (Array.isArray(ops.not)) {
5484
- const formattedValues = ops.not.map((v) => formatSurrealValue(v)).join(', ');
5485
- parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
5499
+ const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
5500
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
5486
5501
  }
5487
5502
  else {
5488
- parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
5503
+ parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
5489
5504
  }
5490
5505
  }
5491
- // Comparison operators — ensure property exists (actual comparison
5492
- // may be post-filtered in JS at runtime, but the SurrealQL condition
5493
- // is valid for compile-time getter generation too).
5506
+ // Comparison operators — ensure property exists
5494
5507
  const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
5495
5508
  ops.lt !== undefined || ops.lte !== undefined ||
5496
5509
  ops.between !== undefined || ops.contains !== undefined;
5497
5510
  if (hasComparisonOps) {
5498
- parts.push(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
5511
+ parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
5499
5512
  }
5500
- return parts.join(' AND ');
5513
+ return parts.join(' ');
5501
5514
  }
5502
5515
  else {
5503
5516
  // Simple equality
5504
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
5517
+ return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
5505
5518
  }
5506
5519
  }
5507
5520
  /**
5508
- * Compile a full `Where` clause to an array of SurrealQL condition strings.
5521
+ * Compile a full `Where` clause to an array of SPARQL condition strings.
5509
5522
  *
5510
5523
  * When `metadata` is provided, property names are resolved to predicates
5511
5524
  * using the model's property metadata. When `metadata` is `null`, property
@@ -5675,7 +5688,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5675
5688
  // ── Constructor / Destructor entries ────────────────────────────
5676
5689
  const effectiveInitial = propMeta.initial
5677
5690
  ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
5678
- ? "literal://string:" : undefined);
5691
+ ? "literal:string:" : undefined);
5679
5692
  if (effectiveInitial) {
5680
5693
  constructorActions.push({
5681
5694
  action: "addLink",
@@ -5726,7 +5739,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5726
5739
  // ── Build Getter (conformance filter) ───────────────────────────
5727
5740
  // Priority chain:
5728
5741
  // 1. Explicit getter string → use verbatim
5729
- // 2. `where` clause → compile DSL to SurrealQL getter
5742
+ // 2. `where` clause → compile DSL to SPARQL getter
5730
5743
  // 3. target + filter !== false → auto-derive from shape
5731
5744
  if (relMeta.getter) {
5732
5745
  relShape.getter = relMeta.getter;
@@ -5739,8 +5752,8 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5739
5752
  : null;
5740
5753
  const conditions = compileWhereClause(relMeta.where, targetMetadata);
5741
5754
  if (conditions.length > 0) {
5742
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
5743
- relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
5755
+ const escapedPredicate = escapeQueryString(relMeta.predicate);
5756
+ relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
5744
5757
  }
5745
5758
  }
5746
5759
  catch (e) {
@@ -5748,18 +5761,42 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5748
5761
  }
5749
5762
  }
5750
5763
  else if (relMeta.target && relMeta.filter !== false) {
5751
- try {
5752
- const TargetClass = relMeta.target();
5753
- const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
5754
- if (filter) {
5755
- relShape.getter = filter.getter;
5756
- relShape.conformanceConditions = filter.conformanceConditions;
5764
+ // Lazy conformance filter: store deferred reference,
5765
+ // resolve on first access via a getter on relShape
5766
+ const targetThunk = relMeta.target;
5767
+ const predicate = relMeta.predicate;
5768
+ let resolved = false;
5769
+ let cachedGetter;
5770
+ let cachedConditions;
5771
+ const resolveFilter = () => {
5772
+ if (resolved)
5773
+ return;
5774
+ resolved = true;
5775
+ try {
5776
+ const TargetClass = targetThunk();
5777
+ const filter = conformanceFilterFn(predicate, TargetClass);
5778
+ if (filter) {
5779
+ cachedGetter = filter.getter;
5780
+ cachedConditions = filter.conformanceConditions;
5781
+ }
5757
5782
  }
5758
- }
5759
- catch (e) {
5760
- // Target class may not be available yet — getter will be
5761
- // absent and runtime will fall back to unfiltered get_links
5762
- }
5783
+ catch (e) {
5784
+ // Target class may not be available yet
5785
+ }
5786
+ };
5787
+ // Define lazy getters that resolve on first access
5788
+ Object.defineProperty(relShape, 'getter', {
5789
+ get() { resolveFilter(); return cachedGetter; },
5790
+ set(v) { resolved = true; cachedGetter = v; },
5791
+ enumerable: true,
5792
+ configurable: true,
5793
+ });
5794
+ Object.defineProperty(relShape, 'conformanceConditions', {
5795
+ get() { resolveFilter(); return cachedConditions; },
5796
+ set(v) { resolved = true; cachedConditions = v; },
5797
+ enumerable: true,
5798
+ configurable: true,
5799
+ });
5763
5800
  }
5764
5801
  // ── sh:class — target shape reference ───────────────────────────
5765
5802
  if (relMeta.target) {
@@ -5777,7 +5814,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5777
5814
  shape.addProperty(relShape);
5778
5815
  }
5779
5816
  // Always set constructor and destructor actions on the shape, even
5780
- // when empty. An empty array serialises to `literal://string:[]`
5817
+ // when empty. An empty array serialises to `literal:string:[]`
5781
5818
  // which the Rust executor parses as a valid (no-op) command list,
5782
5819
  // avoiding "No SHACL constructor found" errors for models whose
5783
5820
  // properties are all optional and have no @Flag.
@@ -5793,11 +5830,21 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
5793
5830
  const propertyRegistry = new WeakMap();
5794
5831
  /** Registry of relation metadata keyed by constructor → { propName → metadata } */
5795
5832
  const relationRegistry = new WeakMap();
5833
+ /** Memoisation cache for getPropertiesMetadata — avoids repeated prototype-chain walks */
5834
+ const propertiesMetadataCache = new WeakMap();
5835
+ /** Memoisation cache for getRelationsMetadata — avoids repeated prototype-chain walks */
5836
+ const relationsMetadataCache = new WeakMap();
5837
+ /** Memoisation cache for generateSHACL — avoids recomputing SHACL shapes */
5838
+ const shaclCache = new WeakMap();
5796
5839
  /**
5797
5840
  * Retrieve property metadata for a given class constructor.
5798
5841
  * Walks the prototype chain so subclass decorators compose with parent decorators.
5842
+ * Results are memoised per class constructor.
5799
5843
  */
5800
5844
  function getPropertiesMetadata(ctor) {
5845
+ const cached = propertiesMetadataCache.get(ctor);
5846
+ if (cached)
5847
+ return cached;
5801
5848
  const result = {};
5802
5849
  const chain = [];
5803
5850
  let current = ctor;
@@ -5810,13 +5857,18 @@ function getPropertiesMetadata(ctor) {
5810
5857
  if (meta)
5811
5858
  Object.assign(result, meta);
5812
5859
  }
5860
+ propertiesMetadataCache.set(ctor, result);
5813
5861
  return result;
5814
5862
  }
5815
5863
  /**
5816
5864
  * Retrieve relation metadata for a given class constructor.
5817
5865
  * Walks the prototype chain so subclass decorators compose with parent decorators.
5866
+ * Results are memoised per class constructor.
5818
5867
  */
5819
5868
  function getRelationsMetadata(ctor) {
5869
+ const cached = relationsMetadataCache.get(ctor);
5870
+ if (cached)
5871
+ return cached;
5820
5872
  const result = {};
5821
5873
  const chain = [];
5822
5874
  let current = ctor;
@@ -5829,6 +5881,18 @@ function getRelationsMetadata(ctor) {
5829
5881
  if (meta)
5830
5882
  Object.assign(result, meta);
5831
5883
  }
5884
+ relationsMetadataCache.set(ctor, result);
5885
+ return result;
5886
+ }
5887
+ /**
5888
+ * Get or compute memoised SHACL for a class. Used by @Model decorator.
5889
+ */
5890
+ function getMemoizedSHACL(target, compute) {
5891
+ const cached = shaclCache.get(target);
5892
+ if (cached)
5893
+ return cached;
5894
+ const result = compute();
5895
+ shaclCache.set(target, result);
5832
5896
  return result;
5833
5897
  }
5834
5898
  /**
@@ -5854,7 +5918,7 @@ function setRelationRegistryEntry(ctor, relName, meta) {
5854
5918
  *
5855
5919
  * Inspects the target class's property metadata to derive:
5856
5920
  * - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
5857
- * - `getter`: Pre-computed SurrealQL expression that traverses outgoing links and filters
5921
+ * - `getter`: Pre-computed graph traversal expression that traverses outgoing links and filters
5858
5922
  * target nodes to only those conforming to the target shape.
5859
5923
  *
5860
5924
  * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
@@ -5865,7 +5929,8 @@ function buildConformanceFilter(relationPredicate, targetClass) {
5865
5929
  try {
5866
5930
  const targetProps = getPropertiesMetadata(targetClass);
5867
5931
  const conditions = [];
5868
- const surrealConditions = [];
5932
+ const sparqlConditions = [];
5933
+ let varIdx = 0;
5869
5934
  // 1. Flags — check predicate + value
5870
5935
  for (const [_propName, propMeta] of Object.entries(targetProps)) {
5871
5936
  if (propMeta.flag && propMeta.initial && propMeta.through) {
@@ -5874,7 +5939,7 @@ function buildConformanceFilter(relationPredicate, targetClass) {
5874
5939
  predicate: propMeta.through,
5875
5940
  value: propMeta.initial,
5876
5941
  });
5877
- surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
5942
+ sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> <${escapeQueryString(propMeta.initial)}> .`);
5878
5943
  }
5879
5944
  }
5880
5945
  // 2. Required (non-flag) properties — check predicate exists
@@ -5885,14 +5950,13 @@ function buildConformanceFilter(relationPredicate, targetClass) {
5885
5950
  type: 'required',
5886
5951
  predicate: propMeta.through,
5887
5952
  });
5888
- surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}']) > 0`);
5953
+ sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> ?_v${varIdx++} .`);
5889
5954
  }
5890
5955
  }
5891
5956
  if (conditions.length === 0) {
5892
5957
  return undefined;
5893
5958
  }
5894
- const escapedPredicate = escapeSurrealString(relationPredicate);
5895
- const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
5959
+ const getter = `SELECT ?target WHERE { <Base> <${escapeQueryString(relationPredicate)}> ?target . ${sparqlConditions.join(' ')} }`;
5896
5960
  return { getter, conformanceConditions: conditions };
5897
5961
  }
5898
5962
  catch (e) {
@@ -5913,8 +5977,8 @@ function applyPropertyMetadata(opts) {
5913
5977
  if (opts.required && !opts.initial) {
5914
5978
  throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
5915
5979
  }
5916
- if (!opts.through && !opts.prologGetter) {
5917
- throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
5980
+ if (!opts.through && !opts.prologGetter && !opts.getter) {
5981
+ throw new Error("SubjectProperty requires either 'through' or 'prologGetter' or 'getter' option");
5918
5982
  }
5919
5983
  // Write to WeakMap registry (keyed by constructor)
5920
5984
  const ctor = target.constructor;
@@ -6099,7 +6163,7 @@ function Model(opts) {
6099
6163
  return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
6100
6164
  };
6101
6165
  target.generateSHACL = function () {
6102
- return buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter);
6166
+ return getMemoizedSHACL(target, () => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter));
6103
6167
  };
6104
6168
  Object.defineProperty(target, 'type', { configurable: true });
6105
6169
  };
@@ -6122,7 +6186,7 @@ function Model(opts) {
6122
6186
  * Properties are optional by default. When a model instance is created without
6123
6187
  * providing a value for an optional property, no link is added to the graph.
6124
6188
  * Set `required: true` explicitly when a property must always be present (this
6125
- * also adds a `"literal://string:uninitialized"` sentinel as the initial value
6189
+ * also adds a `"literal:string:uninitialized"` sentinel as the initial value
6126
6190
  * so that the SDNA constructor creates a placeholder link).
6127
6191
  *
6128
6192
  * @example
@@ -6161,7 +6225,7 @@ function Model(opts) {
6161
6225
  * @param {PropertyOptions} opts - Property configuration
6162
6226
  * @param {string} opts.through - The predicate URI for the property
6163
6227
  * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
6164
- * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized" when required)
6228
+ * @param {string} [opts.initial] - Initial value (defaults to "literal:string:uninitialized" when required)
6165
6229
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
6166
6230
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
6167
6231
  * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
@@ -6174,7 +6238,7 @@ function Property(opts) {
6174
6238
  required,
6175
6239
  readOnly: opts.readOnly ?? false,
6176
6240
  resolveLanguage: opts.resolveLanguage ?? "literal",
6177
- initial: opts.initial ?? (required ? "literal://string:uninitialized" : undefined),
6241
+ initial: opts.initial ?? (required ? "literal:string:uninitialized" : undefined),
6178
6242
  });
6179
6243
  }
6180
6244
  /**
@@ -6263,7 +6327,7 @@ function resolveRelationArgs(first, second) {
6263
6327
  }
6264
6328
  if (opts.where) {
6265
6329
  throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
6266
- 'Use `where` for DSL-based filtering, or `getter` for raw SurrealQL.');
6330
+ 'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');
6267
6331
  }
6268
6332
  return opts;
6269
6333
  }
@@ -6406,6 +6470,73 @@ function BelongsToMany(first, second) {
6406
6470
  };
6407
6471
  }
6408
6472
 
6473
+ /**
6474
+ * Query Result TTL Cache
6475
+ *
6476
+ * Short-lived cache (200ms TTL) for SPARQL query results.
6477
+ * Prevents redundant queries during rapid render cycles where
6478
+ * multiple components issue the same query within milliseconds.
6479
+ *
6480
+ * Key: `perspectiveUUID + queryText`
6481
+ */
6482
+ const cache = new Map();
6483
+ const DEFAULT_TTL_MS = 200;
6484
+ function makeKey$1(perspectiveUUID, queryText) {
6485
+ return `${perspectiveUUID}:${queryText}`;
6486
+ }
6487
+ /**
6488
+ * Get a cached query result if it exists and hasn't expired.
6489
+ */
6490
+ function getCachedResult(perspectiveUUID, queryText) {
6491
+ const key = makeKey$1(perspectiveUUID, queryText);
6492
+ const entry = cache.get(key);
6493
+ if (!entry)
6494
+ return undefined;
6495
+ if (Date.now() > entry.expiry) {
6496
+ cache.delete(key);
6497
+ return undefined;
6498
+ }
6499
+ return entry.result;
6500
+ }
6501
+ /**
6502
+ * Store a query result in the cache with TTL.
6503
+ */
6504
+ function setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {
6505
+ // Lazy eviction of expired entries
6506
+ const now = Date.now();
6507
+ for (const [key, entry] of cache) {
6508
+ if (now > entry.expiry) {
6509
+ cache.delete(key);
6510
+ }
6511
+ }
6512
+ const cacheKey = makeKey$1(perspectiveUUID, queryText);
6513
+ cache.set(cacheKey, { result, expiry: now + ttlMs });
6514
+ }
6515
+ /**
6516
+ * Invalidate all cache entries for a given perspective.
6517
+ * Called after write operations to ensure stale data isn't served.
6518
+ */
6519
+ function invalidatePerspectiveCache(perspectiveUUID) {
6520
+ const prefix = perspectiveUUID + ':';
6521
+ for (const [key] of cache) {
6522
+ if (key.startsWith(prefix)) {
6523
+ cache.delete(key);
6524
+ }
6525
+ }
6526
+ }
6527
+ /**
6528
+ * Clear all cache entries (useful for testing).
6529
+ */
6530
+ function clearQueryCache() {
6531
+ cache.clear();
6532
+ }
6533
+ /**
6534
+ * Get the current size of the cache (useful for testing).
6535
+ */
6536
+ function queryCacheSize() {
6537
+ return cache.size;
6538
+ }
6539
+
6409
6540
  /**
6410
6541
  * SHACL Flow - represents a state machine for AD4M expressions
6411
6542
  *
@@ -6521,7 +6652,7 @@ class SHACLFlow {
6521
6652
  }
6522
6653
  /**
6523
6654
  * Serialize the flow to AD4M links
6524
- * These links can be stored in a perspective and queried via SurrealDB
6655
+ * These links can be stored in a perspective and queried via SPARQL
6525
6656
  *
6526
6657
  * @returns Array of Link objects representing the flow
6527
6658
  */
@@ -6552,7 +6683,7 @@ class SHACLFlow {
6552
6683
  links.push({
6553
6684
  source: flowUri,
6554
6685
  predicate: "ad4m://flowable",
6555
- target: `literal://string:${encodeURIComponent(JSON.stringify(this.flowable))}`
6686
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
6556
6687
  });
6557
6688
  }
6558
6689
  // Start action
@@ -6560,7 +6691,7 @@ class SHACLFlow {
6560
6691
  links.push({
6561
6692
  source: flowUri,
6562
6693
  predicate: "ad4m://startAction",
6563
- target: `literal://string:${encodeURIComponent(JSON.stringify(this.startAction))}`
6694
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
6564
6695
  });
6565
6696
  }
6566
6697
  // States
@@ -6594,7 +6725,7 @@ class SHACLFlow {
6594
6725
  links.push({
6595
6726
  source: stateUri,
6596
6727
  predicate: "ad4m://stateCheck",
6597
- target: `literal://string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
6728
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
6598
6729
  });
6599
6730
  }
6600
6731
  // Transitions
@@ -6636,7 +6767,7 @@ class SHACLFlow {
6636
6767
  links.push({
6637
6768
  source: transitionUri,
6638
6769
  predicate: "ad4m://transitionActions",
6639
- target: `literal://string:${encodeURIComponent(JSON.stringify(transition.actions))}`
6770
+ target: `literal:string:${encodeURIComponent(JSON.stringify(transition.actions))}`
6640
6771
  });
6641
6772
  }
6642
6773
  return links;
@@ -6668,7 +6799,7 @@ class SHACLFlow {
6668
6799
  }
6669
6800
  else {
6670
6801
  try {
6671
- const jsonStr = flowableLink.target.replace('literal://string:', '');
6802
+ const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6672
6803
  flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
6673
6804
  }
6674
6805
  catch {
@@ -6680,7 +6811,7 @@ class SHACLFlow {
6680
6811
  const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
6681
6812
  if (startActionLink) {
6682
6813
  try {
6683
- const jsonStr = startActionLink.target.replace('literal://string:', '');
6814
+ const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6684
6815
  flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
6685
6816
  }
6686
6817
  catch {
@@ -6706,7 +6837,7 @@ class SHACLFlow {
6706
6837
  let stateCheck = { predicate: "", target: "" };
6707
6838
  if (checkLink) {
6708
6839
  try {
6709
- const jsonStr = checkLink.target.replace('literal://string:', '');
6840
+ const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6710
6841
  stateCheck = JSON.parse(decodeURIComponent(jsonStr));
6711
6842
  }
6712
6843
  catch {
@@ -6735,7 +6866,7 @@ class SHACLFlow {
6735
6866
  let actions = [];
6736
6867
  if (actionsLink) {
6737
6868
  try {
6738
- const jsonStr = actionsLink.target.replace('literal://string:', '');
6869
+ const jsonStr = actionsLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
6739
6870
  actions = JSON.parse(decodeURIComponent(jsonStr));
6740
6871
  }
6741
6872
  catch {
@@ -6787,7 +6918,7 @@ var __classPrivateFieldGet$9 = (undefined && undefined.__classPrivateFieldGet) |
6787
6918
  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");
6788
6919
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6789
6920
  };
6790
- 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;
6921
+ 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;
6791
6922
  /** Proxy object for a subscribed Prolog query that provides real-time updates
6792
6923
  *
6793
6924
  * This class handles:
@@ -6842,7 +6973,6 @@ class QuerySubscriptionProxy {
6842
6973
  _QuerySubscriptionProxy_initReject.set(this, void 0);
6843
6974
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
6844
6975
  _QuerySubscriptionProxy_query.set(this, void 0);
6845
- this.isSurrealDB = false;
6846
6976
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_uuid, uuid, "f");
6847
6977
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_query, query, "f");
6848
6978
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_client, client, "f");
@@ -6873,12 +7003,7 @@ class QuerySubscriptionProxy {
6873
7003
  try {
6874
7004
  // Initialize the query subscription
6875
7005
  let initialResult;
6876
- if (this.isSurrealDB) {
6877
- initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
6878
- }
6879
- else {
6880
- initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
6881
- }
7006
+ initialResult = await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_query, "f"));
6882
7007
  __classPrivateFieldSet$9(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
6883
7008
  // Process the initial result immediately for fast UX
6884
7009
  if (initialResult.result) {
@@ -6931,12 +7056,7 @@ class QuerySubscriptionProxy {
6931
7056
  if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_disposed, "f"))
6932
7057
  return;
6933
7058
  try {
6934
- if (this.isSurrealDB) {
6935
- await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
6936
- }
6937
- else {
6938
- await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
6939
- }
7059
+ await __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"));
6940
7060
  }
6941
7061
  catch (e) {
6942
7062
  console.error('Error in keepalive:', e);
@@ -7043,14 +7163,8 @@ class QuerySubscriptionProxy {
7043
7163
  }
7044
7164
  // Tell the backend to dispose of the subscription
7045
7165
  if (__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
7046
- if (this.isSurrealDB) {
7047
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
7048
- .catch(e => console.error('Error disposing surreal query subscription:', e));
7049
- }
7050
- else {
7051
- __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
7052
- .catch(e => console.error('Error disposing query subscription:', e));
7053
- }
7166
+ __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$9(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$9(this, _QuerySubscriptionProxy_subscriptionId, "f"))
7167
+ .catch(e => console.error('Error disposing query subscription:', e));
7054
7168
  }
7055
7169
  }
7056
7170
  }
@@ -7115,6 +7229,12 @@ class PerspectiveProxy {
7115
7229
  _PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);
7116
7230
  _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
7117
7231
  _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
7232
+ _PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()
7233
+ /**
7234
+ * Creates a new PerspectiveProxy instance.
7235
+ * Note: Don't create this directly, use ad4m.perspective.add() instead.
7236
+ */
7237
+ );
7118
7238
  __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
7119
7239
  __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
7120
7240
  __classPrivateFieldSet$9(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
@@ -7205,7 +7325,9 @@ class PerspectiveProxy {
7205
7325
  * @param batchId - Optional batch ID to group this operation with others
7206
7326
  */
7207
7327
  async executeAction(actions, expression, parameters, batchId) {
7208
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
7328
+ 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);
7329
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7330
+ return result;
7209
7331
  }
7210
7332
  /**
7211
7333
  * Retrieves links from the perspective that match the given query.
@@ -7258,34 +7380,28 @@ class PerspectiveProxy {
7258
7380
  return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7259
7381
  }
7260
7382
  /**
7261
- * Executes a SurrealQL query against the perspective's link cache.
7262
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
7383
+ * Executes a SPARQL query against the perspective's link cache.
7384
+ * This allows powerful SQL-like queries on the link data stored in SPARQL.
7263
7385
  *
7264
7386
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
7265
7387
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
7266
7388
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
7267
7389
  *
7268
- * @param query - SurrealQL query string (read-only operations only)
7390
+ * @param query - SPARQL query string (read-only operations only)
7269
7391
  * @returns Query results as parsed JSON
7270
7392
  *
7271
- * @example
7272
- * ```typescript
7273
- * // Get all links
7274
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
7275
- *
7276
- * // Filter links by predicate
7277
- * const follows = await perspective.querySurrealDB(
7278
- * "SELECT * FROM link WHERE predicate = 'follows'"
7279
- * );
7393
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
7280
7394
  *
7281
- * // Complex aggregation query
7282
- * const stats = await perspective.querySurrealDB(
7283
- * "SELECT predicate, count() as total FROM link GROUP BY predicate"
7284
- * );
7285
- * ```
7395
+ * @param query - SPARQL query string
7396
+ * @returns Query results as parsed JSON
7286
7397
  */
7287
- async querySurrealDB(query) {
7288
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7398
+ async querySparql(query) {
7399
+ const cached = getCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7400
+ if (cached !== undefined)
7401
+ return cached;
7402
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query);
7403
+ setCachedResult(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, query, result);
7404
+ return result;
7289
7405
  }
7290
7406
  /**
7291
7407
  * Adds a new link to the perspective.
@@ -7313,7 +7429,9 @@ class PerspectiveProxy {
7313
7429
  * ```
7314
7430
  */
7315
7431
  async add(link, status = 'shared', batchId) {
7316
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
7432
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
7433
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7434
+ return result;
7317
7435
  }
7318
7436
  /**
7319
7437
  * Adds multiple links to the perspective in a single operation.
@@ -7325,7 +7443,9 @@ class PerspectiveProxy {
7325
7443
  * @returns Array of created LinkExpressions
7326
7444
  */
7327
7445
  async addLinks(links, status = 'shared', batchId) {
7328
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
7446
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
7447
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7448
+ return result;
7329
7449
  }
7330
7450
  /**
7331
7451
  * Removes multiple links from the perspective.
@@ -7335,7 +7455,9 @@ class PerspectiveProxy {
7335
7455
  * @returns Array of removed LinkExpressions
7336
7456
  */
7337
7457
  async removeLinks(links, batchId) {
7338
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
7458
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
7459
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7460
+ return result;
7339
7461
  }
7340
7462
  /**
7341
7463
  * Applies a set of link mutations (adds and removes) in a single operation.
@@ -7346,7 +7468,9 @@ class PerspectiveProxy {
7346
7468
  * @returns Object containing results of the mutations
7347
7469
  */
7348
7470
  async linkMutations(mutations, status = 'shared') {
7349
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
7471
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
7472
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7473
+ return result;
7350
7474
  }
7351
7475
  /**
7352
7476
  * Adds a pre-signed LinkExpression to the perspective.
@@ -7367,7 +7491,9 @@ class PerspectiveProxy {
7367
7491
  * @param batchId - Optional batch ID to group this operation with others
7368
7492
  */
7369
7493
  async update(oldLink, newLink, batchId) {
7370
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
7494
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
7495
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7496
+ return result;
7371
7497
  }
7372
7498
  /**
7373
7499
  * Removes a link from the perspective.
@@ -7376,7 +7502,9 @@ class PerspectiveProxy {
7376
7502
  * @param batchId - Optional batch ID to group this operation with others
7377
7503
  */
7378
7504
  async remove(link, batchId) {
7379
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
7505
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
7506
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7507
+ return result;
7380
7508
  }
7381
7509
  /** Creates a new batch for grouping operations */
7382
7510
  async createBatch() {
@@ -7384,7 +7512,9 @@ class PerspectiveProxy {
7384
7512
  }
7385
7513
  /** Commits a batch of operations */
7386
7514
  async commitBatch(batchId) {
7387
- return await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, batchId);
7515
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, batchId);
7516
+ invalidatePerspectiveCache(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
7517
+ return result;
7388
7518
  }
7389
7519
  /**
7390
7520
  * Retrieves and renders an Expression referenced in this perspective.
@@ -7759,6 +7889,13 @@ class PerspectiveProxy {
7759
7889
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
7760
7890
  return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
7761
7891
  }
7892
+ /**
7893
+ * Adds a subject class to the perspective.
7894
+ * Alias for addSdna() with sdnaType='subject_class'.
7895
+ */
7896
+ async addSubjectClass(name, shaclJson) {
7897
+ return this.addSdna(name, '', 'subject_class', shaclJson);
7898
+ }
7762
7899
  /**
7763
7900
  * **Recommended way to add SDNA schemas.**
7764
7901
  *
@@ -7790,7 +7927,7 @@ class PerspectiveProxy {
7790
7927
  // Serialize shape to links
7791
7928
  const shapeLinks = shape.toLinks();
7792
7929
  // Create name -> shape mapping links
7793
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
7930
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
7794
7931
  const allLinks = [
7795
7932
  ...shapeLinks.map(l => new exports.Link({
7796
7933
  source: l.source,
@@ -7816,7 +7953,7 @@ class PerspectiveProxy {
7816
7953
  */
7817
7954
  async getShacl(name) {
7818
7955
  // Find the shape URI from the name mapping
7819
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
7956
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
7820
7957
  const shapeUriLinks = await this.get(new exports.LinkQuery({
7821
7958
  source: nameMapping.toUrl(),
7822
7959
  predicate: "ad4m://shacl_shape_uri"
@@ -7825,22 +7962,25 @@ class PerspectiveProxy {
7825
7962
  return null;
7826
7963
  }
7827
7964
  const shapeUri = shapeUriLinks[0].data.target;
7828
- escapeSurrealString(shapeUri);
7829
7965
  // First get property shape URIs so we can query everything in one go
7830
7966
  const propertyLinks = await this.get(new exports.LinkQuery({
7831
7967
  source: shapeUri,
7832
7968
  predicate: "sh://property"
7833
7969
  }));
7834
- // Build a single surreal query that fetches all relevant links
7970
+ // Fetch all links from the shape and its property shapes
7835
7971
  const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
7836
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
7837
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
7838
- const result = await this.querySurrealDB(query);
7839
- const shapeLinks = (result || []).map((r) => ({
7840
- source: r.source,
7841
- predicate: r.predicate,
7842
- target: r.target
7843
- }));
7972
+ const allLinks = [];
7973
+ for (const uri of sourceUris) {
7974
+ const links = await this.get(new exports.LinkQuery({ source: uri }));
7975
+ for (const l of links) {
7976
+ allLinks.push({
7977
+ source: l.data.source,
7978
+ predicate: l.data.predicate,
7979
+ target: l.data.target
7980
+ });
7981
+ }
7982
+ }
7983
+ const shapeLinks = allLinks;
7844
7984
  return SHACLShape.fromLinks(shapeLinks, shapeUri);
7845
7985
  }
7846
7986
  /**
@@ -7942,19 +8082,20 @@ class PerspectiveProxy {
7942
8082
  return null;
7943
8083
  }
7944
8084
  const flowUri = flowUriLinks[0].data.target;
7945
- const escapedFlowUri = escapeSurrealString(flowUri);
7946
8085
  // Compute alternate prefix for state/transition URIs
7947
8086
  const alternatePrefix = flowUri.endsWith('Flow')
7948
8087
  ? flowUri.slice(0, -4) + '.'
7949
8088
  : flowUri + '.';
7950
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
7951
- // Single surreal query to get all flow-related links
7952
- 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}')`;
7953
- const result = await this.querySurrealDB(query);
7954
- const flowLinks = (result || []).map((r) => ({
7955
- source: r.source,
7956
- predicate: r.predicate,
7957
- target: r.target
8089
+ // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
8090
+ const sparqlQuery = `SELECT ?s ?p ?o WHERE {
8091
+ ?s ?p ?o .
8092
+ FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
8093
+ }`;
8094
+ const sparqlResult = await this.querySparql(sparqlQuery);
8095
+ const flowLinks = (sparqlResult || []).map((r) => ({
8096
+ source: r.s,
8097
+ predicate: r.p,
8098
+ target: r.o
7958
8099
  }));
7959
8100
  return SHACLFlow.fromLinks(flowLinks, flowUri);
7960
8101
  }
@@ -8063,8 +8204,8 @@ class PerspectiveProxy {
8063
8204
  const links = await this.get(new exports.LinkQuery({ predicate }));
8064
8205
  for (const link of links) {
8065
8206
  if (shapePattern.test(link.data.source)) {
8066
- // Parse actions from literal://string:{json}
8067
- const prefix = "literal://string:";
8207
+ // Parse actions from literal:string:{json}
8208
+ const prefix = "literal:string:";
8068
8209
  if (link.data.target.startsWith(prefix)) {
8069
8210
  const jsonStr = link.data.target.slice(prefix.length);
8070
8211
  // Decode URL-encoded JSON if needed, with fallback for raw % characters
@@ -8120,35 +8261,20 @@ class PerspectiveProxy {
8120
8261
  }
8121
8262
  // If no required triples, any expression with links is an instance
8122
8263
  if (metadata.requiredTriples.length === 0) {
8123
- const escapedExpression = escapeSurrealString(expression);
8124
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
8125
- const result = await this.querySurrealDB(checkQuery);
8126
- const count = result[0]?.count ?? 0;
8127
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
8128
- return countValue > 0;
8264
+ const links = await this.get(new exports.LinkQuery({ source: expression }));
8265
+ return links.length > 0;
8129
8266
  }
8130
8267
  // Check if the expression has all required triples (predicate + optional exact target)
8131
8268
  for (const triple of metadata.requiredTriples) {
8132
- const escapedExpression = escapeSurrealString(expression);
8133
- const escapedPredicate = escapeSurrealString(triple.predicate);
8134
- let checkQuery;
8269
+ let query;
8135
8270
  if (triple.target) {
8136
- // Flag: must match both predicate AND exact target value
8137
- const escapedTarget = escapeSurrealString(triple.target);
8138
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
8271
+ query = new exports.LinkQuery({ source: expression, predicate: triple.predicate, target: triple.target });
8139
8272
  }
8140
8273
  else {
8141
- // Property: just check predicate exists
8142
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
8143
- }
8144
- const result = await this.querySurrealDB(checkQuery);
8145
- if (!result || result.length === 0) {
8146
- return false;
8274
+ query = new exports.LinkQuery({ source: expression, predicate: triple.predicate });
8147
8275
  }
8148
- const count = result[0]?.count ?? 0;
8149
- // Handle potential object response like {Int: 0}
8150
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
8151
- if (countValue === 0) {
8276
+ const links = await this.get(query);
8277
+ if (!links || links.length === 0) {
8152
8278
  return false;
8153
8279
  }
8154
8280
  }
@@ -8176,6 +8302,10 @@ class PerspectiveProxy {
8176
8302
  * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
8177
8303
  * Retrieves the SHACL shape and extracts metadata for instance queries.
8178
8304
  */
8305
+ async getSubjectClassMetadata(className) {
8306
+ return this.getSubjectClassMetadataFromSDNA(className);
8307
+ }
8308
+ /** @deprecated Use getSubjectClassMetadata() */
8179
8309
  async getSubjectClassMetadataFromSDNA(className) {
8180
8310
  try {
8181
8311
  // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
@@ -8230,33 +8360,55 @@ class PerspectiveProxy {
8230
8360
  }
8231
8361
  }
8232
8362
  /**
8233
- * Generates a SurrealDB query to find instances based on class metadata.
8363
+ * Generates a SPARQL query to find instances based on class metadata.
8364
+ */
8365
+ /**
8366
+ * Finds all instances matching subject class metadata by querying links.
8367
+ * Returns base URIs of matching instances.
8234
8368
  */
8235
- generateSurrealInstanceQuery(metadata) {
8369
+ async findInstancesByMetadata(metadata) {
8236
8370
  if (metadata.requiredTriples.length === 0) {
8237
- // No required triples - any node with links is an instance
8238
- return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
8371
+ // No required triples - return all unique sources that have any link
8372
+ const allLinks = await this.get(new exports.LinkQuery({}));
8373
+ const sources = new Set(allLinks.map(l => l.data.source));
8374
+ return Array.from(sources).map(s => ({ base: s }));
8239
8375
  }
8240
- // Generate WHERE conditions for each required triple (predicate + optional exact target)
8241
- const whereConditions = metadata.requiredTriples.map(triple => {
8242
- const escapedPredicate = escapeSurrealString(triple.predicate);
8243
- if (triple.target) {
8244
- // Flag: must match both predicate AND exact target value
8245
- const escapedTarget = escapeSurrealString(triple.target);
8246
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
8247
- }
8248
- else {
8249
- // Property: just check predicate exists
8250
- return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
8376
+ // Use first required triple to get candidate set, then filter by rest
8377
+ const first = metadata.requiredTriples[0];
8378
+ let query;
8379
+ if (first.target) {
8380
+ query = new exports.LinkQuery({ predicate: first.predicate, target: first.target });
8381
+ }
8382
+ else {
8383
+ query = new exports.LinkQuery({ predicate: first.predicate });
8384
+ }
8385
+ const candidateLinks = await this.get(query);
8386
+ let candidates = [...new Set(candidateLinks.map(l => l.data.source))];
8387
+ // Filter by remaining required triples
8388
+ for (let i = 1; i < metadata.requiredTriples.length; i++) {
8389
+ const triple = metadata.requiredTriples[i];
8390
+ const remaining = [];
8391
+ for (const expr of candidates) {
8392
+ let q;
8393
+ if (triple.target) {
8394
+ q = new exports.LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
8395
+ }
8396
+ else {
8397
+ q = new exports.LinkQuery({ source: expr, predicate: triple.predicate });
8398
+ }
8399
+ const links = await this.get(q);
8400
+ if (links.length > 0)
8401
+ remaining.push(expr);
8251
8402
  }
8252
- }).join(' AND ');
8253
- return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
8403
+ candidates = remaining;
8404
+ }
8405
+ return candidates.map(c => ({ base: c }));
8254
8406
  }
8255
8407
  /**
8256
- * Gets a property value using SurrealDB when Prolog fails.
8408
+ * Gets a property value using SPARQL when Prolog fails.
8257
8409
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
8258
8410
  */
8259
- async getPropertyValueViaSurreal(baseExpression, className, propertyName) {
8411
+ async getPropertyValueViaSparql(baseExpression, className, propertyName) {
8260
8412
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8261
8413
  if (!metadata) {
8262
8414
  return undefined;
@@ -8265,14 +8417,11 @@ class PerspectiveProxy {
8265
8417
  if (!propMeta) {
8266
8418
  return undefined;
8267
8419
  }
8268
- const escapedBaseExpression = escapeSurrealString(baseExpression);
8269
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
8270
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
8271
- const result = await this.querySurrealDB(query);
8272
- if (!result || result.length === 0) {
8420
+ const links = await this.get(new exports.LinkQuery({ source: baseExpression, predicate: propMeta.predicate }));
8421
+ if (!links || links.length === 0) {
8273
8422
  return undefined;
8274
8423
  }
8275
- const value = result[0].value;
8424
+ const value = links[0].data.target;
8276
8425
  // Handle expression resolution if needed
8277
8426
  if (propMeta.resolveLanguage && value) {
8278
8427
  try {
@@ -8291,11 +8440,11 @@ class PerspectiveProxy {
8291
8440
  return value;
8292
8441
  }
8293
8442
  /**
8294
- * Gets relation values using SurrealDB when Prolog fails.
8443
+ * Gets relation values using SPARQL when Prolog fails.
8295
8444
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
8296
8445
  * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
8297
8446
  */
8298
- async getRelationValuesViaSurreal(baseExpression, className, relationName) {
8447
+ async getRelationValuesViaSparql(baseExpression, className, relationName) {
8299
8448
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8300
8449
  if (!metadata) {
8301
8450
  return [];
@@ -8304,14 +8453,13 @@ class PerspectiveProxy {
8304
8453
  if (!relMeta) {
8305
8454
  return [];
8306
8455
  }
8307
- const escapedBaseExpression = escapeSurrealString(baseExpression);
8308
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
8309
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
8310
- const result = await this.querySurrealDB(query);
8311
- if (!result || result.length === 0) {
8456
+ const links = await this.get(new exports.LinkQuery({ source: baseExpression, predicate: relMeta.predicate }));
8457
+ if (!links || links.length === 0) {
8312
8458
  return [];
8313
8459
  }
8314
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
8460
+ // Sort by timestamp ascending
8461
+ links.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
8462
+ let values = links.map(l => l.data.target).filter(v => v !== "" && v !== '');
8315
8463
  // Apply condition filtering if present
8316
8464
  if (relMeta.condition && values.length > 0) {
8317
8465
  try {
@@ -8321,13 +8469,28 @@ class PerspectiveProxy {
8321
8469
  .replace(/\$perspective/g, `'${this.uuid}'`)
8322
8470
  .replace(/\$base/g, `'${baseExpression}'`)
8323
8471
  .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
8324
- // If condition starts with WHERE, wrap in array length check
8325
- if (condition.trim().startsWith('WHERE')) {
8326
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
8472
+ // Parse condition to extract link query parameters
8473
+ // Conditions typically look like: WHERE in.uri = 'X' AND predicate = 'Y' AND out.uri = 'Z'
8474
+ // or: array::len(SELECT * FROM link WHERE ...) > 0
8475
+ // Convert to queryLinks calls
8476
+ const sourceMatch = condition.match(/in\.uri\s*=\s*'([^']+)'/);
8477
+ const predicateMatch = condition.match(/predicate\s*=\s*'([^']+)'/);
8478
+ const targetMatch = condition.match(/out\.uri\s*=\s*'([^']+)'/);
8479
+ if (sourceMatch || predicateMatch || targetMatch) {
8480
+ const linkQuery = {};
8481
+ if (sourceMatch)
8482
+ linkQuery.source = sourceMatch[1];
8483
+ if (predicateMatch)
8484
+ linkQuery.predicate = predicateMatch[1];
8485
+ if (targetMatch)
8486
+ linkQuery.target = targetMatch[1];
8487
+ const matchingLinks = await this.get(new exports.LinkQuery(linkQuery));
8488
+ if (matchingLinks.length > 0) {
8489
+ filteredValues.push(value);
8490
+ }
8327
8491
  }
8328
- const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
8329
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
8330
- if (isTrue) {
8492
+ else {
8493
+ // Can't parse condition, include by default
8331
8494
  filteredValues.push(value);
8332
8495
  }
8333
8496
  }
@@ -8355,7 +8518,7 @@ class PerspectiveProxy {
8355
8518
  return values;
8356
8519
  }
8357
8520
  /**
8358
- * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
8521
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SPARQL queries.
8359
8522
  * This avoids N+1 query problems by checking all values at once.
8360
8523
  */
8361
8524
  async batchCheckSubjectInstances(expressions, metadata) {
@@ -8364,30 +8527,31 @@ class PerspectiveProxy {
8364
8527
  }
8365
8528
  // If no required triples, check which expressions have any links
8366
8529
  if (metadata.requiredTriples.length === 0) {
8367
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
8368
- const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
8369
- const result = await this.querySurrealDB(checkQuery);
8370
- return result.map(r => r.uri);
8530
+ const results = [];
8531
+ for (const expr of expressions) {
8532
+ const links = await this.get(new exports.LinkQuery({ source: expr }));
8533
+ if (links.length > 0)
8534
+ results.push(expr);
8535
+ }
8536
+ return results;
8371
8537
  }
8372
- // For each required triple, build a query that finds matching expressions
8538
+ // For each required triple, find which expressions match
8373
8539
  const validExpressionSets = [];
8374
8540
  for (const triple of metadata.requiredTriples) {
8375
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
8376
- const escapedPredicate = escapeSurrealString(triple.predicate);
8377
- let checkQuery;
8378
- if (triple.target) {
8379
- // Flag: must match both predicate AND exact target value
8380
- const escapedTarget = escapeSurrealString(triple.target);
8381
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
8382
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
8383
- }
8384
- else {
8385
- // Property: just check predicate exists
8386
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
8387
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
8541
+ const matchingExprs = new Set();
8542
+ for (const expr of expressions) {
8543
+ let query;
8544
+ if (triple.target) {
8545
+ query = new exports.LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
8546
+ }
8547
+ else {
8548
+ query = new exports.LinkQuery({ source: expr, predicate: triple.predicate });
8549
+ }
8550
+ const links = await this.get(query);
8551
+ if (links.length > 0)
8552
+ matchingExprs.add(expr);
8388
8553
  }
8389
- const result = await this.querySurrealDB(checkQuery);
8390
- validExpressionSets.push(new Set(result.map(r => r.uri)));
8554
+ validExpressionSets.push(matchingExprs);
8391
8555
  }
8392
8556
  // Find intersection: expressions that passed ALL required triple checks
8393
8557
  if (validExpressionSets.length === 0) {
@@ -8439,13 +8603,12 @@ class PerspectiveProxy {
8439
8603
  let instances = [];
8440
8604
  for (let className of classes) {
8441
8605
  //console.log(`getAllSubjectInstances: Processing class ${className}`);
8442
- // Query SDNA for metadata, then query SurrealDB for instances
8606
+ // Query SDNA for metadata, then query SPARQL for instances
8443
8607
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8444
8608
  //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
8445
8609
  if (metadata) {
8446
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
8447
- const results = await this.querySurrealDB(surrealQuery);
8448
- // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
8610
+ const results = await this.findInstancesByMetadata(metadata);
8611
+ // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);
8449
8612
  for (const result of results || []) {
8450
8613
  //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
8451
8614
  try {
@@ -8489,11 +8652,10 @@ class PerspectiveProxy {
8489
8652
  }
8490
8653
  let instances = [];
8491
8654
  for (let className of classes) {
8492
- // Query SDNA for metadata, then query SurrealDB for instances
8655
+ // Query SDNA for metadata, then query SPARQL for instances
8493
8656
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
8494
8657
  if (metadata) {
8495
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
8496
- const results = await this.querySurrealDB(surrealQuery);
8658
+ const results = await this.findInstancesByMetadata(metadata);
8497
8659
  for (const result of results || []) {
8498
8660
  try {
8499
8661
  let subject = new Subject(this, result.base, className);
@@ -8538,15 +8700,16 @@ class PerspectiveProxy {
8538
8700
  if (properties.length === 0 && relations.length === 0) {
8539
8701
  return null;
8540
8702
  }
8541
- // Single SurrealDB query to find all classes and their properties/relations
8542
- const query = `SELECT
8543
- in.uri AS shape_source,
8544
- predicate,
8545
- out.uri AS target
8546
- FROM link
8547
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
8548
- const results = await this.querySurrealDB(query);
8549
- if (!results || results.length === 0)
8703
+ // Query links for class shapes using queryLinks
8704
+ const typeLinks = await this.get(new exports.LinkQuery({ predicate: 'rdf://type', target: 'ad4m://SubjectClass' }));
8705
+ const propLinks = await this.get(new exports.LinkQuery({ predicate: 'sh://property' }));
8706
+ const collLinks = await this.get(new exports.LinkQuery({ predicate: 'sh://collection' }));
8707
+ const results = [
8708
+ ...typeLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
8709
+ ...propLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
8710
+ ...collLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
8711
+ ];
8712
+ if (results.length === 0)
8550
8713
  return null;
8551
8714
  // Build a map of className -> { properties, relations }
8552
8715
  const classShapes = new Map();
@@ -8644,8 +8807,15 @@ class PerspectiveProxy {
8644
8807
  * static generateSDNA() function and adds it to the perspective's SDNA.
8645
8808
  */
8646
8809
  async ensureSDNASubjectClass(jsClass) {
8810
+ return this.ensureSubjectClass(jsClass);
8811
+ }
8812
+ /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
8813
+ async ensureSubjectClass(jsClass) {
8647
8814
  // Get the class name from the JS class
8648
8815
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
8816
+ // Skip if already registered for this perspective instance
8817
+ if (__classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
8818
+ return;
8649
8819
  // Note: Duplicate checking is handled on the Rust side in add_sdna
8650
8820
  // Generate SHACL SDNA (Prolog-free)
8651
8821
  if (!jsClass.generateSHACL) {
@@ -8658,6 +8828,14 @@ class PerspectiveProxy {
8658
8828
  // Pass SHACL JSON to backend (Prolog-free)
8659
8829
  // Backend stores SHACL links directly
8660
8830
  await this.addSdna(className, '', 'subject_class', shaclJson);
8831
+ // Mark as registered for this perspective instance
8832
+ __classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(className);
8833
+ }
8834
+ /** Clear the per-instance ensured subject class cache.
8835
+ * Call this after wiping a perspective's links so that
8836
+ * subsequent register() calls re-add SHACL definitions. */
8837
+ clearEnsuredSubjectClasses() {
8838
+ __classPrivateFieldGet$9(this, _PerspectiveProxy_ensuredSubjectClasses, "f").clear();
8661
8839
  }
8662
8840
  getNeighbourhoodProxy() {
8663
8841
  return __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveProxy_handle, "f").uuid);
@@ -8727,7 +8905,7 @@ class PerspectiveProxy {
8727
8905
  return subscriptionProxy;
8728
8906
  }
8729
8907
  /**
8730
- * Creates a subscription for a SurrealQL query that updates in real-time.
8908
+ * Creates a subscription for a SPARQL query that updates in real-time.
8731
8909
  *
8732
8910
  * This method:
8733
8911
  * 1. Creates the subscription on the Rust side
@@ -8742,12 +8920,12 @@ class PerspectiveProxy {
8742
8920
  * when dispose() is called. Make sure to call dispose() when you're done to
8743
8921
  * prevent memory leaks and ensure proper cleanup of resources.
8744
8922
  *
8745
- * @param query - SurrealQL query string
8923
+ /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
8924
+ * @param query - Query string
8746
8925
  * @returns Initialized QuerySubscriptionProxy instance
8747
8926
  */
8748
- async subscribeSurrealDB(query) {
8927
+ async subscribeQuery(query) {
8749
8928
  const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$9(this, _PerspectiveProxy_client, "f"));
8750
- subscriptionProxy.isSurrealDB = true;
8751
8929
  // Start the subscription on the Rust side first to get the real subscription ID
8752
8930
  await subscriptionProxy.subscribe();
8753
8931
  // Wait for the initial result
@@ -8755,7 +8933,7 @@ class PerspectiveProxy {
8755
8933
  return subscriptionProxy;
8756
8934
  }
8757
8935
  }
8758
- _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
8936
+ _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();
8759
8937
 
8760
8938
  var __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8761
8939
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -8894,23 +9072,14 @@ class PerspectiveClient {
8894
9072
  }));
8895
9073
  return JSON.parse(perspectiveQueryProlog);
8896
9074
  }
8897
- /**
8898
- * Executes a read-only SurrealQL query against a perspective's link cache.
8899
- *
8900
- * Security: Only SELECT, RETURN, and other read-only queries are permitted.
8901
- * Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
8902
- *
8903
- * Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
8904
- * as generated from Rust method "perspective_query_surreal_db"
8905
- */
8906
- async querySurrealDB(uuid, query) {
8907
- const { perspectiveQuerySurrealDb } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").query({
8908
- query: gql `query perspectiveQuerySurrealDb($uuid: String!, $query: String!) {
8909
- perspectiveQuerySurrealDb(uuid: $uuid, query: $query)
9075
+ async querySparql(uuid, query) {
9076
+ const { perspectiveQuerySparql } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").query({
9077
+ query: gql `query perspectiveQuerySparql($uuid: String!, $query: String!) {
9078
+ perspectiveQuerySparql(uuid: $uuid, query: $query)
8910
9079
  }`,
8911
9080
  variables: { uuid, query }
8912
9081
  }));
8913
- return JSON.parse(perspectiveQuerySurrealDb);
9082
+ return JSON.parse(perspectiveQuerySparql);
8914
9083
  }
8915
9084
  async subscribeQuery(uuid, query) {
8916
9085
  const { perspectiveSubscribeQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
@@ -8937,49 +9106,6 @@ class PerspectiveClient {
8937
9106
  }
8938
9107
  return { subscriptionId, result: finalResult, isInit };
8939
9108
  }
8940
- async perspectiveSubscribeSurrealQuery(uuid, query) {
8941
- const { perspectiveSubscribeSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
8942
- mutation: gql `mutation perspectiveSubscribeSurrealQuery($uuid: String!, $query: String!) {
8943
- perspectiveSubscribeSurrealQuery(uuid: $uuid, query: $query) {
8944
- subscriptionId
8945
- result
8946
- }
8947
- }`,
8948
- variables: { uuid, query }
8949
- }));
8950
- const { subscriptionId, result } = perspectiveSubscribeSurrealQuery;
8951
- let finalResult = result;
8952
- let isInit = false;
8953
- if (finalResult.startsWith("#init#")) {
8954
- finalResult = finalResult.substring(6);
8955
- isInit = true;
8956
- }
8957
- try {
8958
- finalResult = JSON.parse(finalResult);
8959
- }
8960
- catch (e) {
8961
- console.error('Error parsing perspectiveSubscribeSurrealQuery result:', e);
8962
- }
8963
- return { subscriptionId, result: finalResult, isInit };
8964
- }
8965
- async perspectiveKeepAliveSurrealQuery(uuid, subscriptionId) {
8966
- const { perspectiveKeepAliveSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
8967
- mutation: gql `mutation perspectiveKeepAliveSurrealQuery($uuid: String!, $subscriptionId: String!) {
8968
- perspectiveKeepAliveSurrealQuery(uuid: $uuid, subscriptionId: $subscriptionId)
8969
- }`,
8970
- variables: { uuid, subscriptionId }
8971
- }));
8972
- return perspectiveKeepAliveSurrealQuery;
8973
- }
8974
- async perspectiveDisposeSurrealQuerySubscription(uuid, subscriptionId) {
8975
- const { perspectiveDisposeSurrealQuerySubscription } = unwrapApolloResult(await __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").mutate({
8976
- mutation: gql `mutation perspectiveDisposeSurrealQuerySubscription($uuid: String!, $subscriptionId: String!) {
8977
- perspectiveDisposeSurrealQuerySubscription(uuid: $uuid, subscriptionId: $subscriptionId)
8978
- }`,
8979
- variables: { uuid, subscriptionId }
8980
- }));
8981
- return perspectiveDisposeSurrealQuerySubscription;
8982
- }
8983
9109
  subscribeToQueryUpdates(subscriptionId, onData) {
8984
9110
  const subscription = __classPrivateFieldGet$8(this, _PerspectiveClient_apolloClient, "f").subscribe({
8985
9111
  query: gql `
@@ -9376,7 +9502,7 @@ var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) |
9376
9502
  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");
9377
9503
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
9378
9504
  };
9379
- var _AgentClient_apolloClient, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks;
9505
+ var _AgentClient_apolloClient, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks;
9380
9506
  const AGENT_SUBITEMS = `
9381
9507
  did
9382
9508
  directMessageLanguage
@@ -9440,11 +9566,13 @@ class AgentClient {
9440
9566
  _AgentClient_updatedCallbacks.set(this, void 0);
9441
9567
  _AgentClient_agentStatusChangedCallbacks.set(this, void 0);
9442
9568
  _AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);
9569
+ _AgentClient_computeLogUpdatedCallbacks.set(this, void 0);
9443
9570
  __classPrivateFieldSet$7(this, _AgentClient_apolloClient, client, "f");
9444
9571
  __classPrivateFieldSet$7(this, _AgentClient_updatedCallbacks, [], "f");
9445
9572
  __classPrivateFieldSet$7(this, _AgentClient_agentStatusChangedCallbacks, [], "f");
9446
9573
  __classPrivateFieldSet$7(this, _AgentClient_appsChangedCallback, [], "f");
9447
9574
  __classPrivateFieldSet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, [], "f");
9575
+ __classPrivateFieldSet$7(this, _AgentClient_computeLogUpdatedCallbacks, [], "f");
9448
9576
  if (subscribe) {
9449
9577
  this.subscribeAgentUpdated();
9450
9578
  this.subscribeAgentStatusChanged();
@@ -9728,6 +9856,32 @@ class AgentClient {
9728
9856
  error: (e) => console.error(e),
9729
9857
  });
9730
9858
  }
9859
+ addComputeLogUpdatedListener(listener) {
9860
+ __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, "f").push(listener);
9861
+ }
9862
+ subscribeComputeLogUpdated() {
9863
+ __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f")
9864
+ .subscribe({
9865
+ query: gql `subscription {
9866
+ runtimeComputeLogUpdated {
9867
+ id
9868
+ userEmail
9869
+ timestamp
9870
+ operation
9871
+ summary
9872
+ cost
9873
+ creditsAfter
9874
+ }
9875
+ }`,
9876
+ })
9877
+ .subscribe({
9878
+ next: (result) => {
9879
+ const entry = result.data.runtimeComputeLogUpdated;
9880
+ __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, "f").forEach((cb) => cb(entry));
9881
+ },
9882
+ error: (e) => console.error(e),
9883
+ });
9884
+ }
9731
9885
  async requestCapability(authInfo) {
9732
9886
  const { agentRequestCapability } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
9733
9887
  mutation: gql `
@@ -9874,6 +10028,24 @@ class AgentClient {
9874
10028
  }));
9875
10029
  return runtimeHostingUserInfo;
9876
10030
  }
10031
+ async computeLog(since, limit, userEmail) {
10032
+ const { runtimeComputeLog } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").query({
10033
+ query: gql `query runtimeComputeLog($since: String, $limit: Int, $userEmail: String) {
10034
+ runtimeComputeLog(since: $since, limit: $limit, userEmail: $userEmail) {
10035
+ id
10036
+ userEmail
10037
+ timestamp
10038
+ operation
10039
+ summary
10040
+ cost
10041
+ creditsAfter
10042
+ }
10043
+ }`,
10044
+ variables: { since, limit, userEmail },
10045
+ fetchPolicy: 'network-only',
10046
+ }));
10047
+ return runtimeComputeLog;
10048
+ }
9877
10049
  async setHotWalletAddress(address) {
9878
10050
  const { runtimeSetHotWalletAddress } = unwrapApolloResult(await __classPrivateFieldGet$7(this, _AgentClient_apolloClient, "f").mutate({
9879
10051
  mutation: gql `mutation runtimeSetHotWalletAddress($address: String!) {
@@ -9896,7 +10068,7 @@ class AgentClient {
9896
10068
  return runtimeRequestPayment;
9897
10069
  }
9898
10070
  }
9899
- _AgentClient_apolloClient = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap();
10071
+ _AgentClient_apolloClient = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap();
9900
10072
 
9901
10073
  var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
9902
10074
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -18687,11 +18859,11 @@ function exprRef2String(ref) {
18687
18859
  return `${ref.language.address}://${ref.expression}`;
18688
18860
  }
18689
18861
  function parseExprUrl(url) {
18690
- if (url.startsWith("literal://")) {
18862
+ if (url.startsWith("literal:")) {
18691
18863
  const languageRef = new exports.LanguageRef();
18692
18864
  languageRef.address = 'literal';
18693
18865
  languageRef.name = 'literal';
18694
- const content = url.substring(10);
18866
+ const content = url.substring(8);
18695
18867
  return new exports.ExpressionRef(languageRef, content);
18696
18868
  }
18697
18869
  const URIregexp = /^([^:^\s]+):\/\/([\s\S]+)$/;
@@ -19012,7 +19184,7 @@ exports.PerspectiveHandle = __decorate$2([
19012
19184
  ], exports.PerspectiveHandle);
19013
19185
 
19014
19186
  /**
19015
- * WakerSubscriptionManager — manages live SurrealDB subscriptions for the waker.
19187
+ * WakerSubscriptionManager — manages live query subscriptions for the waker.
19016
19188
  *
19017
19189
  * Lives in core so it can be imported by both the plugin and integration tests
19018
19190
  * without ESM/CJS import issues.
@@ -19036,7 +19208,7 @@ class WakerSubscriptionManager {
19036
19208
  this.previousSeenMessages = options.previousSeenMessages ?? {};
19037
19209
  }
19038
19210
  /**
19039
- * Create a live SurrealDB subscription.
19211
+ * Create a live SPARQL subscription.
19040
19212
  * If a subscription with the same id already exists, it is disposed first.
19041
19213
  */
19042
19214
  async subscribe(sub) {
@@ -19047,9 +19219,9 @@ class WakerSubscriptionManager {
19047
19219
  }
19048
19220
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
19049
19221
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
19050
- this.logger.info(`[waker] ${sub.id}: SurrealQL query:\n${sub.query}`);
19222
+ this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
19051
19223
  const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
19052
- proxy.isSurrealDB = true;
19224
+ proxy.isSPARQL = true;
19053
19225
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
19054
19226
  // rejects this promise internally when subscribe() fails, and if nobody catches
19055
19227
  // it before the next microtask it crashes the process.
@@ -19082,7 +19254,7 @@ class WakerSubscriptionManager {
19082
19254
  }
19083
19255
  proxy.onResult(async (result) => {
19084
19256
  this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
19085
- // SurrealDB can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
19257
+ // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
19086
19258
  if (!Array.isArray(result)) {
19087
19259
  this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
19088
19260
  return;
@@ -19107,10 +19279,9 @@ class WakerSubscriptionManager {
19107
19279
  for (const msgAddr of newMessages) {
19108
19280
  const parents = [];
19109
19281
  try {
19110
- const escaped = msgAddr.replace(/'/g, "\\'");
19111
- const parentQuery = `SELECT * FROM link WHERE predicate = 'ad4m://has_child' AND target = '${escaped}'`;
19282
+ const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
19112
19283
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
19113
- const parentResult = await this.perspectiveClient.querySurrealDB(sub.perspective, parentQuery);
19284
+ const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
19114
19285
  if (Array.isArray(parentResult)) {
19115
19286
  for (const link of parentResult) {
19116
19287
  if (link && link.source) {
@@ -19309,7 +19480,7 @@ class SmartLiteral {
19309
19480
  _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
19310
19481
 
19311
19482
  /**
19312
- * Shared query helpers used by both the Prolog and SurrealQL query pipelines.
19483
+ * Shared query helpers used by both the Prolog and SPARQL query pipelines.
19313
19484
  */
19314
19485
  /**
19315
19486
  * Resolves the predicate for a parent query.
@@ -19747,14 +19918,14 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
19747
19918
  }
19748
19919
  // Default resolveLanguage to 'literal' for all remaining property types,
19749
19920
  // matching the @Property decorator behaviour. Without this, string values
19750
- // stored as literal:// URLs are returned unparsed.
19921
+ // stored as literal: URLs are returned unparsed.
19751
19922
  if (resolveLanguage === undefined || resolveLanguage === null) {
19752
19923
  resolveLanguage = 'literal';
19753
19924
  }
19754
19925
  // If property is required, ensure it has an initial value
19755
19926
  if (isRequired && !initial) {
19756
19927
  if (isObjectType(propertySchema)) {
19757
- initial = 'literal://json:{}';
19928
+ initial = 'literal:json:{}';
19758
19929
  }
19759
19930
  else {
19760
19931
  initial = "ad4m://undefined";
@@ -19810,250 +19981,433 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
19810
19981
  }
19811
19982
 
19812
19983
  /**
19813
- * SurrealQL query building utilities for Ad4mModel.
19984
+ * SPARQL query building utilities for Ad4mModel.
19814
19985
  *
19815
- * Contains the graph-traversal WHERE clause builder, legacy
19816
- * subquery-based clause builders, SELECT-field builders, and
19817
- * the main `buildSurrealQLQuery()` function that produces a
19818
- * complete SurrealQL query string from a `Query` object.
19986
+ * Uses the direct triple + named graph storage model where each AD4M link
19987
+ * is stored in a named graph (keyed by link hash) with metadata in the default graph.
19819
19988
  *
19820
- * All functions are stateless — model metadata and relation metadata
19821
- * are passed in as parameters instead of accessed via `this`.
19989
+ * All AD4M URIs (source, predicate, target) become RDF IRIs.
19822
19990
  *
19823
19991
  * @module
19824
19992
  */
19825
- // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
19826
19993
  /**
19827
- * Builds WHERE clause filters using SurrealDB graph traversal syntax.
19828
- *
19829
- * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
19830
- * filters that SurrealDB can optimize via graph indexes.
19831
- *
19832
- * @param metadata - Model metadata from `getModelMetadata()`
19833
- * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
19834
- * direction detection)
19835
- * @param where - User-supplied where conditions
19836
- * @returns Combined AND-joined condition string, or empty string
19994
+ * Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).
19995
+ * Properties with resolveLanguage === "literal" AND properties without resolveLanguage
19996
+ * both store values as literal: URIs. Only properties with a non-literal resolveLanguage
19997
+ * (e.g. file storage) or flag properties store raw URIs.
19837
19998
  */
19838
- function buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where) {
19839
- if (!where)
19840
- return '';
19841
- const conditions = [];
19842
- for (const [propertyName, condition] of Object.entries(where)) {
19843
- const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
19844
- if (isSpecial) {
19845
- if (propertyName === 'author' || propertyName === 'timestamp') {
19846
- continue; // Filtered post-query in JS
19847
- }
19848
- const columnName = 'uri';
19849
- if (Array.isArray(condition)) {
19850
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19851
- conditions.push(`${columnName} IN [${formattedValues}]`);
19852
- }
19853
- else if (typeof condition === 'object' && condition !== null) {
19854
- const ops = condition;
19855
- if (ops.not !== undefined) {
19856
- if (Array.isArray(ops.not)) {
19857
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19858
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
19859
- }
19860
- else {
19861
- conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
19862
- }
19863
- }
19864
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
19865
- conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
19866
- }
19867
- if (ops.gt !== undefined) {
19868
- conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
19869
- }
19870
- if (ops.gte !== undefined) {
19871
- conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
19872
- }
19873
- if (ops.lt !== undefined) {
19874
- conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
19875
- }
19876
- if (ops.lte !== undefined) {
19877
- conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
19878
- }
19879
- if (ops.contains !== undefined) {
19880
- conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
19881
- }
19882
- }
19883
- else {
19884
- conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
19885
- }
19886
- }
19887
- else {
19888
- // Regular properties — check relation metadata first for direction
19889
- const relMeta = allRelationsMetadata[propertyName];
19890
- const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
19891
- if (relMeta) {
19892
- const predicate = escapeSurrealString(relMeta.predicate);
19893
- if (Array.isArray(condition)) {
19894
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19895
- if (isBelongs) {
19896
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
19897
- }
19898
- else {
19899
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
19900
- }
19901
- }
19902
- else if (typeof condition === 'object' && condition !== null) {
19903
- const ops = condition;
19904
- if (ops.not !== undefined) {
19905
- if (Array.isArray(ops.not)) {
19906
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19907
- if (isBelongs) {
19908
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
19909
- }
19910
- else {
19911
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
19912
- }
19913
- }
19914
- else {
19915
- if (isBelongs) {
19916
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
19917
- }
19918
- else {
19919
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
19920
- }
19921
- }
19922
- }
19923
- }
19924
- else {
19925
- if (isBelongs) {
19926
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
19927
- }
19928
- else {
19929
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
19930
- }
19931
- }
19932
- continue;
19933
- }
19934
- const propMeta = metadata.properties[propertyName];
19935
- if (!propMeta)
19936
- continue;
19937
- const predicate = escapeSurrealString(propMeta.predicate);
19938
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
19939
- if (Array.isArray(condition)) {
19940
- const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
19941
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
19942
- }
19943
- else if (typeof condition === 'object' && condition !== null) {
19944
- const ops = condition;
19945
- if (ops.not !== undefined) {
19946
- if (Array.isArray(ops.not)) {
19947
- const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
19948
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
19949
- }
19950
- else {
19951
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
19952
- }
19953
- }
19954
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
19955
- ops.lt !== undefined || ops.lte !== undefined ||
19956
- ops.between !== undefined || ops.contains !== undefined;
19957
- if (hasComparisonOps) {
19958
- conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
19959
- }
19960
- }
19961
- else {
19962
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
19963
- }
19964
- }
19999
+ function isLiteralStoredProperty(propMeta) {
20000
+ if (propMeta.flag)
20001
+ return false;
20002
+ // If resolveLanguage is set to something other than "literal", it's a language expression URI
20003
+ if (propMeta.resolveLanguage && propMeta.resolveLanguage !== "literal")
20004
+ return false;
20005
+ // Everything else (resolveLanguage === "literal" or undefined) stores as literal: URIs
20006
+ return true;
20007
+ }
20008
+ /**
20009
+ * Escape a string for use as a SPARQL string literal.
20010
+ */
20011
+ function escapeSPARQL(value) {
20012
+ return value
20013
+ .replace(/\\/g, "\\\\")
20014
+ .replace(/"/g, '\\"')
20015
+ .replace(/\n/g, "\\n")
20016
+ .replace(/\r/g, "\\r")
20017
+ .replace(/\t/g, "\\t");
20018
+ }
20019
+ /**
20020
+ * Format a value as a SPARQL string literal (double-quoted).
20021
+ */
20022
+ function formatSPARQLValue(value) {
20023
+ if (typeof value === "string") {
20024
+ return `"${escapeSPARQL(value)}"`;
19965
20025
  }
19966
- return conditions.join(' AND ');
20026
+ return `"${String(value)}"`;
19967
20027
  }
19968
- // ─── Main Query Builder ─────────────────────────────────────────────────────
19969
20028
  /**
19970
- * Builds a complete SurrealQL query from a Query object and model metadata.
19971
- *
19972
- * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
19973
- * It produces a graph-traversal query that:
19974
- * 1. Filters nodes by required predicates (conformance check)
19975
- * 2. Applies user WHERE conditions
19976
- * 3. Fetches all outgoing links for hydration
20029
+ * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
20030
+ * All AD4M link source/predicate/target values become IRIs in angle brackets.
20031
+ * The Rust SPARQL service transparently transforms these to valid IRI format.
20032
+ */
20033
+ function iri(value) {
20034
+ return `<${value}>`;
20035
+ }
20036
+ /**
20037
+ * Build a SPARQL query that returns all links belonging to instances of
20038
+ * the given model class, optionally filtered by `where` conditions.
19977
20039
  *
19978
- * @param metadata - Model metadata from `getModelMetadata()`
19979
- * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
19980
- * @param query - Query parameters
19981
- * @param modelClass - The model class (for `resolveParentPredicate`)
19982
- * @returns Complete SurrealQL query string
20040
+ * Uses direct triple patterns: ?source ?predicate ?target
20041
+ * with named graph storage and metadata keyed by graph IRI.
19983
20042
  */
19984
- function buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass) {
19985
- const { where } = query;
19986
- // Build graph traversal filters for required predicates
19987
- const graphTraversalFilters = [];
19988
- // Parent filter
20043
+ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
20044
+ const joinPatterns = [];
20045
+ const filterExpressions = [];
20046
+ // Parent filter — direct triple pattern
19989
20047
  if (query.parent) {
19990
20048
  const parentPredicate = resolveParentPredicate(query.parent, modelClass);
19991
- graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
20049
+ joinPatterns.push(`
20050
+ ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
19992
20051
  }
19993
- // Required property filters
20052
+ // Required property JOIN patterns — direct triple patterns
20053
+ let hasConformance = false;
19994
20054
  for (const [, propMeta] of Object.entries(metadata.properties)) {
19995
20055
  if (propMeta.required) {
19996
20056
  if (propMeta.getter)
19997
20057
  continue;
20058
+ hasConformance = true;
19998
20059
  if (propMeta.flag && propMeta.initial) {
19999
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
20060
+ joinPatterns.push(`
20061
+ ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
20000
20062
  }
20001
20063
  else {
20002
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
20064
+ joinPatterns.push(`
20065
+ ?source ${iri(propMeta.predicate)} ?cfTarget_${propMeta.name} .`);
20003
20066
  }
20004
20067
  }
20005
20068
  }
20006
- // Fallback: initial-value filters
20007
- if (graphTraversalFilters.length === 0) {
20069
+ // Fallback: initial-value JOIN patterns
20070
+ if (!hasConformance) {
20008
20071
  for (const [, propMeta] of Object.entries(metadata.properties)) {
20009
20072
  if (propMeta.initial) {
20073
+ hasConformance = true;
20010
20074
  if (propMeta.flag) {
20011
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
20075
+ joinPatterns.push(`
20076
+ ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
20012
20077
  }
20013
20078
  else {
20014
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
20079
+ joinPatterns.push(`
20080
+ ?source ${iri(propMeta.predicate)} ?cfInitTarget_${propMeta.name} .`);
20015
20081
  }
20016
20082
  break;
20017
20083
  }
20018
20084
  }
20019
20085
  }
20020
20086
  // Fallback: open-world structural matching
20021
- if (graphTraversalFilters.length === 0) {
20022
- const structuralPredicates = [];
20087
+ // Use a subquery with DISTINCT to avoid row multiplication when the main
20088
+ // ?source ?predicate ?target pattern cross-joins with multiple structural matches.
20089
+ if (!hasConformance && joinPatterns.length === 0) {
20090
+ const knownPredicates = [];
20023
20091
  for (const [, propMeta] of Object.entries(metadata.properties)) {
20024
20092
  if (propMeta.predicate) {
20025
- structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
20093
+ knownPredicates.push(iri(propMeta.predicate));
20026
20094
  }
20027
20095
  }
20028
20096
  if (metadata.relations) {
20029
20097
  for (const [, relMeta] of Object.entries(metadata.relations)) {
20030
20098
  if (relMeta.predicate) {
20031
- structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
20099
+ knownPredicates.push(iri(relMeta.predicate));
20032
20100
  }
20033
20101
  }
20034
20102
  }
20035
- if (structuralPredicates.length > 0) {
20036
- graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
20103
+ if (knownPredicates.length > 0) {
20104
+ joinPatterns.push(`
20105
+ { SELECT DISTINCT ?source WHERE { ?source ?cf_structPred ?cf_structTarget . FILTER(?cf_structPred IN (${knownPredicates.join(", ")})) } }`);
20037
20106
  }
20038
20107
  }
20039
- // User WHERE clause
20040
- const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
20041
- const whereConditions = [];
20042
- whereConditions.push(...graphTraversalFilters);
20043
- if (userWhereClause) {
20044
- whereConditions.push(userWhereClause);
20108
+ // Build WHERE clause filters from user query
20109
+ const { joins: userJoins, filters: userFilters } = buildSPARQLWhereFilters(metadata, allRelationsMetadata, query.where);
20110
+ joinPatterns.push(...userJoins);
20111
+ filterExpressions.push(...userFilters);
20112
+ // Main triple pattern — fetches all links for matched sources
20113
+ // The direct triple in named graph: GRAPH ?linkGraph { ?source ?predicate ?target }
20114
+ // FILTER(isIRI(?source)) excludes non-IRI subjects
20115
+ const joinClause = joinPatterns.join("\n");
20116
+ const filterClause = filterExpressions.length > 0
20117
+ ? `FILTER(\n ${filterExpressions.join(" &&\n ")}\n )`
20118
+ : "";
20119
+ return `
20120
+ SELECT ?source ?predicate ?target ?author ?timestamp WHERE {${joinClause}
20121
+ GRAPH ?linkGraph { ?source ?predicate ?target . }
20122
+ FILTER(isIRI(?source) && isIRI(?predicate))
20123
+ ?linkGraph <ad4m://ontology/author> ?author .
20124
+ ?linkGraph <ad4m://ontology/timestamp> ?timestamp .
20125
+ ${filterClause}
20126
+ }
20127
+ ${buildSPARQLOrderLimitOffset()}
20128
+ `.trim();
20129
+ }
20130
+ /**
20131
+ * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
20132
+ */
20133
+ function buildSPARQLOrderLimitOffset(_metadata, _query) {
20134
+ return "";
20135
+ }
20136
+ /**
20137
+ * Build a SPARQL query to fetch all links for a single instance.
20138
+ */
20139
+ function buildSPARQLGetDataQuery(baseExpression) {
20140
+ return `
20141
+ SELECT ?source ?predicate ?target ?author ?timestamp WHERE {
20142
+ GRAPH ?linkGraph { ${iri(baseExpression)} ?predicate ?target . }
20143
+ FILTER(isIRI(?predicate))
20144
+ BIND(${iri(baseExpression)} AS ?source)
20145
+ ?linkGraph <ad4m://ontology/author> ?author .
20146
+ ?linkGraph <ad4m://ontology/timestamp> ?timestamp .
20147
+ }
20148
+ `.trim();
20149
+ }
20150
+ /**
20151
+ * Group flat SPARQL link rows into the same shape that SPARQL returned:
20152
+ * `{ source_uri: string, links: Array<{predicate, target, author, timestamp}> }`
20153
+ */
20154
+ function groupSPARQLResults(rows) {
20155
+ const grouped = new Map();
20156
+ for (const row of rows) {
20157
+ const key = row.source;
20158
+ if (!grouped.has(key)) {
20159
+ grouped.set(key, []);
20160
+ }
20161
+ grouped.get(key).push({
20162
+ predicate: row.predicate,
20163
+ target: row.target,
20164
+ author: row.author,
20165
+ timestamp: row.timestamp,
20166
+ });
20167
+ }
20168
+ return Array.from(grouped.entries()).map(([source_uri, links]) => ({
20169
+ source_uri,
20170
+ links,
20171
+ }));
20172
+ }
20173
+ /**
20174
+ * Build SPARQL FILTER expressions from user `where` conditions.
20175
+ * Uses direct triple patterns instead of link-node reification.
20176
+ */
20177
+ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
20178
+ if (!where)
20179
+ return { joins: [], filters: [] };
20180
+ const joins = [];
20181
+ const filters = [];
20182
+ for (const [propertyName, condition] of Object.entries(where)) {
20183
+ // 'base' maps to ?source
20184
+ if (propertyName === "base" || propertyName === "id") {
20185
+ if (Array.isArray(condition)) {
20186
+ const formatted = condition.map(v => iri(v)).join(", ");
20187
+ filters.push(`?source IN (${formatted})`);
20188
+ }
20189
+ else if (typeof condition === "object" && condition !== null) {
20190
+ const ops = condition;
20191
+ if (ops.not !== undefined) {
20192
+ if (Array.isArray(ops.not)) {
20193
+ const formatted = ops.not.map(v => iri(v)).join(", ");
20194
+ filters.push(`!(?source IN (${formatted}))`);
20195
+ }
20196
+ else {
20197
+ filters.push(`?source != ${iri(ops.not)}`);
20198
+ }
20199
+ }
20200
+ }
20201
+ else {
20202
+ filters.push(`?source = ${iri(String(condition))}`);
20203
+ }
20204
+ continue;
20205
+ }
20206
+ if (propertyName === "author" || propertyName === "timestamp") {
20207
+ continue;
20208
+ }
20209
+ const propMeta = metadata.properties[propertyName];
20210
+ if (!propMeta)
20211
+ continue;
20212
+ // Skip reverse relations (belongsToOne / belongsToMany) — these are registered as
20213
+ // read-only properties but the link direction is reversed (target→source, not source→target).
20214
+ // Adding a forward join pattern would match nothing. These are filtered in JS post-filter.
20215
+ const relMeta = _allRelationsMetadata[propertyName];
20216
+ if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {
20217
+ continue;
20218
+ }
20219
+ // Determine if this property stores values as literal: IRIs
20220
+ const useParseLiteral = isLiteralStoredProperty(propMeta);
20221
+ // For literal-stored properties, skip SPARQL-level FILTER expressions entirely.
20222
+ // The parse_literal custom function is unreliable across oxigraph versions and
20223
+ // environments. All property-level where filtering is done in JS post-filter
20224
+ // (instancesFromQueryResult) after hydration resolves values to JS primitives.
20225
+ // We only add a JOIN pattern to ensure the property exists (conformance check).
20226
+ if (useParseLiteral) {
20227
+ // Just ensure the property exists — no value filtering in SPARQL
20228
+ if (typeof condition === "object" && condition !== null && !Array.isArray(condition)) {
20229
+ const ops = condition;
20230
+ const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
20231
+ ops.lt !== undefined || ops.lte !== undefined ||
20232
+ ops.between !== undefined || ops.contains !== undefined ||
20233
+ ops.not !== undefined;
20234
+ if (hasCompOps) {
20235
+ joins.push(`
20236
+ ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
20237
+ }
20238
+ // NOT filters: no SPARQL-level filtering — handled in JS
20239
+ }
20240
+ else {
20241
+ // Simple equality or IN — add join for conformance.
20242
+ // NOTE: push-down FILTER with fn::parse_literal was attempted but removed because
20243
+ // Oxigraph's query parser rejects the fn:: custom function syntax at parse time
20244
+ // (custom functions are only available at execution time). All literal property
20245
+ // filtering is done in JS post-filter after hydration resolves values.
20246
+ joins.push(`
20247
+ ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
20248
+ }
20249
+ }
20250
+ else if (Array.isArray(condition)) {
20251
+ const formatted = condition.map(v => iri(v)).join(", ");
20252
+ joins.push(`
20253
+ ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
20254
+ filters.push(`?wTarget_${propertyName} IN (${formatted})`);
20255
+ }
20256
+ else if (typeof condition === "object" && condition !== null) {
20257
+ const ops = condition;
20258
+ if (ops.not !== undefined) {
20259
+ if (Array.isArray(ops.not)) {
20260
+ const formatted = ops.not.map(v => iri(v)).join(", ");
20261
+ filters.push(`
20262
+ NOT EXISTS {
20263
+ ?source ${iri(propMeta.predicate)} ?wTarget_not_${propertyName} .
20264
+ FILTER(?wTarget_not_${propertyName} IN (${formatted}))
20265
+ }
20266
+ `);
20267
+ }
20268
+ else {
20269
+ filters.push(`
20270
+ NOT EXISTS {
20271
+ ?source ${iri(propMeta.predicate)} ${iri(ops.not)} .
20272
+ }
20273
+ `);
20274
+ }
20275
+ }
20276
+ const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
20277
+ ops.lt !== undefined || ops.lte !== undefined ||
20278
+ ops.between !== undefined || ops.contains !== undefined;
20279
+ if (hasCompOps) {
20280
+ joins.push(`
20281
+ ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
20282
+ }
20283
+ }
20284
+ else {
20285
+ // Simple equality — non-literal property, use exact IRI match
20286
+ joins.push(`
20287
+ ?source ${iri(propMeta.predicate)} ${iri(String(condition))} .`);
20288
+ }
20289
+ }
20290
+ return { joins, filters };
20291
+ }
20292
+
20293
+ /**
20294
+ * Subscription Pool — deduplicates identical SPARQL subscriptions.
20295
+ *
20296
+ * When multiple UI components subscribe to the same SPARQL query on the same
20297
+ * perspective, the pool shares a single `subscribeQuery()` call and distributes
20298
+ * results to all registered callbacks. Hydration happens once per result set,
20299
+ * then is shared across all subscribers.
20300
+ *
20301
+ * Key: `perspectiveUUID + sparqlQuery`
20302
+ */
20303
+ const pool = new Map();
20304
+ function makeKey(perspectiveUUID, sparqlQuery) {
20305
+ return `${perspectiveUUID}::${sparqlQuery}`;
20306
+ }
20307
+ /**
20308
+ * Subscribe to a SPARQL query, sharing the underlying subscription
20309
+ * with any other subscribers using the same perspective + query.
20310
+ *
20311
+ * @param perspective - The perspective proxy
20312
+ * @param sparqlQuery - The SPARQL query text
20313
+ * @param hydrate - Async function that takes raw SPARQL results and returns hydrated results
20314
+ * @param onResult - Callback for subsequent result updates (hydrated)
20315
+ * @returns PooledSubscription with initial result and dispose function
20316
+ */
20317
+ async function pooledSubscribe(perspective, sparqlQuery, hydrate, onResult) {
20318
+ const uuid = perspective.uuid || perspective.handle?.uuid || '';
20319
+ const key = makeKey(uuid, sparqlQuery);
20320
+ const entry = pool.get(key);
20321
+ const subscriber = { onResult, hydrate };
20322
+ if (entry) {
20323
+ // Join existing subscription
20324
+ entry.callbacks.add(subscriber);
20325
+ entry.refCount++;
20326
+ // Hydrate latest result for this new subscriber
20327
+ let initialResult;
20328
+ if (entry.latestHydrated !== undefined) {
20329
+ initialResult = entry.latestHydrated;
20330
+ }
20331
+ else if (entry.latestRaw !== undefined) {
20332
+ initialResult = await hydrate(entry.latestRaw);
20333
+ }
20334
+ return {
20335
+ initialResult,
20336
+ dispose: () => disposeSubscriber(key, subscriber),
20337
+ };
20338
+ }
20339
+ // Create new subscription
20340
+ const subscription = await perspective.subscribeQuery(sparqlQuery);
20341
+ const newEntry = {
20342
+ subscription,
20343
+ callbacks: new Set([subscriber]),
20344
+ latestRaw: subscription.result,
20345
+ latestHydrated: undefined,
20346
+ hydrating: false,
20347
+ refCount: 1,
20348
+ };
20349
+ pool.set(key, newEntry);
20350
+ // Set up shared result handler
20351
+ subscription.onResult(async (rawResult) => {
20352
+ newEntry.latestRaw = rawResult;
20353
+ newEntry.hydrating = true;
20354
+ try {
20355
+ // Hydrate ONCE using the first subscriber's hydrate function
20356
+ const firstSub = newEntry.callbacks.values().next().value;
20357
+ if (firstSub) {
20358
+ const hydrated = await firstSub.hydrate(rawResult);
20359
+ newEntry.latestHydrated = hydrated;
20360
+ // Distribute to all callbacks
20361
+ for (const cb of newEntry.callbacks) {
20362
+ try {
20363
+ cb.onResult(hydrated);
20364
+ }
20365
+ catch (e) { /* subscriber error */ }
20366
+ }
20367
+ }
20368
+ }
20369
+ finally {
20370
+ newEntry.hydrating = false;
20371
+ }
20372
+ });
20373
+ // Hydrate initial result
20374
+ const initialResult = await hydrate(subscription.result);
20375
+ newEntry.latestHydrated = initialResult;
20376
+ return {
20377
+ initialResult,
20378
+ dispose: () => disposeSubscriber(key, subscriber),
20379
+ };
20380
+ }
20381
+ function disposeSubscriber(key, subscriber) {
20382
+ const entry = pool.get(key);
20383
+ if (!entry)
20384
+ return;
20385
+ entry.callbacks.delete(subscriber);
20386
+ entry.refCount--;
20387
+ if (entry.refCount <= 0) {
20388
+ // Last subscriber — tear down the underlying subscription
20389
+ if (entry.subscription?.dispose) {
20390
+ entry.subscription.dispose();
20391
+ }
20392
+ pool.delete(key);
20045
20393
  }
20046
- whereConditions.push(`count(->link) > 0`);
20047
- const fullQuery = `
20048
- SELECT
20049
- id AS source,
20050
- uri AS source_uri,
20051
- ->link AS links
20052
- FROM node
20053
- WHERE ${whereConditions.join(' AND ')}
20054
- FETCH links
20055
- `.trim();
20056
- return fullQuery;
20394
+ }
20395
+ /**
20396
+ * Clear the entire pool (for testing).
20397
+ */
20398
+ function clearSubscriptionPool() {
20399
+ for (const entry of pool.values()) {
20400
+ if (entry.subscription?.dispose) {
20401
+ entry.subscription.dispose();
20402
+ }
20403
+ }
20404
+ pool.clear();
20405
+ }
20406
+ /**
20407
+ * Get the current pool size (for testing).
20408
+ */
20409
+ function subscriptionPoolSize() {
20410
+ return pool.size;
20057
20411
  }
20058
20412
 
20059
20413
  /**
@@ -20086,7 +20440,7 @@ class ModelQueryBuilder {
20086
20440
  constructor(perspective, ctor, query) {
20087
20441
  this.queryParams = {};
20088
20442
  this.modelClassName = null;
20089
- this.useSurrealDBFlag = true;
20443
+ this.engineFlag = 'sparql';
20090
20444
  this.perspective = perspective;
20091
20445
  this.ctor = ctor;
20092
20446
  if (query)
@@ -20294,32 +20648,10 @@ class ModelQueryBuilder {
20294
20648
  return this;
20295
20649
  }
20296
20650
  /**
20297
- * Enables or disables SurrealDB query path.
20298
- *
20299
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
20300
- * @returns The query builder for chaining
20301
- *
20302
- * @example
20303
- * ```typescript
20304
- * // Use SurrealDB (default)
20305
- * const recipes = await Recipe.query(perspective)
20306
- * .where({ category: "Dessert" })
20307
- * .useSurrealDB(true)
20308
- * .get();
20309
- *
20310
- * // Use Prolog (legacy)
20311
- * const recipesProlog = await Recipe.query(perspective)
20312
- * .where({ category: "Dessert" })
20313
- * .useSurrealDB(false)
20314
- * .get();
20315
- * ```
20316
- *
20317
- * @remarks
20318
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
20319
- * if useSurrealDB(true) is set (default).
20651
+ * Sets the query engine to use.
20320
20652
  */
20321
- useSurrealDB(enabled = true) {
20322
- this.useSurrealDBFlag = enabled;
20653
+ engine(eng) {
20654
+ this.engineFlag = eng;
20323
20655
  return this;
20324
20656
  }
20325
20657
  /**
@@ -20336,10 +20668,8 @@ class ModelQueryBuilder {
20336
20668
  */
20337
20669
  async get() {
20338
20670
  let results;
20339
- if (this.useSurrealDBFlag) {
20340
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20341
- const result = await this.perspective.querySurrealDB(surrealQuery);
20342
- ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
20671
+ if (this.engineFlag === 'sparql') {
20672
+ results = await this.executeSparqlQuery();
20343
20673
  }
20344
20674
  else {
20345
20675
  const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
@@ -20348,6 +20678,29 @@ class ModelQueryBuilder {
20348
20678
  }
20349
20679
  return results;
20350
20680
  }
20681
+ /**
20682
+ * Executes the query once using SPARQL and returns the results.
20683
+ */
20684
+ async getSparql() {
20685
+ return this.executeSparqlQuery();
20686
+ }
20687
+ /**
20688
+ * Shared SPARQL query execution logic used by both get() and getSparql().
20689
+ */
20690
+ async executeSparqlQuery() {
20691
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20692
+ const rawResult = await this.perspective.querySparql(sparqlQuery);
20693
+ const { results } = await this.processSparqlResult(rawResult);
20694
+ return results;
20695
+ }
20696
+ /**
20697
+ * Groups raw SPARQL results and hydrates them into model instances.
20698
+ * Centralises the repeated groupSPARQLResults → instancesFromQueryResult pipeline.
20699
+ */
20700
+ async processSparqlResult(rawResult, queryOverride) {
20701
+ const grouped = groupSPARQLResults(Array.isArray(rawResult) ? rawResult : []);
20702
+ return await this.ctor.instancesFromQueryResult(this.perspective, queryOverride || this.queryParams, grouped);
20703
+ }
20351
20704
  /**
20352
20705
  * Returns the first matching instance, or `null` if none match.
20353
20706
  *
@@ -20371,7 +20724,7 @@ class ModelQueryBuilder {
20371
20724
  * Subscribes to the query and receives updates when results change.
20372
20725
  *
20373
20726
  * This method:
20374
- * 1. Creates and initializes a SurrealDB live query subscription (default)
20727
+ * 1. Creates and initializes a SPARQL live query subscription (default)
20375
20728
  * 2. Sets up the callback to process future updates
20376
20729
  * 3. Returns the initial results immediately
20377
20730
  *
@@ -20395,26 +20748,40 @@ class ModelQueryBuilder {
20395
20748
  * ```
20396
20749
  *
20397
20750
  * @remarks
20398
- * By default, this uses SurrealDB live queries for real-time updates.
20399
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
20751
+ * By default, this uses SPARQL live queries for real-time updates.
20752
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20400
20753
  */
20401
20754
  async subscribe(callback) {
20402
20755
  // Clean up any existing subscription
20403
20756
  this.dispose();
20404
20757
  const ctor = this.ctor;
20405
- if (this.useSurrealDBFlag) {
20406
- const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
20407
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20408
- const processResults = async (result) => {
20409
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20410
- callback(results);
20758
+ if (this.engineFlag === 'sparql') {
20759
+ const sparqlQuery = await ctor.queryToSPARQL(this.perspective, this.queryParams);
20760
+ // Track last emitted result fingerprint to suppress duplicate callbacks
20761
+ let lastResultFingerprint = null;
20762
+ const buildFingerprint = (results) => {
20763
+ if (results.length === 0)
20764
+ return '0:';
20765
+ const ids = results.map((r) => r.id || '').sort().join(',');
20766
+ const ts = results.map((r) => r.updatedAt || r.timestamp || '').join(',');
20767
+ return `${results.length}:${ids}:${ts}`;
20411
20768
  };
20412
- this.currentSubscription.onResult(processResults);
20413
- // Process initial result
20414
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20415
- // Also invoke callback with initial results so subscribers see them
20416
- callback(results);
20417
- return results;
20769
+ const hydrate = async (rawResult) => {
20770
+ const { results } = await this.processSparqlResult(rawResult);
20771
+ return results;
20772
+ };
20773
+ const pooled = await pooledSubscribe(this.perspective, sparqlQuery, hydrate, (hydratedResults) => {
20774
+ const fp = buildFingerprint(hydratedResults);
20775
+ if (fp === lastResultFingerprint)
20776
+ return;
20777
+ lastResultFingerprint = fp;
20778
+ callback(hydratedResults);
20779
+ });
20780
+ // Store dispose function as subscription
20781
+ this.currentSubscription = { dispose: pooled.dispose };
20782
+ const initialResults = pooled.initialResult;
20783
+ lastResultFingerprint = buildFingerprint(initialResults);
20784
+ return initialResults;
20418
20785
  }
20419
20786
  else {
20420
20787
  const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
@@ -20425,11 +20792,26 @@ class ModelQueryBuilder {
20425
20792
  };
20426
20793
  this.currentSubscription.onResult(processResults);
20427
20794
  const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
20428
- // Also invoke callback with initial results so subscribers see them
20429
- callback(results);
20795
+ // Initial results returned via Promise only — callback is for subsequent updates
20430
20796
  return results;
20431
20797
  }
20432
20798
  }
20799
+ /**
20800
+ * Subscribes to the query and receives updates using SPARQL.
20801
+ */
20802
+ async subscribeSparql(callback) {
20803
+ this.dispose();
20804
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20805
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20806
+ const processResults = async (result) => {
20807
+ const { results } = await this.processSparqlResult(result);
20808
+ callback(results);
20809
+ };
20810
+ this.currentSubscription.onResult(processResults);
20811
+ const { results } = await this.processSparqlResult(this.currentSubscription.result);
20812
+ // Initial results returned via Promise only — callback is for subsequent updates
20813
+ return results;
20814
+ }
20433
20815
  /**
20434
20816
  * Gets the total count of matching entities.
20435
20817
  *
@@ -20443,13 +20825,10 @@ class ModelQueryBuilder {
20443
20825
  * ```
20444
20826
  */
20445
20827
  async count() {
20446
- if (this.useSurrealDBFlag) {
20447
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20448
- const result = await this.perspective.querySurrealDB(surrealQuery);
20449
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
20450
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
20451
- // This ensures count() returns the same number as get().length
20452
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20828
+ if (this.engineFlag === 'sparql') {
20829
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20830
+ const rawResult = await this.perspective.querySparql(sparqlQuery);
20831
+ const { totalCount } = await this.processSparqlResult(rawResult);
20453
20832
  return totalCount;
20454
20833
  }
20455
20834
  else {
@@ -20458,11 +20837,25 @@ class ModelQueryBuilder {
20458
20837
  return result?.[0]?.TotalCount || 0;
20459
20838
  }
20460
20839
  }
20840
+ /**
20841
+ * Gets the total count of matching entities using SPARQL.
20842
+ * Delegates to count() with SPARQL engine forced.
20843
+ */
20844
+ async countSparql() {
20845
+ const prev = this.engineFlag;
20846
+ this.engineFlag = 'sparql';
20847
+ try {
20848
+ return await this.count();
20849
+ }
20850
+ finally {
20851
+ this.engineFlag = prev;
20852
+ }
20853
+ }
20461
20854
  /**
20462
20855
  * Subscribes to count updates for matching entities.
20463
20856
  *
20464
20857
  * This method:
20465
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
20858
+ * 1. Creates and initializes a SPARQL live query subscription for the count (default)
20466
20859
  * 2. Sets up the callback to process future count updates
20467
20860
  * 3. Returns the initial count immediately
20468
20861
  *
@@ -20486,22 +20879,22 @@ class ModelQueryBuilder {
20486
20879
  * ```
20487
20880
  *
20488
20881
  * @remarks
20489
- * By default, this uses SurrealDB live queries for real-time updates.
20490
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
20882
+ * By default, this uses SPARQL live queries for real-time updates.
20883
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20491
20884
  */
20492
20885
  async countSubscribe(callback) {
20493
20886
  // Clean up any existing subscription
20494
20887
  this.dispose();
20495
- if (this.useSurrealDBFlag) {
20496
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20497
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20888
+ if (this.engineFlag === 'sparql') {
20889
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20890
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20498
20891
  const processResults = async (result) => {
20499
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20892
+ const { totalCount } = await this.processSparqlResult(result);
20500
20893
  callback(totalCount);
20501
20894
  };
20502
20895
  this.currentSubscription.onResult(processResults);
20503
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20504
- callback(totalCount);
20896
+ const { totalCount } = await this.processSparqlResult(this.currentSubscription.result);
20897
+ // Initial count returned via Promise — callback for updates only
20505
20898
  return totalCount;
20506
20899
  }
20507
20900
  else {
@@ -20513,10 +20906,26 @@ class ModelQueryBuilder {
20513
20906
  };
20514
20907
  this.currentSubscription.onResult(processResults);
20515
20908
  const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
20516
- callback(initialCount);
20909
+ // Initial count returned via Promise — callback for subsequent updates only
20517
20910
  return initialCount;
20518
20911
  }
20519
20912
  }
20913
+ /**
20914
+ * Subscribes to count updates using SPARQL.
20915
+ */
20916
+ async countSubscribeSparql(callback) {
20917
+ this.dispose();
20918
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
20919
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20920
+ const processResults = async (result) => {
20921
+ const { totalCount } = await this.processSparqlResult(result);
20922
+ callback(totalCount);
20923
+ };
20924
+ this.currentSubscription.onResult(processResults);
20925
+ const { totalCount } = await this.processSparqlResult(this.currentSubscription.result);
20926
+ // Initial count returned via Promise — callback for updates only
20927
+ return totalCount;
20928
+ }
20520
20929
  /**
20521
20930
  * Gets a page of results with pagination metadata.
20522
20931
  *
@@ -20534,10 +20943,10 @@ class ModelQueryBuilder {
20534
20943
  */
20535
20944
  async paginate(pageSize, pageNumber) {
20536
20945
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20537
- if (this.useSurrealDBFlag) {
20538
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20539
- const result = await this.perspective.querySurrealDB(surrealQuery);
20540
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
20946
+ if (this.engineFlag === 'sparql') {
20947
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
20948
+ const result = await this.perspective.querySparql(sparqlQuery);
20949
+ const { results, totalCount } = await this.processSparqlResult(result, paginationQuery);
20541
20950
  return { results, totalCount, pageSize, pageNumber };
20542
20951
  }
20543
20952
  else {
@@ -20547,11 +20956,25 @@ class ModelQueryBuilder {
20547
20956
  return { results, totalCount, pageSize, pageNumber };
20548
20957
  }
20549
20958
  }
20959
+ /**
20960
+ * Gets a page of results using SPARQL.
20961
+ * Delegates to paginate() with SPARQL engine forced.
20962
+ */
20963
+ async paginateSparql(pageSize, pageNumber) {
20964
+ const prev = this.engineFlag;
20965
+ this.engineFlag = 'sparql';
20966
+ try {
20967
+ return await this.paginate(pageSize, pageNumber);
20968
+ }
20969
+ finally {
20970
+ this.engineFlag = prev;
20971
+ }
20972
+ }
20550
20973
  /**
20551
20974
  * Subscribes to paginated results updates.
20552
20975
  *
20553
20976
  * This method:
20554
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
20977
+ * 1. Creates and initializes a SPARQL live query subscription for the paginated results (default)
20555
20978
  * 2. Sets up the callback to process future page updates
20556
20979
  * 3. Returns the initial page immediately
20557
20980
  *
@@ -20577,24 +21000,24 @@ class ModelQueryBuilder {
20577
21000
  * ```
20578
21001
  *
20579
21002
  * @remarks
20580
- * By default, this uses SurrealDB live queries for real-time updates.
20581
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
21003
+ * By default, this uses SPARQL live queries for real-time updates.
21004
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
20582
21005
  */
20583
21006
  async paginateSubscribe(pageSize, pageNumber, callback) {
20584
21007
  // Clean up any existing subscription
20585
21008
  this.dispose();
20586
21009
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
20587
- if (this.useSurrealDBFlag) {
20588
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20589
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
21010
+ if (this.engineFlag === 'sparql') {
21011
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
21012
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
20590
21013
  const processResults = async (result) => {
20591
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
21014
+ const { results, totalCount } = await this.processSparqlResult(result, paginationQuery);
20592
21015
  callback({ results, totalCount, pageSize, pageNumber });
20593
21016
  };
20594
21017
  this.currentSubscription.onResult(processResults);
20595
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
21018
+ const { results, totalCount } = await this.processSparqlResult(this.currentSubscription.result, paginationQuery);
20596
21019
  const initialPage = { results, totalCount, pageSize, pageNumber };
20597
- callback(initialPage);
21020
+ // Initial page returned via Promise — callback for subsequent updates only
20598
21021
  return initialPage;
20599
21022
  }
20600
21023
  else {
@@ -20607,17 +21030,31 @@ class ModelQueryBuilder {
20607
21030
  this.currentSubscription.onResult(processResults);
20608
21031
  const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
20609
21032
  const initialPrologPage = { results, totalCount, pageSize, pageNumber };
20610
- callback(initialPrologPage);
21033
+ // Initial page returned via Promise — callback for subsequent updates only
20611
21034
  return initialPrologPage;
20612
21035
  }
20613
21036
  }
21037
+ /**
21038
+ * Subscribes to paginated results updates using SPARQL.
21039
+ * Delegates to paginateSubscribe() with SPARQL engine forced.
21040
+ */
21041
+ async paginateSubscribeSparql(pageSize, pageNumber, callback) {
21042
+ const prev = this.engineFlag;
21043
+ this.engineFlag = 'sparql';
21044
+ try {
21045
+ return await this.paginateSubscribe(pageSize, pageNumber, callback);
21046
+ }
21047
+ finally {
21048
+ this.engineFlag = prev;
21049
+ }
21050
+ }
20614
21051
  }
20615
21052
 
20616
21053
  /**
20617
21054
  * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
20618
21055
  *
20619
21056
  * Pure / stateless functions that populate Ad4mModel instances from
20620
- * raw link arrays, Prolog tuples, or SurrealDB rows. None of these
21057
+ * raw link arrays, Prolog tuples, or query results. None of these
20621
21058
  * functions depend on the `Ad4mModel` class at runtime — they accept
20622
21059
  * the instance, metadata, or perspective as explicit parameters.
20623
21060
  */
@@ -20712,7 +21149,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
20712
21149
  if (propMeta.resolveLanguage != null &&
20713
21150
  propMeta.resolveLanguage !== 'literal' &&
20714
21151
  typeof target === 'string' &&
20715
- !target.startsWith('literal://')) {
21152
+ !target.startsWith('literal:')) {
20716
21153
  try {
20717
21154
  const expression = await perspective.getExpression(target);
20718
21155
  if (expression) {
@@ -20731,7 +21168,7 @@ async function hydratePropertyValue(target, propMeta, perspective, expectedType)
20731
21168
  // Literal URI parsing
20732
21169
  else if (propMeta.resolveLanguage === 'literal' &&
20733
21170
  typeof target === 'string' &&
20734
- target.startsWith('literal://')) {
21171
+ target.startsWith('literal:')) {
20735
21172
  try {
20736
21173
  const parsed = Literal.fromUrl(target).get();
20737
21174
  value = parsed.data !== undefined ? parsed.data : parsed;
@@ -20963,10 +21400,10 @@ async function assignValuesToInstance(perspective, instance, values) {
20963
21400
  Object.assign(instance, writableProps);
20964
21401
  }
20965
21402
  // ──────────────────────────────────────────────────────────
20966
- // SurrealQL custom getter evaluation
21403
+ // SPARQL custom getter evaluation
20967
21404
  // ──────────────────────────────────────────────────────────
20968
21405
  /**
20969
- * Builds a SurrealQL conformance getter for a relation whose `target` model
21406
+ * Builds a SPARQL conformance getter for a relation whose `target` model
20970
21407
  * is known but no explicit `getter` string was supplied.
20971
21408
  *
20972
21409
  * The generated getter traverses outgoing links matching the relation's
@@ -20978,7 +21415,7 @@ async function assignValuesToInstance(perspective, instance, values) {
20978
21415
  *
20979
21416
  * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
20980
21417
  * @param targetClass - The target model class (result of calling the `target()` thunk)
20981
- * @returns A SurrealQL expression string, or `undefined` if no conformance
21418
+ * @returns A SPARQL expression string, or `undefined` if no conformance
20982
21419
  * conditions could be derived from the target model.
20983
21420
  */
20984
21421
  function buildConformanceGetter(relationPredicate, targetClass) {
@@ -20997,7 +21434,7 @@ function buildConformanceGetter(relationPredicate, targetClass) {
20997
21434
  * getter is auto-generated from the target model's metadata (unless `filter: false`).
20998
21435
  */
20999
21436
  async function evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
21000
- const safeBaseExpression = formatSurrealValue(instance.id);
21437
+ `<${instance.id}>`;
21001
21438
  // Build projection filter — when requestedProperties is active, only
21002
21439
  // evaluate getters for fields that are requested (or included).
21003
21440
  const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
@@ -21008,12 +21445,28 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21008
21445
  continue;
21009
21446
  if (propMeta.getter) {
21010
21447
  try {
21011
- // Replace 'Base' placeholder with actual base expression
21012
- const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
21013
- // Query from node table to have graph traversal context
21014
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
21015
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
21016
- instance[propName] = result[0].value;
21448
+ const rawGetter = propMeta.getter;
21449
+ const getterWithBase = rawGetter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/Base/g, `<${instance.id}>`);
21450
+ // If the getter is already SPARQL (starts with SELECT/ASK/CONSTRUCT), execute directly
21451
+ const trimmed = getterWithBase.trim().toUpperCase();
21452
+ if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
21453
+ const result = await perspective.querySparql(getterWithBase);
21454
+ if (trimmed.startsWith('ASK')) {
21455
+ instance[propName] = result === true || result === 'true';
21456
+ }
21457
+ else if (result && result.length > 0) {
21458
+ // Get first binding's first value
21459
+ const firstRow = result[0];
21460
+ const firstKey = Object.keys(firstRow)[0];
21461
+ const val = firstRow[firstKey]?.value ?? firstRow[firstKey];
21462
+ if (val !== undefined && val !== null && val !== 'None' && val !== '') {
21463
+ instance[propName] = val;
21464
+ }
21465
+ }
21466
+ }
21467
+ else {
21468
+ // Legacy SurrealDB-style getter — no longer supported
21469
+ console.warn(`Unsupported legacy getter syntax for property ${propName} — use native SPARQL (SELECT/ASK): ${rawGetter.slice(0, 100)}`);
21017
21470
  }
21018
21471
  }
21019
21472
  catch (error) {
@@ -21029,12 +21482,11 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21029
21482
  const meta = relMeta;
21030
21483
  // Determine the getter to execute:
21031
21484
  // 1. Explicit `getter` always wins
21032
- // 2. `where` clause → compile DSL to SurrealQL getter
21033
- // 3. If `target` is set and `filter !== false`, auto-generate from target metadata
21485
+ // 2. If `target` is set and `filter !== false`, auto-generate conformance getter
21034
21486
  // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
21035
- // because buildConformanceGetter traverses outgoing links (->link) which is
21036
- // wrong for reverse relations. Their values are already populated by the
21037
- // reverse link lookup in instancesFromSurrealResult / getData.
21487
+ // because buildConformanceGetter traverses outgoing links which is wrong for
21488
+ // reverse relations. Their values are already populated by the reverse link
21489
+ // lookup in instancesFromQueryResult / getData.
21038
21490
  let getter = meta.getter;
21039
21491
  if (!getter && meta.where && meta.direction !== 'reverse') {
21040
21492
  try {
@@ -21042,14 +21494,35 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21042
21494
  const targetMetadata = TargetClass
21043
21495
  ? TargetClass.getModelMetadata?.() ?? null
21044
21496
  : null;
21045
- const conditions = compileWhereClause(meta.where, targetMetadata);
21046
- if (conditions.length > 0) {
21047
- const escapedPred = escapeSurrealString(meta.predicate);
21048
- getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
21497
+ // Check if all where conditions can be SPARQL-filtered.
21498
+ // literal-resolved properties store signed expressions (literal:json:{…}),
21499
+ // not raw literal:string: IRIs, so SPARQL exact-match fails for them.
21500
+ let allSparqlFilterable = true;
21501
+ if (targetMetadata) {
21502
+ for (const propName of Object.keys(meta.where)) {
21503
+ if (['id', 'author', 'timestamp'].includes(propName))
21504
+ continue;
21505
+ const propMeta = targetMetadata.properties[propName];
21506
+ if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
21507
+ allSparqlFilterable = false;
21508
+ break;
21509
+ }
21510
+ }
21511
+ }
21512
+ else {
21513
+ allSparqlFilterable = false;
21049
21514
  }
21515
+ if (allSparqlFilterable) {
21516
+ const conditions = compileWhereClause(meta.where, targetMetadata);
21517
+ if (conditions.length > 0) {
21518
+ const escapedPredicate = escapeQueryString(meta.predicate);
21519
+ getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;
21520
+ }
21521
+ }
21522
+ // If not filterable, fall through to buildConformanceGetter + JS post-filter below
21050
21523
  }
21051
21524
  catch (e) {
21052
- // Target metadata may not be available yet
21525
+ console.warn(`[Ad4mModel] where-clause compilation failed for relation "${relName}":`, e);
21053
21526
  }
21054
21527
  }
21055
21528
  if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
@@ -21066,23 +21539,57 @@ async function evaluateCustomGettersForInstance(instance, perspective, metadata,
21066
21539
  }
21067
21540
  if (getter) {
21068
21541
  try {
21069
- // Replace 'Base' placeholder with actual base expression
21070
- const query = getter.replace(/Base/g, safeBaseExpression);
21071
- const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
21072
- // Query from node table to have graph traversal context
21073
- const result = await perspective.querySurrealDB(fullQuery);
21074
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
21075
- // Filter out 'None' from relation results
21076
- const value = result[0].value;
21077
- instance[relName] = Array.isArray(value)
21078
- ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
21079
- : value;
21542
+ const getterWithBase = getter.replace(/\?source\b/g, `<${instance.id}>`).replace(/<Base>/g, `<${instance.id}>`).replace(/\bBase\b/g, `<${instance.id}>`);
21543
+ const trimmed = getterWithBase.trim().toUpperCase();
21544
+ if (trimmed.startsWith('SELECT') || trimmed.startsWith('ASK') || trimmed.startsWith('CONSTRUCT')) {
21545
+ // Native SPARQL getter — execute directly
21546
+ const result = await perspective.querySparql(getterWithBase);
21547
+ if (result && result.length > 0) {
21548
+ const values = result.map((r) => {
21549
+ const firstKey = Object.keys(r)[0];
21550
+ return r[firstKey]?.value ?? r[firstKey];
21551
+ }).filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
21552
+ instance[relName] = values;
21553
+ }
21554
+ }
21555
+ else {
21556
+ // Legacy SurrealDB-style getter — no longer supported
21557
+ console.warn(`Unsupported legacy getter syntax for relation ${relName} — use native SPARQL (SELECT/ASK): ${getter.slice(0, 100)}`);
21080
21558
  }
21081
21559
  }
21082
21560
  catch (error) {
21083
21561
  console.warn(`Failed to evaluate getter for ${relName}:`, error);
21084
21562
  }
21085
21563
  }
21564
+ // JS post-filter for where conditions that couldn't be SPARQL-filtered
21565
+ // (e.g. literal-resolved properties storing signed expressions)
21566
+ const currentValues = instance[relName];
21567
+ if (meta.where && Array.isArray(currentValues) && currentValues.length > 0) {
21568
+ const TargetClass = meta.target?.();
21569
+ if (TargetClass) {
21570
+ const filtered = [];
21571
+ for (const targetId of currentValues) {
21572
+ try {
21573
+ const inst = new TargetClass(perspective, targetId);
21574
+ await inst.get();
21575
+ let matches = true;
21576
+ for (const [prop, expected] of Object.entries(meta.where)) {
21577
+ if (inst[prop] !== expected) {
21578
+ matches = false;
21579
+ break;
21580
+ }
21581
+ }
21582
+ if (matches)
21583
+ filtered.push(targetId);
21584
+ }
21585
+ catch {
21586
+ // If we can't hydrate, keep the value (conservative)
21587
+ filtered.push(targetId);
21588
+ }
21589
+ }
21590
+ instance[relName] = filtered;
21591
+ }
21592
+ }
21086
21593
  }
21087
21594
  }
21088
21595
  /**
@@ -21597,7 +22104,7 @@ class Ad4mModel {
21597
22104
  * const recipe = new Recipe(perspective);
21598
22105
  *
21599
22106
  * // Create with specific base expression
21600
- * const recipe = new Recipe(perspective, "literal://...");
22107
+ * const recipe = new Recipe(perspective, "literal:...");
21601
22108
  * ```
21602
22109
  */
21603
22110
  constructor(perspective, baseExpression) {
@@ -21824,19 +22331,13 @@ class Ad4mModel {
21824
22331
  }
21825
22332
  async getData(opts) {
21826
22333
  // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
21827
- // Use SurrealDB for data queries
22334
+ // Use SPARQL for data queries
21828
22335
  try {
21829
22336
  const ctor = this.constructor;
21830
22337
  const metadata = ctor.getModelMetadata();
21831
22338
  // Query for all links from this specific node (base expression)
21832
- const safeBaseExpression = formatSurrealValue(this._baseExpression);
21833
- const linksQuery = `
21834
- SELECT id, predicate, out.uri AS target, author, timestamp
21835
- FROM link
21836
- WHERE in.uri = ${safeBaseExpression}
21837
- ORDER BY timestamp ASC
21838
- `;
21839
- const links = await this._perspective.querySurrealDB(linksQuery);
22339
+ const linksQuery = buildSPARQLGetDataQuery(this._baseExpression);
22340
+ const links = await this._perspective.querySparql(linksQuery);
21840
22341
  if (links && links.length > 0) {
21841
22342
  // Core hydration: properties (latest-wins), relations, timestamps/author
21842
22343
  const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
@@ -21861,7 +22362,7 @@ class Ad4mModel {
21861
22362
  this[relName] = sourceIds;
21862
22363
  }
21863
22364
  }
21864
- // Evaluate SurrealQL getters
22365
+ // Evaluate SPARQL getters
21865
22366
  const getterOpts = opts?.properties || opts?.include
21866
22367
  ? { requestedProperties: opts?.properties, include: opts?.include }
21867
22368
  : undefined;
@@ -21872,7 +22373,7 @@ class Ad4mModel {
21872
22373
  }
21873
22374
  }
21874
22375
  catch (e) {
21875
- console.error(`SurrealDB getData also failed for ${this._baseExpression}:`, e);
22376
+ console.error(`SPARQL getData also failed for ${this._baseExpression}:`, e);
21876
22377
  }
21877
22378
  this.takeSnapshot();
21878
22379
  return this;
@@ -21902,13 +22403,13 @@ class Ad4mModel {
21902
22403
  return fullQuery;
21903
22404
  }
21904
22405
  /**
21905
- * Generates a SurrealQL query from a Query object.
22406
+ * Generates a SPARQL query from a Query object.
21906
22407
  *
21907
22408
  * @description
21908
- * This method translates high-level query parameters into a SurrealQL query string
21909
- * that can be executed against the SurrealDB backend. Unlike Prolog queries which
21910
- * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
21911
- * stored in SurrealDB.
22409
+ * This method translates high-level query parameters into a SPARQL query string
22410
+ * that can be executed against the SPARQL backend. Unlike Prolog queries which
22411
+ * operate on SDNA-aware predicates, SPARQL queries operate directly on raw links
22412
+ * stored in SPARQL.
21912
22413
  *
21913
22414
  * The generated query uses a CTE (Common Table Expression) pattern:
21914
22415
  * 1. First, identify candidate base expressions by filtering links based on where conditions
@@ -21916,7 +22417,7 @@ class Ad4mModel {
21916
22417
  * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
21917
22418
  *
21918
22419
  * Key architectural notes:
21919
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
22420
+ * - SPARQL stores only raw links (source, predicate, target, author, timestamp)
21920
22421
  * - No SDNA knowledge at the database level
21921
22422
  * - Properties are resolved via subqueries that look for links with specific predicates
21922
22423
  * - Relations are similar but return multiple values instead of one
@@ -21924,11 +22425,11 @@ class Ad4mModel {
21924
22425
  *
21925
22426
  * @param perspective - The perspective to query (used for metadata extraction)
21926
22427
  * @param query - Query parameters (where, order, limit, offset, properties, relations)
21927
- * @returns Complete SurrealQL query string ready for execution
22428
+ * @returns Complete SPARQL query string ready for execution
21928
22429
  *
21929
22430
  * @example
21930
22431
  * ```typescript
21931
- * const query = Recipe.queryToSurrealQL(perspective, {
22432
+ * const query = Recipe.queryToSPARQL(perspective, {
21932
22433
  * where: { name: "Pasta", rating: { gt: 4 } },
21933
22434
  * order: { timestamp: "DESC" },
21934
22435
  * limit: 10
@@ -21937,10 +22438,10 @@ class Ad4mModel {
21937
22438
  * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
21938
22439
  * ```
21939
22440
  */
21940
- static async queryToSurrealQL(perspective, query) {
22441
+ static async queryToSPARQL(perspective, query) {
21941
22442
  const metadata = this.getModelMetadata();
21942
22443
  const allRelMeta = getRelationsMetadata(this);
21943
- return buildSurrealQLQuery(metadata, allRelMeta, query, this);
22444
+ return buildSPARQLQuery(metadata, allRelMeta, query, this);
21944
22445
  }
21945
22446
  static async instancesFromPrologResult(perspective, query, result) {
21946
22447
  if (!result?.[0]?.AllInstances)
@@ -21985,16 +22486,16 @@ class Ad4mModel {
21985
22486
  return { results: instances, totalCount: result[0].TotalCount };
21986
22487
  }
21987
22488
  /**
21988
- * Converts SurrealDB query results to Ad4mModel instances.
22489
+ * Converts SPARQL query results to Ad4mModel instances.
21989
22490
  *
21990
22491
  * @param perspective - The perspective context
21991
22492
  * @param query - The query parameters used
21992
- * @param result - Array of result objects from SurrealDB
22493
+ * @param result - Array of result objects from SPARQL
21993
22494
  * @returns Promise resolving to results with total count
21994
22495
  *
21995
22496
  * @internal
21996
22497
  */
21997
- static async instancesFromSurrealResult(perspective, query, result) {
22498
+ static async instancesFromQueryResult(perspective, query, result) {
21998
22499
  if (!result || result.length === 0)
21999
22500
  return { results: [], totalCount: 0 };
22000
22501
  const metadata = this.getModelMetadata();
@@ -22015,33 +22516,25 @@ class Ad4mModel {
22015
22516
  }
22016
22517
  const links = row.links || [];
22017
22518
  const instance = new this(perspective, base);
22018
- // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
22019
- await hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
22020
- // When specific properties are requested, delete unrequested properties
22021
- // so they return undefined instead of their constructor defaults (e.g. 0, [])
22022
- if (requestedProperties.length > 0) {
22023
- const requested = new Set(requestedProperties);
22024
- for (const propName of Object.keys(metadata.properties)) {
22025
- if (!requested.has(propName)) {
22026
- delete instance[propName];
22027
- }
22028
- }
22029
- for (const relName of Object.keys(metadata.relations)) {
22030
- if (!requested.has(relName) && !(query.include && relName in query.include)) {
22031
- delete instance[relName];
22032
- }
22033
- }
22034
- // Also strip metadata fields unless explicitly requested
22035
- for (const metaField of ['author', 'createdAt', 'updatedAt']) {
22036
- if (!requested.has(metaField)) {
22037
- delete instance[metaField];
22519
+ // Core hydration via unified helper (pass requestedProperties for sparse fieldset).
22520
+ // Also hydrate any properties referenced in `where` so the JS post-filter can match them,
22521
+ // even if they're not in the user's `properties` projection.
22522
+ let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
22523
+ if (hydrationProps && query.where) {
22524
+ for (const key of Object.keys(query.where)) {
22525
+ if (!hydrationProps.includes(key)) {
22526
+ hydrationProps.push(key);
22038
22527
  }
22039
22528
  }
22040
22529
  }
22530
+ await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
22531
+ // NOTE: Property deletion for sparse fieldsets is deferred until AFTER
22532
+ // where-filtering so that where conditions can reference any property,
22533
+ // even ones not in the `properties` projection.
22041
22534
  instances.push(instance);
22042
22535
  }
22043
22536
  catch (error) {
22044
- console.error(`Failed to process SurrealDB instance ${base}:`, error);
22537
+ console.error(`Failed to process SPARQL instance ${base}:`, error);
22045
22538
  }
22046
22539
  }
22047
22540
  // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
@@ -22074,17 +22567,19 @@ class Ad4mModel {
22074
22567
  for (const instance of instances) {
22075
22568
  await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
22076
22569
  }
22077
- // Filter by where conditions that couldn't be filtered in SQL
22570
+ // Filter by where conditions that couldn't be filtered in SPARQL
22078
22571
  // This includes:
22079
22572
  // - author/timestamp (computed from grouped links)
22080
22573
  // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
22081
- // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
22574
+ // because fn::parse_literal() comparisons in SPARQL subqueries don't work reliably
22575
+ // - Relation-based where clauses (e.g., { post: postId } for @BelongsToOne)
22576
+ // which require reverse-link resolution before filtering
22082
22577
  let filteredInstances = instances;
22083
22578
  if (query.where) {
22084
22579
  filteredInstances = instances.filter(instance => {
22085
22580
  for (const [propertyName, condition] of Object.entries(query.where)) {
22086
- // Skip 'base' as it's filtered in SQL
22087
- if (propertyName === 'base')
22581
+ // Skip 'base'/'id' as it's filtered in SPARQL
22582
+ if (propertyName === 'base' || propertyName === 'id')
22088
22583
  continue;
22089
22584
  // For author and timestamp, always filter in JS
22090
22585
  if (propertyName === 'author' || propertyName === 'timestamp') {
@@ -22093,19 +22588,20 @@ class Ad4mModel {
22093
22588
  }
22094
22589
  continue;
22095
22590
  }
22096
- // For regular properties, only filter comparison operators in JS
22097
- // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
22098
- if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
22099
- const ops = condition;
22100
- // Check if any comparison operators are present
22101
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
22102
- ops.lt !== undefined || ops.lte !== undefined ||
22103
- ops.between !== undefined || ops.contains !== undefined;
22104
- if (hasComparisonOps) {
22105
- if (!matchesCondition(instance[propertyName], condition)) {
22106
- return false;
22107
- }
22591
+ // Check if this is a relation field (not in properties metadata)
22592
+ const isPropField = propertyName in metadata.properties;
22593
+ if (!isPropField) {
22594
+ // Relation-based where — filter in JS against the populated field
22595
+ if (!matchesCondition(instance[propertyName], condition)) {
22596
+ return false;
22108
22597
  }
22598
+ continue;
22599
+ }
22600
+ // Filter ALL property conditions in JS (equality, NOT, IN, comparison operators).
22601
+ // SPARQL-level filtering with parse_literal is unreliable across environments,
22602
+ // so we do all property filtering here after hydration resolves values.
22603
+ if (!matchesCondition(instance[propertyName], condition)) {
22604
+ return false;
22109
22605
  }
22110
22606
  }
22111
22607
  return true;
@@ -22157,6 +22653,28 @@ class Ad4mModel {
22157
22653
  const end = query.limit ? start + query.limit : undefined;
22158
22654
  paginatedInstances = filteredInstances.slice(start, end);
22159
22655
  }
22656
+ // Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
22657
+ // This must happen AFTER where-filtering so conditions can reference any property.
22658
+ if (requestedProperties.length > 0) {
22659
+ const requested = new Set(requestedProperties);
22660
+ for (const inst of paginatedInstances) {
22661
+ for (const propName of Object.keys(metadata.properties)) {
22662
+ if (!requested.has(propName)) {
22663
+ delete inst[propName];
22664
+ }
22665
+ }
22666
+ for (const relName of Object.keys(metadata.relations)) {
22667
+ if (!requested.has(relName) && !(query.include && relName in query.include)) {
22668
+ delete inst[relName];
22669
+ }
22670
+ }
22671
+ for (const metaField of ['author', 'createdAt', 'updatedAt']) {
22672
+ if (!requested.has(metaField)) {
22673
+ delete inst[metaField];
22674
+ }
22675
+ }
22676
+ }
22677
+ }
22160
22678
  // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
22161
22679
  if (query.include && paginatedInstances.length > 0) {
22162
22680
  await hydrateRelations(this, paginatedInstances, perspective, query.include);
@@ -22181,15 +22699,15 @@ class Ad4mModel {
22181
22699
  *
22182
22700
  * @param perspective - The perspective to search in
22183
22701
  * @param query - Optional query parameters to filter results
22184
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22702
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22185
22703
  * @returns Array of matching models
22186
22704
  *
22187
22705
  * @example
22188
22706
  * ```typescript
22189
- * // Get all recipes (uses SurrealDB by default)
22707
+ * // Get all recipes (uses SPARQL by default)
22190
22708
  * const allRecipes = await Recipe.findAll(perspective);
22191
22709
  *
22192
- * // Get recipes with specific criteria (uses SurrealDB)
22710
+ * // Get recipes with specific criteria (uses SPARQL)
22193
22711
  * const recipes = await Recipe.findAll(perspective, {
22194
22712
  * where: {
22195
22713
  * name: "Pasta",
@@ -22203,14 +22721,23 @@ class Ad4mModel {
22203
22721
  * const recipesProlog = await Recipe.findAll(perspective, {}, false);
22204
22722
  * ```
22205
22723
  */
22206
- static async findAll(perspective, query = {}, useSurrealDB = true) {
22724
+ static async findAll(perspective, query = {}, engine = 'sparql') {
22207
22725
  if (query.properties && query.properties.length === 0) {
22208
22726
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
22209
22727
  }
22210
- if (useSurrealDB) {
22211
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22212
- const result = await perspective.querySurrealDB(surrealQuery);
22213
- const { results } = await this.instancesFromSurrealResult(perspective, query, result);
22728
+ // Backward compatibility: boolean maps to sparql (true) or prolog (false)
22729
+ const resolvedEngine = typeof engine === 'boolean'
22730
+ ? (engine ? 'sparql' : 'prolog')
22731
+ : engine;
22732
+ if (resolvedEngine === 'sparql') {
22733
+ // Always use the regular SPARQL path + JS-level hydrateRelations for includes.
22734
+ // The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
22735
+ // non-conforming node filtering, and parse_literal compatibility.
22736
+ // hydrateRelations handles all of these correctly via per-relation findAll calls.
22737
+ const sparqlQuery = await this.queryToSPARQL(perspective, query);
22738
+ const rawResult = await perspective.querySparql(sparqlQuery);
22739
+ const grouped = groupSPARQLResults(rawResult);
22740
+ const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
22214
22741
  return results;
22215
22742
  }
22216
22743
  else {
@@ -22227,7 +22754,7 @@ class Ad4mModel {
22227
22754
  *
22228
22755
  * @param perspective - The perspective to search in
22229
22756
  * @param query - Optional query parameters to filter results
22230
- * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
22757
+ * @param useSPARQL - Whether to use SPARQL (default: true) or Prolog (legacy)
22231
22758
  * @returns The first matching instance, or `null`
22232
22759
  *
22233
22760
  * @example
@@ -22240,9 +22767,9 @@ class Ad4mModel {
22240
22767
  * }
22241
22768
  * ```
22242
22769
  */
22243
- static async findOne(perspective, query = {}, useSurrealDB = true) {
22770
+ static async findOne(perspective, query = {}, engine = 'sparql') {
22244
22771
  const limitedQuery = { ...query, limit: 1 };
22245
- const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
22772
+ const results = await this.findAll(perspective, limitedQuery, engine);
22246
22773
  return results[0] ?? null;
22247
22774
  }
22248
22775
  /**
@@ -22250,7 +22777,7 @@ class Ad4mModel {
22250
22777
  *
22251
22778
  * @param perspective - The perspective to search in
22252
22779
  * @param query - Optional query parameters to filter results
22253
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22780
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22254
22781
  * @returns Object containing results array and total count
22255
22782
  *
22256
22783
  * @example
@@ -22265,11 +22792,15 @@ class Ad4mModel {
22265
22792
  * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
22266
22793
  * ```
22267
22794
  */
22268
- static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
22269
- if (useSurrealDB) {
22270
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22271
- const result = await perspective.querySurrealDB(surrealQuery);
22272
- return await this.instancesFromSurrealResult(perspective, query, result);
22795
+ static async findAllAndCount(perspective, query = {}, engine = 'sparql') {
22796
+ const resolvedEngine = typeof engine === 'boolean'
22797
+ ? (engine ? 'sparql' : 'prolog')
22798
+ : engine;
22799
+ if (resolvedEngine === 'sparql') {
22800
+ const sparqlQuery = await this.queryToSPARQL(perspective, query);
22801
+ const rawResult = await perspective.querySparql(sparqlQuery);
22802
+ const grouped = groupSPARQLResults(rawResult);
22803
+ return await this.instancesFromQueryResult(perspective, query, grouped);
22273
22804
  }
22274
22805
  else {
22275
22806
  const prologQuery = await this.queryToProlog(perspective, query);
@@ -22284,7 +22815,7 @@ class Ad4mModel {
22284
22815
  * @param pageSize - Number of items per page
22285
22816
  * @param pageNumber - Which page to retrieve (1-based)
22286
22817
  * @param query - Optional additional query parameters
22287
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22818
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22288
22819
  * @returns Paginated results with metadata
22289
22820
  *
22290
22821
  * @example
@@ -22298,12 +22829,16 @@ class Ad4mModel {
22298
22829
  * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
22299
22830
  * ```
22300
22831
  */
22301
- static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
22832
+ static async paginate(perspective, pageSize, pageNumber, query, engine = 'sparql') {
22302
22833
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
22303
- if (useSurrealDB) {
22304
- const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
22305
- const result = await perspective.querySurrealDB(surrealQuery);
22306
- const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
22834
+ const resolvedEngine = typeof engine === 'boolean'
22835
+ ? (engine ? 'sparql' : 'prolog')
22836
+ : engine;
22837
+ if (resolvedEngine === 'sparql') {
22838
+ const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
22839
+ const rawResult = await perspective.querySparql(sparqlQuery);
22840
+ const grouped = groupSPARQLResults(rawResult);
22841
+ const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped);
22307
22842
  return { results, totalCount, pageSize, pageNumber };
22308
22843
  }
22309
22844
  else {
@@ -22332,28 +22867,28 @@ class Ad4mModel {
22332
22867
  return fullQuery;
22333
22868
  }
22334
22869
  /**
22335
- * Generates a SurrealQL COUNT query for the model.
22870
+ * Generates a SPARQL COUNT query for the model.
22336
22871
  *
22337
22872
  * @param perspective - The perspective context
22338
22873
  * @param query - Query parameters to filter the count
22339
- * @returns SurrealQL COUNT query string
22874
+ * @returns SPARQL COUNT query string
22340
22875
  *
22341
22876
  * @private
22342
22877
  */
22343
- static async countQueryToSurrealQL(perspective, query) {
22878
+ static async countQueryToSPARQL(perspective, query) {
22344
22879
  // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
22345
22880
  // We'll count the number of rows returned (one row per source)
22346
22881
  const countQuery = { ...query };
22347
22882
  delete countQuery.limit;
22348
22883
  delete countQuery.offset;
22349
- return await this.queryToSurrealQL(perspective, countQuery);
22884
+ return await this.queryToSPARQL(perspective, countQuery);
22350
22885
  }
22351
22886
  /**
22352
22887
  * Gets a count of all matching instances.
22353
22888
  *
22354
22889
  * @param perspective - The perspective to search in
22355
22890
  * @param query - Optional query parameters to filter results
22356
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
22891
+ * @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
22357
22892
  * @returns Total count of matching entities
22358
22893
  *
22359
22894
  * @example
@@ -22367,14 +22902,15 @@ class Ad4mModel {
22367
22902
  * const countProlog = await Recipe.count(perspective, {}, false);
22368
22903
  * ```
22369
22904
  */
22370
- static async count(perspective, query = {}, useSurrealDB = true) {
22371
- if (useSurrealDB) {
22372
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
22373
- const result = await perspective.querySurrealDB(surrealQuery);
22374
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
22375
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
22376
- // This ensures count() returns the same number as findAll().length
22377
- const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
22905
+ static async count(perspective, query = {}, engine = 'sparql') {
22906
+ const resolvedEngine = typeof engine === 'boolean'
22907
+ ? (engine ? 'sparql' : 'prolog')
22908
+ : engine;
22909
+ if (resolvedEngine === 'sparql') {
22910
+ const sparqlQuery = await this.queryToSPARQL(perspective, query);
22911
+ const rawResult = await perspective.querySparql(sparqlQuery);
22912
+ const grouped = groupSPARQLResults(rawResult);
22913
+ const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped);
22378
22914
  return totalCount;
22379
22915
  }
22380
22916
  else {
@@ -22392,7 +22928,7 @@ class Ad4mModel {
22392
22928
  const actions = this.generatePropertySetterAction(key, metadata);
22393
22929
  // Get resolve language from metadata (replaces Prolog query)
22394
22930
  let resolveLanguage = metadata.resolveLanguage;
22395
- // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
22931
+ // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
22396
22932
  if (value === undefined || value === null || value === "") {
22397
22933
  return;
22398
22934
  }
@@ -23259,6 +23795,16 @@ input CapabilityInput {
23259
23795
  with: ResourceInput!
23260
23796
  }
23261
23797
 
23798
+ type ComputeLogEntry {
23799
+ cost: Float!
23800
+ creditsAfter: Float!
23801
+ id: Float!
23802
+ operation: String!
23803
+ summary: String
23804
+ timestamp: String!
23805
+ userEmail: String!
23806
+ }
23807
+
23262
23808
  scalar DateTime
23263
23809
 
23264
23810
  type EntanglementProof {
@@ -23667,9 +24213,9 @@ type Query {
23667
24213
  perspective(uuid: String!): PerspectiveHandle
23668
24214
  perspectiveQueryLinks(query: LinkQuery!, uuid: String!): [LinkExpression!]
23669
24215
  perspectiveQueryProlog(query: String!, uuid: String!): String!
23670
- perspectiveQuerySurrealDB(query: String!, uuid: String!): String!
23671
24216
  perspectiveSnapshot(uuid: String!): Perspective
23672
24217
  perspectives: [PerspectiveHandle!]!
24218
+ runtimeComputeLog(limit: Float, since: String, userEmail: String): [ComputeLogEntry!]!
23673
24219
  runtimeFreeHostingEnabled: Boolean!
23674
24220
  runtimeFriendStatus(did: String!): PerspectiveExpression
23675
24221
  runtimeFriends: [String!]!
@@ -24144,6 +24690,49 @@ exports.PaymentRequestResult = __decorate([
24144
24690
  ObjectType(),
24145
24691
  __metadata("design:paramtypes", [Boolean, String])
24146
24692
  ], exports.PaymentRequestResult);
24693
+ exports.ComputeLogEntry = class ComputeLogEntry {
24694
+ constructor(id, userEmail, timestamp, operation, cost, creditsAfter, summary) {
24695
+ this.id = id;
24696
+ this.userEmail = userEmail;
24697
+ this.timestamp = timestamp;
24698
+ this.operation = operation;
24699
+ this.cost = cost;
24700
+ this.creditsAfter = creditsAfter;
24701
+ this.summary = summary;
24702
+ }
24703
+ };
24704
+ __decorate([
24705
+ Field(),
24706
+ __metadata("design:type", Number)
24707
+ ], exports.ComputeLogEntry.prototype, "id", void 0);
24708
+ __decorate([
24709
+ Field(),
24710
+ __metadata("design:type", String)
24711
+ ], exports.ComputeLogEntry.prototype, "userEmail", void 0);
24712
+ __decorate([
24713
+ Field(),
24714
+ __metadata("design:type", String)
24715
+ ], exports.ComputeLogEntry.prototype, "timestamp", void 0);
24716
+ __decorate([
24717
+ Field(),
24718
+ __metadata("design:type", String)
24719
+ ], exports.ComputeLogEntry.prototype, "operation", void 0);
24720
+ __decorate([
24721
+ Field(),
24722
+ __metadata("design:type", String)
24723
+ ], exports.ComputeLogEntry.prototype, "summary", void 0);
24724
+ __decorate([
24725
+ Field(),
24726
+ __metadata("design:type", Number)
24727
+ ], exports.ComputeLogEntry.prototype, "cost", void 0);
24728
+ __decorate([
24729
+ Field(),
24730
+ __metadata("design:type", Number)
24731
+ ], exports.ComputeLogEntry.prototype, "creditsAfter", void 0);
24732
+ exports.ComputeLogEntry = __decorate([
24733
+ ObjectType(),
24734
+ __metadata("design:paramtypes", [Number, String, String, String, Number, Number, String])
24735
+ ], exports.ComputeLogEntry);
24147
24736
  /**
24148
24737
  * Resolver classes are used here to define the GraphQL schema
24149
24738
  * (through the type-graphql annotations)
@@ -24364,6 +24953,9 @@ let RuntimeResolver = class RuntimeResolver {
24364
24953
  runtimeHostingUserInfo() {
24365
24954
  return new exports.HostingUserInfo("test@example.com", "100000000", null, false);
24366
24955
  }
24956
+ runtimeComputeLog(since, limit, userEmail) {
24957
+ return [];
24958
+ }
24367
24959
  runtimeSetHotWalletAddress(address) {
24368
24960
  return true;
24369
24961
  }
@@ -24746,6 +25338,15 @@ __decorate([
24746
25338
  __metadata("design:paramtypes", []),
24747
25339
  __metadata("design:returntype", exports.HostingUserInfo)
24748
25340
  ], RuntimeResolver.prototype, "runtimeHostingUserInfo", null);
25341
+ __decorate([
25342
+ Query(),
25343
+ __param(0, Arg()),
25344
+ __param(1, Arg()),
25345
+ __param(2, Arg()),
25346
+ __metadata("design:type", Function),
25347
+ __metadata("design:paramtypes", [String, Number, String]),
25348
+ __metadata("design:returntype", Array)
25349
+ ], RuntimeResolver.prototype, "runtimeComputeLog", null);
24749
25350
  __decorate([
24750
25351
  Mutation(),
24751
25352
  __param(0, Arg()),
@@ -24868,7 +25469,6 @@ exports.buildAuthorAndTimestampQuery = buildAuthorAndTimestampQuery;
24868
25469
  exports.buildConformanceFilter = buildConformanceFilter;
24869
25470
  exports.buildConformanceGetter = buildConformanceGetter;
24870
25471
  exports.buildCountQuery = buildCountQuery;
24871
- exports.buildGraphTraversalWhereClause = buildGraphTraversalWhereClause;
24872
25472
  exports.buildLimitQuery = buildLimitQuery;
24873
25473
  exports.buildModelFromJSONSchema = buildModelFromJSONSchema;
24874
25474
  exports.buildOffsetQuery = buildOffsetQuery;
@@ -24877,23 +25477,34 @@ exports.buildParentQuery = buildParentQuery;
24877
25477
  exports.buildPropertiesQuery = buildPropertiesQuery;
24878
25478
  exports.buildSDNA = buildSDNA;
24879
25479
  exports.buildSHACL = buildSHACL;
24880
- exports.buildSurrealQLQuery = buildSurrealQLQuery;
25480
+ exports.buildSPARQLGetDataQuery = buildSPARQLGetDataQuery;
25481
+ exports.buildSPARQLQuery = buildSPARQLQuery;
25482
+ exports.buildWhereCondition = buildWhereCondition;
24881
25483
  exports.buildWhereQuery = buildWhereQuery;
24882
25484
  exports.capSentence = capSentence;
25485
+ exports.clearQueryCache = clearQueryCache;
25486
+ exports.clearSubscriptionPool = clearSubscriptionPool;
25487
+ exports.compileWhereClause = compileWhereClause;
24883
25488
  exports.determineNamespace = determineNamespace;
24884
25489
  exports.determinePredicate = determinePredicate;
24885
- exports.escapeSurrealString = escapeSurrealString;
25490
+ exports.escapeQueryString = escapeQueryString;
24886
25491
  exports.evaluateCustomGettersForInstance = evaluateCustomGettersForInstance;
24887
25492
  exports.exprRef2String = exprRef2String;
24888
25493
  exports.formatList = formatList;
25494
+ exports.formatQueryValue = formatQueryValue;
25495
+ exports.formatSPARQLValue = formatSPARQLValue;
24889
25496
  exports.generatePrologFacts = generatePrologFacts;
25497
+ exports.getCachedResult = getCachedResult;
24890
25498
  exports.getDefaultValueForType = getDefaultValueForType;
25499
+ exports.getMemoizedSHACL = getMemoizedSHACL;
24891
25500
  exports.getPropertiesMetadata = getPropertiesMetadata;
24892
25501
  exports.getPropertyOption = getPropertyOption;
24893
25502
  exports.getRelationsMetadata = getRelationsMetadata;
25503
+ exports.groupSPARQLResults = groupSPARQLResults;
24894
25504
  exports.hydrateFromLinks = hydrateFromLinks;
24895
25505
  exports.hydratePropertyValue = hydratePropertyValue;
24896
25506
  exports.hydrateRelations = hydrateRelations;
25507
+ exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
24897
25508
  exports.isArrayType = isArrayType;
24898
25509
  exports.isExpression = isExpression;
24899
25510
  exports.isLink = isLink;
@@ -24906,7 +25517,11 @@ exports.normalizeNamespaceString = normalizeNamespaceString;
24906
25517
  exports.normalizeSchemaType = normalizeSchemaType;
24907
25518
  exports.normalizeValue = normalizeValue;
24908
25519
  exports.parseExprUrl = parseExprUrl;
25520
+ exports.pooledSubscribe = pooledSubscribe;
25521
+ exports.queryCacheSize = queryCacheSize;
24909
25522
  exports.resolveParentPredicate = resolveParentPredicate;
25523
+ exports.setCachedResult = setCachedResult;
24910
25524
  exports.setPropertyRegistryEntry = setPropertyRegistryEntry;
24911
25525
  exports.setRelationRegistryEntry = setRelationRegistryEntry;
25526
+ exports.subscriptionPoolSize = subscriptionPoolSize;
24912
25527
  exports.typeDefsString = typeDefsString;