@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.
@@ -14,6 +14,7 @@ import { Literal } from "../Literal";
14
14
  import { Link } from "../links/Links";
15
15
  import { makeRandomPrologAtom, ModelOptions } from "./decorators";
16
16
  import { propertyNameToSetterName } from "./util";
17
+ import { escapeSurrealString } from "../utils";
17
18
  function capitalize(word) {
18
19
  return word.charAt(0).toUpperCase() + word.slice(1);
19
20
  }
@@ -488,6 +489,10 @@ export class Ad4mModel {
488
489
  * @private
489
490
  */
490
491
  generatePropertySetterAction(key, metadata) {
492
+ // Check if property is read-only
493
+ if (metadata.writable === false) {
494
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
495
+ }
491
496
  if (metadata.setter) {
492
497
  // Custom setter - throw error for now (Phase 2)
493
498
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -580,34 +585,20 @@ export class Ad4mModel {
580
585
  }
581
586
  async getData() {
582
587
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
583
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
584
- const fullQuery = `
585
- Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
586
- subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
587
- ${subQueries.join(", ")}
588
- `;
589
- // Try Prolog first
590
- try {
591
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
592
- if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
593
- const { Properties, Collections, Timestamp, Author } = result[0];
594
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
595
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
596
- return this;
597
- }
598
- }
599
- catch (e) {
600
- console.log(`Prolog getData failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}, falling back to SurrealDB`);
601
- }
602
- // Fallback to SurrealDB (SdnaOnly mode)
588
+ // Use SurrealDB for data queries
603
589
  try {
604
590
  const ctor = this.constructor;
605
591
  const metadata = ctor.getModelMetadata();
606
592
  // Query for all links from this specific node (base expression)
593
+ // Using formatSurrealValue to prevent SQL injection by properly escaping the value
594
+ const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
595
+ // Note: We use ORDER BY timestamp ASC because:
596
+ // - For collections: we want chronological order (oldest to newest)
597
+ // - For properties: we select the LAST element to get "latest wins" semantics
607
598
  const linksQuery = `
608
599
  SELECT id, predicate, out.uri AS target, author, timestamp
609
600
  FROM link
610
- WHERE in.uri = '${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'
601
+ WHERE in.uri = ${safeBaseExpression}
611
602
  ORDER BY timestamp ASC
612
603
  `;
613
604
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
@@ -618,7 +609,9 @@ export class Ad4mModel {
618
609
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
619
610
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
620
611
  if (matching.length > 0) {
621
- const link = matching[0]; // Take first/latest
612
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
613
+ // The last element has the most recent timestamp and represents the current property value.
614
+ const link = matching[matching.length - 1];
622
615
  let value = link.target;
623
616
  // Track timestamp/author
624
617
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -662,7 +655,8 @@ export class Ad4mModel {
662
655
  // Process collections
663
656
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
664
657
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
665
- // Links are already sorted by timestamp ASC from the query, so map preserves order
658
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
659
+ // so the collection reflects the order in which items were added (oldest to newest).
666
660
  this[collName] = matching.map((l) => l.target);
667
661
  }
668
662
  // Set author and timestamp
@@ -753,10 +747,10 @@ export class Ad4mModel {
753
747
  if (propMeta.required) {
754
748
  // For flag properties, also filter by the target value
755
749
  if (propMeta.flag && propMeta.initial) {
756
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
750
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
757
751
  }
758
752
  else {
759
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
753
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
760
754
  }
761
755
  }
762
756
  }
@@ -767,10 +761,10 @@ export class Ad4mModel {
767
761
  if (propMeta.initial) {
768
762
  // For flag properties, also filter by the target value
769
763
  if (propMeta.flag) {
770
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
764
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
771
765
  }
772
766
  else {
773
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
767
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
774
768
  }
775
769
  break; // Just need one defining property
776
770
  }
@@ -882,7 +876,7 @@ WHERE ${whereConditions.join(' AND ')}
882
876
  const propMeta = metadata.properties[propertyName];
883
877
  if (!propMeta)
884
878
  continue; // Skip if property not found in metadata
885
- const predicate = propMeta.predicate;
879
+ const predicate = escapeSurrealString(propMeta.predicate);
886
880
  // Use fn::parse_literal() for properties with resolveLanguage
887
881
  const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
888
882
  if (Array.isArray(condition)) {
@@ -1014,7 +1008,7 @@ WHERE ${whereConditions.join(' AND ')}
1014
1008
  const propMeta = metadata.properties[propertyName];
1015
1009
  if (!propMeta)
1016
1010
  continue; // Skip if property not found in metadata
1017
- const predicate = propMeta.predicate;
1011
+ const predicate = escapeSurrealString(propMeta.predicate);
1018
1012
  // Use fn::parse_literal() for properties with resolveLanguage
1019
1013
  const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
1020
1014
  if (Array.isArray(condition)) {
@@ -1089,7 +1083,8 @@ WHERE ${whereConditions.join(' AND ')}
1089
1083
  if (!propMeta)
1090
1084
  continue; // Skip if not found
1091
1085
  // Reference source directly since we're selecting from link table
1092
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${propMeta.predicate}' LIMIT 1) AS ${propName}`);
1086
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
1087
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
1093
1088
  }
1094
1089
  // Determine collections to fetch
1095
1090
  const collsToFetch = collections || Object.keys(metadata.collections);
@@ -1098,7 +1093,8 @@ WHERE ${whereConditions.join(' AND ')}
1098
1093
  if (!collMeta)
1099
1094
  continue; // Skip if not found
1100
1095
  // Reference source directly since we're selecting from link table
1101
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${collMeta.predicate}') AS ${collName}`);
1096
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
1097
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
1102
1098
  }
1103
1099
  // Always add author and timestamp fields
1104
1100
  fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
@@ -1120,7 +1116,8 @@ WHERE ${whereConditions.join(' AND ')}
1120
1116
  if (!propMeta)
1121
1117
  continue; // Skip if not found
1122
1118
  // Use array::first to get the first target value for this predicate
1123
- fields.push(`array::first(target[WHERE predicate = '${propMeta.predicate}']) AS ${propName}`);
1119
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
1120
+ fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
1124
1121
  }
1125
1122
  // Determine collections to fetch
1126
1123
  const collsToFetch = collections || Object.keys(metadata.collections);
@@ -1129,7 +1126,8 @@ WHERE ${whereConditions.join(' AND ')}
1129
1126
  if (!collMeta)
1130
1127
  continue; // Skip if not found
1131
1128
  // Use array filtering to get all target values for this predicate
1132
- fields.push(`target[WHERE predicate = '${collMeta.predicate}'] AS ${collName}`);
1129
+ const escapedPredicate = escapeSurrealString(collMeta.predicate);
1130
+ fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
1133
1131
  }
1134
1132
  // Always add author and timestamp fields using array::first
1135
1133
  fields.push(`array::first(author) AS author`);
@@ -1748,7 +1746,7 @@ WHERE ${whereConditions.join(' AND ')}
1748
1746
  }
1749
1747
  // Generate actions from metadata (replaces Prolog query)
1750
1748
  const actions = this.generateCollectionAction(key, 'setter');
1751
- if (value) {
1749
+ if (value != null) {
1752
1750
  if (Array.isArray(value)) {
1753
1751
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
1754
1752
  }
@@ -1766,7 +1764,7 @@ WHERE ${whereConditions.join(' AND ')}
1766
1764
  }
1767
1765
  // Generate actions from metadata (replaces Prolog query)
1768
1766
  const actions = this.generateCollectionAction(key, 'adder');
1769
- if (value) {
1767
+ if (value != null) {
1770
1768
  if (Array.isArray(value)) {
1771
1769
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
1772
1770
  }
@@ -1784,7 +1782,7 @@ WHERE ${whereConditions.join(' AND ')}
1784
1782
  }
1785
1783
  // Generate actions from metadata (replaces Prolog query)
1786
1784
  const actions = this.generateCollectionAction(key, 'remover');
1787
- if (value) {
1785
+ if (value != null) {
1788
1786
  if (Array.isArray(value)) {
1789
1787
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
1790
1788
  }
@@ -1874,11 +1872,8 @@ WHERE ${whereConditions.join(' AND ')}
1874
1872
  }
1875
1873
  }
1876
1874
  else if (Array.isArray(value)) {
1877
- // Handle all arrays as collections, even empty ones
1878
- if (value.length > 0) {
1879
- await this.setCollectionSetter(key, value, batchId);
1880
- }
1881
- // Skip empty arrays - don't try to set them as properties
1875
+ // Handle all arrays as collections, including empty ones (which clears the collection)
1876
+ await this.setCollectionSetter(key, value, batchId);
1882
1877
  }
1883
1878
  else if (value !== undefined && value !== null && value !== "") {
1884
1879
  if (setProperties) {
@@ -55,39 +55,7 @@ export class Subject {
55
55
  Object.defineProperty(this, p, {
56
56
  configurable: true,
57
57
  get: async () => {
58
- // Try Prolog first
59
- try {
60
- let results = await __classPrivateFieldGet(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Subject_subjectClassName, "f")}", C), property_getter(C, "${__classPrivateFieldGet(this, _Subject_baseExpression, "f")}", "${p}", Value)`);
61
- if (results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
62
- let expressionURI = results[0].Value;
63
- if (resolveExpressionURI) {
64
- try {
65
- if (expressionURI) {
66
- const expression = await __classPrivateFieldGet(this, _Subject_perspective, "f").getExpression(expressionURI);
67
- try {
68
- return JSON.parse(expression.data);
69
- }
70
- catch (e) {
71
- return expression.data;
72
- }
73
- }
74
- else {
75
- return expressionURI;
76
- }
77
- }
78
- catch (err) {
79
- return expressionURI;
80
- }
81
- }
82
- else {
83
- return expressionURI;
84
- }
85
- }
86
- }
87
- catch (err) {
88
- // Prolog query failed, fall through to SurrealDB
89
- }
90
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
58
+ // Use SurrealDB for data queries
91
59
  try {
92
60
  return await __classPrivateFieldGet(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), p);
93
61
  }
@@ -126,20 +94,7 @@ export class Subject {
126
94
  Object.defineProperty(this, c, {
127
95
  configurable: true,
128
96
  get: async () => {
129
- // Try Prolog first
130
- try {
131
- let results = await __classPrivateFieldGet(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Subject_subjectClassName, "f")}", C), collection_getter(C, "${__classPrivateFieldGet(this, _Subject_baseExpression, "f")}", "${c}", Value)`);
132
- if (results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
133
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
134
- if (collectionContent.length > 0) {
135
- return collectionContent;
136
- }
137
- }
138
- }
139
- catch (err) {
140
- // Prolog query failed, fall through to SurrealDB
141
- }
142
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
97
+ // Use SurrealDB for data queries
143
98
  try {
144
99
  return await __classPrivateFieldGet(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), c);
145
100
  }
@@ -179,6 +179,16 @@ export declare class PerspectiveProxy {
179
179
  * Note: Don't create this directly, use ad4m.perspective.add() instead.
180
180
  */
181
181
  constructor(handle: PerspectiveHandle, ad4m: PerspectiveClient);
182
+ /**
183
+ * Escapes special regex characters in a string to prevent ReDoS attacks
184
+ * and regex injection when building dynamic regular expressions.
185
+ *
186
+ * @param str - The string to escape
187
+ * @returns The escaped string safe for use in RegExp constructor
188
+ *
189
+ * @private
190
+ */
191
+ private escapeRegExp;
182
192
  /**
183
193
  * Executes a set of actions on an expression with optional parameters.
184
194
  * Used internally by Social DNA flows and subject class operations.
@@ -587,13 +597,22 @@ export declare class PerspectiveProxy {
587
597
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
588
598
  */
589
599
  getCollectionValuesViaSurreal(baseExpression: string, className: string, collectionName: string): Promise<any[]>;
600
+ /**
601
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
602
+ * This avoids N+1 query problems by checking all values at once.
603
+ */
604
+ private batchCheckSubjectInstances;
605
+ /**
606
+ * Fallback sequential instance checking when batch checking isn't available.
607
+ */
608
+ private filterInstancesSequential;
590
609
  /** Returns all subject instances of the given subject class as proxy objects.
591
610
  * @param subjectClass Either a string with the name of the subject class, or an object
592
611
  * with the properties of the subject class. In the latter case, all subject classes
593
612
  * that match the given properties will be used.
594
613
  */
595
614
  getAllSubjectInstances<T>(subjectClass: T): Promise<T[]>;
596
- /** Returns all subject proxies of the given subject class.
615
+ /** Returns all subject proxies of the given subject class as proxy objects.
597
616
  * @param subjectClass Either a string with the name of the subject class, or an object
598
617
  * with the properties of the subject class. In the latter case, all subject classes
599
618
  * that match the given properties will be used.