@coasys/ad4m 0.11.2-dev-multi-user-email-2 → 0.11.2-dev-sdna-only-prolog

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
@@ -4490,36 +4490,44 @@ class Subject {
4490
4490
  Object.defineProperty(this, p, {
4491
4491
  configurable: true,
4492
4492
  get: async () => {
4493
- 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)`);
4494
- if (results && results.length > 0) {
4495
- let expressionURI = results[0].Value;
4496
- if (resolveExpressionURI) {
4497
- try {
4498
- if (expressionURI) {
4499
- const expression = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getExpression(expressionURI);
4500
- try {
4501
- return JSON.parse(expression.data);
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
+ }
4502
4508
  }
4503
- catch (e) {
4504
- return expression.data;
4509
+ else {
4510
+ return expressionURI;
4505
4511
  }
4506
4512
  }
4507
- else {
4513
+ catch (err) {
4508
4514
  return expressionURI;
4509
4515
  }
4510
4516
  }
4511
- catch (err) {
4517
+ else {
4512
4518
  return expressionURI;
4513
4519
  }
4514
4520
  }
4515
- else {
4516
- return expressionURI;
4517
- }
4518
4521
  }
4519
- else if (results) {
4520
- return results;
4522
+ catch (err) {
4523
+ // Prolog query failed, fall through to SurrealDB
4521
4524
  }
4522
- else {
4525
+ // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4526
+ try {
4527
+ return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), p);
4528
+ }
4529
+ catch (err) {
4530
+ console.warn(`Failed to get property ${p} via SurrealDB:`, err);
4523
4531
  return undefined;
4524
4532
  }
4525
4533
  }
@@ -4553,12 +4561,25 @@ class Subject {
4553
4561
  Object.defineProperty(this, c, {
4554
4562
  configurable: true,
4555
4563
  get: async () => {
4556
- 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)`);
4557
- if (results && results.length > 0 && results[0].Value) {
4558
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
4559
- return collectionContent;
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
+ }
4560
4573
  }
4561
- else {
4574
+ catch (err) {
4575
+ // Prolog query failed, fall through to SurrealDB
4576
+ }
4577
+ // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4578
+ try {
4579
+ return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), c);
4580
+ }
4581
+ catch (err) {
4582
+ console.warn(`Failed to get collection ${c} via SurrealDB:`, err);
4562
4583
  return [];
4563
4584
  }
4564
4585
  }
@@ -5578,14 +5599,48 @@ class PerspectiveProxy {
5578
5599
  */
5579
5600
  async isSubjectInstance(expression, subjectClass) {
5580
5601
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
5581
- let isInstance = false;
5582
- const maxAttempts = 5;
5583
- let attempts = 0;
5584
- while (attempts < maxAttempts && !isInstance) {
5585
- isInstance = await this.infer(`subject_class("${className}", C), instance(C, "${expression}")`);
5586
- attempts++;
5602
+ // Get metadata from SDNA using Prolog metaprogramming
5603
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5604
+ if (!metadata) {
5605
+ return false;
5606
+ }
5607
+ // If no required triples, any expression with links is an instance
5608
+ 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);
5612
+ const result = await this.querySurrealDB(checkQuery);
5613
+ console.log("result", result);
5614
+ const count = result[0]?.count ?? 0;
5615
+ const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
5616
+ return countValue > 0;
5617
+ }
5618
+ // Check if the expression has all required triples (predicate + optional exact target)
5619
+ for (const triple of metadata.requiredTriples) {
5620
+ console.log("checking triple", triple);
5621
+ let checkQuery;
5622
+ if (triple.target) {
5623
+ // 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}'`;
5625
+ }
5626
+ else {
5627
+ // Property: just check predicate exists
5628
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}'`;
5629
+ }
5630
+ console.log("checkQuery", checkQuery);
5631
+ const result = await this.querySurrealDB(checkQuery);
5632
+ console.log("result", result);
5633
+ if (!result || result.length === 0) {
5634
+ return false;
5635
+ }
5636
+ const count = result[0]?.count ?? 0;
5637
+ // Handle potential object response like {Int: 0}
5638
+ const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
5639
+ if (countValue === 0) {
5640
+ return false;
5641
+ }
5587
5642
  }
5588
- return isInstance;
5643
+ return true;
5589
5644
  }
5590
5645
  /** For an existing subject instance (existing in the perspective's links)
5591
5646
  * this function returns a proxy object that can be used to access the subject's
@@ -5605,6 +5660,254 @@ class PerspectiveProxy {
5605
5660
  await subject.init();
5606
5661
  return subject;
5607
5662
  }
5663
+ /**
5664
+ * Extracts subject class metadata from SDNA by parsing the Prolog text.
5665
+ * Parses the instance rule to extract required predicates.
5666
+ * Returns required predicates that define what makes something an instance,
5667
+ * plus a map of property/collection names to their predicates.
5668
+ */
5669
+ async getSubjectClassMetadataFromSDNA(className) {
5670
+ try {
5671
+ // Get SDNA code from perspective - it's stored as a link
5672
+ const sdnaLinks = await this.get(new LinkQuery({
5673
+ source: `literal://string:${className}`,
5674
+ predicate: "ad4m://sdna"
5675
+ }));
5676
+ //console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
5677
+ if (!sdnaLinks || sdnaLinks.length === 0) {
5678
+ console.warn(`No SDNA found for class ${className}`);
5679
+ return null;
5680
+ }
5681
+ if (!sdnaLinks[0].data.target) {
5682
+ console.error(`SDNA link for ${className} has no target:`, sdnaLinks[0]);
5683
+ return null;
5684
+ }
5685
+ // Extract SDNA code from the literal
5686
+ const sdnaCode = Literal.fromUrl(sdnaLinks[0].data.target).get();
5687
+ //console.log("sdnaCode for", className, ":", sdnaCode.substring(0, 200));
5688
+ // Store required triples as {predicate, target?}
5689
+ // target is only set for flags (exact matches), otherwise undefined
5690
+ const requiredTriples = [];
5691
+ // Parse the instance rule from the SDNA code
5692
+ // 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) {
5695
+ const ruleBody = instanceRuleMatch[1];
5696
+ console.log("instance rule body:", ruleBody);
5697
+ // Extract all triple(Base, "predicate", Target) patterns
5698
+ // Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
5699
+ const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
5700
+ let match;
5701
+ while ((match = tripleRegex.exec(ruleBody)) !== null) {
5702
+ const predicate = match[1];
5703
+ const target = match[2]; // undefined if matched "_"
5704
+ requiredTriples.push({ predicate, target });
5705
+ console.log(`Extracted triple: predicate="${predicate}", target="${target}"`);
5706
+ }
5707
+ }
5708
+ else {
5709
+ console.warn(`No instance rule found in SDNA for ${className}`);
5710
+ }
5711
+ // For backward compatibility, also maintain requiredPredicates array
5712
+ const requiredPredicates = requiredTriples.map(t => t.predicate);
5713
+ console.log("extracted requiredTriples:", requiredTriples);
5714
+ // Extract property metadata
5715
+ const properties = new Map();
5716
+ const propertyResults = await this.infer(`subject_class("${className}", C), property(C, P)`);
5717
+ //console.log("propertyResults", propertyResults);
5718
+ if (propertyResults) {
5719
+ for (const result of propertyResults) {
5720
+ const propName = result.P;
5721
+ let predicate = null;
5722
+ // Try to extract predicate from property_setter first
5723
+ const setterResults = await this.infer(`subject_class("${className}", C), property_setter(C, "${propName}", Setter)`);
5724
+ if (setterResults && setterResults.length > 0) {
5725
+ const setterString = setterResults[0].Setter;
5726
+ const predicateMatch = setterString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
5727
+ if (predicateMatch) {
5728
+ predicate = predicateMatch[1] || predicateMatch[2];
5729
+ }
5730
+ }
5731
+ // If no setter, try to extract from SDNA property_getter Prolog code
5732
+ if (!predicate) {
5733
+ // Parse the SDNA code for property_getter definition
5734
+ const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${propName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
5735
+ if (getterMatch) {
5736
+ predicate = getterMatch[1];
5737
+ }
5738
+ }
5739
+ if (predicate) {
5740
+ // Check if property has resolveLanguage
5741
+ const resolveResults = await this.infer(`subject_class("${className}", C), property_resolve_language(C, "${propName}", Lang)`);
5742
+ const resolveLanguage = resolveResults && resolveResults.length > 0 ? resolveResults[0].Lang : undefined;
5743
+ properties.set(propName, { predicate, resolveLanguage });
5744
+ }
5745
+ }
5746
+ }
5747
+ //console.log("properties", properties);
5748
+ // Extract collection metadata
5749
+ const collections = new Map();
5750
+ const collectionResults = await this.infer(`subject_class("${className}", C), collection(C, Coll)`);
5751
+ //console.log("collectionResults", collectionResults);
5752
+ if (collectionResults) {
5753
+ for (const result of collectionResults) {
5754
+ const collName = result.Coll;
5755
+ let predicate = null;
5756
+ let instanceFilter = undefined;
5757
+ // Try to extract predicate from collection_adder first
5758
+ const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
5759
+ if (adderResults && adderResults.length > 0) {
5760
+ const adderString = adderResults[0].Adder;
5761
+ const predicateMatch = adderString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
5762
+ if (predicateMatch) {
5763
+ predicate = predicateMatch[1] || predicateMatch[2];
5764
+ }
5765
+ }
5766
+ // Parse collection_getter from SDNA to extract predicate and instanceFilter
5767
+ // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
5768
+ // Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
5769
+ // Use a line-based match to avoid capturing multiple collections
5770
+ const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${collName}"[^)]*\\)\\s*:-[^.]+\\.`);
5771
+ const getterLineMatch = sdnaCode.match(getterLinePattern);
5772
+ if (getterLineMatch) {
5773
+ const getterLine = getterLineMatch[0];
5774
+ // Extract the body between setof/findall and the final ).
5775
+ // Pattern: findall(Var, Body, List) or setof(Var, (Body), List)
5776
+ const bodyPattern = /(?:setof|findall)\([^,]+,\s*(.+),\s*\w+\)\./;
5777
+ const bodyMatch = getterLine.match(bodyPattern);
5778
+ if (bodyMatch) {
5779
+ let getterBody = bodyMatch[1];
5780
+ // Remove outer parentheses if present (setof case)
5781
+ if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
5782
+ getterBody = getterBody.substring(1, getterBody.length - 1);
5783
+ }
5784
+ console.log(`Collection "${collName}" getter body:`, getterBody);
5785
+ // Extract predicate from triple(Base, "predicate", Target)
5786
+ if (!predicate) {
5787
+ const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
5788
+ if (tripleMatch) {
5789
+ predicate = tripleMatch[1];
5790
+ }
5791
+ }
5792
+ // Check for instance filter: subject_class("ClassName", OtherClass)
5793
+ const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
5794
+ if (instanceMatch) {
5795
+ instanceFilter = instanceMatch[1];
5796
+ console.log(`Collection "${collName}" has instanceFilter: ${instanceFilter}`);
5797
+ }
5798
+ }
5799
+ }
5800
+ if (predicate) {
5801
+ collections.set(collName, { predicate, instanceFilter });
5802
+ }
5803
+ }
5804
+ }
5805
+ //console.log("collections", collections);
5806
+ return { requiredPredicates, requiredTriples, properties, collections };
5807
+ }
5808
+ catch (e) {
5809
+ console.error(`Error getting metadata for ${className}:`, e);
5810
+ return null;
5811
+ }
5812
+ }
5813
+ /**
5814
+ * Generates a SurrealDB query to find instances based on class metadata.
5815
+ */
5816
+ generateSurrealInstanceQuery(metadata) {
5817
+ console.log("generateSurrealInstanceQuery called with requiredTriples:", metadata.requiredTriples);
5818
+ if (metadata.requiredTriples.length === 0) {
5819
+ // 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;
5823
+ }
5824
+ // Generate WHERE conditions for each required triple (predicate + optional exact target)
5825
+ const whereConditions = metadata.requiredTriples.map(triple => {
5826
+ if (triple.target) {
5827
+ // Flag: must match both predicate AND exact target value
5828
+ return `count(->link[WHERE predicate = '${triple.predicate}' AND out.uri = '${triple.target}']) > 0`;
5829
+ }
5830
+ else {
5831
+ // Property: just check predicate exists
5832
+ return `count(->link[WHERE predicate = '${triple.predicate}']) > 0`;
5833
+ }
5834
+ }).join(' AND ');
5835
+ const query = `SELECT uri AS base FROM node WHERE ${whereConditions}`;
5836
+ console.log("Generated query:", query);
5837
+ return query;
5838
+ }
5839
+ /**
5840
+ * Gets a property value using SurrealDB when Prolog fails.
5841
+ * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
5842
+ */
5843
+ async getPropertyValueViaSurreal(baseExpression, className, propertyName) {
5844
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5845
+ if (!metadata) {
5846
+ return undefined;
5847
+ }
5848
+ const propMeta = metadata.properties.get(propertyName);
5849
+ if (!propMeta) {
5850
+ return undefined;
5851
+ }
5852
+ const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${propMeta.predicate}' LIMIT 1`;
5853
+ const result = await this.querySurrealDB(query);
5854
+ if (!result || result.length === 0) {
5855
+ return undefined;
5856
+ }
5857
+ const value = result[0].value;
5858
+ // Handle expression resolution if needed
5859
+ if (propMeta.resolveLanguage && value) {
5860
+ try {
5861
+ const expression = await this.getExpression(value);
5862
+ try {
5863
+ return JSON.parse(expression.data);
5864
+ }
5865
+ catch (e) {
5866
+ return expression.data;
5867
+ }
5868
+ }
5869
+ catch (err) {
5870
+ return value;
5871
+ }
5872
+ }
5873
+ return value;
5874
+ }
5875
+ /**
5876
+ * Gets collection values using SurrealDB when Prolog fails.
5877
+ * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
5878
+ */
5879
+ async getCollectionValuesViaSurreal(baseExpression, className, collectionName) {
5880
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5881
+ if (!metadata) {
5882
+ return [];
5883
+ }
5884
+ const collMeta = metadata.collections.get(collectionName);
5885
+ if (!collMeta) {
5886
+ return [];
5887
+ }
5888
+ const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${collMeta.predicate}' ORDER BY timestamp ASC`;
5889
+ const result = await this.querySurrealDB(query);
5890
+ if (!result || result.length === 0) {
5891
+ return [];
5892
+ }
5893
+ 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
5896
+ 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}`);
5902
+ if (isInstance) {
5903
+ filteredValues.push(value);
5904
+ }
5905
+ }
5906
+ console.log(` After filtering: ${filteredValues.length} values`);
5907
+ return filteredValues;
5908
+ }
5909
+ return values;
5910
+ }
5608
5911
  /** Returns all subject instances of the given subject class as proxy objects.
5609
5912
  * @param subjectClass Either a string with the name of the subject class, or an object
5610
5913
  * with the properties of the subject class. In the latter case, all subject classes
@@ -5620,10 +5923,29 @@ class PerspectiveProxy {
5620
5923
  }
5621
5924
  let instances = [];
5622
5925
  for (let className of classes) {
5623
- let instanceBaseExpressions = await this.infer(`subject_class("${className}", C), instance(C, X)`);
5624
- let newInstances = await Promise.all(instanceBaseExpressions.map(async (x) => await this.getSubjectProxy(x.X, className)));
5625
- instances = instances.concat(newInstances);
5926
+ //console.log(`getAllSubjectInstances: Processing class ${className}`);
5927
+ // Query SDNA for metadata, then query SurrealDB for instances
5928
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5929
+ //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
5930
+ if (metadata) {
5931
+ const surrealQuery = this.generateSurrealInstanceQuery(metadata);
5932
+ const results = await this.querySurrealDB(surrealQuery);
5933
+ // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
5934
+ for (const result of results || []) {
5935
+ //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
5936
+ try {
5937
+ let subject = new Subject(this, result.base, className);
5938
+ await subject.init();
5939
+ instances.push(subject);
5940
+ //console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);
5941
+ }
5942
+ catch (e) {
5943
+ //console.warn(`Failed to create subject for ${result.base}:`, e);
5944
+ }
5945
+ }
5946
+ }
5626
5947
  }
5948
+ //console.log(`getAllSubjectInstances: Returning ${instances.length} instances`);
5627
5949
  return instances;
5628
5950
  }
5629
5951
  /** Returns all subject proxies of the given subject class.
@@ -5641,8 +5963,24 @@ class PerspectiveProxy {
5641
5963
  }
5642
5964
  let instances = [];
5643
5965
  for (let className of classes) {
5644
- instances = await this.infer(`subject_class("${className}", C), instance(C, X)`);
5966
+ //console.log(`getAllSubjectProxies: Processing class ${className}`);
5967
+ // Query SDNA for metadata, then query SurrealDB for instances
5968
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5969
+ //console.log(`getAllSubjectProxies: Got metadata for ${className}`);
5970
+ if (metadata) {
5971
+ const surrealQuery = this.generateSurrealInstanceQuery(metadata);
5972
+ console.log("surrealQuery", surrealQuery);
5973
+ 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}`);
5981
+ }
5645
5982
  }
5983
+ //console.log(`getAllSubjectProxies: Returning ${instances.length} proxies`);
5646
5984
  return instances;
5647
5985
  }
5648
5986
  buildQueryFromTemplate(obj) {
@@ -16054,20 +16392,46 @@ function InstanceQuery(options) {
16054
16392
  if (options && options.condition) {
16055
16393
  query += ', ' + options.condition;
16056
16394
  }
16057
- let results = await perspective.infer(query);
16058
- if (results == false) {
16059
- return instances;
16395
+ // Try Prolog first
16396
+ try {
16397
+ let results = await perspective.infer(query);
16398
+ if (results && results !== false && typeof results !== "string" && results.length > 0) {
16399
+ for (let result of results) {
16400
+ let instance = result.Instance;
16401
+ let subject = new Subject(perspective, instance, subjectClassName);
16402
+ await subject.init();
16403
+ instances.push(subject);
16404
+ }
16405
+ return instances;
16406
+ }
16060
16407
  }
16061
- if (typeof results == "string") {
16062
- throw results;
16408
+ catch (e) {
16409
+ // Prolog failed, fall through to SurrealDB
16063
16410
  }
16064
- for (let result of results) {
16065
- let instance = result.Instance;
16066
- let subject = new Subject(perspective, instance, subjectClassName);
16067
- await subject.init();
16068
- instances.push(subject);
16411
+ // Fallback to SurrealDB (SdnaOnly mode)
16412
+ // Get all instances first
16413
+ let allInstances = await perspective.getAllSubjectInstances(subjectClassName);
16414
+ // Filter by where clause if provided
16415
+ if (options && options.where) {
16416
+ let filtered = [];
16417
+ for (let instance of allInstances) {
16418
+ let matches = true;
16419
+ for (let prop in options.where) {
16420
+ let expectedValue = options.where[prop];
16421
+ //@ts-ignore
16422
+ let actualValue = await instance[prop];
16423
+ if (actualValue !== expectedValue) {
16424
+ matches = false;
16425
+ break;
16426
+ }
16427
+ }
16428
+ if (matches) {
16429
+ filtered.push(instance);
16430
+ }
16431
+ }
16432
+ return filtered;
16069
16433
  }
16070
- return instances;
16434
+ return allInstances;
16071
16435
  };
16072
16436
  };
16073
16437
  }
@@ -18575,6 +18939,70 @@ class Ad4mModel {
18575
18939
  get perspective() {
18576
18940
  return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
18577
18941
  }
18942
+ /**
18943
+ * Get property metadata from decorator (Phase 1: Prolog-free refactor)
18944
+ * @private
18945
+ */
18946
+ getPropertyMetadata(key) {
18947
+ const proto = Object.getPrototypeOf(this);
18948
+ return proto.__properties?.[key];
18949
+ }
18950
+ /**
18951
+ * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
18952
+ * @private
18953
+ */
18954
+ getCollectionMetadata(key) {
18955
+ const proto = Object.getPrototypeOf(this);
18956
+ return proto.__collections?.[key];
18957
+ }
18958
+ /**
18959
+ * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
18960
+ * Replaces Prolog query: property_setter(C, key, Setter)
18961
+ * @private
18962
+ */
18963
+ generatePropertySetterAction(key, metadata) {
18964
+ if (metadata.setter) {
18965
+ // Custom setter - throw error for now (Phase 2)
18966
+ throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
18967
+ `Use standard @Property decorator or enable Prolog for custom setters.`);
18968
+ }
18969
+ if (!metadata.through) {
18970
+ throw new Error(`Property "${key}" has no 'through' predicate defined`);
18971
+ }
18972
+ return [{
18973
+ action: "setSingleTarget",
18974
+ source: "this",
18975
+ predicate: metadata.through,
18976
+ target: "value",
18977
+ ...(metadata.local && { local: true })
18978
+ }];
18979
+ }
18980
+ /**
18981
+ * Generate collection action from metadata (Phase 1: Prolog-free refactor)
18982
+ * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
18983
+ * @private
18984
+ */
18985
+ generateCollectionAction(key, actionType) {
18986
+ const metadata = this.getCollectionMetadata(key);
18987
+ if (!metadata) {
18988
+ throw new Error(`Collection "${key}" has no metadata defined`);
18989
+ }
18990
+ if (!metadata.through) {
18991
+ throw new Error(`Collection "${key}" has no 'through' predicate defined`);
18992
+ }
18993
+ const actionMap = {
18994
+ adder: "addLink",
18995
+ remover: "removeLink",
18996
+ setter: "collectionSetter"
18997
+ };
18998
+ return [{
18999
+ action: actionMap[actionType],
19000
+ source: "this",
19001
+ predicate: metadata.through,
19002
+ target: "value",
19003
+ ...(metadata.local && { local: true })
19004
+ }];
19005
+ }
18578
19006
  static async assignValuesToInstance(perspective, instance, values) {
18579
19007
  // Map properties to object
18580
19008
  const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
@@ -18631,11 +19059,96 @@ class Ad4mModel {
18631
19059
  subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
18632
19060
  ${subQueries.join(", ")}
18633
19061
  `;
18634
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
18635
- if (result?.[0]) {
18636
- const { Properties, Collections, Timestamp, Author } = result?.[0];
18637
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
18638
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
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)
19076
+ try {
19077
+ const ctor = this.constructor;
19078
+ const metadata = ctor.getModelMetadata();
19079
+ // Query for all links from this specific node (base expression)
19080
+ const linksQuery = `
19081
+ SELECT id, predicate, out.uri AS target, author, timestamp
19082
+ FROM link
19083
+ WHERE in.uri = '${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'
19084
+ ORDER BY timestamp ASC
19085
+ `;
19086
+ const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
19087
+ if (links && links.length > 0) {
19088
+ let maxTimestamp = null;
19089
+ let latestAuthor = null;
19090
+ // Process properties
19091
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19092
+ const matching = links.filter((l) => l.predicate === propMeta.predicate);
19093
+ if (matching.length > 0) {
19094
+ const link = matching[0]; // Take first/latest
19095
+ let value = link.target;
19096
+ // Track timestamp/author
19097
+ if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19098
+ maxTimestamp = link.timestamp;
19099
+ latestAuthor = link.author;
19100
+ }
19101
+ // Handle resolveLanguage
19102
+ if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
19103
+ try {
19104
+ const expression = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getExpression(value);
19105
+ if (expression) {
19106
+ try {
19107
+ value = JSON.parse(expression.data);
19108
+ }
19109
+ catch {
19110
+ value = expression.data;
19111
+ }
19112
+ }
19113
+ }
19114
+ catch (e) {
19115
+ console.warn(`Failed to resolve expression for ${propName}:`, e);
19116
+ }
19117
+ }
19118
+ else if (typeof value === 'string' && value.startsWith('literal://')) {
19119
+ // Parse literal URL
19120
+ try {
19121
+ const parsed = Literal.fromUrl(value).get();
19122
+ value = parsed.data !== undefined ? parsed.data : parsed;
19123
+ }
19124
+ catch (e) {
19125
+ // Keep original value
19126
+ }
19127
+ }
19128
+ // Apply transform if exists
19129
+ if (propMeta.transform && typeof propMeta.transform === 'function') {
19130
+ value = propMeta.transform(value);
19131
+ }
19132
+ this[propName] = value;
19133
+ }
19134
+ }
19135
+ // Process collections
19136
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19137
+ const matching = links.filter((l) => l.predicate === collMeta.predicate);
19138
+ // Links are already sorted by timestamp ASC from the query, so map preserves order
19139
+ this[collName] = matching.map((l) => l.target);
19140
+ }
19141
+ // Set author and timestamp
19142
+ if (latestAuthor) {
19143
+ this.author = latestAuthor;
19144
+ }
19145
+ if (maxTimestamp) {
19146
+ this.timestamp = maxTimestamp;
19147
+ }
19148
+ }
19149
+ }
19150
+ catch (e) {
19151
+ console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
18639
19152
  }
18640
19153
  return this;
18641
19154
  }
@@ -19219,7 +19732,7 @@ WHERE ${whereConditions.join(' AND ')}
19219
19732
  if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
19220
19733
  let convertedValue = target;
19221
19734
  // Only process if target has a value
19222
- if (target !== undefined && target !== null) {
19735
+ if (target !== undefined && target !== null && target !== '') {
19223
19736
  // Check if we need to resolve a non-literal language expression
19224
19737
  if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string') {
19225
19738
  // For non-literal languages, resolve the expression via perspective.getExpression()
@@ -19238,7 +19751,8 @@ WHERE ${whereConditions.join(' AND ')}
19238
19751
  }
19239
19752
  }
19240
19753
  catch (e) {
19241
- console.warn(`Failed to resolve expression for ${propName}:`, e);
19754
+ console.warn(`Failed to resolve expression for ${propName} with target "${target}":`, e);
19755
+ console.warn("Falling back to raw value");
19242
19756
  convertedValue = target; // Fall back to raw value
19243
19757
  }
19244
19758
  }
@@ -19683,65 +20197,72 @@ WHERE ${whereConditions.join(' AND ')}
19683
20197
  }
19684
20198
  }
19685
20199
  async setProperty(key, value, batchId) {
19686
- const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
19687
- if (setters && setters.length > 0) {
19688
- const actions = eval(setters[0].Setter);
19689
- const resolveLanguageResults = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_resolve_language(C, "${key}", Language)`);
19690
- let resolveLanguage;
19691
- if (resolveLanguageResults && resolveLanguageResults.length > 0) {
19692
- resolveLanguage = resolveLanguageResults[0].Language;
19693
- }
19694
- if (resolveLanguage) {
19695
- value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
19696
- }
19697
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
20200
+ // Phase 1: Use metadata instead of Prolog queries
20201
+ const metadata = this.getPropertyMetadata(key);
20202
+ if (!metadata) {
20203
+ console.warn(`Property "${key}" has no metadata, skipping`);
20204
+ return;
20205
+ }
20206
+ // Generate actions from metadata (replaces Prolog query)
20207
+ const actions = this.generatePropertySetterAction(key, metadata);
20208
+ // Get resolve language from metadata (replaces Prolog query)
20209
+ let resolveLanguage = metadata.resolveLanguage;
20210
+ if (resolveLanguage) {
20211
+ value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
19698
20212
  }
20213
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19699
20214
  }
19700
20215
  async setCollectionSetter(key, value, batchId) {
19701
- let collectionSetters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
19702
- if (!collectionSetters)
19703
- collectionSetters = [];
19704
- if (collectionSetters.length > 0) {
19705
- const actions = eval(collectionSetters[0].Setter);
19706
- if (value) {
19707
- if (Array.isArray(value)) {
19708
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
19709
- }
19710
- else {
19711
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19712
- }
20216
+ // Phase 1: Use metadata instead of Prolog queries
20217
+ const metadata = this.getCollectionMetadata(key);
20218
+ if (!metadata) {
20219
+ console.warn(`Collection "${key}" has no metadata, skipping`);
20220
+ return;
20221
+ }
20222
+ // Generate actions from metadata (replaces Prolog query)
20223
+ const actions = this.generateCollectionAction(key, 'setter');
20224
+ if (value) {
20225
+ if (Array.isArray(value)) {
20226
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20227
+ }
20228
+ else {
20229
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19713
20230
  }
19714
20231
  }
19715
20232
  }
19716
20233
  async setCollectionAdder(key, value, batchId) {
19717
- let adders = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
19718
- if (!adders)
19719
- adders = [];
19720
- if (adders.length > 0) {
19721
- const actions = eval(adders[0].Adder);
19722
- if (value) {
19723
- if (Array.isArray(value)) {
19724
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
19725
- }
19726
- else {
19727
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19728
- }
20234
+ // Phase 1: Use metadata instead of Prolog queries
20235
+ const metadata = this.getCollectionMetadata(key);
20236
+ if (!metadata) {
20237
+ console.warn(`Collection "${key}" has no metadata, skipping`);
20238
+ return;
20239
+ }
20240
+ // Generate actions from metadata (replaces Prolog query)
20241
+ const actions = this.generateCollectionAction(key, 'adder');
20242
+ if (value) {
20243
+ if (Array.isArray(value)) {
20244
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20245
+ }
20246
+ else {
20247
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19729
20248
  }
19730
20249
  }
19731
20250
  }
19732
20251
  async setCollectionRemover(key, value, batchId) {
19733
- let removers = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
19734
- if (!removers)
19735
- removers = [];
19736
- if (removers.length > 0) {
19737
- const actions = eval(removers[0].Remover);
19738
- if (value) {
19739
- if (Array.isArray(value)) {
19740
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
19741
- }
19742
- else {
19743
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19744
- }
20252
+ // Phase 1: Use metadata instead of Prolog queries
20253
+ const metadata = this.getCollectionMetadata(key);
20254
+ if (!metadata) {
20255
+ console.warn(`Collection "${key}" has no metadata, skipping`);
20256
+ return;
20257
+ }
20258
+ // Generate actions from metadata (replaces Prolog query)
20259
+ const actions = this.generateCollectionAction(key, 'remover');
20260
+ if (value) {
20261
+ if (Array.isArray(value)) {
20262
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20263
+ }
20264
+ else {
20265
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
19745
20266
  }
19746
20267
  }
19747
20268
  }
@@ -19825,11 +20346,21 @@ WHERE ${whereConditions.join(' AND ')}
19825
20346
  break;
19826
20347
  }
19827
20348
  }
19828
- else if (Array.isArray(value) && value.length > 0) {
19829
- await this.setCollectionSetter(key, value, batchId);
20349
+ 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
19830
20355
  }
19831
20356
  else if (value !== undefined && value !== null && value !== "") {
19832
20357
  if (setProperties) {
20358
+ // Check if this is a collection property (has collection metadata)
20359
+ const collMetadata = this.getCollectionMetadata(key);
20360
+ if (collMetadata) {
20361
+ // Skip - it's a collection, not a regular property
20362
+ continue;
20363
+ }
19833
20364
  await this.setProperty(key, value, batchId);
19834
20365
  }
19835
20366
  }