@coasys/ad4m 0.11.2-dev.2 → 0.11.2-dev.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -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
  *
@@ -18912,6 +18919,7 @@ class Ad4mModel {
18912
18919
  ...(options.initial !== undefined && { initial: options.initial }),
18913
18920
  ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
18914
18921
  ...(options.getter !== undefined && { getter: options.getter }),
18922
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter }),
18915
18923
  ...(options.setter !== undefined && { setter: options.setter }),
18916
18924
  ...(options.local !== undefined && { local: options.local }),
18917
18925
  ...(options.transform !== undefined && { transform: options.transform }),
@@ -18927,7 +18935,8 @@ class Ad4mModel {
18927
18935
  name: collectionName,
18928
18936
  predicate: options.through || "",
18929
18937
  ...(options.where !== undefined && { where: options.where }),
18930
- ...(options.local !== undefined && { local: options.local })
18938
+ ...(options.local !== undefined && { local: options.local }),
18939
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter })
18931
18940
  };
18932
18941
  }
18933
18942
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -19148,20 +19157,30 @@ class Ad4mModel {
19148
19157
  `;
19149
19158
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
19150
19159
  if (links && links.length > 0) {
19160
+ let minTimestamp = null;
19151
19161
  let maxTimestamp = null;
19152
19162
  let latestAuthor = null;
19153
- // Process properties
19163
+ let originalAuthor = null;
19164
+ // Process properties (skip those with surrealGetter)
19154
19165
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19166
+ if (propMeta.surrealGetter)
19167
+ continue; // Handle via surrealGetter evaluation
19155
19168
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19156
19169
  if (matching.length > 0) {
19157
19170
  // "Latest wins" semantics: select the last element since links are ordered ASC.
19158
19171
  // The last element has the most recent timestamp and represents the current property value.
19159
19172
  const link = matching[matching.length - 1];
19160
19173
  let value = link.target;
19161
- // Track timestamp/author
19162
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19163
- maxTimestamp = link.timestamp;
19164
- latestAuthor = link.author;
19174
+ // Track timestamps/authors for createdAt and updatedAt
19175
+ if (link.timestamp) {
19176
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19177
+ minTimestamp = link.timestamp;
19178
+ originalAuthor = link.author;
19179
+ }
19180
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19181
+ maxTimestamp = link.timestamp;
19182
+ latestAuthor = link.author;
19183
+ }
19165
19184
  }
19166
19185
  // Handle resolveLanguage
19167
19186
  if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
@@ -19197,21 +19216,44 @@ class Ad4mModel {
19197
19216
  this[propName] = value;
19198
19217
  }
19199
19218
  }
19200
- // Process collections
19219
+ // Process collections (skip those with surrealGetter)
19201
19220
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19221
+ if (collMeta.surrealGetter)
19222
+ continue; // Handle via surrealGetter evaluation
19202
19223
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19203
19224
  // Collections preserve chronological order: links are sorted ASC by timestamp,
19204
19225
  // so the collection reflects the order in which items were added (oldest to newest).
19205
- this[collName] = matching.map((l) => l.target);
19226
+ let values = matching.map((l) => l.target);
19227
+ // Apply where.isInstance filtering if present
19228
+ if (collMeta.where?.isInstance && values.length > 0) {
19229
+ try {
19230
+ const className = typeof collMeta.where.isInstance === 'string'
19231
+ ? collMeta.where.isInstance
19232
+ : collMeta.where.isInstance.name;
19233
+ const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
19234
+ if (filterMetadata) {
19235
+ values = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(values, filterMetadata);
19236
+ }
19237
+ }
19238
+ catch (error) {
19239
+ // Keep unfiltered values on error
19240
+ }
19241
+ }
19242
+ this[collName] = values;
19243
+ }
19244
+ // Set author and timestamps
19245
+ if (originalAuthor) {
19246
+ this.author = originalAuthor;
19206
19247
  }
19207
- // Set author and timestamp
19208
- if (latestAuthor) {
19209
- this.author = latestAuthor;
19248
+ if (minTimestamp) {
19249
+ this.createdAt = minTimestamp;
19210
19250
  }
19211
19251
  if (maxTimestamp) {
19212
- this.timestamp = maxTimestamp;
19252
+ this.updatedAt = maxTimestamp;
19213
19253
  }
19214
19254
  }
19255
+ // Evaluate SurrealQL getters
19256
+ await ctor.evaluateSurrealGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
19215
19257
  }
19216
19258
  catch (e) {
19217
19259
  console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
@@ -19240,6 +19282,51 @@ class Ad4mModel {
19240
19282
  `;
19241
19283
  return fullQuery;
19242
19284
  }
19285
+ /**
19286
+ * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
19287
+ * @private
19288
+ */
19289
+ static async evaluateSurrealGettersForInstance(instance, perspective, metadata) {
19290
+ const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
19291
+ // Evaluate property surrealGetters
19292
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19293
+ if (propMeta.surrealGetter) {
19294
+ try {
19295
+ // Replace 'Base' placeholder with actual base expression
19296
+ const query = propMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19297
+ // Query from node table to have graph traversal context
19298
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19299
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
19300
+ instance[propName] = result[0].value;
19301
+ }
19302
+ }
19303
+ catch (error) {
19304
+ console.warn(`Failed to evaluate surrealGetter for ${propName}:`, error);
19305
+ }
19306
+ }
19307
+ }
19308
+ // Evaluate collection surrealGetters
19309
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19310
+ if (collMeta.surrealGetter) {
19311
+ try {
19312
+ // Replace 'Base' placeholder with actual base expression
19313
+ const query = collMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19314
+ // Query from node table to have graph traversal context
19315
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19316
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
19317
+ // Filter out 'None' from collection results
19318
+ const value = result[0].value;
19319
+ instance[collName] = Array.isArray(value)
19320
+ ? value.filter((v) => v && v !== '' && v !== 'None')
19321
+ : value;
19322
+ }
19323
+ }
19324
+ catch (error) {
19325
+ console.warn(`Failed to evaluate surrealGetter for ${collName}:`, error);
19326
+ }
19327
+ }
19328
+ }
19329
+ }
19243
19330
  /**
19244
19331
  * Generates a SurrealQL query from a Query object.
19245
19332
  *
@@ -19642,8 +19729,9 @@ WHERE ${whereConditions.join(' AND ')}
19642
19729
  fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
19643
19730
  }
19644
19731
  // Always add author and timestamp fields
19645
- fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
19646
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
19732
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
19733
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
19734
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
19647
19735
  return fields.join(',\n ');
19648
19736
  }
19649
19737
  /**
@@ -19674,9 +19762,10 @@ WHERE ${whereConditions.join(' AND ')}
19674
19762
  const escapedPredicate = escapeSurrealString(collMeta.predicate);
19675
19763
  fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
19676
19764
  }
19677
- // Always add author and timestamp fields using array::first
19765
+ // Always add author and timestamp fields
19678
19766
  fields.push(`array::first(author) AS author`);
19679
- fields.push(`array::first(timestamp) AS timestamp`);
19767
+ fields.push(`array::first(timestamp) AS createdAt`);
19768
+ fields.push(`array::last(timestamp) AS updatedAt`);
19680
19769
  return fields.join(',\n ');
19681
19770
  }
19682
19771
  /**
@@ -19775,8 +19864,10 @@ WHERE ${whereConditions.join(' AND ')}
19775
19864
  }
19776
19865
  const links = row.links || [];
19777
19866
  const instance = new this(perspective, base);
19778
- // Track the most recent timestamp and corresponding author
19867
+ // Track both earliest (createdAt) and most recent (updatedAt) timestamps
19868
+ let minTimestamp = null;
19779
19869
  let maxTimestamp = null;
19870
+ let originalAuthor = null;
19780
19871
  let latestAuthor = null;
19781
19872
  // Process each link (track index for collection ordering)
19782
19873
  for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
@@ -19786,14 +19877,22 @@ WHERE ${whereConditions.join(' AND ')}
19786
19877
  // Skip 'None' values
19787
19878
  if (target === 'None')
19788
19879
  continue;
19789
- // Track the most recent timestamp and its author
19790
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19791
- maxTimestamp = link.timestamp;
19792
- latestAuthor = link.author;
19880
+ // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
19881
+ if (link.timestamp) {
19882
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19883
+ minTimestamp = link.timestamp;
19884
+ originalAuthor = link.author;
19885
+ }
19886
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19887
+ maxTimestamp = link.timestamp;
19888
+ latestAuthor = link.author;
19889
+ }
19793
19890
  }
19794
- // Find matching property
19891
+ // Find matching property (skip those with surrealGetter)
19795
19892
  let foundProperty = false;
19796
19893
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19894
+ if (propMeta.surrealGetter)
19895
+ continue; // Handle via surrealGetter evaluation
19797
19896
  if (propMeta.predicate === predicate) {
19798
19897
  // For properties, take the first value (or we could use timestamp to get latest)
19799
19898
  // Note: Empty objects {} are truthy, so we need to check for them explicitly
@@ -19863,9 +19962,11 @@ WHERE ${whereConditions.join(' AND ')}
19863
19962
  break;
19864
19963
  }
19865
19964
  }
19866
- // If not a property, check if it's a collection
19965
+ // If not a property, check if it's a collection (skip those with surrealGetter)
19867
19966
  if (!foundProperty) {
19868
19967
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19968
+ if (collMeta.surrealGetter)
19969
+ continue; // Handle via surrealGetter evaluation
19869
19970
  if (collMeta.predicate === predicate) {
19870
19971
  // For collections, accumulate all values with their timestamps and indices for sorting
19871
19972
  if (!instance[collName]) {
@@ -19891,20 +19992,34 @@ WHERE ${whereConditions.join(' AND ')}
19891
19992
  }
19892
19993
  }
19893
19994
  }
19894
- // Set author and timestamp from the most recent link
19895
- if (latestAuthor && maxTimestamp) {
19896
- instance.author = latestAuthor;
19897
- // Convert timestamp to number (milliseconds) if it's an ISO string
19995
+ // Set author and timestamps
19996
+ if (originalAuthor) {
19997
+ instance.author = originalAuthor;
19998
+ }
19999
+ // Set createdAt from earliest timestamp
20000
+ if (minTimestamp) {
20001
+ if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
20002
+ instance.createdAt = new Date(minTimestamp).getTime();
20003
+ }
20004
+ else if (typeof minTimestamp === 'string') {
20005
+ const parsed = parseInt(minTimestamp, 10);
20006
+ instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
20007
+ }
20008
+ else {
20009
+ instance.createdAt = minTimestamp;
20010
+ }
20011
+ }
20012
+ // Set updatedAt from most recent timestamp
20013
+ if (maxTimestamp) {
19898
20014
  if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
19899
- instance.timestamp = new Date(maxTimestamp).getTime();
20015
+ instance.updatedAt = new Date(maxTimestamp).getTime();
19900
20016
  }
19901
20017
  else if (typeof maxTimestamp === 'string') {
19902
- // Try to parse as number string
19903
20018
  const parsed = parseInt(maxTimestamp, 10);
19904
- instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
20019
+ instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
19905
20020
  }
19906
20021
  else {
19907
- instance.timestamp = maxTimestamp;
20022
+ instance.updatedAt = maxTimestamp;
19908
20023
  }
19909
20024
  }
19910
20025
  // Sort collections by timestamp to maintain insertion order
@@ -19928,8 +20043,10 @@ WHERE ${whereConditions.join(' AND ')}
19928
20043
  // Use original index as tiebreaker for stable sorting
19929
20044
  return a.originalIndex - b.originalIndex;
19930
20045
  });
19931
- // Replace collection with sorted values
19932
- instance[collName] = pairs.map(p => p.value);
20046
+ // Replace collection with sorted values, filtering out empty strings and None
20047
+ instance[collName] = pairs
20048
+ .map(p => p.value)
20049
+ .filter((v) => v && v !== '' && v !== 'None');
19933
20050
  // Clean up temporary arrays
19934
20051
  delete instance[timestampsKey];
19935
20052
  delete instance[indicesKey];
@@ -19951,6 +20068,40 @@ WHERE ${whereConditions.join(' AND ')}
19951
20068
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
19952
20069
  }
19953
20070
  }
20071
+ // Evaluate SurrealQL getters for all instances
20072
+ for (const instance of instances) {
20073
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20074
+ }
20075
+ // Filter collections by where.isInstance if specified
20076
+ // Do this for all instances that have collections with filters
20077
+ for (const instance of instances) {
20078
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
20079
+ if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
20080
+ try {
20081
+ const targetClass = collMeta.where.isInstance;
20082
+ const subjects = instance[collName];
20083
+ // Get the class metadata from SDNA to pass to batchCheckSubjectInstances
20084
+ const targetClassName = typeof targetClass === 'string'
20085
+ ? targetClass
20086
+ : targetClass.prototype?.className || targetClass.name;
20087
+ const classMetadata = await perspective.getSubjectClassMetadataFromSDNA(targetClassName);
20088
+ if (!classMetadata) {
20089
+ continue;
20090
+ }
20091
+ // Check which subjects are instances of the target class
20092
+ const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
20093
+ instance[collName] = validSubjects;
20094
+ }
20095
+ catch (error) {
20096
+ // On error, leave the collection unfiltered rather than breaking everything
20097
+ }
20098
+ }
20099
+ }
20100
+ }
20101
+ // Evaluate SurrealQL getters for all instances
20102
+ for (const instance of instances) {
20103
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20104
+ }
19954
20105
  // Filter by where conditions that couldn't be filtered in SQL
19955
20106
  // This includes:
19956
20107
  // - author/timestamp (computed from grouped links)
@@ -103,6 +103,8 @@ export interface PropertyMetadata {
103
103
  getter?: string;
104
104
  /** Custom Prolog setter code */
105
105
  setter?: string;
106
+ /** Custom SurrealQL getter code */
107
+ surrealGetter?: string;
106
108
  /** Whether stored locally only */
107
109
  local?: boolean;
108
110
  /** Transform function */
@@ -123,6 +125,8 @@ export interface CollectionMetadata {
123
125
  isInstance?: any;
124
126
  condition?: string;
125
127
  };
128
+ /** Custom SurrealQL getter code */
129
+ surrealGetter?: string;
126
130
  /** Whether stored locally only */
127
131
  local?: boolean;
128
132
  }
@@ -239,9 +243,15 @@ export interface ModelMetadata {
239
243
  export declare class Ad4mModel {
240
244
  #private;
241
245
  author: string;
242
- timestamp: string;
246
+ createdAt: any;
247
+ updatedAt: any;
243
248
  private static classNamesByClass;
244
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;
245
255
  /**
246
256
  * Extracts metadata from decorators for query building.
247
257
  *
@@ -335,6 +345,11 @@ export declare class Ad4mModel {
335
345
  static assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]): Promise<void>;
336
346
  private getData;
337
347
  static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
348
+ /**
349
+ * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
350
+ * @private
351
+ */
352
+ private static evaluateSurrealGettersForInstance;
338
353
  /**
339
354
  * Generates a SurrealQL query from a Query object.
340
355
  *