@coasys/ad4m 0.11.2-dev.5 → 0.12.0-dev-whisper-lang

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.
@@ -29,9 +29,9 @@ export interface InstanceQueryParams {
29
29
  where?: object;
30
30
 
31
31
  /**
32
- * A string representing the condition clause of the query.
32
+ * A string representing the Prolog condition clause of the query.
33
33
  */
34
- condition?: string;
34
+ prologCondition?: string;
35
35
  }
36
36
 
37
37
  /**
@@ -65,14 +65,14 @@ condition?: string;
65
65
  * static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
66
66
  *
67
67
  * // Get highly rated recipes using a custom condition
68
- * @InstanceQuery({ condition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
68
+ * @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
69
69
  * static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
70
70
  * }
71
71
  * ```
72
72
  *
73
73
  * @param {Object} [options] - Query options
74
74
  * @param {object} [options.where] - Object with property-value pairs to match
75
- * @param {string} [options.condition] - Custom Prolog condition for more complex queries
75
+ * @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
76
76
  */
77
77
  export function InstanceQuery(options?: InstanceQueryParams) {
78
78
  return function <T>(target: T, key: keyof T, descriptor: PropertyDescriptor) {
@@ -93,8 +93,8 @@ export function InstanceQuery(options?: InstanceQueryParams) {
93
93
  }
94
94
  }
95
95
 
96
- if(options && options.condition) {
97
- query += ', ' + options.condition
96
+ if(options && options.prologCondition) {
97
+ query += ', ' + options.prologCondition
98
98
  }
99
99
 
100
100
  // Try Prolog first
@@ -171,21 +171,21 @@ export interface PropertyOptions {
171
171
  resolveLanguage?: string;
172
172
 
173
173
  /**
174
- * Custom getter to get the value of the property in the prolog engine. If not provided, the default getter will be used.
174
+ * Custom Prolog getter to get the value of the property. If not provided, the default getter will be used.
175
175
  */
176
- getter?: string;
176
+ prologGetter?: string;
177
177
 
178
178
  /**
179
- * Custom setter to set the value of the property in the prolog engine. Only available if the property is writable.
179
+ * Custom Prolog setter to set the value of the property. Only available if the property is writable.
180
180
  */
181
- setter?: string;
181
+ prologSetter?: string;
182
182
 
183
183
  /**
184
184
  * Custom SurrealQL getter to resolve the property value. Use this for custom graph traversals.
185
185
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
186
186
  * Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)[0]"
187
187
  */
188
- surrealGetter?: string;
188
+ getter?: string;
189
189
 
190
190
  /**
191
191
  * Indicates whether the property is stored locally in the perspective and not in the network. Useful for properties that are not meant to be shared with the network.
@@ -276,8 +276,8 @@ export interface PropertyOptions {
276
276
  * @param {boolean} [opts.required] - Whether the property must have a value
277
277
  * @param {boolean} [opts.writable=true] - Whether the property can be modified
278
278
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
279
- * @param {string} [opts.getter] - Custom Prolog code for getting the property value
280
- * @param {string} [opts.setter] - Custom Prolog code for setting the property value
279
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
280
+ * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
281
281
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
282
282
  */
283
283
  export function Optional(opts: PropertyOptions) {
@@ -290,8 +290,8 @@ export function Optional(opts: PropertyOptions) {
290
290
  throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
291
291
  }
292
292
 
293
- if (!opts.through && !opts.getter) {
294
- throw new Error("SubjectProperty requires either 'through' or 'getter' option")
293
+ if (!opts.through && !opts.prologGetter) {
294
+ throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option")
295
295
  }
296
296
 
297
297
  target["__properties"] = target["__properties"] || {};
@@ -405,6 +405,7 @@ export function Flag(opts: FlagOptions) {
405
405
 
406
406
  interface WhereOptions {
407
407
  isInstance?: any
408
+ prologCondition?: string
408
409
  condition?: string
409
410
  }
410
411
 
@@ -424,7 +425,7 @@ export interface CollectionOptions {
424
425
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
425
426
  * Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)"
426
427
  */
427
- surrealGetter?: string;
428
+ getter?: string;
428
429
 
429
430
  /**
430
431
  * Indicates whether the property is stored locally in the perspective and not in the network. Useful for properties that are not meant to be shared with the network.
@@ -468,13 +469,20 @@ export interface CollectionOptions {
468
469
  * })
469
470
  * comments: string[] = [];
470
471
  *
471
- * // Collection with custom filter condition
472
+ * // Collection with custom Prolog filter condition
472
473
  * @Collection({
473
474
  * through: "recipe://step",
474
- * where: { condition: `triple(Target, "step://order", Order), Order < 3` }
475
+ * where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
475
476
  * })
476
477
  * firstSteps: string[] = [];
477
478
  *
479
+ * // Collection with custom SurrealDB filter condition
480
+ * @Collection({
481
+ * through: "recipe://entries",
482
+ * where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
483
+ * })
484
+ * ingredients: string[] = [];
485
+ *
478
486
  * // Local-only collection not shared with network
479
487
  * @Collection({
480
488
  * through: "recipe://note",
@@ -494,7 +502,7 @@ export interface CollectionOptions {
494
502
  * @param {string} opts.through - The predicate URI for collection links
495
503
  * @param {WhereOptions} [opts.where] - Filter conditions for collection values
496
504
  * @param {any} [opts.where.isInstance] - Model class to filter instances by
497
- * @param {string} [opts.where.condition] - Custom Prolog condition for filtering
505
+ * @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
498
506
  * @param {boolean} [opts.local] - Whether collection links are stored locally only
499
507
  */
500
508
  export function Collection(opts: CollectionOptions) {
@@ -614,15 +622,15 @@ export function ModelOptions(opts: ModelOptionsOptions) {
614
622
  for(let property in properties) {
615
623
  let propertyCode = `property(${uuid}, "${property}").\n`
616
624
 
617
- let { through, initial, required, resolveLanguage, writable, flag, getter, setter, local } = properties[property]
625
+ let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property]
618
626
 
619
627
  if(resolveLanguage) {
620
628
  propertyCode += `property_resolve(${uuid}, "${property}").\n`
621
629
  propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`
622
630
  }
623
631
 
624
- if(getter) {
625
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${getter}.\n`
632
+ if(prologGetter) {
633
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`
626
634
  } else if(through) {
627
635
  propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`
628
636
 
@@ -635,8 +643,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
635
643
  }
636
644
  }
637
645
 
638
- if(setter) {
639
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${setter}.\n`
646
+ if(prologSetter) {
647
+ propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`
640
648
  } else if (writable && through) {
641
649
  let setter = obj[propertyNameToSetterName(property)]
642
650
  if(typeof setter === "function") {
@@ -679,8 +687,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
679
687
 
680
688
  if(through) {
681
689
  if(where) {
682
- if(!where.isInstance && !where.condition) {
683
- throw "'where' needs one of 'isInstance' or 'condition'"
690
+ if(!where.isInstance && !where.prologCondition && !where.condition) {
691
+ throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'"
684
692
  }
685
693
 
686
694
  let conditions = []
@@ -695,13 +703,19 @@ export function ModelOptions(opts: ModelOptionsOptions) {
695
703
  conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`)
696
704
  }
697
705
 
698
- if(where.condition) {
699
- conditions.push(where.condition)
706
+ if(where.prologCondition) {
707
+ conditions.push(where.prologCondition)
700
708
  }
701
709
 
702
- const conditionString = conditions.join(", ")
703
-
704
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`
710
+ // If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
711
+ // If only condition is present, use simple findall (SurrealDB will filter later)
712
+ if(conditions.length > 0) {
713
+ const conditionString = conditions.join(", ")
714
+ collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`
715
+ } else {
716
+ // Only SurrealDB condition present (no Prolog filtering)
717
+ collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
718
+ }
705
719
  } else {
706
720
  collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
707
721
  }
@@ -810,8 +824,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
810
824
  * @param {string} opts.through - The predicate URI for the property
811
825
  * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
812
826
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
813
- * @param {string} [opts.getter] - Custom Prolog code for getting the property value
814
- * @param {string} [opts.setter] - Custom Prolog code for setting the property value
827
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
828
+ * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
815
829
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
816
830
  */
817
831
  export function Property(opts: PropertyOptions) {
@@ -875,7 +889,7 @@ export function Property(opts: PropertyOptions) {
875
889
  * @param {string} opts.through - The predicate URI for the property
876
890
  * @param {string} [opts.initial] - Initial value (if property should have one)
877
891
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
878
- * @param {string} [opts.getter] - Custom Prolog code for getting the property value
892
+ * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
879
893
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
880
894
  */
881
895
  export function ReadOnly(opts: PropertyOptions) {
@@ -1182,7 +1182,7 @@ export class PerspectiveProxy {
1182
1182
  requiredPredicates: string[],
1183
1183
  requiredTriples: Array<{predicate: string, target?: string}>,
1184
1184
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1185
- collections: Map<string, { predicate: string, instanceFilter?: string }>
1185
+ collections: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1186
1186
  } | null> {
1187
1187
  try {
1188
1188
  // Get SDNA code from perspective - it's stored as a link
@@ -1286,7 +1286,7 @@ export class PerspectiveProxy {
1286
1286
  //console.log("properties", properties);
1287
1287
 
1288
1288
  // Extract collection metadata
1289
- const collections = new Map<string, { predicate: string, instanceFilter?: string }>();
1289
+ const collections = new Map<string, { predicate: string, instanceFilter?: string, condition?: string }>();
1290
1290
  const collectionResults = await this.infer(`subject_class("${className}", C), collection(C, Coll)`);
1291
1291
  //console.log("collectionResults", collectionResults);
1292
1292
  if (collectionResults) {
@@ -1294,6 +1294,7 @@ export class PerspectiveProxy {
1294
1294
  const collName = result.Coll;
1295
1295
  let predicate: string | null = null;
1296
1296
  let instanceFilter: string | undefined = undefined;
1297
+ let condition: string | undefined = undefined;
1297
1298
 
1298
1299
  // Try to extract predicate from collection_adder first
1299
1300
  const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
@@ -1304,6 +1305,9 @@ export class PerspectiveProxy {
1304
1305
  predicate = predicateMatch[1] || predicateMatch[2];
1305
1306
  }
1306
1307
  }
1308
+
1309
+ // Note: condition is not stored in SDNA, it's read from class metadata
1310
+ // It will be populated by augmentMetadataWithCollectionOptions() when needed
1307
1311
 
1308
1312
  // Parse collection_getter from SDNA to extract predicate and instanceFilter
1309
1313
  // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
@@ -1345,7 +1349,7 @@ export class PerspectiveProxy {
1345
1349
  }
1346
1350
 
1347
1351
  if (predicate) {
1348
- collections.set(collName, { predicate, instanceFilter });
1352
+ collections.set(collName, { predicate, instanceFilter, condition });
1349
1353
  }
1350
1354
  }
1351
1355
  }
@@ -1364,7 +1368,7 @@ export class PerspectiveProxy {
1364
1368
  requiredPredicates: string[],
1365
1369
  requiredTriples: Array<{predicate: string, target?: string}>,
1366
1370
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1367
- collections: Map<string, { predicate: string }>
1371
+ collections: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1368
1372
  }): string {
1369
1373
  if (metadata.requiredTriples.length === 0) {
1370
1374
  // No required triples - any node with links is an instance
@@ -1433,6 +1437,7 @@ export class PerspectiveProxy {
1433
1437
  /**
1434
1438
  * Gets collection values using SurrealDB when Prolog fails.
1435
1439
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1440
+ * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
1436
1441
  */
1437
1442
  async getCollectionValuesViaSurreal(baseExpression: string, className: string, collectionName: string): Promise<any[]> {
1438
1443
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
@@ -1455,6 +1460,35 @@ export class PerspectiveProxy {
1455
1460
  }
1456
1461
 
1457
1462
  let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1463
+
1464
+ // Apply condition filtering if present
1465
+ if (collMeta.condition && values.length > 0) {
1466
+ try {
1467
+ const filteredValues: string[] = [];
1468
+
1469
+ for (const value of values) {
1470
+ let condition = collMeta.condition
1471
+ .replace(/\$perspective/g, `'${this.uuid}'`)
1472
+ .replace(/\$base/g, `'${baseExpression}'`)
1473
+ .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
1474
+
1475
+ // If condition starts with WHERE, wrap in array length check
1476
+ if (condition.trim().startsWith('WHERE')) {
1477
+ condition = `array::len(SELECT * FROM link ${condition}) > 0`;
1478
+ }
1479
+
1480
+ const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
1481
+ const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
1482
+ if (isTrue) {
1483
+ filteredValues.push(value);
1484
+ }
1485
+ }
1486
+
1487
+ values = filteredValues;
1488
+ } catch (error) {
1489
+ console.warn(`Failed to apply condition filter for ${collectionName}:`, error);
1490
+ }
1491
+ }
1458
1492
 
1459
1493
  // Apply instance filter if present - batch-check all values at once
1460
1494
  if (collMeta.instanceFilter) {
@@ -1485,7 +1519,7 @@ export class PerspectiveProxy {
1485
1519
  requiredPredicates: string[],
1486
1520
  requiredTriples: Array<{predicate: string, target?: string}>,
1487
1521
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1488
- collections: Map<string, { predicate: string, instanceFilter?: string }>
1522
+ collections: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1489
1523
  }
1490
1524
  ): Promise<string[]> {
1491
1525
  if (expressions.length === 0) {
@@ -1511,10 +1545,12 @@ export class PerspectiveProxy {
1511
1545
  if (triple.target) {
1512
1546
  // Flag: must match both predicate AND exact target value
1513
1547
  const escapedTarget = escapeSurrealString(triple.target);
1514
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}' GROUP BY in.uri`;
1548
+ // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1549
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1515
1550
  } else {
1516
1551
  // Property: just check predicate exists
1517
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' GROUP BY in.uri`;
1552
+ // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1553
+ checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
1518
1554
  }
1519
1555
 
1520
1556
  const result = await this.querySurrealDB(checkQuery);