@coasys/ad4m 0.11.2-dev.3 → 0.11.2-dev.5

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 CHANGED
@@ -18855,6 +18855,13 @@ class Ad4mModel {
18855
18855
  }
18856
18856
  return classCache[perspectiveID];
18857
18857
  }
18858
+ /**
18859
+ * Backwards compatibility alias for createdAt.
18860
+ * @deprecated Use createdAt instead. This will be removed in a future version.
18861
+ */
18862
+ get timestamp() {
18863
+ return this.createdAt;
18864
+ }
18858
18865
  /**
18859
18866
  * Extracts metadata from decorators for query building.
18860
18867
  *
@@ -19131,8 +19138,26 @@ class Ad4mModel {
19131
19138
  }
19132
19139
  return [name, finalValue];
19133
19140
  })));
19141
+ // Filter out properties that are read-only (getters without setters)
19142
+ const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
19143
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
19144
+ if (!descriptor) {
19145
+ // No descriptor means it's a regular property on the instance, allow it
19146
+ return true;
19147
+ }
19148
+ // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
19149
+ const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
19150
+ if (isAccessor) {
19151
+ // Accessor descriptor: only allow if it has a setter
19152
+ return descriptor.set !== undefined;
19153
+ }
19154
+ else {
19155
+ // Data descriptor: only allow if writable is not explicitly false
19156
+ return descriptor.writable !== false;
19157
+ }
19158
+ }));
19134
19159
  // Assign properties to instance
19135
- Object.assign(instance, propsObject);
19160
+ Object.assign(instance, writableProps);
19136
19161
  }
19137
19162
  async getData() {
19138
19163
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
@@ -19154,8 +19179,10 @@ class Ad4mModel {
19154
19179
  `;
19155
19180
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
19156
19181
  if (links && links.length > 0) {
19182
+ let minTimestamp = null;
19157
19183
  let maxTimestamp = null;
19158
19184
  let latestAuthor = null;
19185
+ let originalAuthor = null;
19159
19186
  // Process properties (skip those with surrealGetter)
19160
19187
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19161
19188
  if (propMeta.surrealGetter)
@@ -19166,10 +19193,16 @@ class Ad4mModel {
19166
19193
  // The last element has the most recent timestamp and represents the current property value.
19167
19194
  const link = matching[matching.length - 1];
19168
19195
  let value = link.target;
19169
- // Track timestamp/author
19170
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19171
- maxTimestamp = link.timestamp;
19172
- latestAuthor = link.author;
19196
+ // Track timestamps/authors for createdAt and updatedAt
19197
+ if (link.timestamp) {
19198
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19199
+ minTimestamp = link.timestamp;
19200
+ originalAuthor = link.author;
19201
+ }
19202
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19203
+ maxTimestamp = link.timestamp;
19204
+ latestAuthor = link.author;
19205
+ }
19173
19206
  }
19174
19207
  // Handle resolveLanguage
19175
19208
  if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
@@ -19230,16 +19263,38 @@ class Ad4mModel {
19230
19263
  }
19231
19264
  this[collName] = values;
19232
19265
  }
19233
- // Set author and timestamp
19234
- if (latestAuthor) {
19235
- this.author = latestAuthor;
19266
+ // Set author and timestamps
19267
+ if (originalAuthor) {
19268
+ this.author = originalAuthor;
19269
+ }
19270
+ if (minTimestamp) {
19271
+ this.createdAt = minTimestamp;
19236
19272
  }
19237
19273
  if (maxTimestamp) {
19238
- this.timestamp = maxTimestamp;
19274
+ this.updatedAt = maxTimestamp;
19239
19275
  }
19240
19276
  }
19241
19277
  // Evaluate SurrealQL getters
19242
19278
  await ctor.evaluateSurrealGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
19279
+ // Apply where.isInstance filtering to surrealGetter collections
19280
+ // (non-surrealGetter collections were already filtered above)
19281
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19282
+ if (collMeta.surrealGetter && collMeta.where?.isInstance && this[collName]?.length > 0) {
19283
+ try {
19284
+ const className = typeof collMeta.where.isInstance === 'string'
19285
+ ? collMeta.where.isInstance
19286
+ : collMeta.where.isInstance.name;
19287
+ const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
19288
+ if (filterMetadata) {
19289
+ const filtered = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(this[collName], filterMetadata);
19290
+ this[collName] = filtered;
19291
+ }
19292
+ }
19293
+ catch (error) {
19294
+ // Keep unfiltered values on error
19295
+ }
19296
+ }
19297
+ }
19243
19298
  }
19244
19299
  catch (e) {
19245
19300
  console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
@@ -19303,7 +19358,7 @@ class Ad4mModel {
19303
19358
  // Filter out 'None' from collection results
19304
19359
  const value = result[0].value;
19305
19360
  instance[collName] = Array.isArray(value)
19306
- ? value.filter((v) => v && v !== '' && v !== 'None')
19361
+ ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
19307
19362
  : value;
19308
19363
  }
19309
19364
  }
@@ -19715,8 +19770,9 @@ WHERE ${whereConditions.join(' AND ')}
19715
19770
  fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
19716
19771
  }
19717
19772
  // Always add author and timestamp fields
19718
- fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
19719
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
19773
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
19774
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
19775
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
19720
19776
  return fields.join(',\n ');
19721
19777
  }
19722
19778
  /**
@@ -19747,9 +19803,10 @@ WHERE ${whereConditions.join(' AND ')}
19747
19803
  const escapedPredicate = escapeSurrealString(collMeta.predicate);
19748
19804
  fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
19749
19805
  }
19750
- // Always add author and timestamp fields using array::first
19806
+ // Always add author and timestamp fields
19751
19807
  fields.push(`array::first(author) AS author`);
19752
- fields.push(`array::first(timestamp) AS timestamp`);
19808
+ fields.push(`array::first(timestamp) AS createdAt`);
19809
+ fields.push(`array::last(timestamp) AS updatedAt`);
19753
19810
  return fields.join(',\n ');
19754
19811
  }
19755
19812
  /**
@@ -19804,7 +19861,7 @@ WHERE ${whereConditions.join(' AND ')}
19804
19861
  });
19805
19862
  }
19806
19863
  // Collect values to assign to instance
19807
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
19864
+ const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
19808
19865
  await Ad4mModel.assignValuesToInstance(perspective, instance, values);
19809
19866
  return instance;
19810
19867
  }
@@ -19848,8 +19905,10 @@ WHERE ${whereConditions.join(' AND ')}
19848
19905
  }
19849
19906
  const links = row.links || [];
19850
19907
  const instance = new this(perspective, base);
19851
- // Track the most recent timestamp and corresponding author
19908
+ // Track both earliest (createdAt) and most recent (updatedAt) timestamps
19909
+ let minTimestamp = null;
19852
19910
  let maxTimestamp = null;
19911
+ let originalAuthor = null;
19853
19912
  let latestAuthor = null;
19854
19913
  // Process each link (track index for collection ordering)
19855
19914
  for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
@@ -19859,10 +19918,16 @@ WHERE ${whereConditions.join(' AND ')}
19859
19918
  // Skip 'None' values
19860
19919
  if (target === 'None')
19861
19920
  continue;
19862
- // Track the most recent timestamp and its author
19863
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19864
- maxTimestamp = link.timestamp;
19865
- latestAuthor = link.author;
19921
+ // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
19922
+ if (link.timestamp) {
19923
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19924
+ minTimestamp = link.timestamp;
19925
+ originalAuthor = link.author;
19926
+ }
19927
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19928
+ maxTimestamp = link.timestamp;
19929
+ latestAuthor = link.author;
19930
+ }
19866
19931
  }
19867
19932
  // Find matching property (skip those with surrealGetter)
19868
19933
  let foundProperty = false;
@@ -19968,20 +20033,34 @@ WHERE ${whereConditions.join(' AND ')}
19968
20033
  }
19969
20034
  }
19970
20035
  }
19971
- // Set author and timestamp from the most recent link
19972
- if (latestAuthor && maxTimestamp) {
19973
- instance.author = latestAuthor;
19974
- // Convert timestamp to number (milliseconds) if it's an ISO string
20036
+ // Set author and timestamps
20037
+ if (originalAuthor) {
20038
+ instance.author = originalAuthor;
20039
+ }
20040
+ // Set createdAt from earliest timestamp
20041
+ if (minTimestamp) {
20042
+ if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
20043
+ instance.createdAt = new Date(minTimestamp).getTime();
20044
+ }
20045
+ else if (typeof minTimestamp === 'string') {
20046
+ const parsed = parseInt(minTimestamp, 10);
20047
+ instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
20048
+ }
20049
+ else {
20050
+ instance.createdAt = minTimestamp;
20051
+ }
20052
+ }
20053
+ // Set updatedAt from most recent timestamp
20054
+ if (maxTimestamp) {
19975
20055
  if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
19976
- instance.timestamp = new Date(maxTimestamp).getTime();
20056
+ instance.updatedAt = new Date(maxTimestamp).getTime();
19977
20057
  }
19978
20058
  else if (typeof maxTimestamp === 'string') {
19979
- // Try to parse as number string
19980
20059
  const parsed = parseInt(maxTimestamp, 10);
19981
- instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
20060
+ instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
19982
20061
  }
19983
20062
  else {
19984
- instance.timestamp = maxTimestamp;
20063
+ instance.updatedAt = maxTimestamp;
19985
20064
  }
19986
20065
  }
19987
20066
  // Sort collections by timestamp to maintain insertion order
@@ -20008,7 +20087,7 @@ WHERE ${whereConditions.join(' AND ')}
20008
20087
  // Replace collection with sorted values, filtering out empty strings and None
20009
20088
  instance[collName] = pairs
20010
20089
  .map(p => p.value)
20011
- .filter((v) => v && v !== '' && v !== 'None');
20090
+ .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
20012
20091
  // Clean up temporary arrays
20013
20092
  delete instance[timestampsKey];
20014
20093
  delete instance[indicesKey];
@@ -20018,8 +20097,9 @@ WHERE ${whereConditions.join(' AND ')}
20018
20097
  if (requestedProperties.length > 0 || requestedCollections.length > 0) {
20019
20098
  const requestedAttributes = [...requestedProperties, ...requestedCollections];
20020
20099
  Object.keys(instance).forEach((key) => {
20021
- // Keep only requested attributes, plus always keep timestamp and author
20022
- if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
20100
+ // Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
20101
+ // Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
20102
+ if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
20023
20103
  delete instance[key];
20024
20104
  }
20025
20105
  });
@@ -20030,12 +20110,13 @@ WHERE ${whereConditions.join(' AND ')}
20030
20110
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
20031
20111
  }
20032
20112
  }
20033
- // Evaluate SurrealQL getters for all instances
20113
+ // Evaluate SurrealQL getters for all instances (single pass)
20114
+ // This populates collection values needed for where.isInstance filtering
20034
20115
  for (const instance of instances) {
20035
20116
  await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20036
20117
  }
20037
20118
  // Filter collections by where.isInstance if specified
20038
- // Do this for all instances that have collections with filters
20119
+ // Do this after initial evaluation so collection values exist for filtering
20039
20120
  for (const instance of instances) {
20040
20121
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
20041
20122
  if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
@@ -20052,6 +20133,7 @@ WHERE ${whereConditions.join(' AND ')}
20052
20133
  }
20053
20134
  // Check which subjects are instances of the target class
20054
20135
  const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
20136
+ // Update the collection with filtered instances
20055
20137
  instance[collName] = validSubjects;
20056
20138
  }
20057
20139
  catch (error) {
@@ -20060,10 +20142,6 @@ WHERE ${whereConditions.join(' AND ')}
20060
20142
  }
20061
20143
  }
20062
20144
  }
20063
- // Evaluate SurrealQL getters for all instances
20064
- for (const instance of instances) {
20065
- await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20066
- }
20067
20145
  // Filter by where conditions that couldn't be filtered in SQL
20068
20146
  // This includes:
20069
20147
  // - author/timestamp (computed from grouped links)
package/lib/index.js CHANGED
@@ -18851,6 +18851,13 @@ class Ad4mModel {
18851
18851
  }
18852
18852
  return classCache[perspectiveID];
18853
18853
  }
18854
+ /**
18855
+ * Backwards compatibility alias for createdAt.
18856
+ * @deprecated Use createdAt instead. This will be removed in a future version.
18857
+ */
18858
+ get timestamp() {
18859
+ return this.createdAt;
18860
+ }
18854
18861
  /**
18855
18862
  * Extracts metadata from decorators for query building.
18856
18863
  *
@@ -19127,8 +19134,26 @@ class Ad4mModel {
19127
19134
  }
19128
19135
  return [name, finalValue];
19129
19136
  })));
19137
+ // Filter out properties that are read-only (getters without setters)
19138
+ const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
19139
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
19140
+ if (!descriptor) {
19141
+ // No descriptor means it's a regular property on the instance, allow it
19142
+ return true;
19143
+ }
19144
+ // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
19145
+ const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
19146
+ if (isAccessor) {
19147
+ // Accessor descriptor: only allow if it has a setter
19148
+ return descriptor.set !== undefined;
19149
+ }
19150
+ else {
19151
+ // Data descriptor: only allow if writable is not explicitly false
19152
+ return descriptor.writable !== false;
19153
+ }
19154
+ }));
19130
19155
  // Assign properties to instance
19131
- Object.assign(instance, propsObject);
19156
+ Object.assign(instance, writableProps);
19132
19157
  }
19133
19158
  async getData() {
19134
19159
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
@@ -19150,8 +19175,10 @@ class Ad4mModel {
19150
19175
  `;
19151
19176
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
19152
19177
  if (links && links.length > 0) {
19178
+ let minTimestamp = null;
19153
19179
  let maxTimestamp = null;
19154
19180
  let latestAuthor = null;
19181
+ let originalAuthor = null;
19155
19182
  // Process properties (skip those with surrealGetter)
19156
19183
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19157
19184
  if (propMeta.surrealGetter)
@@ -19162,10 +19189,16 @@ class Ad4mModel {
19162
19189
  // The last element has the most recent timestamp and represents the current property value.
19163
19190
  const link = matching[matching.length - 1];
19164
19191
  let value = link.target;
19165
- // Track timestamp/author
19166
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19167
- maxTimestamp = link.timestamp;
19168
- latestAuthor = link.author;
19192
+ // Track timestamps/authors for createdAt and updatedAt
19193
+ if (link.timestamp) {
19194
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19195
+ minTimestamp = link.timestamp;
19196
+ originalAuthor = link.author;
19197
+ }
19198
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19199
+ maxTimestamp = link.timestamp;
19200
+ latestAuthor = link.author;
19201
+ }
19169
19202
  }
19170
19203
  // Handle resolveLanguage
19171
19204
  if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
@@ -19226,16 +19259,38 @@ class Ad4mModel {
19226
19259
  }
19227
19260
  this[collName] = values;
19228
19261
  }
19229
- // Set author and timestamp
19230
- if (latestAuthor) {
19231
- this.author = latestAuthor;
19262
+ // Set author and timestamps
19263
+ if (originalAuthor) {
19264
+ this.author = originalAuthor;
19265
+ }
19266
+ if (minTimestamp) {
19267
+ this.createdAt = minTimestamp;
19232
19268
  }
19233
19269
  if (maxTimestamp) {
19234
- this.timestamp = maxTimestamp;
19270
+ this.updatedAt = maxTimestamp;
19235
19271
  }
19236
19272
  }
19237
19273
  // Evaluate SurrealQL getters
19238
19274
  await ctor.evaluateSurrealGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
19275
+ // Apply where.isInstance filtering to surrealGetter collections
19276
+ // (non-surrealGetter collections were already filtered above)
19277
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19278
+ if (collMeta.surrealGetter && collMeta.where?.isInstance && this[collName]?.length > 0) {
19279
+ try {
19280
+ const className = typeof collMeta.where.isInstance === 'string'
19281
+ ? collMeta.where.isInstance
19282
+ : collMeta.where.isInstance.name;
19283
+ const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
19284
+ if (filterMetadata) {
19285
+ const filtered = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(this[collName], filterMetadata);
19286
+ this[collName] = filtered;
19287
+ }
19288
+ }
19289
+ catch (error) {
19290
+ // Keep unfiltered values on error
19291
+ }
19292
+ }
19293
+ }
19239
19294
  }
19240
19295
  catch (e) {
19241
19296
  console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
@@ -19299,7 +19354,7 @@ class Ad4mModel {
19299
19354
  // Filter out 'None' from collection results
19300
19355
  const value = result[0].value;
19301
19356
  instance[collName] = Array.isArray(value)
19302
- ? value.filter((v) => v && v !== '' && v !== 'None')
19357
+ ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
19303
19358
  : value;
19304
19359
  }
19305
19360
  }
@@ -19711,8 +19766,9 @@ WHERE ${whereConditions.join(' AND ')}
19711
19766
  fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
19712
19767
  }
19713
19768
  // Always add author and timestamp fields
19714
- fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
19715
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
19769
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
19770
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
19771
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
19716
19772
  return fields.join(',\n ');
19717
19773
  }
19718
19774
  /**
@@ -19743,9 +19799,10 @@ WHERE ${whereConditions.join(' AND ')}
19743
19799
  const escapedPredicate = escapeSurrealString(collMeta.predicate);
19744
19800
  fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
19745
19801
  }
19746
- // Always add author and timestamp fields using array::first
19802
+ // Always add author and timestamp fields
19747
19803
  fields.push(`array::first(author) AS author`);
19748
- fields.push(`array::first(timestamp) AS timestamp`);
19804
+ fields.push(`array::first(timestamp) AS createdAt`);
19805
+ fields.push(`array::last(timestamp) AS updatedAt`);
19749
19806
  return fields.join(',\n ');
19750
19807
  }
19751
19808
  /**
@@ -19800,7 +19857,7 @@ WHERE ${whereConditions.join(' AND ')}
19800
19857
  });
19801
19858
  }
19802
19859
  // Collect values to assign to instance
19803
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
19860
+ const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
19804
19861
  await Ad4mModel.assignValuesToInstance(perspective, instance, values);
19805
19862
  return instance;
19806
19863
  }
@@ -19844,8 +19901,10 @@ WHERE ${whereConditions.join(' AND ')}
19844
19901
  }
19845
19902
  const links = row.links || [];
19846
19903
  const instance = new this(perspective, base);
19847
- // Track the most recent timestamp and corresponding author
19904
+ // Track both earliest (createdAt) and most recent (updatedAt) timestamps
19905
+ let minTimestamp = null;
19848
19906
  let maxTimestamp = null;
19907
+ let originalAuthor = null;
19849
19908
  let latestAuthor = null;
19850
19909
  // Process each link (track index for collection ordering)
19851
19910
  for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
@@ -19855,10 +19914,16 @@ WHERE ${whereConditions.join(' AND ')}
19855
19914
  // Skip 'None' values
19856
19915
  if (target === 'None')
19857
19916
  continue;
19858
- // Track the most recent timestamp and its author
19859
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19860
- maxTimestamp = link.timestamp;
19861
- latestAuthor = link.author;
19917
+ // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
19918
+ if (link.timestamp) {
19919
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19920
+ minTimestamp = link.timestamp;
19921
+ originalAuthor = link.author;
19922
+ }
19923
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19924
+ maxTimestamp = link.timestamp;
19925
+ latestAuthor = link.author;
19926
+ }
19862
19927
  }
19863
19928
  // Find matching property (skip those with surrealGetter)
19864
19929
  let foundProperty = false;
@@ -19964,20 +20029,34 @@ WHERE ${whereConditions.join(' AND ')}
19964
20029
  }
19965
20030
  }
19966
20031
  }
19967
- // Set author and timestamp from the most recent link
19968
- if (latestAuthor && maxTimestamp) {
19969
- instance.author = latestAuthor;
19970
- // Convert timestamp to number (milliseconds) if it's an ISO string
20032
+ // Set author and timestamps
20033
+ if (originalAuthor) {
20034
+ instance.author = originalAuthor;
20035
+ }
20036
+ // Set createdAt from earliest timestamp
20037
+ if (minTimestamp) {
20038
+ if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
20039
+ instance.createdAt = new Date(minTimestamp).getTime();
20040
+ }
20041
+ else if (typeof minTimestamp === 'string') {
20042
+ const parsed = parseInt(minTimestamp, 10);
20043
+ instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
20044
+ }
20045
+ else {
20046
+ instance.createdAt = minTimestamp;
20047
+ }
20048
+ }
20049
+ // Set updatedAt from most recent timestamp
20050
+ if (maxTimestamp) {
19971
20051
  if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
19972
- instance.timestamp = new Date(maxTimestamp).getTime();
20052
+ instance.updatedAt = new Date(maxTimestamp).getTime();
19973
20053
  }
19974
20054
  else if (typeof maxTimestamp === 'string') {
19975
- // Try to parse as number string
19976
20055
  const parsed = parseInt(maxTimestamp, 10);
19977
- instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
20056
+ instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
19978
20057
  }
19979
20058
  else {
19980
- instance.timestamp = maxTimestamp;
20059
+ instance.updatedAt = maxTimestamp;
19981
20060
  }
19982
20061
  }
19983
20062
  // Sort collections by timestamp to maintain insertion order
@@ -20004,7 +20083,7 @@ WHERE ${whereConditions.join(' AND ')}
20004
20083
  // Replace collection with sorted values, filtering out empty strings and None
20005
20084
  instance[collName] = pairs
20006
20085
  .map(p => p.value)
20007
- .filter((v) => v && v !== '' && v !== 'None');
20086
+ .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
20008
20087
  // Clean up temporary arrays
20009
20088
  delete instance[timestampsKey];
20010
20089
  delete instance[indicesKey];
@@ -20014,8 +20093,9 @@ WHERE ${whereConditions.join(' AND ')}
20014
20093
  if (requestedProperties.length > 0 || requestedCollections.length > 0) {
20015
20094
  const requestedAttributes = [...requestedProperties, ...requestedCollections];
20016
20095
  Object.keys(instance).forEach((key) => {
20017
- // Keep only requested attributes, plus always keep timestamp and author
20018
- if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
20096
+ // Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
20097
+ // Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
20098
+ if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
20019
20099
  delete instance[key];
20020
20100
  }
20021
20101
  });
@@ -20026,12 +20106,13 @@ WHERE ${whereConditions.join(' AND ')}
20026
20106
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
20027
20107
  }
20028
20108
  }
20029
- // Evaluate SurrealQL getters for all instances
20109
+ // Evaluate SurrealQL getters for all instances (single pass)
20110
+ // This populates collection values needed for where.isInstance filtering
20030
20111
  for (const instance of instances) {
20031
20112
  await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20032
20113
  }
20033
20114
  // Filter collections by where.isInstance if specified
20034
- // Do this for all instances that have collections with filters
20115
+ // Do this after initial evaluation so collection values exist for filtering
20035
20116
  for (const instance of instances) {
20036
20117
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
20037
20118
  if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
@@ -20048,6 +20129,7 @@ WHERE ${whereConditions.join(' AND ')}
20048
20129
  }
20049
20130
  // Check which subjects are instances of the target class
20050
20131
  const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
20132
+ // Update the collection with filtered instances
20051
20133
  instance[collName] = validSubjects;
20052
20134
  }
20053
20135
  catch (error) {
@@ -20056,10 +20138,6 @@ WHERE ${whereConditions.join(' AND ')}
20056
20138
  }
20057
20139
  }
20058
20140
  }
20059
- // Evaluate SurrealQL getters for all instances
20060
- for (const instance of instances) {
20061
- await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20062
- }
20063
20141
  // Filter by where conditions that couldn't be filtered in SQL
20064
20142
  // This includes:
20065
20143
  // - author/timestamp (computed from grouped links)
@@ -243,9 +243,15 @@ export interface ModelMetadata {
243
243
  export declare class Ad4mModel {
244
244
  #private;
245
245
  author: string;
246
- timestamp: string;
246
+ createdAt: any;
247
+ updatedAt: any;
247
248
  private static classNamesByClass;
248
249
  static getClassName(perspective: PerspectiveProxy): Promise<string>;
250
+ /**
251
+ * Backwards compatibility alias for createdAt.
252
+ * @deprecated Use createdAt instead. This will be removed in a future version.
253
+ */
254
+ get timestamp(): any;
249
255
  /**
250
256
  * Extracts metadata from decorators for query building.
251
257
  *
@@ -306,6 +306,13 @@ export class Ad4mModel {
306
306
  }
307
307
  return classCache[perspectiveID];
308
308
  }
309
+ /**
310
+ * Backwards compatibility alias for createdAt.
311
+ * @deprecated Use createdAt instead. This will be removed in a future version.
312
+ */
313
+ get timestamp() {
314
+ return this.createdAt;
315
+ }
309
316
  /**
310
317
  * Extracts metadata from decorators for query building.
311
318
  *
@@ -582,8 +589,26 @@ export class Ad4mModel {
582
589
  }
583
590
  return [name, finalValue];
584
591
  })));
592
+ // Filter out properties that are read-only (getters without setters)
593
+ const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
594
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
595
+ if (!descriptor) {
596
+ // No descriptor means it's a regular property on the instance, allow it
597
+ return true;
598
+ }
599
+ // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
600
+ const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
601
+ if (isAccessor) {
602
+ // Accessor descriptor: only allow if it has a setter
603
+ return descriptor.set !== undefined;
604
+ }
605
+ else {
606
+ // Data descriptor: only allow if writable is not explicitly false
607
+ return descriptor.writable !== false;
608
+ }
609
+ }));
585
610
  // Assign properties to instance
586
- Object.assign(instance, propsObject);
611
+ Object.assign(instance, writableProps);
587
612
  }
588
613
  async getData() {
589
614
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
@@ -605,8 +630,10 @@ export class Ad4mModel {
605
630
  `;
606
631
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
607
632
  if (links && links.length > 0) {
633
+ let minTimestamp = null;
608
634
  let maxTimestamp = null;
609
635
  let latestAuthor = null;
636
+ let originalAuthor = null;
610
637
  // Process properties (skip those with surrealGetter)
611
638
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
612
639
  if (propMeta.surrealGetter)
@@ -617,10 +644,16 @@ export class Ad4mModel {
617
644
  // The last element has the most recent timestamp and represents the current property value.
618
645
  const link = matching[matching.length - 1];
619
646
  let value = link.target;
620
- // Track timestamp/author
621
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
622
- maxTimestamp = link.timestamp;
623
- latestAuthor = link.author;
647
+ // Track timestamps/authors for createdAt and updatedAt
648
+ if (link.timestamp) {
649
+ if (!minTimestamp || link.timestamp < minTimestamp) {
650
+ minTimestamp = link.timestamp;
651
+ originalAuthor = link.author;
652
+ }
653
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
654
+ maxTimestamp = link.timestamp;
655
+ latestAuthor = link.author;
656
+ }
624
657
  }
625
658
  // Handle resolveLanguage
626
659
  if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
@@ -681,16 +714,38 @@ export class Ad4mModel {
681
714
  }
682
715
  this[collName] = values;
683
716
  }
684
- // Set author and timestamp
685
- if (latestAuthor) {
686
- this.author = latestAuthor;
717
+ // Set author and timestamps
718
+ if (originalAuthor) {
719
+ this.author = originalAuthor;
720
+ }
721
+ if (minTimestamp) {
722
+ this.createdAt = minTimestamp;
687
723
  }
688
724
  if (maxTimestamp) {
689
- this.timestamp = maxTimestamp;
725
+ this.updatedAt = maxTimestamp;
690
726
  }
691
727
  }
692
728
  // Evaluate SurrealQL getters
693
729
  await ctor.evaluateSurrealGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
730
+ // Apply where.isInstance filtering to surrealGetter collections
731
+ // (non-surrealGetter collections were already filtered above)
732
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
733
+ if (collMeta.surrealGetter && collMeta.where?.isInstance && this[collName]?.length > 0) {
734
+ try {
735
+ const className = typeof collMeta.where.isInstance === 'string'
736
+ ? collMeta.where.isInstance
737
+ : collMeta.where.isInstance.name;
738
+ const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
739
+ if (filterMetadata) {
740
+ const filtered = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(this[collName], filterMetadata);
741
+ this[collName] = filtered;
742
+ }
743
+ }
744
+ catch (error) {
745
+ // Keep unfiltered values on error
746
+ }
747
+ }
748
+ }
694
749
  }
695
750
  catch (e) {
696
751
  console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
@@ -754,7 +809,7 @@ export class Ad4mModel {
754
809
  // Filter out 'None' from collection results
755
810
  const value = result[0].value;
756
811
  instance[collName] = Array.isArray(value)
757
- ? value.filter((v) => v && v !== '' && v !== 'None')
812
+ ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
758
813
  : value;
759
814
  }
760
815
  }
@@ -1166,8 +1221,9 @@ WHERE ${whereConditions.join(' AND ')}
1166
1221
  fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
1167
1222
  }
1168
1223
  // Always add author and timestamp fields
1169
- fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
1170
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
1224
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
1225
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
1226
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
1171
1227
  return fields.join(',\n ');
1172
1228
  }
1173
1229
  /**
@@ -1198,9 +1254,10 @@ WHERE ${whereConditions.join(' AND ')}
1198
1254
  const escapedPredicate = escapeSurrealString(collMeta.predicate);
1199
1255
  fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
1200
1256
  }
1201
- // Always add author and timestamp fields using array::first
1257
+ // Always add author and timestamp fields
1202
1258
  fields.push(`array::first(author) AS author`);
1203
- fields.push(`array::first(timestamp) AS timestamp`);
1259
+ fields.push(`array::first(timestamp) AS createdAt`);
1260
+ fields.push(`array::last(timestamp) AS updatedAt`);
1204
1261
  return fields.join(',\n ');
1205
1262
  }
1206
1263
  /**
@@ -1255,7 +1312,7 @@ WHERE ${whereConditions.join(' AND ')}
1255
1312
  });
1256
1313
  }
1257
1314
  // Collect values to assign to instance
1258
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
1315
+ const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
1259
1316
  await Ad4mModel.assignValuesToInstance(perspective, instance, values);
1260
1317
  return instance;
1261
1318
  }
@@ -1299,8 +1356,10 @@ WHERE ${whereConditions.join(' AND ')}
1299
1356
  }
1300
1357
  const links = row.links || [];
1301
1358
  const instance = new this(perspective, base);
1302
- // Track the most recent timestamp and corresponding author
1359
+ // Track both earliest (createdAt) and most recent (updatedAt) timestamps
1360
+ let minTimestamp = null;
1303
1361
  let maxTimestamp = null;
1362
+ let originalAuthor = null;
1304
1363
  let latestAuthor = null;
1305
1364
  // Process each link (track index for collection ordering)
1306
1365
  for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
@@ -1310,10 +1369,16 @@ WHERE ${whereConditions.join(' AND ')}
1310
1369
  // Skip 'None' values
1311
1370
  if (target === 'None')
1312
1371
  continue;
1313
- // Track the most recent timestamp and its author
1314
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
1315
- maxTimestamp = link.timestamp;
1316
- latestAuthor = link.author;
1372
+ // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
1373
+ if (link.timestamp) {
1374
+ if (!minTimestamp || link.timestamp < minTimestamp) {
1375
+ minTimestamp = link.timestamp;
1376
+ originalAuthor = link.author;
1377
+ }
1378
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
1379
+ maxTimestamp = link.timestamp;
1380
+ latestAuthor = link.author;
1381
+ }
1317
1382
  }
1318
1383
  // Find matching property (skip those with surrealGetter)
1319
1384
  let foundProperty = false;
@@ -1419,20 +1484,34 @@ WHERE ${whereConditions.join(' AND ')}
1419
1484
  }
1420
1485
  }
1421
1486
  }
1422
- // Set author and timestamp from the most recent link
1423
- if (latestAuthor && maxTimestamp) {
1424
- instance.author = latestAuthor;
1425
- // Convert timestamp to number (milliseconds) if it's an ISO string
1487
+ // Set author and timestamps
1488
+ if (originalAuthor) {
1489
+ instance.author = originalAuthor;
1490
+ }
1491
+ // Set createdAt from earliest timestamp
1492
+ if (minTimestamp) {
1493
+ if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
1494
+ instance.createdAt = new Date(minTimestamp).getTime();
1495
+ }
1496
+ else if (typeof minTimestamp === 'string') {
1497
+ const parsed = parseInt(minTimestamp, 10);
1498
+ instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
1499
+ }
1500
+ else {
1501
+ instance.createdAt = minTimestamp;
1502
+ }
1503
+ }
1504
+ // Set updatedAt from most recent timestamp
1505
+ if (maxTimestamp) {
1426
1506
  if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
1427
- instance.timestamp = new Date(maxTimestamp).getTime();
1507
+ instance.updatedAt = new Date(maxTimestamp).getTime();
1428
1508
  }
1429
1509
  else if (typeof maxTimestamp === 'string') {
1430
- // Try to parse as number string
1431
1510
  const parsed = parseInt(maxTimestamp, 10);
1432
- instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
1511
+ instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
1433
1512
  }
1434
1513
  else {
1435
- instance.timestamp = maxTimestamp;
1514
+ instance.updatedAt = maxTimestamp;
1436
1515
  }
1437
1516
  }
1438
1517
  // Sort collections by timestamp to maintain insertion order
@@ -1459,7 +1538,7 @@ WHERE ${whereConditions.join(' AND ')}
1459
1538
  // Replace collection with sorted values, filtering out empty strings and None
1460
1539
  instance[collName] = pairs
1461
1540
  .map(p => p.value)
1462
- .filter((v) => v && v !== '' && v !== 'None');
1541
+ .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
1463
1542
  // Clean up temporary arrays
1464
1543
  delete instance[timestampsKey];
1465
1544
  delete instance[indicesKey];
@@ -1469,8 +1548,9 @@ WHERE ${whereConditions.join(' AND ')}
1469
1548
  if (requestedProperties.length > 0 || requestedCollections.length > 0) {
1470
1549
  const requestedAttributes = [...requestedProperties, ...requestedCollections];
1471
1550
  Object.keys(instance).forEach((key) => {
1472
- // Keep only requested attributes, plus always keep timestamp and author
1473
- if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
1551
+ // Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
1552
+ // Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
1553
+ if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
1474
1554
  delete instance[key];
1475
1555
  }
1476
1556
  });
@@ -1481,12 +1561,13 @@ WHERE ${whereConditions.join(' AND ')}
1481
1561
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
1482
1562
  }
1483
1563
  }
1484
- // Evaluate SurrealQL getters for all instances
1564
+ // Evaluate SurrealQL getters for all instances (single pass)
1565
+ // This populates collection values needed for where.isInstance filtering
1485
1566
  for (const instance of instances) {
1486
1567
  await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
1487
1568
  }
1488
1569
  // Filter collections by where.isInstance if specified
1489
- // Do this for all instances that have collections with filters
1570
+ // Do this after initial evaluation so collection values exist for filtering
1490
1571
  for (const instance of instances) {
1491
1572
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1492
1573
  if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
@@ -1503,6 +1584,7 @@ WHERE ${whereConditions.join(' AND ')}
1503
1584
  }
1504
1585
  // Check which subjects are instances of the target class
1505
1586
  const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
1587
+ // Update the collection with filtered instances
1506
1588
  instance[collName] = validSubjects;
1507
1589
  }
1508
1590
  catch (error) {
@@ -1511,10 +1593,6 @@ WHERE ${whereConditions.join(' AND ')}
1511
1593
  }
1512
1594
  }
1513
1595
  }
1514
- // Evaluate SurrealQL getters for all instances
1515
- for (const instance of instances) {
1516
- await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
1517
- }
1518
1596
  // Filter by where conditions that couldn't be filtered in SQL
1519
1597
  // This includes:
1520
1598
  // - author/timestamp (computed from grouped links)
package/package.json CHANGED
@@ -57,7 +57,7 @@
57
57
  "react-dom": "*"
58
58
  },
59
59
  "patchedDependencies": {},
60
- "version": "0.11.2-dev.3",
60
+ "version": "0.11.2-dev.5",
61
61
  "scripts": {
62
62
  "build": "patch-package && tsc && pnpm run buildSchema && pnpm run bundle",
63
63
  "buildSchema": "node --es-module-specifier-resolution=node lib/src/buildSchema.js",
@@ -413,7 +413,8 @@ export class Ad4mModel {
413
413
  #source: string;
414
414
  #perspective: PerspectiveProxy;
415
415
  author: string;
416
- timestamp: string;
416
+ createdAt: any;
417
+ updatedAt: any;
417
418
 
418
419
  private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
419
420
 
@@ -442,6 +443,14 @@ export class Ad4mModel {
442
443
  return classCache[perspectiveID];
443
444
  }
444
445
 
446
+ /**
447
+ * Backwards compatibility alias for createdAt.
448
+ * @deprecated Use createdAt instead. This will be removed in a future version.
449
+ */
450
+ get timestamp(): any {
451
+ return (this as any).createdAt;
452
+ }
453
+
445
454
  /**
446
455
  * Extracts metadata from decorators for query building.
447
456
  *
@@ -749,8 +758,27 @@ export class Ad4mModel {
749
758
  })
750
759
  )
751
760
  );
761
+ // Filter out properties that are read-only (getters without setters)
762
+ const writableProps = Object.fromEntries(
763
+ Object.entries(propsObject).filter(([key]) => {
764
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
765
+ if (!descriptor) {
766
+ // No descriptor means it's a regular property on the instance, allow it
767
+ return true;
768
+ }
769
+ // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
770
+ const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
771
+ if (isAccessor) {
772
+ // Accessor descriptor: only allow if it has a setter
773
+ return descriptor.set !== undefined;
774
+ } else {
775
+ // Data descriptor: only allow if writable is not explicitly false
776
+ return descriptor.writable !== false;
777
+ }
778
+ })
779
+ );
752
780
  // Assign properties to instance
753
- Object.assign(instance, propsObject);
781
+ Object.assign(instance, writableProps);
754
782
  }
755
783
 
756
784
  private async getData() {
@@ -775,8 +803,10 @@ export class Ad4mModel {
775
803
  const links = await this.#perspective.querySurrealDB(linksQuery);
776
804
 
777
805
  if (links && links.length > 0) {
806
+ let minTimestamp = null;
778
807
  let maxTimestamp = null;
779
808
  let latestAuthor = null;
809
+ let originalAuthor = null;
780
810
 
781
811
  // Process properties (skip those with surrealGetter)
782
812
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
@@ -788,10 +818,16 @@ export class Ad4mModel {
788
818
  const link = matching[matching.length - 1];
789
819
  let value = link.target;
790
820
 
791
- // Track timestamp/author
792
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
793
- maxTimestamp = link.timestamp;
794
- latestAuthor = link.author;
821
+ // Track timestamps/authors for createdAt and updatedAt
822
+ if (link.timestamp) {
823
+ if (!minTimestamp || link.timestamp < minTimestamp) {
824
+ minTimestamp = link.timestamp;
825
+ originalAuthor = link.author;
826
+ }
827
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
828
+ maxTimestamp = link.timestamp;
829
+ latestAuthor = link.author;
830
+ }
795
831
  }
796
832
 
797
833
  // Handle resolveLanguage
@@ -854,17 +890,40 @@ export class Ad4mModel {
854
890
  (this as any)[collName] = values;
855
891
  }
856
892
 
857
- // Set author and timestamp
858
- if (latestAuthor) {
859
- (this as any).author = latestAuthor;
893
+ // Set author and timestamps
894
+ if (originalAuthor) {
895
+ (this as any).author = originalAuthor;
896
+ }
897
+ if (minTimestamp) {
898
+ (this as any).createdAt = minTimestamp;
860
899
  }
861
900
  if (maxTimestamp) {
862
- (this as any).timestamp = maxTimestamp;
901
+ (this as any).updatedAt = maxTimestamp;
863
902
  }
864
903
  }
865
904
 
866
905
  // Evaluate SurrealQL getters
867
906
  await ctor.evaluateSurrealGettersForInstance(this, this.#perspective, metadata);
907
+
908
+ // Apply where.isInstance filtering to surrealGetter collections
909
+ // (non-surrealGetter collections were already filtered above)
910
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
911
+ if (collMeta.surrealGetter && collMeta.where?.isInstance && (this as any)[collName]?.length > 0) {
912
+ try {
913
+ const className = typeof collMeta.where.isInstance === 'string'
914
+ ? collMeta.where.isInstance
915
+ : collMeta.where.isInstance.name;
916
+
917
+ const filterMetadata = await this.#perspective.getSubjectClassMetadataFromSDNA(className);
918
+ if (filterMetadata) {
919
+ const filtered = await this.#perspective.batchCheckSubjectInstances((this as any)[collName], filterMetadata);
920
+ (this as any)[collName] = filtered;
921
+ }
922
+ } catch (error) {
923
+ // Keep unfiltered values on error
924
+ }
925
+ }
926
+ }
868
927
  } catch (e) {
869
928
  console.error(`SurrealDB getData also failed for ${this.#baseExpression}:`, e);
870
929
  }
@@ -943,7 +1002,7 @@ export class Ad4mModel {
943
1002
  // Filter out 'None' from collection results
944
1003
  const value = result[0].value;
945
1004
  instance[collName] = Array.isArray(value)
946
- ? value.filter((v: any) => v && v !== '' && v !== 'None')
1005
+ ? value.filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None')
947
1006
  : value;
948
1007
  }
949
1008
  } catch (error) {
@@ -1378,8 +1437,9 @@ WHERE ${whereConditions.join(' AND ')}
1378
1437
  }
1379
1438
 
1380
1439
  // Always add author and timestamp fields
1381
- fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
1382
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
1440
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
1441
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
1442
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
1383
1443
 
1384
1444
  return fields.join(',\n ');
1385
1445
  }
@@ -1415,9 +1475,10 @@ WHERE ${whereConditions.join(' AND ')}
1415
1475
  fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
1416
1476
  }
1417
1477
 
1418
- // Always add author and timestamp fields using array::first
1478
+ // Always add author and timestamp fields
1419
1479
  fields.push(`array::first(author) AS author`);
1420
- fields.push(`array::first(timestamp) AS timestamp`);
1480
+ fields.push(`array::first(timestamp) AS createdAt`);
1481
+ fields.push(`array::last(timestamp) AS updatedAt`);
1421
1482
 
1422
1483
  return fields.join(',\n ');
1423
1484
  }
@@ -1477,7 +1538,7 @@ WHERE ${whereConditions.join(' AND ')}
1477
1538
  });
1478
1539
  }
1479
1540
  // Collect values to assign to instance
1480
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
1541
+ const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
1481
1542
  await Ad4mModel.assignValuesToInstance(perspective, instance, values);
1482
1543
 
1483
1544
  return instance;
@@ -1534,8 +1595,10 @@ WHERE ${whereConditions.join(' AND ')}
1534
1595
 
1535
1596
  const instance = new this(perspective, base) as any;
1536
1597
 
1537
- // Track the most recent timestamp and corresponding author
1598
+ // Track both earliest (createdAt) and most recent (updatedAt) timestamps
1599
+ let minTimestamp = null;
1538
1600
  let maxTimestamp = null;
1601
+ let originalAuthor = null;
1539
1602
  let latestAuthor = null;
1540
1603
 
1541
1604
  // Process each link (track index for collection ordering)
@@ -1547,10 +1610,16 @@ WHERE ${whereConditions.join(' AND ')}
1547
1610
  // Skip 'None' values
1548
1611
  if (target === 'None') continue;
1549
1612
 
1550
- // Track the most recent timestamp and its author
1551
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
1552
- maxTimestamp = link.timestamp;
1553
- latestAuthor = link.author;
1613
+ // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
1614
+ if (link.timestamp) {
1615
+ if (!minTimestamp || link.timestamp < minTimestamp) {
1616
+ minTimestamp = link.timestamp;
1617
+ originalAuthor = link.author;
1618
+ }
1619
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
1620
+ maxTimestamp = link.timestamp;
1621
+ latestAuthor = link.author;
1622
+ }
1554
1623
  }
1555
1624
 
1556
1625
  // Find matching property (skip those with surrealGetter)
@@ -1653,18 +1722,32 @@ WHERE ${whereConditions.join(' AND ')}
1653
1722
  }
1654
1723
  }
1655
1724
 
1656
- // Set author and timestamp from the most recent link
1657
- if (latestAuthor && maxTimestamp) {
1658
- instance.author = latestAuthor;
1659
- // Convert timestamp to number (milliseconds) if it's an ISO string
1725
+ // Set author and timestamps
1726
+ if (originalAuthor) {
1727
+ instance.author = originalAuthor;
1728
+ }
1729
+
1730
+ // Set createdAt from earliest timestamp
1731
+ if (minTimestamp) {
1732
+ if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
1733
+ instance.createdAt = new Date(minTimestamp).getTime();
1734
+ } else if (typeof minTimestamp === 'string') {
1735
+ const parsed = parseInt(minTimestamp, 10);
1736
+ instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
1737
+ } else {
1738
+ instance.createdAt = minTimestamp;
1739
+ }
1740
+ }
1741
+
1742
+ // Set updatedAt from most recent timestamp
1743
+ if (maxTimestamp) {
1660
1744
  if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
1661
- instance.timestamp = new Date(maxTimestamp).getTime();
1745
+ instance.updatedAt = new Date(maxTimestamp).getTime();
1662
1746
  } else if (typeof maxTimestamp === 'string') {
1663
- // Try to parse as number string
1664
1747
  const parsed = parseInt(maxTimestamp, 10);
1665
- instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
1748
+ instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
1666
1749
  } else {
1667
- instance.timestamp = maxTimestamp;
1750
+ instance.updatedAt = maxTimestamp;
1668
1751
  }
1669
1752
  }
1670
1753
 
@@ -1691,7 +1774,7 @@ WHERE ${whereConditions.join(' AND ')}
1691
1774
  // Replace collection with sorted values, filtering out empty strings and None
1692
1775
  instance[collName] = pairs
1693
1776
  .map(p => p.value)
1694
- .filter((v: any) => v && v !== '' && v !== 'None');
1777
+ .filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None');
1695
1778
  // Clean up temporary arrays
1696
1779
  delete instance[timestampsKey];
1697
1780
  delete instance[indicesKey];
@@ -1702,8 +1785,9 @@ WHERE ${whereConditions.join(' AND ')}
1702
1785
  if (requestedProperties.length > 0 || requestedCollections.length > 0) {
1703
1786
  const requestedAttributes = [...requestedProperties, ...requestedCollections];
1704
1787
  Object.keys(instance).forEach((key) => {
1705
- // Keep only requested attributes, plus always keep timestamp and author
1706
- if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
1788
+ // Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
1789
+ // Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
1790
+ if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
1707
1791
  delete instance[key];
1708
1792
  }
1709
1793
  });
@@ -1715,13 +1799,14 @@ WHERE ${whereConditions.join(' AND ')}
1715
1799
  }
1716
1800
  }
1717
1801
 
1718
- // Evaluate SurrealQL getters for all instances
1802
+ // Evaluate SurrealQL getters for all instances (single pass)
1803
+ // This populates collection values needed for where.isInstance filtering
1719
1804
  for (const instance of instances) {
1720
1805
  await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
1721
1806
  }
1722
1807
 
1723
1808
  // Filter collections by where.isInstance if specified
1724
- // Do this for all instances that have collections with filters
1809
+ // Do this after initial evaluation so collection values exist for filtering
1725
1810
  for (const instance of instances) {
1726
1811
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1727
1812
  if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
@@ -1742,6 +1827,7 @@ WHERE ${whereConditions.join(' AND ')}
1742
1827
  // Check which subjects are instances of the target class
1743
1828
  const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
1744
1829
 
1830
+ // Update the collection with filtered instances
1745
1831
  instance[collName] = validSubjects;
1746
1832
  } catch (error) {
1747
1833
  // On error, leave the collection unfiltered rather than breaking everything
@@ -1750,11 +1836,6 @@ WHERE ${whereConditions.join(' AND ')}
1750
1836
  }
1751
1837
  }
1752
1838
 
1753
- // Evaluate SurrealQL getters for all instances
1754
- for (const instance of instances) {
1755
- await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
1756
- }
1757
-
1758
1839
  // Filter by where conditions that couldn't be filtered in SQL
1759
1840
  // This includes:
1760
1841
  // - author/timestamp (computed from grouped links)