@coasys/ad4m 0.11.2-dev-sdna-only-prolog-2 → 0.11.2-dev.3

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
@@ -4486,43 +4486,11 @@ class Subject {
4486
4486
  let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property(C, Property)`);
4487
4487
  let properties = results.map(result => result.Property);
4488
4488
  for (let p of properties) {
4489
- const resolveExpressionURI = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4489
+ await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4490
4490
  Object.defineProperty(this, p, {
4491
4491
  configurable: true,
4492
4492
  get: async () => {
4493
- // Try Prolog first
4494
- try {
4495
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${p}", Value)`);
4496
- if (results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
4497
- let expressionURI = results[0].Value;
4498
- if (resolveExpressionURI) {
4499
- try {
4500
- if (expressionURI) {
4501
- const expression = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getExpression(expressionURI);
4502
- try {
4503
- return JSON.parse(expression.data);
4504
- }
4505
- catch (e) {
4506
- return expression.data;
4507
- }
4508
- }
4509
- else {
4510
- return expressionURI;
4511
- }
4512
- }
4513
- catch (err) {
4514
- return expressionURI;
4515
- }
4516
- }
4517
- else {
4518
- return expressionURI;
4519
- }
4520
- }
4521
- }
4522
- catch (err) {
4523
- // Prolog query failed, fall through to SurrealDB
4524
- }
4525
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4493
+ // Use SurrealDB for data queries
4526
4494
  try {
4527
4495
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), p);
4528
4496
  }
@@ -4561,20 +4529,7 @@ class Subject {
4561
4529
  Object.defineProperty(this, c, {
4562
4530
  configurable: true,
4563
4531
  get: async () => {
4564
- // Try Prolog first
4565
- try {
4566
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), collection_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${c}", Value)`);
4567
- if (results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
4568
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
4569
- if (collectionContent.length > 0) {
4570
- return collectionContent;
4571
- }
4572
- }
4573
- }
4574
- catch (err) {
4575
- // Prolog query failed, fall through to SurrealDB
4576
- }
4577
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4532
+ // Use SurrealDB for data queries
4578
4533
  try {
4579
4534
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), c);
4580
4535
  }
@@ -18957,6 +18912,7 @@ class Ad4mModel {
18957
18912
  ...(options.initial !== undefined && { initial: options.initial }),
18958
18913
  ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
18959
18914
  ...(options.getter !== undefined && { getter: options.getter }),
18915
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter }),
18960
18916
  ...(options.setter !== undefined && { setter: options.setter }),
18961
18917
  ...(options.local !== undefined && { local: options.local }),
18962
18918
  ...(options.transform !== undefined && { transform: options.transform }),
@@ -18972,7 +18928,8 @@ class Ad4mModel {
18972
18928
  name: collectionName,
18973
18929
  predicate: options.through || "",
18974
18930
  ...(options.where !== undefined && { where: options.where }),
18975
- ...(options.local !== undefined && { local: options.local })
18931
+ ...(options.local !== undefined && { local: options.local }),
18932
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter })
18976
18933
  };
18977
18934
  }
18978
18935
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -19079,6 +19036,10 @@ class Ad4mModel {
19079
19036
  * @private
19080
19037
  */
19081
19038
  generatePropertySetterAction(key, metadata) {
19039
+ // Check if property is read-only
19040
+ if (metadata.writable === false) {
19041
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
19042
+ }
19082
19043
  if (metadata.setter) {
19083
19044
  // Custom setter - throw error for now (Phase 2)
19084
19045
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -19171,32 +19132,16 @@ class Ad4mModel {
19171
19132
  }
19172
19133
  async getData() {
19173
19134
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
19174
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
19175
- const fullQuery = `
19176
- Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
19177
- subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
19178
- ${subQueries.join(", ")}
19179
- `;
19180
- // Try Prolog first
19181
- try {
19182
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
19183
- if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
19184
- const { Properties, Collections, Timestamp, Author } = result[0];
19185
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
19186
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
19187
- return this;
19188
- }
19189
- }
19190
- catch (e) {
19191
- console.log(`Prolog getData failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}, falling back to SurrealDB`);
19192
- }
19193
- // Fallback to SurrealDB (SdnaOnly mode)
19135
+ // Use SurrealDB for data queries
19194
19136
  try {
19195
19137
  const ctor = this.constructor;
19196
19138
  const metadata = ctor.getModelMetadata();
19197
19139
  // Query for all links from this specific node (base expression)
19198
19140
  // Using formatSurrealValue to prevent SQL injection by properly escaping the value
19199
19141
  const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
19142
+ // Note: We use ORDER BY timestamp ASC because:
19143
+ // - For collections: we want chronological order (oldest to newest)
19144
+ // - For properties: we select the LAST element to get "latest wins" semantics
19200
19145
  const linksQuery = `
19201
19146
  SELECT id, predicate, out.uri AS target, author, timestamp
19202
19147
  FROM link
@@ -19207,11 +19152,15 @@ class Ad4mModel {
19207
19152
  if (links && links.length > 0) {
19208
19153
  let maxTimestamp = null;
19209
19154
  let latestAuthor = null;
19210
- // Process properties
19155
+ // Process properties (skip those with surrealGetter)
19211
19156
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19157
+ if (propMeta.surrealGetter)
19158
+ continue; // Handle via surrealGetter evaluation
19212
19159
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19213
19160
  if (matching.length > 0) {
19214
- const link = matching[0]; // Take first/latest
19161
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
19162
+ // The last element has the most recent timestamp and represents the current property value.
19163
+ const link = matching[matching.length - 1];
19215
19164
  let value = link.target;
19216
19165
  // Track timestamp/author
19217
19166
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -19252,11 +19201,30 @@ class Ad4mModel {
19252
19201
  this[propName] = value;
19253
19202
  }
19254
19203
  }
19255
- // Process collections
19204
+ // Process collections (skip those with surrealGetter)
19256
19205
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19206
+ if (collMeta.surrealGetter)
19207
+ continue; // Handle via surrealGetter evaluation
19257
19208
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19258
- // Links are already sorted by timestamp ASC from the query, so map preserves order
19259
- this[collName] = matching.map((l) => l.target);
19209
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
19210
+ // so the collection reflects the order in which items were added (oldest to newest).
19211
+ let values = matching.map((l) => l.target);
19212
+ // Apply where.isInstance filtering if present
19213
+ if (collMeta.where?.isInstance && values.length > 0) {
19214
+ try {
19215
+ const className = typeof collMeta.where.isInstance === 'string'
19216
+ ? collMeta.where.isInstance
19217
+ : collMeta.where.isInstance.name;
19218
+ const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
19219
+ if (filterMetadata) {
19220
+ values = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(values, filterMetadata);
19221
+ }
19222
+ }
19223
+ catch (error) {
19224
+ // Keep unfiltered values on error
19225
+ }
19226
+ }
19227
+ this[collName] = values;
19260
19228
  }
19261
19229
  // Set author and timestamp
19262
19230
  if (latestAuthor) {
@@ -19266,6 +19234,8 @@ class Ad4mModel {
19266
19234
  this.timestamp = maxTimestamp;
19267
19235
  }
19268
19236
  }
19237
+ // Evaluate SurrealQL getters
19238
+ await ctor.evaluateSurrealGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
19269
19239
  }
19270
19240
  catch (e) {
19271
19241
  console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
@@ -19294,6 +19264,51 @@ class Ad4mModel {
19294
19264
  `;
19295
19265
  return fullQuery;
19296
19266
  }
19267
+ /**
19268
+ * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
19269
+ * @private
19270
+ */
19271
+ static async evaluateSurrealGettersForInstance(instance, perspective, metadata) {
19272
+ const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
19273
+ // Evaluate property surrealGetters
19274
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19275
+ if (propMeta.surrealGetter) {
19276
+ try {
19277
+ // Replace 'Base' placeholder with actual base expression
19278
+ const query = propMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19279
+ // Query from node table to have graph traversal context
19280
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19281
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
19282
+ instance[propName] = result[0].value;
19283
+ }
19284
+ }
19285
+ catch (error) {
19286
+ console.warn(`Failed to evaluate surrealGetter for ${propName}:`, error);
19287
+ }
19288
+ }
19289
+ }
19290
+ // Evaluate collection surrealGetters
19291
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19292
+ if (collMeta.surrealGetter) {
19293
+ try {
19294
+ // Replace 'Base' placeholder with actual base expression
19295
+ const query = collMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19296
+ // Query from node table to have graph traversal context
19297
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19298
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
19299
+ // Filter out 'None' from collection results
19300
+ const value = result[0].value;
19301
+ instance[collName] = Array.isArray(value)
19302
+ ? value.filter((v) => v && v !== '' && v !== 'None')
19303
+ : value;
19304
+ }
19305
+ }
19306
+ catch (error) {
19307
+ console.warn(`Failed to evaluate surrealGetter for ${collName}:`, error);
19308
+ }
19309
+ }
19310
+ }
19311
+ }
19297
19312
  /**
19298
19313
  * Generates a SurrealQL query from a Query object.
19299
19314
  *
@@ -19845,9 +19860,11 @@ WHERE ${whereConditions.join(' AND ')}
19845
19860
  maxTimestamp = link.timestamp;
19846
19861
  latestAuthor = link.author;
19847
19862
  }
19848
- // Find matching property
19863
+ // Find matching property (skip those with surrealGetter)
19849
19864
  let foundProperty = false;
19850
19865
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19866
+ if (propMeta.surrealGetter)
19867
+ continue; // Handle via surrealGetter evaluation
19851
19868
  if (propMeta.predicate === predicate) {
19852
19869
  // For properties, take the first value (or we could use timestamp to get latest)
19853
19870
  // Note: Empty objects {} are truthy, so we need to check for them explicitly
@@ -19917,9 +19934,11 @@ WHERE ${whereConditions.join(' AND ')}
19917
19934
  break;
19918
19935
  }
19919
19936
  }
19920
- // If not a property, check if it's a collection
19937
+ // If not a property, check if it's a collection (skip those with surrealGetter)
19921
19938
  if (!foundProperty) {
19922
19939
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19940
+ if (collMeta.surrealGetter)
19941
+ continue; // Handle via surrealGetter evaluation
19923
19942
  if (collMeta.predicate === predicate) {
19924
19943
  // For collections, accumulate all values with their timestamps and indices for sorting
19925
19944
  if (!instance[collName]) {
@@ -19982,8 +20001,10 @@ WHERE ${whereConditions.join(' AND ')}
19982
20001
  // Use original index as tiebreaker for stable sorting
19983
20002
  return a.originalIndex - b.originalIndex;
19984
20003
  });
19985
- // Replace collection with sorted values
19986
- instance[collName] = pairs.map(p => p.value);
20004
+ // Replace collection with sorted values, filtering out empty strings and None
20005
+ instance[collName] = pairs
20006
+ .map(p => p.value)
20007
+ .filter((v) => v && v !== '' && v !== 'None');
19987
20008
  // Clean up temporary arrays
19988
20009
  delete instance[timestampsKey];
19989
20010
  delete instance[indicesKey];
@@ -20005,6 +20026,40 @@ WHERE ${whereConditions.join(' AND ')}
20005
20026
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
20006
20027
  }
20007
20028
  }
20029
+ // Evaluate SurrealQL getters for all instances
20030
+ for (const instance of instances) {
20031
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20032
+ }
20033
+ // Filter collections by where.isInstance if specified
20034
+ // Do this for all instances that have collections with filters
20035
+ for (const instance of instances) {
20036
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
20037
+ if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
20038
+ try {
20039
+ const targetClass = collMeta.where.isInstance;
20040
+ const subjects = instance[collName];
20041
+ // Get the class metadata from SDNA to pass to batchCheckSubjectInstances
20042
+ const targetClassName = typeof targetClass === 'string'
20043
+ ? targetClass
20044
+ : targetClass.prototype?.className || targetClass.name;
20045
+ const classMetadata = await perspective.getSubjectClassMetadataFromSDNA(targetClassName);
20046
+ if (!classMetadata) {
20047
+ continue;
20048
+ }
20049
+ // Check which subjects are instances of the target class
20050
+ const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
20051
+ instance[collName] = validSubjects;
20052
+ }
20053
+ catch (error) {
20054
+ // On error, leave the collection unfiltered rather than breaking everything
20055
+ }
20056
+ }
20057
+ }
20058
+ }
20059
+ // Evaluate SurrealQL getters for all instances
20060
+ for (const instance of instances) {
20061
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20062
+ }
20008
20063
  // Filter by where conditions that couldn't be filtered in SQL
20009
20064
  // This includes:
20010
20065
  // - author/timestamp (computed from grouped links)
@@ -20345,7 +20400,7 @@ WHERE ${whereConditions.join(' AND ')}
20345
20400
  }
20346
20401
  // Generate actions from metadata (replaces Prolog query)
20347
20402
  const actions = this.generateCollectionAction(key, 'setter');
20348
- if (value) {
20403
+ if (value != null) {
20349
20404
  if (Array.isArray(value)) {
20350
20405
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20351
20406
  }
@@ -20363,7 +20418,7 @@ WHERE ${whereConditions.join(' AND ')}
20363
20418
  }
20364
20419
  // Generate actions from metadata (replaces Prolog query)
20365
20420
  const actions = this.generateCollectionAction(key, 'adder');
20366
- if (value) {
20421
+ if (value != null) {
20367
20422
  if (Array.isArray(value)) {
20368
20423
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20369
20424
  }
@@ -20381,7 +20436,7 @@ WHERE ${whereConditions.join(' AND ')}
20381
20436
  }
20382
20437
  // Generate actions from metadata (replaces Prolog query)
20383
20438
  const actions = this.generateCollectionAction(key, 'remover');
20384
- if (value) {
20439
+ if (value != null) {
20385
20440
  if (Array.isArray(value)) {
20386
20441
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20387
20442
  }
@@ -20471,11 +20526,8 @@ WHERE ${whereConditions.join(' AND ')}
20471
20526
  }
20472
20527
  }
20473
20528
  else if (Array.isArray(value)) {
20474
- // Handle all arrays as collections, even empty ones
20475
- if (value.length > 0) {
20476
- await this.setCollectionSetter(key, value, batchId);
20477
- }
20478
- // Skip empty arrays - don't try to set them as properties
20529
+ // Handle all arrays as collections, including empty ones (which clears the collection)
20530
+ await this.setCollectionSetter(key, value, batchId);
20479
20531
  }
20480
20532
  else if (value !== undefined && value !== null && value !== "") {
20481
20533
  if (setProperties) {
@@ -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
  }
@@ -335,6 +339,11 @@ export declare class Ad4mModel {
335
339
  static assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]): Promise<void>;
336
340
  private getData;
337
341
  static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
342
+ /**
343
+ * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
344
+ * @private
345
+ */
346
+ private static evaluateSurrealGettersForInstance;
338
347
  /**
339
348
  * Generates a SurrealQL query from a Query object.
340
349
  *