@coasys/ad4m 0.11.2-dev-sdna-only-prolog → 0.11.2-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -4486,43 +4486,11 @@ class Subject {
4486
4486
  let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property(C, Property)`);
4487
4487
  let properties = results.map(result => result.Property);
4488
4488
  for (let p of properties) {
4489
- const resolveExpressionURI = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4489
+ await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4490
4490
  Object.defineProperty(this, p, {
4491
4491
  configurable: true,
4492
4492
  get: async () => {
4493
- // Try Prolog first
4494
- try {
4495
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${p}", Value)`);
4496
- if (results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
4497
- let expressionURI = results[0].Value;
4498
- if (resolveExpressionURI) {
4499
- try {
4500
- if (expressionURI) {
4501
- const expression = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getExpression(expressionURI);
4502
- try {
4503
- return JSON.parse(expression.data);
4504
- }
4505
- catch (e) {
4506
- return expression.data;
4507
- }
4508
- }
4509
- else {
4510
- return expressionURI;
4511
- }
4512
- }
4513
- catch (err) {
4514
- return expressionURI;
4515
- }
4516
- }
4517
- else {
4518
- return expressionURI;
4519
- }
4520
- }
4521
- }
4522
- catch (err) {
4523
- // Prolog query failed, fall through to SurrealDB
4524
- }
4525
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4493
+ // Use SurrealDB for data queries
4526
4494
  try {
4527
4495
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), p);
4528
4496
  }
@@ -4561,20 +4529,7 @@ class Subject {
4561
4529
  Object.defineProperty(this, c, {
4562
4530
  configurable: true,
4563
4531
  get: async () => {
4564
- // Try Prolog first
4565
- try {
4566
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), collection_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${c}", Value)`);
4567
- if (results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
4568
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
4569
- if (collectionContent.length > 0) {
4570
- return collectionContent;
4571
- }
4572
- }
4573
- }
4574
- catch (err) {
4575
- // Prolog query failed, fall through to SurrealDB
4576
- }
4577
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4532
+ // Use SurrealDB for data queries
4578
4533
  try {
4579
4534
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), c);
4580
4535
  }
@@ -4643,6 +4598,58 @@ class Subject {
4643
4598
  }
4644
4599
  _Subject_baseExpression = new WeakMap(), _Subject_subjectClassName = new WeakMap(), _Subject_perspective = new WeakMap();
4645
4600
 
4601
+ function formatList(list) {
4602
+ if (!list?.length) {
4603
+ return "";
4604
+ }
4605
+ if (list.length === 1) {
4606
+ return list.toString();
4607
+ }
4608
+ if (list.length === 2) {
4609
+ return list.join(' and ');
4610
+ }
4611
+ return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
4612
+ }
4613
+ function capSentence(cap) {
4614
+ const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
4615
+ const domain = cap.with.domain === "*" ? "" : cap.with.domain;
4616
+ const pointers = cap.with.pointers.includes("*")
4617
+ ? ["all AD4M data"]
4618
+ : cap.with.pointers;
4619
+ return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
4620
+ }
4621
+ /**
4622
+ * Escapes a string value for safe use in SurrealQL queries.
4623
+ *
4624
+ * @description
4625
+ * Prevents SQL injection by properly escaping special characters in string values
4626
+ * that will be interpolated into SurrealQL queries. This handles the most common
4627
+ * special characters that could break SQL queries or enable injection attacks.
4628
+ *
4629
+ * Single quotes, backslashes, and other special characters are escaped using
4630
+ * backslash notation, which is the standard escaping mechanism for SurrealQL.
4631
+ *
4632
+ * @param value - The string value to escape
4633
+ * @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
4634
+ *
4635
+ * @example
4636
+ * ```typescript
4637
+ * const userInput = "user's input with 'quotes'";
4638
+ * const escaped = escapeSurrealString(userInput);
4639
+ * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
4640
+ * // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
4641
+ * ```
4642
+ */
4643
+ function escapeSurrealString(value) {
4644
+ return value
4645
+ .replace(/\\/g, '\\\\') // Backslash -> \\
4646
+ .replace(/'/g, "\\'") // Single quote -> \'
4647
+ .replace(/"/g, '\\"') // Double quote -> \"
4648
+ .replace(/\n/g, '\\n') // Newline -> \n
4649
+ .replace(/\r/g, '\\r') // Carriage return -> \r
4650
+ .replace(/\t/g, '\\t'); // Tab -> \t
4651
+ }
4652
+
4646
4653
  var __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4647
4654
  if (kind === "m") throw new TypeError("Private method is not writable");
4648
4655
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -4999,6 +5006,18 @@ class PerspectiveProxy {
4999
5006
  __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
5000
5007
  __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
5001
5008
  }
5009
+ /**
5010
+ * Escapes special regex characters in a string to prevent ReDoS attacks
5011
+ * and regex injection when building dynamic regular expressions.
5012
+ *
5013
+ * @param str - The string to escape
5014
+ * @returns The escaped string safe for use in RegExp constructor
5015
+ *
5016
+ * @private
5017
+ */
5018
+ escapeRegExp(str) {
5019
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5020
+ }
5002
5021
  /**
5003
5022
  * Executes a set of actions on an expression with optional parameters.
5004
5023
  * Used internally by Social DNA flows and subject class operations.
@@ -5602,34 +5621,43 @@ class PerspectiveProxy {
5602
5621
  // Get metadata from SDNA using Prolog metaprogramming
5603
5622
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5604
5623
  if (!metadata) {
5605
- return false;
5624
+ // Fallback to Prolog check if SDNA metadata isn't available
5625
+ // This handles cases where classes exist in Prolog but not in SDNA
5626
+ try {
5627
+ const escapedClassName = className.replace(/"/g, '\\"');
5628
+ const escapedExpression = expression.replace(/"/g, '\\"');
5629
+ const result = await this.infer(`subject_class("${escapedClassName}", C), instance(C, "${escapedExpression}")`);
5630
+ return result && result.length > 0;
5631
+ }
5632
+ catch (e) {
5633
+ console.warn(`Failed to check instance via Prolog for class ${className}:`, e);
5634
+ return false;
5635
+ }
5606
5636
  }
5607
5637
  // If no required triples, any expression with links is an instance
5608
5638
  if (metadata.requiredTriples.length === 0) {
5609
- console.log("no required triples, checking surrealDB");
5610
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}'`;
5611
- console.log("checkQuery", checkQuery);
5639
+ const escapedExpression = escapeSurrealString(expression);
5640
+ const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
5612
5641
  const result = await this.querySurrealDB(checkQuery);
5613
- console.log("result", result);
5614
5642
  const count = result[0]?.count ?? 0;
5615
5643
  const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
5616
5644
  return countValue > 0;
5617
5645
  }
5618
5646
  // Check if the expression has all required triples (predicate + optional exact target)
5619
5647
  for (const triple of metadata.requiredTriples) {
5620
- console.log("checking triple", triple);
5648
+ const escapedExpression = escapeSurrealString(expression);
5649
+ const escapedPredicate = escapeSurrealString(triple.predicate);
5621
5650
  let checkQuery;
5622
5651
  if (triple.target) {
5623
5652
  // Flag: must match both predicate AND exact target value
5624
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}' AND out.uri = '${triple.target}'`;
5653
+ const escapedTarget = escapeSurrealString(triple.target);
5654
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
5625
5655
  }
5626
5656
  else {
5627
5657
  // Property: just check predicate exists
5628
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}'`;
5658
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
5629
5659
  }
5630
- console.log("checkQuery", checkQuery);
5631
5660
  const result = await this.querySurrealDB(checkQuery);
5632
- console.log("result", result);
5633
5661
  if (!result || result.length === 0) {
5634
5662
  return false;
5635
5663
  }
@@ -5669,8 +5697,9 @@ class PerspectiveProxy {
5669
5697
  async getSubjectClassMetadataFromSDNA(className) {
5670
5698
  try {
5671
5699
  // Get SDNA code from perspective - it's stored as a link
5700
+ // Use canonical Literal.from() to construct the source URL
5672
5701
  const sdnaLinks = await this.get(new LinkQuery({
5673
- source: `literal://string:${className}`,
5702
+ source: Literal.from(className).toUrl(),
5674
5703
  predicate: "ad4m://sdna"
5675
5704
  }));
5676
5705
  //console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
@@ -5690,10 +5719,14 @@ class PerspectiveProxy {
5690
5719
  const requiredTriples = [];
5691
5720
  // Parse the instance rule from the SDNA code
5692
5721
  // Format: instance(c, Base) :- triple(Base, "pred1", _), triple(Base, "pred2", "exact_value").
5693
- const instanceRuleMatch = sdnaCode.match(/instance\([^,]+,\s*\w+\)\s*:-\s*(.+?)\./s);
5694
- if (instanceRuleMatch) {
5722
+ // Use a more robust pattern that handles complex rule bodies
5723
+ // Match from "instance(" to the closing "." using non-greedy matching
5724
+ const instanceRulePattern = /instance\([^)]+\)\s*:-\s*([^.]+)\./g;
5725
+ let instanceRuleMatch;
5726
+ let foundInstanceRule = false;
5727
+ while ((instanceRuleMatch = instanceRulePattern.exec(sdnaCode)) !== null) {
5728
+ foundInstanceRule = true;
5695
5729
  const ruleBody = instanceRuleMatch[1];
5696
- console.log("instance rule body:", ruleBody);
5697
5730
  // Extract all triple(Base, "predicate", Target) patterns
5698
5731
  // Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
5699
5732
  const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
@@ -5702,15 +5735,13 @@ class PerspectiveProxy {
5702
5735
  const predicate = match[1];
5703
5736
  const target = match[2]; // undefined if matched "_"
5704
5737
  requiredTriples.push({ predicate, target });
5705
- console.log(`Extracted triple: predicate="${predicate}", target="${target}"`);
5706
5738
  }
5707
5739
  }
5708
- else {
5740
+ if (!foundInstanceRule) {
5709
5741
  console.warn(`No instance rule found in SDNA for ${className}`);
5710
5742
  }
5711
5743
  // For backward compatibility, also maintain requiredPredicates array
5712
5744
  const requiredPredicates = requiredTriples.map(t => t.predicate);
5713
- console.log("extracted requiredTriples:", requiredTriples);
5714
5745
  // Extract property metadata
5715
5746
  const properties = new Map();
5716
5747
  const propertyResults = await this.infer(`subject_class("${className}", C), property(C, P)`);
@@ -5731,7 +5762,9 @@ class PerspectiveProxy {
5731
5762
  // If no setter, try to extract from SDNA property_getter Prolog code
5732
5763
  if (!predicate) {
5733
5764
  // Parse the SDNA code for property_getter definition
5734
- const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${propName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
5765
+ // Escape propName to prevent regex injection and ReDoS attacks
5766
+ const escapedPropName = this.escapeRegExp(propName);
5767
+ const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedPropName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
5735
5768
  if (getterMatch) {
5736
5769
  predicate = getterMatch[1];
5737
5770
  }
@@ -5767,7 +5800,9 @@ class PerspectiveProxy {
5767
5800
  // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
5768
5801
  // Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
5769
5802
  // Use a line-based match to avoid capturing multiple collections
5770
- const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${collName}"[^)]*\\)\\s*:-[^.]+\\.`);
5803
+ // Escape collName to prevent regex injection and ReDoS attacks
5804
+ const escapedCollName = this.escapeRegExp(collName);
5805
+ const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedCollName}"[^)]*\\)\\s*:-[^.]+\\.`);
5771
5806
  const getterLineMatch = sdnaCode.match(getterLinePattern);
5772
5807
  if (getterLineMatch) {
5773
5808
  const getterLine = getterLineMatch[0];
@@ -5781,7 +5816,6 @@ class PerspectiveProxy {
5781
5816
  if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
5782
5817
  getterBody = getterBody.substring(1, getterBody.length - 1);
5783
5818
  }
5784
- console.log(`Collection "${collName}" getter body:`, getterBody);
5785
5819
  // Extract predicate from triple(Base, "predicate", Target)
5786
5820
  if (!predicate) {
5787
5821
  const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
@@ -5793,7 +5827,6 @@ class PerspectiveProxy {
5793
5827
  const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
5794
5828
  if (instanceMatch) {
5795
5829
  instanceFilter = instanceMatch[1];
5796
- console.log(`Collection "${collName}" has instanceFilter: ${instanceFilter}`);
5797
5830
  }
5798
5831
  }
5799
5832
  }
@@ -5814,27 +5847,24 @@ class PerspectiveProxy {
5814
5847
  * Generates a SurrealDB query to find instances based on class metadata.
5815
5848
  */
5816
5849
  generateSurrealInstanceQuery(metadata) {
5817
- console.log("generateSurrealInstanceQuery called with requiredTriples:", metadata.requiredTriples);
5818
5850
  if (metadata.requiredTriples.length === 0) {
5819
5851
  // No required triples - any node with links is an instance
5820
- const query = `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
5821
- console.log("Generated query (no required triples):", query);
5822
- return query;
5852
+ return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
5823
5853
  }
5824
5854
  // Generate WHERE conditions for each required triple (predicate + optional exact target)
5825
5855
  const whereConditions = metadata.requiredTriples.map(triple => {
5856
+ const escapedPredicate = escapeSurrealString(triple.predicate);
5826
5857
  if (triple.target) {
5827
5858
  // Flag: must match both predicate AND exact target value
5828
- return `count(->link[WHERE predicate = '${triple.predicate}' AND out.uri = '${triple.target}']) > 0`;
5859
+ const escapedTarget = escapeSurrealString(triple.target);
5860
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
5829
5861
  }
5830
5862
  else {
5831
5863
  // Property: just check predicate exists
5832
- return `count(->link[WHERE predicate = '${triple.predicate}']) > 0`;
5864
+ return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
5833
5865
  }
5834
5866
  }).join(' AND ');
5835
- const query = `SELECT uri AS base FROM node WHERE ${whereConditions}`;
5836
- console.log("Generated query:", query);
5837
- return query;
5867
+ return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
5838
5868
  }
5839
5869
  /**
5840
5870
  * Gets a property value using SurrealDB when Prolog fails.
@@ -5849,7 +5879,9 @@ class PerspectiveProxy {
5849
5879
  if (!propMeta) {
5850
5880
  return undefined;
5851
5881
  }
5852
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${propMeta.predicate}' LIMIT 1`;
5882
+ const escapedBaseExpression = escapeSurrealString(baseExpression);
5883
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
5884
+ const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
5853
5885
  const result = await this.querySurrealDB(query);
5854
5886
  if (!result || result.length === 0) {
5855
5887
  return undefined;
@@ -5885,28 +5917,91 @@ class PerspectiveProxy {
5885
5917
  if (!collMeta) {
5886
5918
  return [];
5887
5919
  }
5888
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${collMeta.predicate}' ORDER BY timestamp ASC`;
5920
+ const escapedBaseExpression = escapeSurrealString(baseExpression);
5921
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
5922
+ const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
5889
5923
  const result = await this.querySurrealDB(query);
5890
5924
  if (!result || result.length === 0) {
5891
5925
  return [];
5892
5926
  }
5893
5927
  let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
5894
- console.log(`getCollectionValuesViaSurreal: base="${baseExpression}", collection="${collectionName}", predicate="${collMeta.predicate}", found ${values.length} values:`, values);
5895
- // Apply instance filter if present
5928
+ // Apply instance filter if present - batch-check all values at once
5896
5929
  if (collMeta.instanceFilter) {
5897
- console.log(` Applying instance filter "${collMeta.instanceFilter}" to collection "${collectionName}"`);
5898
- const filteredValues = [];
5899
- for (const value of values) {
5900
- const isInstance = await this.isSubjectInstance(value, collMeta.instanceFilter);
5901
- console.log(` Checking if "${value}" is instance of "${collMeta.instanceFilter}": ${isInstance}`);
5930
+ try {
5931
+ const filterMetadata = await this.getSubjectClassMetadataFromSDNA(collMeta.instanceFilter);
5932
+ if (!filterMetadata) {
5933
+ // Fallback to sequential checks if metadata isn't available
5934
+ return this.filterInstancesSequential(values, collMeta.instanceFilter);
5935
+ }
5936
+ return await this.batchCheckSubjectInstances(values, filterMetadata);
5937
+ }
5938
+ catch (err) {
5939
+ // Fallback to sequential checks on error
5940
+ return this.filterInstancesSequential(values, collMeta.instanceFilter);
5941
+ }
5942
+ }
5943
+ return values;
5944
+ }
5945
+ /**
5946
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
5947
+ * This avoids N+1 query problems by checking all values at once.
5948
+ */
5949
+ async batchCheckSubjectInstances(expressions, metadata) {
5950
+ if (expressions.length === 0) {
5951
+ return [];
5952
+ }
5953
+ // If no required triples, check which expressions have any links
5954
+ if (metadata.requiredTriples.length === 0) {
5955
+ const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
5956
+ const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
5957
+ const result = await this.querySurrealDB(checkQuery);
5958
+ return result.map(r => r.uri);
5959
+ }
5960
+ // For each required triple, build a query that finds matching expressions
5961
+ const validExpressionSets = [];
5962
+ for (const triple of metadata.requiredTriples) {
5963
+ const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
5964
+ const escapedPredicate = escapeSurrealString(triple.predicate);
5965
+ let checkQuery;
5966
+ if (triple.target) {
5967
+ // Flag: must match both predicate AND exact target value
5968
+ const escapedTarget = escapeSurrealString(triple.target);
5969
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}' GROUP BY in.uri`;
5970
+ }
5971
+ else {
5972
+ // Property: just check predicate exists
5973
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' GROUP BY in.uri`;
5974
+ }
5975
+ const result = await this.querySurrealDB(checkQuery);
5976
+ validExpressionSets.push(new Set(result.map(r => r.uri)));
5977
+ }
5978
+ // Find intersection: expressions that passed ALL required triple checks
5979
+ if (validExpressionSets.length === 0) {
5980
+ return expressions;
5981
+ }
5982
+ const validExpressions = expressions.filter(expr => {
5983
+ return validExpressionSets.every(set => set.has(expr));
5984
+ });
5985
+ return validExpressions;
5986
+ }
5987
+ /**
5988
+ * Fallback sequential instance checking when batch checking isn't available.
5989
+ */
5990
+ async filterInstancesSequential(values, instanceFilter) {
5991
+ const filteredValues = [];
5992
+ for (const value of values) {
5993
+ try {
5994
+ const isInstance = await this.isSubjectInstance(value, instanceFilter);
5902
5995
  if (isInstance) {
5903
5996
  filteredValues.push(value);
5904
5997
  }
5905
5998
  }
5906
- console.log(` After filtering: ${filteredValues.length} values`);
5907
- return filteredValues;
5999
+ catch (err) {
6000
+ // Skip values that fail instance check
6001
+ continue;
6002
+ }
5908
6003
  }
5909
- return values;
6004
+ return filteredValues;
5910
6005
  }
5911
6006
  /** Returns all subject instances of the given subject class as proxy objects.
5912
6007
  * @param subjectClass Either a string with the name of the subject class, or an object
@@ -5948,7 +6043,7 @@ class PerspectiveProxy {
5948
6043
  //console.log(`getAllSubjectInstances: Returning ${instances.length} instances`);
5949
6044
  return instances;
5950
6045
  }
5951
- /** Returns all subject proxies of the given subject class.
6046
+ /** Returns all subject proxies of the given subject class as proxy objects.
5952
6047
  * @param subjectClass Either a string with the name of the subject class, or an object
5953
6048
  * with the properties of the subject class. In the latter case, all subject classes
5954
6049
  * that match the given properties will be used.
@@ -5963,24 +6058,23 @@ class PerspectiveProxy {
5963
6058
  }
5964
6059
  let instances = [];
5965
6060
  for (let className of classes) {
5966
- //console.log(`getAllSubjectProxies: Processing class ${className}`);
5967
6061
  // Query SDNA for metadata, then query SurrealDB for instances
5968
6062
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5969
- //console.log(`getAllSubjectProxies: Got metadata for ${className}`);
5970
6063
  if (metadata) {
5971
6064
  const surrealQuery = this.generateSurrealInstanceQuery(metadata);
5972
- console.log("surrealQuery", surrealQuery);
5973
6065
  const results = await this.querySurrealDB(surrealQuery);
5974
- console.log(`getAllSubjectProxies: SurrealDB returned ${results?.length || 0} results`);
5975
- const newInstance = results.map(r => ({ X: r.base }));
5976
- console.log("newInstance", newInstance);
5977
- instances = instances.concat(newInstance);
5978
- }
5979
- else {
5980
- console.warn(`getAllSubjectProxies: No metadata found for ${className}`);
6066
+ for (const result of results || []) {
6067
+ try {
6068
+ let subject = new Subject(this, result.base, className);
6069
+ await subject.init();
6070
+ instances.push(subject);
6071
+ }
6072
+ catch (e) {
6073
+ // Skip subjects that fail to initialize
6074
+ }
6075
+ }
5981
6076
  }
5982
6077
  }
5983
- //console.log(`getAllSubjectProxies: Returning ${instances.length} proxies`);
5984
6078
  return instances;
5985
6079
  }
5986
6080
  buildQueryFromTemplate(obj) {
@@ -17615,27 +17709,6 @@ input VoiceActivityParamsInput {
17615
17709
  }
17616
17710
  `;
17617
17711
 
17618
- function formatList(list) {
17619
- if (!list?.length) {
17620
- return "";
17621
- }
17622
- if (list.length === 1) {
17623
- return list.toString();
17624
- }
17625
- if (list.length === 2) {
17626
- return list.join(' and ');
17627
- }
17628
- return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
17629
- }
17630
- function capSentence(cap) {
17631
- const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
17632
- const domain = cap.with.domain === "*" ? "" : cap.with.domain;
17633
- const pointers = cap.with.pointers.includes("*")
17634
- ? ["all AD4M data"]
17635
- : cap.with.pointers;
17636
- return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
17637
- }
17638
-
17639
17712
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
17640
17713
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17641
17714
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -18961,6 +19034,10 @@ class Ad4mModel {
18961
19034
  * @private
18962
19035
  */
18963
19036
  generatePropertySetterAction(key, metadata) {
19037
+ // Check if property is read-only
19038
+ if (metadata.writable === false) {
19039
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
19040
+ }
18964
19041
  if (metadata.setter) {
18965
19042
  // Custom setter - throw error for now (Phase 2)
18966
19043
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -19053,34 +19130,20 @@ class Ad4mModel {
19053
19130
  }
19054
19131
  async getData() {
19055
19132
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
19056
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
19057
- const fullQuery = `
19058
- Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
19059
- subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
19060
- ${subQueries.join(", ")}
19061
- `;
19062
- // Try Prolog first
19063
- try {
19064
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
19065
- if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
19066
- const { Properties, Collections, Timestamp, Author } = result[0];
19067
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
19068
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
19069
- return this;
19070
- }
19071
- }
19072
- catch (e) {
19073
- console.log(`Prolog getData failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}, falling back to SurrealDB`);
19074
- }
19075
- // Fallback to SurrealDB (SdnaOnly mode)
19133
+ // Use SurrealDB for data queries
19076
19134
  try {
19077
19135
  const ctor = this.constructor;
19078
19136
  const metadata = ctor.getModelMetadata();
19079
19137
  // Query for all links from this specific node (base expression)
19138
+ // Using formatSurrealValue to prevent SQL injection by properly escaping the value
19139
+ const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
19140
+ // Note: We use ORDER BY timestamp ASC because:
19141
+ // - For collections: we want chronological order (oldest to newest)
19142
+ // - For properties: we select the LAST element to get "latest wins" semantics
19080
19143
  const linksQuery = `
19081
19144
  SELECT id, predicate, out.uri AS target, author, timestamp
19082
19145
  FROM link
19083
- WHERE in.uri = '${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'
19146
+ WHERE in.uri = ${safeBaseExpression}
19084
19147
  ORDER BY timestamp ASC
19085
19148
  `;
19086
19149
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
@@ -19091,7 +19154,9 @@ class Ad4mModel {
19091
19154
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19092
19155
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19093
19156
  if (matching.length > 0) {
19094
- const link = matching[0]; // Take first/latest
19157
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
19158
+ // The last element has the most recent timestamp and represents the current property value.
19159
+ const link = matching[matching.length - 1];
19095
19160
  let value = link.target;
19096
19161
  // Track timestamp/author
19097
19162
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -19135,7 +19200,8 @@ class Ad4mModel {
19135
19200
  // Process collections
19136
19201
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19137
19202
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19138
- // Links are already sorted by timestamp ASC from the query, so map preserves order
19203
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
19204
+ // so the collection reflects the order in which items were added (oldest to newest).
19139
19205
  this[collName] = matching.map((l) => l.target);
19140
19206
  }
19141
19207
  // Set author and timestamp
@@ -19226,10 +19292,10 @@ class Ad4mModel {
19226
19292
  if (propMeta.required) {
19227
19293
  // For flag properties, also filter by the target value
19228
19294
  if (propMeta.flag && propMeta.initial) {
19229
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
19295
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
19230
19296
  }
19231
19297
  else {
19232
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
19298
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
19233
19299
  }
19234
19300
  }
19235
19301
  }
@@ -19240,10 +19306,10 @@ class Ad4mModel {
19240
19306
  if (propMeta.initial) {
19241
19307
  // For flag properties, also filter by the target value
19242
19308
  if (propMeta.flag) {
19243
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
19309
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
19244
19310
  }
19245
19311
  else {
19246
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
19312
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
19247
19313
  }
19248
19314
  break; // Just need one defining property
19249
19315
  }
@@ -19355,7 +19421,7 @@ WHERE ${whereConditions.join(' AND ')}
19355
19421
  const propMeta = metadata.properties[propertyName];
19356
19422
  if (!propMeta)
19357
19423
  continue; // Skip if property not found in metadata
19358
- const predicate = propMeta.predicate;
19424
+ const predicate = escapeSurrealString(propMeta.predicate);
19359
19425
  // Use fn::parse_literal() for properties with resolveLanguage
19360
19426
  const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
19361
19427
  if (Array.isArray(condition)) {
@@ -19487,7 +19553,7 @@ WHERE ${whereConditions.join(' AND ')}
19487
19553
  const propMeta = metadata.properties[propertyName];
19488
19554
  if (!propMeta)
19489
19555
  continue; // Skip if property not found in metadata
19490
- const predicate = propMeta.predicate;
19556
+ const predicate = escapeSurrealString(propMeta.predicate);
19491
19557
  // Use fn::parse_literal() for properties with resolveLanguage
19492
19558
  const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
19493
19559
  if (Array.isArray(condition)) {
@@ -19562,7 +19628,8 @@ WHERE ${whereConditions.join(' AND ')}
19562
19628
  if (!propMeta)
19563
19629
  continue; // Skip if not found
19564
19630
  // Reference source directly since we're selecting from link table
19565
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${propMeta.predicate}' LIMIT 1) AS ${propName}`);
19631
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
19632
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
19566
19633
  }
19567
19634
  // Determine collections to fetch
19568
19635
  const collsToFetch = collections || Object.keys(metadata.collections);
@@ -19571,7 +19638,8 @@ WHERE ${whereConditions.join(' AND ')}
19571
19638
  if (!collMeta)
19572
19639
  continue; // Skip if not found
19573
19640
  // Reference source directly since we're selecting from link table
19574
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${collMeta.predicate}') AS ${collName}`);
19641
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
19642
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
19575
19643
  }
19576
19644
  // Always add author and timestamp fields
19577
19645
  fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
@@ -19593,7 +19661,8 @@ WHERE ${whereConditions.join(' AND ')}
19593
19661
  if (!propMeta)
19594
19662
  continue; // Skip if not found
19595
19663
  // Use array::first to get the first target value for this predicate
19596
- fields.push(`array::first(target[WHERE predicate = '${propMeta.predicate}']) AS ${propName}`);
19664
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
19665
+ fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
19597
19666
  }
19598
19667
  // Determine collections to fetch
19599
19668
  const collsToFetch = collections || Object.keys(metadata.collections);
@@ -19602,7 +19671,8 @@ WHERE ${whereConditions.join(' AND ')}
19602
19671
  if (!collMeta)
19603
19672
  continue; // Skip if not found
19604
19673
  // Use array filtering to get all target values for this predicate
19605
- fields.push(`target[WHERE predicate = '${collMeta.predicate}'] AS ${collName}`);
19674
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
19675
+ fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
19606
19676
  }
19607
19677
  // Always add author and timestamp fields using array::first
19608
19678
  fields.push(`array::first(author) AS author`);
@@ -20221,7 +20291,7 @@ WHERE ${whereConditions.join(' AND ')}
20221
20291
  }
20222
20292
  // Generate actions from metadata (replaces Prolog query)
20223
20293
  const actions = this.generateCollectionAction(key, 'setter');
20224
- if (value) {
20294
+ if (value != null) {
20225
20295
  if (Array.isArray(value)) {
20226
20296
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20227
20297
  }
@@ -20239,7 +20309,7 @@ WHERE ${whereConditions.join(' AND ')}
20239
20309
  }
20240
20310
  // Generate actions from metadata (replaces Prolog query)
20241
20311
  const actions = this.generateCollectionAction(key, 'adder');
20242
- if (value) {
20312
+ if (value != null) {
20243
20313
  if (Array.isArray(value)) {
20244
20314
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20245
20315
  }
@@ -20257,7 +20327,7 @@ WHERE ${whereConditions.join(' AND ')}
20257
20327
  }
20258
20328
  // Generate actions from metadata (replaces Prolog query)
20259
20329
  const actions = this.generateCollectionAction(key, 'remover');
20260
- if (value) {
20330
+ if (value != null) {
20261
20331
  if (Array.isArray(value)) {
20262
20332
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20263
20333
  }
@@ -20347,11 +20417,8 @@ WHERE ${whereConditions.join(' AND ')}
20347
20417
  }
20348
20418
  }
20349
20419
  else if (Array.isArray(value)) {
20350
- // Handle all arrays as collections, even empty ones
20351
- if (value.length > 0) {
20352
- await this.setCollectionSetter(key, value, batchId);
20353
- }
20354
- // Skip empty arrays - don't try to set them as properties
20420
+ // Handle all arrays as collections, including empty ones (which clears the collection)
20421
+ await this.setCollectionSetter(key, value, batchId);
20355
20422
  }
20356
20423
  else if (value !== undefined && value !== null && value !== "") {
20357
20424
  if (setProperties) {
@@ -21223,4 +21290,4 @@ class ModelQueryBuilder {
21223
21290
  }
21224
21291
  }
21225
21292
 
21226
- export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, Capability, CapabilityInput, Collection, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, Icon, ImportResult, ImportStats, InstanceQuery, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, ModelOptions, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, Perspective, PerspectiveAction, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, addLink, capSentence, exprRef2String, formatList, hasLink, isExpression, isLink, linkEqual, makeRandomPrologAtom, parseExprUrl, typeDefsString };
21293
+ export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, Capability, CapabilityInput, Collection, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, Icon, ImportResult, ImportStats, InstanceQuery, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, ModelOptions, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, Perspective, PerspectiveAction, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, addLink, capSentence, escapeSurrealString, exprRef2String, formatList, hasLink, isExpression, isLink, linkEqual, makeRandomPrologAtom, parseExprUrl, typeDefsString };