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

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
  }
@@ -19083,6 +19038,10 @@ class Ad4mModel {
19083
19038
  * @private
19084
19039
  */
19085
19040
  generatePropertySetterAction(key, metadata) {
19041
+ // Check if property is read-only
19042
+ if (metadata.writable === false) {
19043
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
19044
+ }
19086
19045
  if (metadata.setter) {
19087
19046
  // Custom setter - throw error for now (Phase 2)
19088
19047
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -19175,32 +19134,16 @@ class Ad4mModel {
19175
19134
  }
19176
19135
  async getData() {
19177
19136
  // 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)
19137
+ // Use SurrealDB for data queries
19198
19138
  try {
19199
19139
  const ctor = this.constructor;
19200
19140
  const metadata = ctor.getModelMetadata();
19201
19141
  // Query for all links from this specific node (base expression)
19202
19142
  // Using formatSurrealValue to prevent SQL injection by properly escaping the value
19203
19143
  const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
19144
+ // Note: We use ORDER BY timestamp ASC because:
19145
+ // - For collections: we want chronological order (oldest to newest)
19146
+ // - For properties: we select the LAST element to get "latest wins" semantics
19204
19147
  const linksQuery = `
19205
19148
  SELECT id, predicate, out.uri AS target, author, timestamp
19206
19149
  FROM link
@@ -19215,7 +19158,9 @@ class Ad4mModel {
19215
19158
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19216
19159
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19217
19160
  if (matching.length > 0) {
19218
- 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];
19219
19164
  let value = link.target;
19220
19165
  // Track timestamp/author
19221
19166
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -19259,7 +19204,8 @@ class Ad4mModel {
19259
19204
  // Process collections
19260
19205
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19261
19206
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19262
- // Links are already sorted by timestamp ASC from the query, so map preserves order
19207
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
19208
+ // so the collection reflects the order in which items were added (oldest to newest).
19263
19209
  this[collName] = matching.map((l) => l.target);
19264
19210
  }
19265
19211
  // Set author and timestamp
@@ -20349,7 +20295,7 @@ WHERE ${whereConditions.join(' AND ')}
20349
20295
  }
20350
20296
  // Generate actions from metadata (replaces Prolog query)
20351
20297
  const actions = this.generateCollectionAction(key, 'setter');
20352
- if (value) {
20298
+ if (value != null) {
20353
20299
  if (Array.isArray(value)) {
20354
20300
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20355
20301
  }
@@ -20367,7 +20313,7 @@ WHERE ${whereConditions.join(' AND ')}
20367
20313
  }
20368
20314
  // Generate actions from metadata (replaces Prolog query)
20369
20315
  const actions = this.generateCollectionAction(key, 'adder');
20370
- if (value) {
20316
+ if (value != null) {
20371
20317
  if (Array.isArray(value)) {
20372
20318
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20373
20319
  }
@@ -20385,7 +20331,7 @@ WHERE ${whereConditions.join(' AND ')}
20385
20331
  }
20386
20332
  // Generate actions from metadata (replaces Prolog query)
20387
20333
  const actions = this.generateCollectionAction(key, 'remover');
20388
- if (value) {
20334
+ if (value != null) {
20389
20335
  if (Array.isArray(value)) {
20390
20336
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20391
20337
  }
@@ -20475,11 +20421,8 @@ WHERE ${whereConditions.join(' AND ')}
20475
20421
  }
20476
20422
  }
20477
20423
  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
20424
+ // Handle all arrays as collections, including empty ones (which clears the collection)
20425
+ await this.setCollectionSetter(key, value, batchId);
20483
20426
  }
20484
20427
  else if (value !== undefined && value !== null && value !== "") {
20485
20428
  if (setProperties) {
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
  }
@@ -19079,6 +19034,10 @@ class Ad4mModel {
19079
19034
  * @private
19080
19035
  */
19081
19036
  generatePropertySetterAction(key, metadata) {
19037
+ // Check if property is read-only
19038
+ if (metadata.writable === false) {
19039
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
19040
+ }
19082
19041
  if (metadata.setter) {
19083
19042
  // Custom setter - throw error for now (Phase 2)
19084
19043
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -19171,32 +19130,16 @@ class Ad4mModel {
19171
19130
  }
19172
19131
  async getData() {
19173
19132
  // 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)
19133
+ // Use SurrealDB for data queries
19194
19134
  try {
19195
19135
  const ctor = this.constructor;
19196
19136
  const metadata = ctor.getModelMetadata();
19197
19137
  // Query for all links from this specific node (base expression)
19198
19138
  // Using formatSurrealValue to prevent SQL injection by properly escaping the value
19199
19139
  const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
19140
+ // Note: We use ORDER BY timestamp ASC because:
19141
+ // - For collections: we want chronological order (oldest to newest)
19142
+ // - For properties: we select the LAST element to get "latest wins" semantics
19200
19143
  const linksQuery = `
19201
19144
  SELECT id, predicate, out.uri AS target, author, timestamp
19202
19145
  FROM link
@@ -19211,7 +19154,9 @@ class Ad4mModel {
19211
19154
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19212
19155
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19213
19156
  if (matching.length > 0) {
19214
- const link = matching[0]; // Take first/latest
19157
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
19158
+ // The last element has the most recent timestamp and represents the current property value.
19159
+ const link = matching[matching.length - 1];
19215
19160
  let value = link.target;
19216
19161
  // Track timestamp/author
19217
19162
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -19255,7 +19200,8 @@ class Ad4mModel {
19255
19200
  // Process collections
19256
19201
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19257
19202
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19258
- // Links are already sorted by timestamp ASC from the query, so map preserves order
19203
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
19204
+ // so the collection reflects the order in which items were added (oldest to newest).
19259
19205
  this[collName] = matching.map((l) => l.target);
19260
19206
  }
19261
19207
  // Set author and timestamp
@@ -20345,7 +20291,7 @@ WHERE ${whereConditions.join(' AND ')}
20345
20291
  }
20346
20292
  // Generate actions from metadata (replaces Prolog query)
20347
20293
  const actions = this.generateCollectionAction(key, 'setter');
20348
- if (value) {
20294
+ if (value != null) {
20349
20295
  if (Array.isArray(value)) {
20350
20296
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
20351
20297
  }
@@ -20363,7 +20309,7 @@ WHERE ${whereConditions.join(' AND ')}
20363
20309
  }
20364
20310
  // Generate actions from metadata (replaces Prolog query)
20365
20311
  const actions = this.generateCollectionAction(key, 'adder');
20366
- if (value) {
20312
+ if (value != null) {
20367
20313
  if (Array.isArray(value)) {
20368
20314
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20369
20315
  }
@@ -20381,7 +20327,7 @@ WHERE ${whereConditions.join(' AND ')}
20381
20327
  }
20382
20328
  // Generate actions from metadata (replaces Prolog query)
20383
20329
  const actions = this.generateCollectionAction(key, 'remover');
20384
- if (value) {
20330
+ if (value != null) {
20385
20331
  if (Array.isArray(value)) {
20386
20332
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
20387
20333
  }
@@ -20471,11 +20417,8 @@ WHERE ${whereConditions.join(' AND ')}
20471
20417
  }
20472
20418
  }
20473
20419
  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
20420
+ // Handle all arrays as collections, including empty ones (which clears the collection)
20421
+ await this.setCollectionSetter(key, value, batchId);
20479
20422
  }
20480
20423
  else if (value !== undefined && value !== null && value !== "") {
20481
20424
  if (setProperties) {
@@ -489,6 +489,10 @@ export class Ad4mModel {
489
489
  * @private
490
490
  */
491
491
  generatePropertySetterAction(key, metadata) {
492
+ // Check if property is read-only
493
+ if (metadata.writable === false) {
494
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
495
+ }
492
496
  if (metadata.setter) {
493
497
  // Custom setter - throw error for now (Phase 2)
494
498
  throw new Error(`Custom setter for property "${key}" not yet supported without Prolog. ` +
@@ -581,32 +585,16 @@ export class Ad4mModel {
581
585
  }
582
586
  async getData() {
583
587
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
584
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
585
- const fullQuery = `
586
- Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
587
- subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
588
- ${subQueries.join(", ")}
589
- `;
590
- // Try Prolog first
591
- try {
592
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
593
- if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
594
- const { Properties, Collections, Timestamp, Author } = result[0];
595
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
596
- await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
597
- return this;
598
- }
599
- }
600
- catch (e) {
601
- console.log(`Prolog getData failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}, falling back to SurrealDB`);
602
- }
603
- // Fallback to SurrealDB (SdnaOnly mode)
588
+ // Use SurrealDB for data queries
604
589
  try {
605
590
  const ctor = this.constructor;
606
591
  const metadata = ctor.getModelMetadata();
607
592
  // Query for all links from this specific node (base expression)
608
593
  // Using formatSurrealValue to prevent SQL injection by properly escaping the value
609
594
  const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
595
+ // Note: We use ORDER BY timestamp ASC because:
596
+ // - For collections: we want chronological order (oldest to newest)
597
+ // - For properties: we select the LAST element to get "latest wins" semantics
610
598
  const linksQuery = `
611
599
  SELECT id, predicate, out.uri AS target, author, timestamp
612
600
  FROM link
@@ -621,7 +609,9 @@ export class Ad4mModel {
621
609
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
622
610
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
623
611
  if (matching.length > 0) {
624
- const link = matching[0]; // Take first/latest
612
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
613
+ // The last element has the most recent timestamp and represents the current property value.
614
+ const link = matching[matching.length - 1];
625
615
  let value = link.target;
626
616
  // Track timestamp/author
627
617
  if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
@@ -665,7 +655,8 @@ export class Ad4mModel {
665
655
  // Process collections
666
656
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
667
657
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
668
- // Links are already sorted by timestamp ASC from the query, so map preserves order
658
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
659
+ // so the collection reflects the order in which items were added (oldest to newest).
669
660
  this[collName] = matching.map((l) => l.target);
670
661
  }
671
662
  // Set author and timestamp
@@ -1755,7 +1746,7 @@ WHERE ${whereConditions.join(' AND ')}
1755
1746
  }
1756
1747
  // Generate actions from metadata (replaces Prolog query)
1757
1748
  const actions = this.generateCollectionAction(key, 'setter');
1758
- if (value) {
1749
+ if (value != null) {
1759
1750
  if (Array.isArray(value)) {
1760
1751
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
1761
1752
  }
@@ -1773,7 +1764,7 @@ WHERE ${whereConditions.join(' AND ')}
1773
1764
  }
1774
1765
  // Generate actions from metadata (replaces Prolog query)
1775
1766
  const actions = this.generateCollectionAction(key, 'adder');
1776
- if (value) {
1767
+ if (value != null) {
1777
1768
  if (Array.isArray(value)) {
1778
1769
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
1779
1770
  }
@@ -1791,7 +1782,7 @@ WHERE ${whereConditions.join(' AND ')}
1791
1782
  }
1792
1783
  // Generate actions from metadata (replaces Prolog query)
1793
1784
  const actions = this.generateCollectionAction(key, 'remover');
1794
- if (value) {
1785
+ if (value != null) {
1795
1786
  if (Array.isArray(value)) {
1796
1787
  await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
1797
1788
  }
@@ -1881,11 +1872,8 @@ WHERE ${whereConditions.join(' AND ')}
1881
1872
  }
1882
1873
  }
1883
1874
  else if (Array.isArray(value)) {
1884
- // Handle all arrays as collections, even empty ones
1885
- if (value.length > 0) {
1886
- await this.setCollectionSetter(key, value, batchId);
1887
- }
1888
- // Skip empty arrays - don't try to set them as properties
1875
+ // Handle all arrays as collections, including empty ones (which clears the collection)
1876
+ await this.setCollectionSetter(key, value, batchId);
1889
1877
  }
1890
1878
  else if (value !== undefined && value !== null && value !== "") {
1891
1879
  if (setProperties) {
@@ -55,39 +55,7 @@ export class Subject {
55
55
  Object.defineProperty(this, p, {
56
56
  configurable: true,
57
57
  get: async () => {
58
- // Try Prolog first
59
- try {
60
- let results = await __classPrivateFieldGet(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Subject_subjectClassName, "f")}", C), property_getter(C, "${__classPrivateFieldGet(this, _Subject_baseExpression, "f")}", "${p}", Value)`);
61
- if (results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
62
- let expressionURI = results[0].Value;
63
- if (resolveExpressionURI) {
64
- try {
65
- if (expressionURI) {
66
- const expression = await __classPrivateFieldGet(this, _Subject_perspective, "f").getExpression(expressionURI);
67
- try {
68
- return JSON.parse(expression.data);
69
- }
70
- catch (e) {
71
- return expression.data;
72
- }
73
- }
74
- else {
75
- return expressionURI;
76
- }
77
- }
78
- catch (err) {
79
- return expressionURI;
80
- }
81
- }
82
- else {
83
- return expressionURI;
84
- }
85
- }
86
- }
87
- catch (err) {
88
- // Prolog query failed, fall through to SurrealDB
89
- }
90
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
58
+ // Use SurrealDB for data queries
91
59
  try {
92
60
  return await __classPrivateFieldGet(this, _Subject_perspective, "f").getPropertyValueViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), p);
93
61
  }
@@ -126,20 +94,7 @@ export class Subject {
126
94
  Object.defineProperty(this, c, {
127
95
  configurable: true,
128
96
  get: async () => {
129
- // Try Prolog first
130
- try {
131
- let results = await __classPrivateFieldGet(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Subject_subjectClassName, "f")}", C), collection_getter(C, "${__classPrivateFieldGet(this, _Subject_baseExpression, "f")}", "${c}", Value)`);
132
- if (results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
133
- let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
134
- if (collectionContent.length > 0) {
135
- return collectionContent;
136
- }
137
- }
138
- }
139
- catch (err) {
140
- // Prolog query failed, fall through to SurrealDB
141
- }
142
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
97
+ // Use SurrealDB for data queries
143
98
  try {
144
99
  return await __classPrivateFieldGet(this, _Subject_perspective, "f").getCollectionValuesViaSurreal(__classPrivateFieldGet(this, _Subject_baseExpression, "f"), __classPrivateFieldGet(this, _Subject_subjectClassName, "f"), c);
145
100
  }
package/package.json CHANGED
@@ -5,13 +5,7 @@
5
5
  "module": "lib/index.js",
6
6
  "types": "lib/src/index.d.ts",
7
7
  "type": "module",
8
-
9
- "scripts": {
10
- "build": "patch-package && tsc && pnpm run buildSchema && pnpm run bundle",
11
- "buildSchema": "node --es-module-specifier-resolution=node lib/src/buildSchema.js",
12
- "bundle": "rollup -c rollup.config.js",
13
- "test": "jest --forceExit"
14
- },
8
+ "private": false,
15
9
  "repository": {
16
10
  "type": "git",
17
11
  "url": "git+https://github.com/coasys/ad4m.git"
@@ -64,10 +58,11 @@
64
58
  "react-dom": "*"
65
59
  },
66
60
  "patchedDependencies": {},
67
- "pnpm": {
68
- "patchedDependencies": {
69
- "graphql@15.7.2": "patches/graphql@15.7.2.patch"
70
- }
71
- },
72
- "version": "0.11.2-dev-sdna-only-prolog-2"
73
- }
61
+ "version": "0.11.2-dev.2",
62
+ "scripts": {
63
+ "build": "patch-package && tsc && pnpm run buildSchema && pnpm run bundle",
64
+ "buildSchema": "node --es-module-specifier-resolution=node lib/src/buildSchema.js",
65
+ "bundle": "rollup -c rollup.config.js",
66
+ "test": "jest --forceExit"
67
+ }
68
+ }
@@ -639,6 +639,11 @@ export class Ad4mModel {
639
639
  * @private
640
640
  */
641
641
  private generatePropertySetterAction(key: string, metadata: PropertyOptions): any[] {
642
+ // Check if property is read-only
643
+ if (metadata.writable === false) {
644
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
645
+ }
646
+
642
647
  if (metadata.setter) {
643
648
  // Custom setter - throw error for now (Phase 2)
644
649
  throw new Error(
@@ -744,27 +749,7 @@ export class Ad4mModel {
744
749
 
745
750
  private async getData() {
746
751
  // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
747
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
748
- const fullQuery = `
749
- Base = "${this.#baseExpression}",
750
- subject_class("${this.#subjectClassName}", SubjectClass),
751
- ${subQueries.join(", ")}
752
- `;
753
-
754
- // Try Prolog first
755
- try {
756
- const result = await this.#perspective.infer(fullQuery);
757
- if (result?.[0] && result[0].Properties && result[0].Properties.length > 0) {
758
- const { Properties, Collections, Timestamp, Author } = result[0];
759
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
760
- await Ad4mModel.assignValuesToInstance(this.#perspective, this, values);
761
- return this;
762
- }
763
- } catch (e) {
764
- console.log(`Prolog getData failed for ${this.#baseExpression}, falling back to SurrealDB`);
765
- }
766
-
767
- // Fallback to SurrealDB (SdnaOnly mode)
752
+ // Use SurrealDB for data queries
768
753
  try {
769
754
  const ctor = this.constructor as typeof Ad4mModel;
770
755
  const metadata = ctor.getModelMetadata();
@@ -772,6 +757,9 @@ export class Ad4mModel {
772
757
  // Query for all links from this specific node (base expression)
773
758
  // Using formatSurrealValue to prevent SQL injection by properly escaping the value
774
759
  const safeBaseExpression = ctor.formatSurrealValue(this.#baseExpression);
760
+ // Note: We use ORDER BY timestamp ASC because:
761
+ // - For collections: we want chronological order (oldest to newest)
762
+ // - For properties: we select the LAST element to get "latest wins" semantics
775
763
  const linksQuery = `
776
764
  SELECT id, predicate, out.uri AS target, author, timestamp
777
765
  FROM link
@@ -788,7 +776,9 @@ export class Ad4mModel {
788
776
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
789
777
  const matching = links.filter((l: any) => l.predicate === propMeta.predicate);
790
778
  if (matching.length > 0) {
791
- const link = matching[0]; // Take first/latest
779
+ // "Latest wins" semantics: select the last element since links are ordered ASC.
780
+ // The last element has the most recent timestamp and represents the current property value.
781
+ const link = matching[matching.length - 1];
792
782
  let value = link.target;
793
783
 
794
784
  // Track timestamp/author
@@ -833,7 +823,8 @@ export class Ad4mModel {
833
823
  // Process collections
834
824
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
835
825
  const matching = links.filter((l: any) => l.predicate === collMeta.predicate);
836
- // Links are already sorted by timestamp ASC from the query, so map preserves order
826
+ // Collections preserve chronological order: links are sorted ASC by timestamp,
827
+ // so the collection reflects the order in which items were added (oldest to newest).
837
828
  (this as any)[collName] = matching.map((l: any) => l.target);
838
829
  }
839
830
 
@@ -2020,7 +2011,7 @@ WHERE ${whereConditions.join(' AND ')}
2020
2011
  // Generate actions from metadata (replaces Prolog query)
2021
2012
  const actions = this.generateCollectionAction(key, 'setter');
2022
2013
 
2023
- if (value) {
2014
+ if (value != null) {
2024
2015
  if (Array.isArray(value)) {
2025
2016
  await this.#perspective.executeAction(
2026
2017
  actions,
@@ -2045,7 +2036,7 @@ WHERE ${whereConditions.join(' AND ')}
2045
2036
  // Generate actions from metadata (replaces Prolog query)
2046
2037
  const actions = this.generateCollectionAction(key, 'adder');
2047
2038
 
2048
- if (value) {
2039
+ if (value != null) {
2049
2040
  if (Array.isArray(value)) {
2050
2041
  await Promise.all(
2051
2042
  value.map((v) =>
@@ -2069,7 +2060,7 @@ WHERE ${whereConditions.join(' AND ')}
2069
2060
  // Generate actions from metadata (replaces Prolog query)
2070
2061
  const actions = this.generateCollectionAction(key, 'remover');
2071
2062
 
2072
- if (value) {
2063
+ if (value != null) {
2073
2064
  if (Array.isArray(value)) {
2074
2065
  await Promise.all(
2075
2066
  value.map((v) =>
@@ -2181,11 +2172,8 @@ WHERE ${whereConditions.join(' AND ')}
2181
2172
  break;
2182
2173
  }
2183
2174
  } else if (Array.isArray(value)) {
2184
- // Handle all arrays as collections, even empty ones
2185
- if (value.length > 0) {
2186
- await this.setCollectionSetter(key, value, batchId);
2187
- }
2188
- // Skip empty arrays - don't try to set them as properties
2175
+ // Handle all arrays as collections, including empty ones (which clears the collection)
2176
+ await this.setCollectionSetter(key, value, batchId);
2189
2177
  } else if (value !== undefined && value !== null && value !== "") {
2190
2178
  if (setProperties) {
2191
2179
  // Check if this is a collection property (has collection metadata)
@@ -50,35 +50,7 @@ export class Subject {
50
50
  Object.defineProperty(this, p, {
51
51
  configurable: true,
52
52
  get: async () => {
53
- // Try Prolog first
54
- try {
55
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), property_getter(C, "${this.#baseExpression}", "${p}", Value)`)
56
- if(results && results.length > 0 && results[0].Value !== undefined && results[0].Value !== null && results[0].Value !== '') {
57
- let expressionURI = results[0].Value
58
- if(resolveExpressionURI) {
59
- try {
60
- if (expressionURI) {
61
- const expression = await this.#perspective.getExpression(expressionURI)
62
- try {
63
- return JSON.parse(expression.data)
64
- } catch(e) {
65
- return expression.data
66
- }
67
- } else {
68
- return expressionURI
69
- }
70
- } catch (err) {
71
- return expressionURI
72
- }
73
- } else {
74
- return expressionURI
75
- }
76
- }
77
- } catch (err) {
78
- // Prolog query failed, fall through to SurrealDB
79
- }
80
-
81
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
53
+ // Use SurrealDB for data queries
82
54
  try {
83
55
  return await this.#perspective.getPropertyValueViaSurreal(this.#baseExpression, this.#subjectClassName, p);
84
56
  } catch (err) {
@@ -119,20 +91,7 @@ export class Subject {
119
91
  Object.defineProperty(this, c, {
120
92
  configurable: true,
121
93
  get: async () => {
122
- // Try Prolog first
123
- try {
124
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClassName}", C), collection_getter(C, "${this.#baseExpression}", "${c}", Value)`)
125
- if(results && results.length > 0 && results[0].Value && Array.isArray(results[0].Value) && results[0].Value.length > 0) {
126
- let collectionContent = results[0].Value.filter((v: any) => v !== "" && v !== '')
127
- if (collectionContent.length > 0) {
128
- return collectionContent
129
- }
130
- }
131
- } catch (err) {
132
- // Prolog query failed, fall through to SurrealDB
133
- }
134
-
135
- // Fallback to SurrealDB if Prolog returned nothing (SdnaOnly mode)
94
+ // Use SurrealDB for data queries
136
95
  try {
137
96
  return await this.#perspective.getCollectionValuesViaSurreal(this.#baseExpression, this.#subjectClassName, c);
138
97
  } catch (err) {