@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.
@@ -614,6 +614,81 @@ export class Ad4mModel {
614
614
  return this.#perspective;
615
615
  }
616
616
 
617
+ /**
618
+ * Get property metadata from decorator (Phase 1: Prolog-free refactor)
619
+ * @private
620
+ */
621
+ private getPropertyMetadata(key: string): PropertyOptions | undefined {
622
+ const proto = Object.getPrototypeOf(this);
623
+ return proto.__properties?.[key];
624
+ }
625
+
626
+ /**
627
+ * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
628
+ * @private
629
+ */
630
+ private getCollectionMetadata(key: string): CollectionOptions | undefined {
631
+ const proto = Object.getPrototypeOf(this);
632
+ return proto.__collections?.[key];
633
+ }
634
+
635
+ /**
636
+ * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
637
+ * Replaces Prolog query: property_setter(C, key, Setter)
638
+ * @private
639
+ */
640
+ private generatePropertySetterAction(key: string, metadata: PropertyOptions): any[] {
641
+ if (metadata.setter) {
642
+ // Custom setter - throw error for now (Phase 2)
643
+ throw new Error(
644
+ `Custom setter for property "${key}" not yet supported without Prolog. ` +
645
+ `Use standard @Property decorator or enable Prolog for custom setters.`
646
+ );
647
+ }
648
+
649
+ if (!metadata.through) {
650
+ throw new Error(`Property "${key}" has no 'through' predicate defined`);
651
+ }
652
+
653
+ return [{
654
+ action: "setSingleTarget",
655
+ source: "this",
656
+ predicate: metadata.through,
657
+ target: "value",
658
+ ...(metadata.local && { local: true })
659
+ }];
660
+ }
661
+
662
+ /**
663
+ * Generate collection action from metadata (Phase 1: Prolog-free refactor)
664
+ * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
665
+ * @private
666
+ */
667
+ private generateCollectionAction(key: string, actionType: 'adder' | 'remover' | 'setter'): any[] {
668
+ const metadata = this.getCollectionMetadata(key);
669
+ if (!metadata) {
670
+ throw new Error(`Collection "${key}" has no metadata defined`);
671
+ }
672
+
673
+ if (!metadata.through) {
674
+ throw new Error(`Collection "${key}" has no 'through' predicate defined`);
675
+ }
676
+
677
+ const actionMap = {
678
+ adder: "addLink",
679
+ remover: "removeLink",
680
+ setter: "collectionSetter"
681
+ };
682
+
683
+ return [{
684
+ action: actionMap[actionType],
685
+ source: "this",
686
+ predicate: metadata.through,
687
+ target: "value",
688
+ ...(metadata.local && { local: true })
689
+ }];
690
+ }
691
+
617
692
  public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
618
693
  // Map properties to object
619
694
  const propsObject = Object.fromEntries(
@@ -675,11 +750,100 @@ export class Ad4mModel {
675
750
  ${subQueries.join(", ")}
676
751
  `;
677
752
 
678
- const result = await this.#perspective.infer(fullQuery);
679
- if (result?.[0]) {
680
- const { Properties, Collections, Timestamp, Author } = result?.[0];
681
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
682
- await Ad4mModel.assignValuesToInstance(this.#perspective, this, values);
753
+ // Try Prolog first
754
+ try {
755
+ const result = await this.#perspective.infer(fullQuery);
756
+ if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
757
+ const { Properties, Collections, Timestamp, Author } = result[0];
758
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
759
+ await Ad4mModel.assignValuesToInstance(this.#perspective, this, values);
760
+ return this;
761
+ }
762
+ } catch (e) {
763
+ console.log(`Prolog getData failed for ${this.#baseExpression}, falling back to SurrealDB`);
764
+ }
765
+
766
+ // Fallback to SurrealDB (SdnaOnly mode)
767
+ try {
768
+ const ctor = this.constructor as typeof Ad4mModel;
769
+ const metadata = ctor.getModelMetadata();
770
+
771
+ // Query for all links from this specific node (base expression)
772
+ const linksQuery = `
773
+ SELECT id, predicate, out.uri AS target, author, timestamp
774
+ FROM link
775
+ WHERE in.uri = '${this.#baseExpression}'
776
+ ORDER BY timestamp ASC
777
+ `;
778
+ const links = await this.#perspective.querySurrealDB(linksQuery);
779
+
780
+ if (links && links.length > 0) {
781
+ let maxTimestamp = null;
782
+ let latestAuthor = null;
783
+
784
+ // Process properties
785
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
786
+ const matching = links.filter((l: any) => l.predicate === propMeta.predicate);
787
+ if (matching.length > 0) {
788
+ const link = matching[0]; // Take first/latest
789
+ let value = link.target;
790
+
791
+ // Track timestamp/author
792
+ if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
793
+ maxTimestamp = link.timestamp;
794
+ latestAuthor = link.author;
795
+ }
796
+
797
+ // Handle resolveLanguage
798
+ if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
799
+ try {
800
+ const expression = await this.#perspective.getExpression(value);
801
+ if (expression) {
802
+ try {
803
+ value = JSON.parse(expression.data);
804
+ } catch {
805
+ value = expression.data;
806
+ }
807
+ }
808
+ } catch (e) {
809
+ console.warn(`Failed to resolve expression for ${propName}:`, e);
810
+ }
811
+ } else if (typeof value === 'string' && value.startsWith('literal://')) {
812
+ // Parse literal URL
813
+ try {
814
+ const parsed = Literal.fromUrl(value).get();
815
+ value = parsed.data !== undefined ? parsed.data : parsed;
816
+ } catch (e) {
817
+ // Keep original value
818
+ }
819
+ }
820
+
821
+ // Apply transform if exists
822
+ if (propMeta.transform && typeof propMeta.transform === 'function') {
823
+ value = propMeta.transform(value);
824
+ }
825
+
826
+ (this as any)[propName] = value;
827
+ }
828
+ }
829
+
830
+ // Process collections
831
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
832
+ const matching = links.filter((l: any) => l.predicate === collMeta.predicate);
833
+ // Links are already sorted by timestamp ASC from the query, so map preserves order
834
+ (this as any)[collName] = matching.map((l: any) => l.target);
835
+ }
836
+
837
+ // Set author and timestamp
838
+ if (latestAuthor) {
839
+ (this as any).author = latestAuthor;
840
+ }
841
+ if (maxTimestamp) {
842
+ (this as any).timestamp = maxTimestamp;
843
+ }
844
+ }
845
+ } catch (e) {
846
+ console.error(`SurrealDB getData also failed for ${this.#baseExpression}:`, e);
683
847
  }
684
848
 
685
849
  return this;
@@ -1320,7 +1484,7 @@ WHERE ${whereConditions.join(' AND ')}
1320
1484
  let convertedValue = target;
1321
1485
 
1322
1486
  // Only process if target has a value
1323
- if (target !== undefined && target !== null) {
1487
+ if (target !== undefined && target !== null && target !== '') {
1324
1488
  // Check if we need to resolve a non-literal language expression
1325
1489
  if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string') {
1326
1490
  // For non-literal languages, resolve the expression via perspective.getExpression()
@@ -1337,7 +1501,8 @@ WHERE ${whereConditions.join(' AND ')}
1337
1501
  }
1338
1502
  }
1339
1503
  } catch (e) {
1340
- console.warn(`Failed to resolve expression for ${propName}:`, e);
1504
+ console.warn(`Failed to resolve expression for ${propName} with target "${target}":`, e);
1505
+ console.warn("Falling back to raw value");
1341
1506
  convertedValue = target; // Fall back to raw value
1342
1507
  }
1343
1508
  } else if (typeof target === 'string' && target.startsWith('literal://')) {
@@ -1817,90 +1982,95 @@ WHERE ${whereConditions.join(' AND ')}
1817
1982
  }
1818
1983
 
1819
1984
  private async setProperty(key: string, value: any, batchId?: string) {
1820
- const setters = await this.#perspective.infer(
1821
- `subject_class("${this.#subjectClassName}", C), property_setter(C, "${key}", Setter)`
1822
- );
1823
- if (setters && setters.length > 0) {
1824
- const actions = eval(setters[0].Setter);
1825
- const resolveLanguageResults = await this.#perspective.infer(
1826
- `subject_class("${this.#subjectClassName}", C), property_resolve_language(C, "${key}", Language)`
1827
- );
1828
- let resolveLanguage;
1829
- if (resolveLanguageResults && resolveLanguageResults.length > 0) {
1830
- resolveLanguage = resolveLanguageResults[0].Language;
1831
- }
1985
+ // Phase 1: Use metadata instead of Prolog queries
1986
+ const metadata = this.getPropertyMetadata(key);
1987
+ if (!metadata) {
1988
+ console.warn(`Property "${key}" has no metadata, skipping`);
1989
+ return;
1990
+ }
1832
1991
 
1833
- if (resolveLanguage) {
1834
- value = await this.#perspective.createExpression(value, resolveLanguage);
1835
- }
1836
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1992
+ // Generate actions from metadata (replaces Prolog query)
1993
+ const actions = this.generatePropertySetterAction(key, metadata);
1994
+
1995
+ // Get resolve language from metadata (replaces Prolog query)
1996
+ let resolveLanguage = metadata.resolveLanguage;
1997
+
1998
+ if (resolveLanguage) {
1999
+ value = await this.#perspective.createExpression(value, resolveLanguage);
1837
2000
  }
2001
+
2002
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1838
2003
  }
1839
2004
 
1840
2005
  private async setCollectionSetter(key: string, value: any, batchId?: string) {
1841
- let collectionSetters = await this.#perspective.infer(
1842
- `subject_class("${this.#subjectClassName}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`
1843
- );
1844
- if (!collectionSetters) collectionSetters = [];
1845
-
1846
- if (collectionSetters.length > 0) {
1847
- const actions = eval(collectionSetters[0].Setter);
1848
-
1849
- if (value) {
1850
- if (Array.isArray(value)) {
1851
- await this.#perspective.executeAction(
1852
- actions,
1853
- this.#baseExpression,
1854
- value.map((v) => ({ name: "value", value: v })),
1855
- batchId
1856
- );
1857
- } else {
1858
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1859
- }
2006
+ // Phase 1: Use metadata instead of Prolog queries
2007
+ const metadata = this.getCollectionMetadata(key);
2008
+ if (!metadata) {
2009
+ console.warn(`Collection "${key}" has no metadata, skipping`);
2010
+ return;
2011
+ }
2012
+
2013
+ // Generate actions from metadata (replaces Prolog query)
2014
+ const actions = this.generateCollectionAction(key, 'setter');
2015
+
2016
+ if (value) {
2017
+ if (Array.isArray(value)) {
2018
+ await this.#perspective.executeAction(
2019
+ actions,
2020
+ this.#baseExpression,
2021
+ value.map((v) => ({ name: "value", value: v })),
2022
+ batchId
2023
+ );
2024
+ } else {
2025
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1860
2026
  }
1861
2027
  }
1862
2028
  }
1863
2029
 
1864
2030
  private async setCollectionAdder(key: string, value: any, batchId?: string) {
1865
- let adders = await this.#perspective.infer(
1866
- `subject_class("${this.#subjectClassName}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`
1867
- );
1868
- if (!adders) adders = [];
1869
-
1870
- if (adders.length > 0) {
1871
- const actions = eval(adders[0].Adder);
1872
- if (value) {
1873
- if (Array.isArray(value)) {
1874
- await Promise.all(
1875
- value.map((v) =>
1876
- this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
1877
- )
1878
- );
1879
- } else {
1880
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1881
- }
2031
+ // Phase 1: Use metadata instead of Prolog queries
2032
+ const metadata = this.getCollectionMetadata(key);
2033
+ if (!metadata) {
2034
+ console.warn(`Collection "${key}" has no metadata, skipping`);
2035
+ return;
2036
+ }
2037
+
2038
+ // Generate actions from metadata (replaces Prolog query)
2039
+ const actions = this.generateCollectionAction(key, 'adder');
2040
+
2041
+ if (value) {
2042
+ if (Array.isArray(value)) {
2043
+ await Promise.all(
2044
+ value.map((v) =>
2045
+ this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
2046
+ )
2047
+ );
2048
+ } else {
2049
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1882
2050
  }
1883
2051
  }
1884
2052
  }
1885
2053
 
1886
2054
  private async setCollectionRemover(key: string, value: any, batchId?: string) {
1887
- let removers = await this.#perspective.infer(
1888
- `subject_class("${this.#subjectClassName}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`
1889
- );
1890
- if (!removers) removers = [];
1891
-
1892
- if (removers.length > 0) {
1893
- const actions = eval(removers[0].Remover);
1894
- if (value) {
1895
- if (Array.isArray(value)) {
1896
- await Promise.all(
1897
- value.map((v) =>
1898
- this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
1899
- )
1900
- );
1901
- } else {
1902
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1903
- }
2055
+ // Phase 1: Use metadata instead of Prolog queries
2056
+ const metadata = this.getCollectionMetadata(key);
2057
+ if (!metadata) {
2058
+ console.warn(`Collection "${key}" has no metadata, skipping`);
2059
+ return;
2060
+ }
2061
+
2062
+ // Generate actions from metadata (replaces Prolog query)
2063
+ const actions = this.generateCollectionAction(key, 'remover');
2064
+
2065
+ if (value) {
2066
+ if (Array.isArray(value)) {
2067
+ await Promise.all(
2068
+ value.map((v) =>
2069
+ this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
2070
+ )
2071
+ );
2072
+ } else {
2073
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
1904
2074
  }
1905
2075
  }
1906
2076
  }
@@ -2003,10 +2173,20 @@ WHERE ${whereConditions.join(' AND ')}
2003
2173
  await this.setCollectionSetter(key, value.value, batchId);
2004
2174
  break;
2005
2175
  }
2006
- } else if (Array.isArray(value) && value.length > 0) {
2007
- await this.setCollectionSetter(key, value, batchId);
2176
+ } else if (Array.isArray(value)) {
2177
+ // Handle all arrays as collections, even empty ones
2178
+ if (value.length > 0) {
2179
+ await this.setCollectionSetter(key, value, batchId);
2180
+ }
2181
+ // Skip empty arrays - don't try to set them as properties
2008
2182
  } else if (value !== undefined && value !== null && value !== "") {
2009
2183
  if (setProperties) {
2184
+ // Check if this is a collection property (has collection metadata)
2185
+ const collMetadata = this.getCollectionMetadata(key);
2186
+ if (collMetadata) {
2187
+ // Skip - it's a collection, not a regular property
2188
+ continue;
2189
+ }
2010
2190
  await this.setProperty(key, value, batchId);
2011
2191
  }
2012
2192
  }
@@ -50,31 +50,40 @@ export class Subject {
50
50
  Object.defineProperty(this, p, {
51
51
  configurable: true,
52
52
  get: async () => {
53
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property_getter(C, "${this.#baseExpression}", "${p}", Value)`)
54
- if(results && results.length > 0) {
55
- let expressionURI = results[0].Value
56
- if(resolveExpressionURI) {
57
- try {
58
- if (expressionURI) {
59
- const expression = await this.#perspective.getExpression(expressionURI)
60
- try {
61
- return JSON.parse(expression.data)
62
- } catch(e) {
63
- return expression.data
53
+ // Try Prolog first
54
+ try {
55
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property_getter(C, "${this.#baseExpression}", "${p}", Value)`)
56
+ if(results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
57
+ let expressionURI = results[0].Value
58
+ if(resolveExpressionURI) {
59
+ try {
60
+ if (expressionURI) {
61
+ const expression = await this.#perspective.getExpression(expressionURI)
62
+ try {
63
+ return JSON.parse(expression.data)
64
+ } catch(e) {
65
+ return expression.data
66
+ }
67
+ } else {
68
+ return expressionURI
64
69
  }
65
- } else {
70
+ } catch (err) {
66
71
  return expressionURI
67
72
  }
68
- } catch (err) {
73
+ } else {
69
74
  return expressionURI
70
75
  }
71
- } else {
72
- return expressionURI
73
76
  }
74
- } else if(results) {
75
- return results
76
- } else {
77
- return undefined
77
+ } catch (err) {
78
+ // Prolog query failed, fall through to SurrealDB
79
+ }
80
+
81
+ // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
82
+ try {
83
+ return await this.#perspective.getPropertyValueViaSurreal(this.#baseExpression, this.#subjectClassName, p);
84
+ } catch (err) {
85
+ console.warn(`Failed to get property ${p} via SurrealDB:`, err);
86
+ return undefined;
78
87
  }
79
88
  }
80
89
  })
@@ -110,12 +119,25 @@ export class Subject {
110
119
  Object.defineProperty(this, c, {
111
120
  configurable: true,
112
121
  get: async () => {
113
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection_getter(C, "${this.#baseExpression}", "${c}", Value)`)
114
- if(results && results.length > 0 && results[0].Value) {
115
- let collectionContent = results[0].Value.filter((v: any) => v !== "" && v !== '')
116
- return collectionContent
117
- } else {
118
- return []
122
+ // Try Prolog first
123
+ try {
124
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection_getter(C, "${this.#baseExpression}", "${c}", Value)`)
125
+ if(results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
126
+ let collectionContent = results[0].Value.filter((v: any) => v !== "" && v !== '')
127
+ if (collectionContent.length > 0) {
128
+ return collectionContent
129
+ }
130
+ }
131
+ } catch (err) {
132
+ // Prolog query failed, fall through to SurrealDB
133
+ }
134
+
135
+ // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
136
+ try {
137
+ return await this.#perspective.getCollectionValuesViaSurreal(this.#baseExpression, this.#subjectClassName, c);
138
+ } catch (err) {
139
+ console.warn(`Failed to get collection ${c} via SurrealDB:`, err);
140
+ return [];
119
141
  }
120
142
  }
121
143
  })
@@ -97,21 +97,48 @@ export function InstanceQuery(options?: InstanceQueryParams) {
97
97
  query += ', ' + options.condition
98
98
  }
99
99
 
100
- let results = await perspective.infer(query)
101
- if(results == false) {
102
- return instances
103
- }
104
- if(typeof results == "string") {
105
- throw results
100
+ // Try Prolog first
101
+ try {
102
+ let results = await perspective.infer(query)
103
+ if(results && results !== false && typeof results !== "string" && results.length > 0) {
104
+ for(let result of results) {
105
+ let instance = result.Instance
106
+ let subject = new Subject(perspective, instance, subjectClassName)
107
+ await subject.init()
108
+ instances.push(subject as T)
109
+ }
110
+ return instances
111
+ }
112
+ } catch (e) {
113
+ // Prolog failed, fall through to SurrealDB
106
114
  }
107
- for(let result of results) {
108
- let instance = result.Instance
109
- let subject = new Subject(perspective, instance, subjectClassName)
110
- await subject.init()
111
- instances.push(subject as T)
115
+
116
+ // Fallback to SurrealDB (SdnaOnly mode)
117
+ // Get all instances first
118
+ let allInstances = await perspective.getAllSubjectInstances(subjectClassName)
119
+
120
+ // Filter by where clause if provided
121
+ if(options && options.where) {
122
+ let filtered = []
123
+ for(let instance of allInstances) {
124
+ let matches = true
125
+ for(let prop in options.where) {
126
+ let expectedValue = options.where[prop]
127
+ //@ts-ignore
128
+ let actualValue = await instance[prop]
129
+ if(actualValue !== expectedValue) {
130
+ matches = false
131
+ break
132
+ }
133
+ }
134
+ if(matches) {
135
+ filtered.push(instance as T)
136
+ }
137
+ }
138
+ return filtered
112
139
  }
113
140
 
114
- return instances
141
+ return allInstances as T[]
115
142
  }
116
143
  };
117
144
  }