@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.cjs CHANGED
@@ -4490,43 +4490,11 @@ class Subject {
4490
4490
  let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property(C, Property)`);
4491
4491
  let properties = results.map(result => result.Property);
4492
4492
  for (let p of properties) {
4493
- const resolveExpressionURI = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4493
+ await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4494
4494
  Object.defineProperty(this, p, {
4495
4495
  configurable: true,
4496
4496
  get: async () => {
4497
- // Try Prolog first
4498
- try {
4499
- 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)`);
4500
- if (results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
4501
- let expressionURI = results[0].Value;
4502
- if (resolveExpressionURI) {
4503
- try {
4504
- if (expressionURI) {
4505
- const expression = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getExpression(expressionURI);
4506
- try {
4507
- return JSON.parse(expression.data);
4508
- }
4509
- catch (e) {
4510
- return expression.data;
4511
- }
4512
- }
4513
- else {
4514
- return expressionURI;
4515
- }
4516
- }
4517
- catch (err) {
4518
- return expressionURI;
4519
- }
4520
- }
4521
- else {
4522
- return expressionURI;
4523
- }
4524
- }
4525
- }
4526
- catch (err) {
4527
- // Prolog query failed, fall through to SurrealDB
4528
- }
4529
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4497
+ // Use SurrealDB for data queries
4530
4498
  try {
4531
4499
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), p);
4532
4500
  }
@@ -4565,20 +4533,7 @@ class Subject {
4565
4533
  Object.defineProperty(this, c, {
4566
4534
  configurable: true,
4567
4535
  get: async () => {
4568
- // Try Prolog first
4569
- try {
4570
- 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)`);
4571
- if (results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
4572
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
4573
- if (collectionContent.length > 0) {
4574
- return collectionContent;
4575
- }
4576
- }
4577
- }
4578
- catch (err) {
4579
- // Prolog query failed, fall through to SurrealDB
4580
- }
4581
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
4536
+ // Use SurrealDB for data queries
4582
4537
  try {
4583
4538
  return await __classPrivateFieldGet$b(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"), c);
4584
4539
  }
@@ -18961,6 +18916,7 @@ class Ad4mModel {
18961
18916
  ...(options.initial !== undefined && { initial: options.initial }),
18962
18917
  ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
18963
18918
  ...(options.getter !== undefined && { getter: options.getter }),
18919
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter }),
18964
18920
  ...(options.setter !== undefined && { setter: options.setter }),
18965
18921
  ...(options.local !== undefined && { local: options.local }),
18966
18922
  ...(options.transform !== undefined && { transform: options.transform }),
@@ -18976,7 +18932,8 @@ class Ad4mModel {
18976
18932
  name: collectionName,
18977
18933
  predicate: options.through || "",
18978
18934
  ...(options.where !== undefined && { where: options.where }),
18979
- ...(options.local !== undefined && { local: options.local })
18935
+ ...(options.local !== undefined && { local: options.local }),
18936
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter })
18980
18937
  };
18981
18938
  }
18982
18939
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -19083,6 +19040,10 @@ class Ad4mModel {
19083
19040
  * @private
19084
19041
  */
19085
19042
  generatePropertySetterAction(key, metadata) {
19043
+ // Check if property is read-only
19044
+ if (metadata.writable === false) {
19045
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
19046
+ }
19086
19047
  if (metadata.setter) {
19087
19048
  // Custom setter - throw error for now (Phase 2)
19088
19049
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -19175,32 +19136,16 @@ class Ad4mModel {
19175
19136
  }
19176
19137
  async getData() {
19177
19138
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
19178
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
19179
- const fullQuery = `
19180
- Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
19181
- subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
19182
- ${subQueries.join(", ")}
19183
- `;
19184
- // Try Prolog first
19185
- try {
19186
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
19187
- if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
19188
- const { Properties, Collections, Timestamp, Author } = result[0];
19189
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
19190
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
19191
- return this;
19192
- }
19193
- }
19194
- catch (e) {
19195
- console.log(`Prolog getData failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}, falling back to SurrealDB`);
19196
- }
19197
- // Fallback to SurrealDB (SdnaOnly mode)
19139
+ // Use SurrealDB for data queries
19198
19140
  try {
19199
19141
  const ctor = this.constructor;
19200
19142
  const metadata = ctor.getModelMetadata();
19201
19143
  // Query for all links from this specific node (base expression)
19202
19144
  // Using formatSurrealValue to prevent SQL injection by properly escaping the value
19203
19145
  const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
19146
+ // Note: We use ORDER BY timestamp ASC because:
19147
+ // - For collections: we want chronological order (oldest to newest)
19148
+ // - For properties: we select the LAST element to get "latest wins" semantics
19204
19149
  const linksQuery = `
19205
19150
  SELECT id, predicate, out.uri AS target, author, timestamp
19206
19151
  FROM link
@@ -19211,11 +19156,15 @@ class Ad4mModel {
19211
19156
  if (links && links.length > 0) {
19212
19157
  let maxTimestamp = null;
19213
19158
  let latestAuthor = null;
19214
- // Process properties
19159
+ // Process properties (skip those with surrealGetter)
19215
19160
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19161
+ if (propMeta.surrealGetter)
19162
+ continue; // Handle via surrealGetter evaluation
19216
19163
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19217
19164
  if (matching.length > 0) {
19218
- const link = matching[0]; // Take first/latest
19165
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
19166
+ // The last element has the most recent timestamp and represents the current property value.
19167
+ const link = matching[matching.length - 1];
19219
19168
  let value = link.target;
19220
19169
  // Track timestamp/author
19221
19170
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -19256,11 +19205,30 @@ class Ad4mModel {
19256
19205
  this[propName] = value;
19257
19206
  }
19258
19207
  }
19259
- // Process collections
19208
+ // Process collections (skip those with surrealGetter)
19260
19209
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19210
+ if (collMeta.surrealGetter)
19211
+ continue; // Handle via surrealGetter evaluation
19261
19212
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19262
- // Links are already sorted by timestamp ASC from the query, so map preserves order
19263
- this[collName] = matching.map((l) => l.target);
19213
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
19214
+ // so the collection reflects the order in which items were added (oldest to newest).
19215
+ let values = matching.map((l) => l.target);
19216
+ // Apply where.isInstance filtering if present
19217
+ if (collMeta.where?.isInstance && values.length > 0) {
19218
+ try {
19219
+ const className = typeof collMeta.where.isInstance === 'string'
19220
+ ? collMeta.where.isInstance
19221
+ : collMeta.where.isInstance.name;
19222
+ const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
19223
+ if (filterMetadata) {
19224
+ values = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(values, filterMetadata);
19225
+ }
19226
+ }
19227
+ catch (error) {
19228
+ // Keep unfiltered values on error
19229
+ }
19230
+ }
19231
+ this[collName] = values;
19264
19232
  }
19265
19233
  // Set author and timestamp
19266
19234
  if (latestAuthor) {
@@ -19270,6 +19238,8 @@ class Ad4mModel {
19270
19238
  this.timestamp = maxTimestamp;
19271
19239
  }
19272
19240
  }
19241
+ // Evaluate SurrealQL getters
19242
+ await ctor.evaluateSurrealGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
19273
19243
  }
19274
19244
  catch (e) {
19275
19245
  console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
@@ -19298,6 +19268,51 @@ class Ad4mModel {
19298
19268
  `;
19299
19269
  return fullQuery;
19300
19270
  }
19271
+ /**
19272
+ * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
19273
+ * @private
19274
+ */
19275
+ static async evaluateSurrealGettersForInstance(instance, perspective, metadata) {
19276
+ const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
19277
+ // Evaluate property surrealGetters
19278
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19279
+ if (propMeta.surrealGetter) {
19280
+ try {
19281
+ // Replace 'Base' placeholder with actual base expression
19282
+ const query = propMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19283
+ // Query from node table to have graph traversal context
19284
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19285
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
19286
+ instance[propName] = result[0].value;
19287
+ }
19288
+ }
19289
+ catch (error) {
19290
+ console.warn(`Failed to evaluate surrealGetter for ${propName}:`, error);
19291
+ }
19292
+ }
19293
+ }
19294
+ // Evaluate collection surrealGetters
19295
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19296
+ if (collMeta.surrealGetter) {
19297
+ try {
19298
+ // Replace 'Base' placeholder with actual base expression
19299
+ const query = collMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19300
+ // Query from node table to have graph traversal context
19301
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19302
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
19303
+ // Filter out 'None' from collection results
19304
+ const value = result[0].value;
19305
+ instance[collName] = Array.isArray(value)
19306
+ ? value.filter((v) => v && v !== '' && v !== 'None')
19307
+ : value;
19308
+ }
19309
+ }
19310
+ catch (error) {
19311
+ console.warn(`Failed to evaluate surrealGetter for ${collName}:`, error);
19312
+ }
19313
+ }
19314
+ }
19315
+ }
19301
19316
  /**
19302
19317
  * Generates a SurrealQL query from a Query object.
19303
19318
  *
@@ -19849,9 +19864,11 @@ WHERE ${whereConditions.join(' AND ')}
19849
19864
  maxTimestamp = link.timestamp;
19850
19865
  latestAuthor = link.author;
19851
19866
  }
19852
- // Find matching property
19867
+ // Find matching property (skip those with surrealGetter)
19853
19868
  let foundProperty = false;
19854
19869
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19870
+ if (propMeta.surrealGetter)
19871
+ continue; // Handle via surrealGetter evaluation
19855
19872
  if (propMeta.predicate === predicate) {
19856
19873
  // For properties, take the first value (or we could use timestamp to get latest)
19857
19874
  // Note: Empty objects {} are truthy, so we need to check for them explicitly
@@ -19921,9 +19938,11 @@ WHERE ${whereConditions.join(' AND ')}
19921
19938
  break;
19922
19939
  }
19923
19940
  }
19924
- // If not a property, check if it's a collection
19941
+ // If not a property, check if it's a collection (skip those with surrealGetter)
19925
19942
  if (!foundProperty) {
19926
19943
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19944
+ if (collMeta.surrealGetter)
19945
+ continue; // Handle via surrealGetter evaluation
19927
19946
  if (collMeta.predicate === predicate) {
19928
19947
  // For collections, accumulate all values with their timestamps and indices for sorting
19929
19948
  if (!instance[collName]) {
@@ -19986,8 +20005,10 @@ WHERE ${whereConditions.join(' AND ')}
19986
20005
  // Use original index as tiebreaker for stable sorting
19987
20006
  return a.originalIndex - b.originalIndex;
19988
20007
  });
19989
- // Replace collection with sorted values
19990
- instance[collName] = pairs.map(p => p.value);
20008
+ // Replace collection with sorted values, filtering out empty strings and None
20009
+ instance[collName] = pairs
20010
+ .map(p => p.value)
20011
+ .filter((v) => v && v !== '' && v !== 'None');
19991
20012
  // Clean up temporary arrays
19992
20013
  delete instance[timestampsKey];
19993
20014
  delete instance[indicesKey];
@@ -20009,6 +20030,40 @@ WHERE ${whereConditions.join(' AND ')}
20009
20030
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
20010
20031
  }
20011
20032
  }
20033
+ // Evaluate SurrealQL getters for all instances
20034
+ for (const instance of instances) {
20035
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20036
+ }
20037
+ // Filter collections by where.isInstance if specified
20038
+ // Do this for all instances that have collections with filters
20039
+ for (const instance of instances) {
20040
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
20041
+ if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
20042
+ try {
20043
+ const targetClass = collMeta.where.isInstance;
20044
+ const subjects = instance[collName];
20045
+ // Get the class metadata from SDNA to pass to batchCheckSubjectInstances
20046
+ const targetClassName = typeof targetClass === 'string'
20047
+ ? targetClass
20048
+ : targetClass.prototype?.className || targetClass.name;
20049
+ const classMetadata = await perspective.getSubjectClassMetadataFromSDNA(targetClassName);
20050
+ if (!classMetadata) {
20051
+ continue;
20052
+ }
20053
+ // Check which subjects are instances of the target class
20054
+ const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
20055
+ instance[collName] = validSubjects;
20056
+ }
20057
+ catch (error) {
20058
+ // On error, leave the collection unfiltered rather than breaking everything
20059
+ }
20060
+ }
20061
+ }
20062
+ }
20063
+ // Evaluate SurrealQL getters for all instances
20064
+ for (const instance of instances) {
20065
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20066
+ }
20012
20067
  // Filter by where conditions that couldn't be filtered in SQL
20013
20068
  // This includes:
20014
20069
  // - author/timestamp (computed from grouped links)
@@ -20349,7 +20404,7 @@ WHERE ${whereConditions.join(' AND ')}
20349
20404
  }
20350
20405
  // Generate actions from metadata (replaces Prolog query)
20351
20406
  const actions = this.generateCollectionAction(key, 'setter');
20352
- if (value) {
20407
+ if (value != null) {
20353
20408
  if (Array.isArray(value)) {
20354
20409
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20355
20410
  }
@@ -20367,7 +20422,7 @@ WHERE ${whereConditions.join(' AND ')}
20367
20422
  }
20368
20423
  // Generate actions from metadata (replaces Prolog query)
20369
20424
  const actions = this.generateCollectionAction(key, 'adder');
20370
- if (value) {
20425
+ if (value != null) {
20371
20426
  if (Array.isArray(value)) {
20372
20427
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20373
20428
  }
@@ -20385,7 +20440,7 @@ WHERE ${whereConditions.join(' AND ')}
20385
20440
  }
20386
20441
  // Generate actions from metadata (replaces Prolog query)
20387
20442
  const actions = this.generateCollectionAction(key, 'remover');
20388
- if (value) {
20443
+ if (value != null) {
20389
20444
  if (Array.isArray(value)) {
20390
20445
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20391
20446
  }
@@ -20475,11 +20530,8 @@ WHERE ${whereConditions.join(' AND ')}
20475
20530
  }
20476
20531
  }
20477
20532
  else if (Array.isArray(value)) {
20478
- // Handle all arrays as collections, even empty ones
20479
- if (value.length > 0) {
20480
- await this.setCollectionSetter(key, value, batchId);
20481
- }
20482
- // Skip empty arrays - don't try to set them as properties
20533
+ // Handle all arrays as collections, including empty ones (which clears the collection)
20534
+ await this.setCollectionSetter(key, value, batchId);
20483
20535
  }
20484
20536
  else if (value !== undefined && value !== null && value !== "") {
20485
20537
  if (setProperties) {