@coasys/ad4m 0.11.2-dev.4 → 0.11.2-dev.6
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.cjs +181 -69
- package/lib/index.js +181 -69
- package/lib/src/model/Ad4mModel.d.ts +6 -5
- package/lib/src/model/Ad4mModel.js +107 -41
- package/lib/src/model/Ad4mModel.test.js +10 -10
- package/lib/src/model/decorators.d.ts +26 -18
- package/lib/src/model/decorators.js +40 -25
- package/lib/src/perspectives/PerspectiveProxy.d.ts +3 -0
- package/lib/src/perspectives/PerspectiveProxy.js +34 -3
- package/package.json +1 -1
- package/src/model/Ad4mModel.test.ts +10 -10
- package/src/model/Ad4mModel.ts +115 -43
- package/src/model/decorators.ts +48 -34
- package/src/perspectives/PerspectiveProxy.ts +43 -7
package/lib/index.cjs
CHANGED
|
@@ -5791,6 +5791,7 @@ class PerspectiveProxy {
|
|
|
5791
5791
|
const collName = result.Coll;
|
|
5792
5792
|
let predicate = null;
|
|
5793
5793
|
let instanceFilter = undefined;
|
|
5794
|
+
let condition = undefined;
|
|
5794
5795
|
// Try to extract predicate from collection_adder first
|
|
5795
5796
|
const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
|
|
5796
5797
|
if (adderResults && adderResults.length > 0) {
|
|
@@ -5800,6 +5801,8 @@ class PerspectiveProxy {
|
|
|
5800
5801
|
predicate = predicateMatch[1] || predicateMatch[2];
|
|
5801
5802
|
}
|
|
5802
5803
|
}
|
|
5804
|
+
// Note: condition is not stored in SDNA, it's read from class metadata
|
|
5805
|
+
// It will be populated by augmentMetadataWithCollectionOptions() when needed
|
|
5803
5806
|
// Parse collection_getter from SDNA to extract predicate and instanceFilter
|
|
5804
5807
|
// Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
|
|
5805
5808
|
// Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
|
|
@@ -5835,7 +5838,7 @@ class PerspectiveProxy {
|
|
|
5835
5838
|
}
|
|
5836
5839
|
}
|
|
5837
5840
|
if (predicate) {
|
|
5838
|
-
collections.set(collName, { predicate, instanceFilter });
|
|
5841
|
+
collections.set(collName, { predicate, instanceFilter, condition });
|
|
5839
5842
|
}
|
|
5840
5843
|
}
|
|
5841
5844
|
}
|
|
@@ -5911,6 +5914,7 @@ class PerspectiveProxy {
|
|
|
5911
5914
|
/**
|
|
5912
5915
|
* Gets collection values using SurrealDB when Prolog fails.
|
|
5913
5916
|
* This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
|
|
5917
|
+
* Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
|
|
5914
5918
|
*/
|
|
5915
5919
|
async getCollectionValuesViaSurreal(baseExpression, className, collectionName) {
|
|
5916
5920
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
@@ -5929,6 +5933,31 @@ class PerspectiveProxy {
|
|
|
5929
5933
|
return [];
|
|
5930
5934
|
}
|
|
5931
5935
|
let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
|
|
5936
|
+
// Apply condition filtering if present
|
|
5937
|
+
if (collMeta.condition && values.length > 0) {
|
|
5938
|
+
try {
|
|
5939
|
+
const filteredValues = [];
|
|
5940
|
+
for (const value of values) {
|
|
5941
|
+
let condition = collMeta.condition
|
|
5942
|
+
.replace(/\$perspective/g, `'${this.uuid}'`)
|
|
5943
|
+
.replace(/\$base/g, `'${baseExpression}'`)
|
|
5944
|
+
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
5945
|
+
// If condition starts with WHERE, wrap in array length check
|
|
5946
|
+
if (condition.trim().startsWith('WHERE')) {
|
|
5947
|
+
condition = `array::len(SELECT * FROM link ${condition}) > 0`;
|
|
5948
|
+
}
|
|
5949
|
+
const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
|
|
5950
|
+
const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
|
|
5951
|
+
if (isTrue) {
|
|
5952
|
+
filteredValues.push(value);
|
|
5953
|
+
}
|
|
5954
|
+
}
|
|
5955
|
+
values = filteredValues;
|
|
5956
|
+
}
|
|
5957
|
+
catch (error) {
|
|
5958
|
+
console.warn(`Failed to apply condition filter for ${collectionName}:`, error);
|
|
5959
|
+
}
|
|
5960
|
+
}
|
|
5932
5961
|
// Apply instance filter if present - batch-check all values at once
|
|
5933
5962
|
if (collMeta.instanceFilter) {
|
|
5934
5963
|
try {
|
|
@@ -5970,11 +5999,13 @@ class PerspectiveProxy {
|
|
|
5970
5999
|
if (triple.target) {
|
|
5971
6000
|
// Flag: must match both predicate AND exact target value
|
|
5972
6001
|
const escapedTarget = escapeSurrealString(triple.target);
|
|
5973
|
-
|
|
6002
|
+
// Note: Removed GROUP BY because it was causing SurrealDB to only return one result
|
|
6003
|
+
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
|
|
5974
6004
|
}
|
|
5975
6005
|
else {
|
|
5976
6006
|
// Property: just check predicate exists
|
|
5977
|
-
|
|
6007
|
+
// Note: Removed GROUP BY because it was causing SurrealDB to only return one result
|
|
6008
|
+
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
|
|
5978
6009
|
}
|
|
5979
6010
|
const result = await this.querySurrealDB(checkQuery);
|
|
5980
6011
|
validExpressionSets.push(new Set(result.map(r => r.uri)));
|
|
@@ -16461,14 +16492,14 @@ function hasLink(predicate) {
|
|
|
16461
16492
|
* static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
|
|
16462
16493
|
*
|
|
16463
16494
|
* // Get highly rated recipes using a custom condition
|
|
16464
|
-
* @InstanceQuery({
|
|
16495
|
+
* @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
|
|
16465
16496
|
* static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
|
|
16466
16497
|
* }
|
|
16467
16498
|
* ```
|
|
16468
16499
|
*
|
|
16469
16500
|
* @param {Object} [options] - Query options
|
|
16470
16501
|
* @param {object} [options.where] - Object with property-value pairs to match
|
|
16471
|
-
* @param {string} [options.
|
|
16502
|
+
* @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
|
|
16472
16503
|
*/
|
|
16473
16504
|
function InstanceQuery(options) {
|
|
16474
16505
|
return function (target, key, descriptor) {
|
|
@@ -16487,8 +16518,8 @@ function InstanceQuery(options) {
|
|
|
16487
16518
|
query += `, property_getter(C, Instance, "${prop}", "${value}")`;
|
|
16488
16519
|
}
|
|
16489
16520
|
}
|
|
16490
|
-
if (options && options.
|
|
16491
|
-
query += ', ' + options.
|
|
16521
|
+
if (options && options.prologCondition) {
|
|
16522
|
+
query += ', ' + options.prologCondition;
|
|
16492
16523
|
}
|
|
16493
16524
|
// Try Prolog first
|
|
16494
16525
|
try {
|
|
@@ -16608,8 +16639,8 @@ function InstanceQuery(options) {
|
|
|
16608
16639
|
* @param {boolean} [opts.required] - Whether the property must have a value
|
|
16609
16640
|
* @param {boolean} [opts.writable=true] - Whether the property can be modified
|
|
16610
16641
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
16611
|
-
* @param {string} [opts.
|
|
16612
|
-
* @param {string} [opts.
|
|
16642
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
16643
|
+
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
16613
16644
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
16614
16645
|
*/
|
|
16615
16646
|
function Optional(opts) {
|
|
@@ -16620,8 +16651,8 @@ function Optional(opts) {
|
|
|
16620
16651
|
if (opts.required && !opts.initial) {
|
|
16621
16652
|
throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
|
|
16622
16653
|
}
|
|
16623
|
-
if (!opts.through && !opts.
|
|
16624
|
-
throw new Error("SubjectProperty requires either 'through' or '
|
|
16654
|
+
if (!opts.through && !opts.prologGetter) {
|
|
16655
|
+
throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
|
|
16625
16656
|
}
|
|
16626
16657
|
target["__properties"] = target["__properties"] || {};
|
|
16627
16658
|
target["__properties"][key] = target["__properties"][key] || {};
|
|
@@ -16747,13 +16778,20 @@ function Flag(opts) {
|
|
|
16747
16778
|
* })
|
|
16748
16779
|
* comments: string[] = [];
|
|
16749
16780
|
*
|
|
16750
|
-
* // Collection with custom filter condition
|
|
16781
|
+
* // Collection with custom Prolog filter condition
|
|
16751
16782
|
* @Collection({
|
|
16752
16783
|
* through: "recipe://step",
|
|
16753
|
-
* where: {
|
|
16784
|
+
* where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
|
|
16754
16785
|
* })
|
|
16755
16786
|
* firstSteps: string[] = [];
|
|
16756
16787
|
*
|
|
16788
|
+
* // Collection with custom SurrealDB filter condition
|
|
16789
|
+
* @Collection({
|
|
16790
|
+
* through: "recipe://entries",
|
|
16791
|
+
* where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
|
|
16792
|
+
* })
|
|
16793
|
+
* ingredients: string[] = [];
|
|
16794
|
+
*
|
|
16757
16795
|
* // Local-only collection not shared with network
|
|
16758
16796
|
* @Collection({
|
|
16759
16797
|
* through: "recipe://note",
|
|
@@ -16773,7 +16811,7 @@ function Flag(opts) {
|
|
|
16773
16811
|
* @param {string} opts.through - The predicate URI for collection links
|
|
16774
16812
|
* @param {WhereOptions} [opts.where] - Filter conditions for collection values
|
|
16775
16813
|
* @param {any} [opts.where.isInstance] - Model class to filter instances by
|
|
16776
|
-
* @param {string} [opts.where.
|
|
16814
|
+
* @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
|
|
16777
16815
|
* @param {boolean} [opts.local] - Whether collection links are stored locally only
|
|
16778
16816
|
*/
|
|
16779
16817
|
function Collection(opts) {
|
|
@@ -16873,13 +16911,13 @@ function ModelOptions(opts) {
|
|
|
16873
16911
|
let properties = obj.__properties || {};
|
|
16874
16912
|
for (let property in properties) {
|
|
16875
16913
|
let propertyCode = `property(${uuid}, "${property}").\n`;
|
|
16876
|
-
let { through, initial, required, resolveLanguage, writable, flag,
|
|
16914
|
+
let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
|
|
16877
16915
|
if (resolveLanguage) {
|
|
16878
16916
|
propertyCode += `property_resolve(${uuid}, "${property}").\n`;
|
|
16879
16917
|
propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
|
|
16880
16918
|
}
|
|
16881
|
-
if (
|
|
16882
|
-
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${
|
|
16919
|
+
if (prologGetter) {
|
|
16920
|
+
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
|
|
16883
16921
|
}
|
|
16884
16922
|
else if (through) {
|
|
16885
16923
|
propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
|
|
@@ -16892,8 +16930,8 @@ function ModelOptions(opts) {
|
|
|
16892
16930
|
}
|
|
16893
16931
|
}
|
|
16894
16932
|
}
|
|
16895
|
-
if (
|
|
16896
|
-
propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${
|
|
16933
|
+
if (prologSetter) {
|
|
16934
|
+
propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
|
|
16897
16935
|
}
|
|
16898
16936
|
else if (writable && through) {
|
|
16899
16937
|
let setter = obj[propertyNameToSetterName(property)];
|
|
@@ -16931,8 +16969,8 @@ function ModelOptions(opts) {
|
|
|
16931
16969
|
let { through, where, local } = collections[collection];
|
|
16932
16970
|
if (through) {
|
|
16933
16971
|
if (where) {
|
|
16934
|
-
if (!where.isInstance && !where.condition) {
|
|
16935
|
-
throw "'where' needs one of 'isInstance' or 'condition'";
|
|
16972
|
+
if (!where.isInstance && !where.prologCondition && !where.condition) {
|
|
16973
|
+
throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'";
|
|
16936
16974
|
}
|
|
16937
16975
|
let conditions = [];
|
|
16938
16976
|
if (where.isInstance) {
|
|
@@ -16945,11 +16983,19 @@ function ModelOptions(opts) {
|
|
|
16945
16983
|
}
|
|
16946
16984
|
conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`);
|
|
16947
16985
|
}
|
|
16948
|
-
if (where.
|
|
16949
|
-
conditions.push(where.
|
|
16986
|
+
if (where.prologCondition) {
|
|
16987
|
+
conditions.push(where.prologCondition);
|
|
16988
|
+
}
|
|
16989
|
+
// If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
|
|
16990
|
+
// If only condition is present, use simple findall (SurrealDB will filter later)
|
|
16991
|
+
if (conditions.length > 0) {
|
|
16992
|
+
const conditionString = conditions.join(", ");
|
|
16993
|
+
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
|
|
16994
|
+
}
|
|
16995
|
+
else {
|
|
16996
|
+
// Only SurrealDB condition present (no Prolog filtering)
|
|
16997
|
+
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
|
|
16950
16998
|
}
|
|
16951
|
-
const conditionString = conditions.join(", ");
|
|
16952
|
-
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
|
|
16953
16999
|
}
|
|
16954
17000
|
else {
|
|
16955
17001
|
collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
|
|
@@ -17051,8 +17097,8 @@ function ModelOptions(opts) {
|
|
|
17051
17097
|
* @param {string} opts.through - The predicate URI for the property
|
|
17052
17098
|
* @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
|
|
17053
17099
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
17054
|
-
* @param {string} [opts.
|
|
17055
|
-
* @param {string} [opts.
|
|
17100
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
17101
|
+
* @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
|
|
17056
17102
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
17057
17103
|
*/
|
|
17058
17104
|
function Property(opts) {
|
|
@@ -17115,7 +17161,7 @@ function Property(opts) {
|
|
|
17115
17161
|
* @param {string} opts.through - The predicate URI for the property
|
|
17116
17162
|
* @param {string} [opts.initial] - Initial value (if property should have one)
|
|
17117
17163
|
* @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
|
|
17118
|
-
* @param {string} [opts.
|
|
17164
|
+
* @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
|
|
17119
17165
|
* @param {boolean} [opts.local] - Whether the property should only be stored locally
|
|
17120
17166
|
*/
|
|
17121
17167
|
function ReadOnly(opts) {
|
|
@@ -18922,9 +18968,9 @@ class Ad4mModel {
|
|
|
18922
18968
|
writable: options.writable || false,
|
|
18923
18969
|
...(options.initial !== undefined && { initial: options.initial }),
|
|
18924
18970
|
...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
|
|
18971
|
+
...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),
|
|
18925
18972
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
18926
|
-
...(options.
|
|
18927
|
-
...(options.setter !== undefined && { setter: options.setter }),
|
|
18973
|
+
...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
|
|
18928
18974
|
...(options.local !== undefined && { local: options.local }),
|
|
18929
18975
|
...(options.transform !== undefined && { transform: options.transform }),
|
|
18930
18976
|
...(options.flag !== undefined && { flag: options.flag })
|
|
@@ -18940,7 +18986,7 @@ class Ad4mModel {
|
|
|
18940
18986
|
predicate: options.through || "",
|
|
18941
18987
|
...(options.where !== undefined && { where: options.where }),
|
|
18942
18988
|
...(options.local !== undefined && { local: options.local }),
|
|
18943
|
-
...(options.
|
|
18989
|
+
...(options.getter !== undefined && { getter: options.getter })
|
|
18944
18990
|
};
|
|
18945
18991
|
}
|
|
18946
18992
|
// Fallback: If both structures are empty but a JSON schema is attached, derive from it
|
|
@@ -19051,9 +19097,9 @@ class Ad4mModel {
|
|
|
19051
19097
|
if (metadata.writable === false) {
|
|
19052
19098
|
throw new Error(`Property "${key}" is read-only and cannot be written`);
|
|
19053
19099
|
}
|
|
19054
|
-
if (metadata.
|
|
19055
|
-
// Custom setter - throw error for now (Phase 2)
|
|
19056
|
-
throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
|
|
19100
|
+
if (metadata.prologSetter) {
|
|
19101
|
+
// Custom Prolog setter - throw error for now (Phase 2)
|
|
19102
|
+
throw new Error(`Custom Prolog setter for property "${key}" not yet supported without Prolog. ` +
|
|
19057
19103
|
`Use standard @Property decorator or enable Prolog for custom setters.`);
|
|
19058
19104
|
}
|
|
19059
19105
|
if (!metadata.through) {
|
|
@@ -19138,8 +19184,26 @@ class Ad4mModel {
|
|
|
19138
19184
|
}
|
|
19139
19185
|
return [name, finalValue];
|
|
19140
19186
|
})));
|
|
19187
|
+
// Filter out properties that are read-only (getters without setters)
|
|
19188
|
+
const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
|
|
19189
|
+
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
|
|
19190
|
+
if (!descriptor) {
|
|
19191
|
+
// No descriptor means it's a regular property on the instance, allow it
|
|
19192
|
+
return true;
|
|
19193
|
+
}
|
|
19194
|
+
// Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
|
|
19195
|
+
const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
|
|
19196
|
+
if (isAccessor) {
|
|
19197
|
+
// Accessor descriptor: only allow if it has a setter
|
|
19198
|
+
return descriptor.set !== undefined;
|
|
19199
|
+
}
|
|
19200
|
+
else {
|
|
19201
|
+
// Data descriptor: only allow if writable is not explicitly false
|
|
19202
|
+
return descriptor.writable !== false;
|
|
19203
|
+
}
|
|
19204
|
+
}));
|
|
19141
19205
|
// Assign properties to instance
|
|
19142
|
-
Object.assign(instance,
|
|
19206
|
+
Object.assign(instance, writableProps);
|
|
19143
19207
|
}
|
|
19144
19208
|
async getData() {
|
|
19145
19209
|
// Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
|
|
@@ -19165,10 +19229,10 @@ class Ad4mModel {
|
|
|
19165
19229
|
let maxTimestamp = null;
|
|
19166
19230
|
let latestAuthor = null;
|
|
19167
19231
|
let originalAuthor = null;
|
|
19168
|
-
// Process properties (skip those with
|
|
19232
|
+
// Process properties (skip those with custom getter)
|
|
19169
19233
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
19170
|
-
if (propMeta.
|
|
19171
|
-
continue; // Handle via
|
|
19234
|
+
if (propMeta.getter)
|
|
19235
|
+
continue; // Handle via custom getter evaluation
|
|
19172
19236
|
const matching = links.filter((l) => l.predicate === propMeta.predicate);
|
|
19173
19237
|
if (matching.length > 0) {
|
|
19174
19238
|
// "Latest wins" semantics: select the last element since links are ordered ASC.
|
|
@@ -19220,14 +19284,44 @@ class Ad4mModel {
|
|
|
19220
19284
|
this[propName] = value;
|
|
19221
19285
|
}
|
|
19222
19286
|
}
|
|
19223
|
-
// Process collections (skip those with
|
|
19287
|
+
// Process collections (skip those with custom getter)
|
|
19224
19288
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19225
|
-
if (collMeta.
|
|
19226
|
-
continue; // Handle via
|
|
19289
|
+
if (collMeta.getter)
|
|
19290
|
+
continue; // Handle via custom getter evaluation
|
|
19227
19291
|
const matching = links.filter((l) => l.predicate === collMeta.predicate);
|
|
19228
19292
|
// Collections preserve chronological order: links are sorted ASC by timestamp,
|
|
19229
19293
|
// so the collection reflects the order in which items were added (oldest to newest).
|
|
19230
19294
|
let values = matching.map((l) => l.target);
|
|
19295
|
+
// Apply where.condition filtering if present
|
|
19296
|
+
if (collMeta.where?.condition && values.length > 0) {
|
|
19297
|
+
try {
|
|
19298
|
+
// Filter values by evaluating condition for each value
|
|
19299
|
+
const filteredValues = [];
|
|
19300
|
+
for (const value of values) {
|
|
19301
|
+
let condition = collMeta.where.condition
|
|
19302
|
+
.replace(/\$perspective/g, `'${__classPrivateFieldGet(this, _Ad4mModel_perspective, "f").uuid}'`)
|
|
19303
|
+
.replace(/\$base/g, `'${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'`)
|
|
19304
|
+
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
19305
|
+
// If condition starts with WHERE, wrap it in array length check pattern
|
|
19306
|
+
// Using array::len() to properly count matching links
|
|
19307
|
+
if (condition.trim().startsWith('WHERE')) {
|
|
19308
|
+
condition = `array::len(SELECT * FROM link ${condition}) > 0`;
|
|
19309
|
+
}
|
|
19310
|
+
const filterQuery = `RETURN ${condition}`;
|
|
19311
|
+
const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(filterQuery);
|
|
19312
|
+
// RETURN can return the value directly or in an array
|
|
19313
|
+
const isTrue = result === true || (Array.isArray(result) && result.length > 0 && result[0] === true);
|
|
19314
|
+
if (isTrue) {
|
|
19315
|
+
filteredValues.push(value);
|
|
19316
|
+
}
|
|
19317
|
+
}
|
|
19318
|
+
values = filteredValues;
|
|
19319
|
+
}
|
|
19320
|
+
catch (error) {
|
|
19321
|
+
console.warn(`Failed to apply condition filter for ${collName}:`, error);
|
|
19322
|
+
// Keep unfiltered values on error
|
|
19323
|
+
}
|
|
19324
|
+
}
|
|
19231
19325
|
// Apply where.isInstance filtering if present
|
|
19232
19326
|
if (collMeta.where?.isInstance && values.length > 0) {
|
|
19233
19327
|
try {
|
|
@@ -19257,7 +19351,26 @@ class Ad4mModel {
|
|
|
19257
19351
|
}
|
|
19258
19352
|
}
|
|
19259
19353
|
// Evaluate SurrealQL getters
|
|
19260
|
-
await ctor.
|
|
19354
|
+
await ctor.evaluateCustomGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
|
|
19355
|
+
// Apply where.isInstance filtering to getter collections
|
|
19356
|
+
// (non-getter collections were already filtered above)
|
|
19357
|
+
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19358
|
+
if (collMeta.getter && collMeta.where?.isInstance && this[collName]?.length > 0) {
|
|
19359
|
+
try {
|
|
19360
|
+
const className = typeof collMeta.where.isInstance === 'string'
|
|
19361
|
+
? collMeta.where.isInstance
|
|
19362
|
+
: collMeta.where.isInstance.name;
|
|
19363
|
+
const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
|
|
19364
|
+
if (filterMetadata) {
|
|
19365
|
+
const filtered = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(this[collName], filterMetadata);
|
|
19366
|
+
this[collName] = filtered;
|
|
19367
|
+
}
|
|
19368
|
+
}
|
|
19369
|
+
catch (error) {
|
|
19370
|
+
// Keep unfiltered values on error
|
|
19371
|
+
}
|
|
19372
|
+
}
|
|
19373
|
+
}
|
|
19261
19374
|
}
|
|
19262
19375
|
catch (e) {
|
|
19263
19376
|
console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
|
|
@@ -19290,14 +19403,14 @@ class Ad4mModel {
|
|
|
19290
19403
|
* Evaluates custom SurrealQL getters for properties and collections on a specific instance.
|
|
19291
19404
|
* @private
|
|
19292
19405
|
*/
|
|
19293
|
-
static async
|
|
19406
|
+
static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
|
|
19294
19407
|
const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
|
|
19295
|
-
// Evaluate property
|
|
19408
|
+
// Evaluate property getters
|
|
19296
19409
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
19297
|
-
if (propMeta.
|
|
19410
|
+
if (propMeta.getter) {
|
|
19298
19411
|
try {
|
|
19299
19412
|
// Replace 'Base' placeholder with actual base expression
|
|
19300
|
-
const query = propMeta.
|
|
19413
|
+
const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
|
|
19301
19414
|
// Query from node table to have graph traversal context
|
|
19302
19415
|
const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
|
|
19303
19416
|
if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
|
|
@@ -19305,28 +19418,28 @@ class Ad4mModel {
|
|
|
19305
19418
|
}
|
|
19306
19419
|
}
|
|
19307
19420
|
catch (error) {
|
|
19308
|
-
console.warn(`Failed to evaluate
|
|
19421
|
+
console.warn(`Failed to evaluate getter for ${propName}:`, error);
|
|
19309
19422
|
}
|
|
19310
19423
|
}
|
|
19311
19424
|
}
|
|
19312
|
-
// Evaluate collection
|
|
19425
|
+
// Evaluate collection getters
|
|
19313
19426
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19314
|
-
if (collMeta.
|
|
19427
|
+
if (collMeta.getter) {
|
|
19315
19428
|
try {
|
|
19316
19429
|
// Replace 'Base' placeholder with actual base expression
|
|
19317
|
-
const query = collMeta.
|
|
19430
|
+
const query = collMeta.getter.replace(/Base/g, safeBaseExpression);
|
|
19318
19431
|
// Query from node table to have graph traversal context
|
|
19319
19432
|
const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
|
|
19320
19433
|
if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
|
|
19321
19434
|
// Filter out 'None' from collection results
|
|
19322
19435
|
const value = result[0].value;
|
|
19323
19436
|
instance[collName] = Array.isArray(value)
|
|
19324
|
-
? value.filter((v) => v && v !== '' && v !== 'None')
|
|
19437
|
+
? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
|
|
19325
19438
|
: value;
|
|
19326
19439
|
}
|
|
19327
19440
|
}
|
|
19328
19441
|
catch (error) {
|
|
19329
|
-
console.warn(`Failed to evaluate
|
|
19442
|
+
console.warn(`Failed to evaluate getter for ${collName}:`, error);
|
|
19330
19443
|
}
|
|
19331
19444
|
}
|
|
19332
19445
|
}
|
|
@@ -19824,7 +19937,7 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
19824
19937
|
});
|
|
19825
19938
|
}
|
|
19826
19939
|
// Collect values to assign to instance
|
|
19827
|
-
const values = [...Properties, ...Collections, ["
|
|
19940
|
+
const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
|
|
19828
19941
|
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
19829
19942
|
return instance;
|
|
19830
19943
|
}
|
|
@@ -19892,11 +20005,11 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
19892
20005
|
latestAuthor = link.author;
|
|
19893
20006
|
}
|
|
19894
20007
|
}
|
|
19895
|
-
// Find matching property (skip those with
|
|
20008
|
+
// Find matching property (skip those with getter)
|
|
19896
20009
|
let foundProperty = false;
|
|
19897
20010
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
19898
|
-
if (propMeta.
|
|
19899
|
-
continue; // Handle via
|
|
20011
|
+
if (propMeta.getter)
|
|
20012
|
+
continue; // Handle via getter evaluation
|
|
19900
20013
|
if (propMeta.predicate === predicate) {
|
|
19901
20014
|
// For properties, take the first value (or we could use timestamp to get latest)
|
|
19902
20015
|
// Note: Empty objects {} are truthy, so we need to check for them explicitly
|
|
@@ -19966,11 +20079,11 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
19966
20079
|
break;
|
|
19967
20080
|
}
|
|
19968
20081
|
}
|
|
19969
|
-
// If not a property, check if it's a collection (skip those with
|
|
20082
|
+
// If not a property, check if it's a collection (skip those with getter)
|
|
19970
20083
|
if (!foundProperty) {
|
|
19971
20084
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
19972
|
-
if (collMeta.
|
|
19973
|
-
continue; // Handle via
|
|
20085
|
+
if (collMeta.getter)
|
|
20086
|
+
continue; // Handle via getter evaluation
|
|
19974
20087
|
if (collMeta.predicate === predicate) {
|
|
19975
20088
|
// For collections, accumulate all values with their timestamps and indices for sorting
|
|
19976
20089
|
if (!instance[collName]) {
|
|
@@ -20050,7 +20163,7 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20050
20163
|
// Replace collection with sorted values, filtering out empty strings and None
|
|
20051
20164
|
instance[collName] = pairs
|
|
20052
20165
|
.map(p => p.value)
|
|
20053
|
-
.filter((v) => v && v !== '' && v !== 'None');
|
|
20166
|
+
.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
20054
20167
|
// Clean up temporary arrays
|
|
20055
20168
|
delete instance[timestampsKey];
|
|
20056
20169
|
delete instance[indicesKey];
|
|
@@ -20060,8 +20173,9 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20060
20173
|
if (requestedProperties.length > 0 || requestedCollections.length > 0) {
|
|
20061
20174
|
const requestedAttributes = [...requestedProperties, ...requestedCollections];
|
|
20062
20175
|
Object.keys(instance).forEach((key) => {
|
|
20063
|
-
// Keep only requested attributes, plus always keep
|
|
20064
|
-
|
|
20176
|
+
// Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
|
|
20177
|
+
// Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
|
|
20178
|
+
if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
|
|
20065
20179
|
delete instance[key];
|
|
20066
20180
|
}
|
|
20067
20181
|
});
|
|
@@ -20072,12 +20186,13 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20072
20186
|
console.error(`Failed to process SurrealDB instance ${base}:`, error);
|
|
20073
20187
|
}
|
|
20074
20188
|
}
|
|
20075
|
-
// Evaluate
|
|
20189
|
+
// Evaluate custom getters for all instances (single pass)
|
|
20190
|
+
// This populates collection values needed for where.isInstance filtering
|
|
20076
20191
|
for (const instance of instances) {
|
|
20077
|
-
await this.
|
|
20192
|
+
await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
|
|
20078
20193
|
}
|
|
20079
20194
|
// Filter collections by where.isInstance if specified
|
|
20080
|
-
// Do this
|
|
20195
|
+
// Do this after initial evaluation so collection values exist for filtering
|
|
20081
20196
|
for (const instance of instances) {
|
|
20082
20197
|
for (const [collName, collMeta] of Object.entries(metadata.collections)) {
|
|
20083
20198
|
if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
|
|
@@ -20094,6 +20209,7 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20094
20209
|
}
|
|
20095
20210
|
// Check which subjects are instances of the target class
|
|
20096
20211
|
const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
|
|
20212
|
+
// Update the collection with filtered instances
|
|
20097
20213
|
instance[collName] = validSubjects;
|
|
20098
20214
|
}
|
|
20099
20215
|
catch (error) {
|
|
@@ -20102,10 +20218,6 @@ WHERE ${whereConditions.join(' AND ')}
|
|
|
20102
20218
|
}
|
|
20103
20219
|
}
|
|
20104
20220
|
}
|
|
20105
|
-
// Evaluate SurrealQL getters for all instances
|
|
20106
|
-
for (const instance of instances) {
|
|
20107
|
-
await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
|
|
20108
|
-
}
|
|
20109
20221
|
// Filter by where conditions that couldn't be filtered in SQL
|
|
20110
20222
|
// This includes:
|
|
20111
20223
|
// - author/timestamp (computed from grouped links)
|