@coasys/ad4m 0.10.1-release-candidate-1 → 0.10.1-release-candidate-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.
Files changed (47) hide show
  1. package/lib/index.cjs +2179 -495
  2. package/lib/index.js +2171 -491
  3. package/lib/src/Literal.js +4 -1
  4. package/lib/src/ai/AIClient.d.ts +1 -1
  5. package/lib/src/ai/AIClient.js +6 -6
  6. package/lib/src/ai/AIResolver.d.ts +1 -1
  7. package/lib/src/ai/AIResolver.js +7 -4
  8. package/lib/src/index.d.ts +3 -3
  9. package/lib/src/index.js +3 -3
  10. package/lib/src/model/Ad4mModel.d.ts +609 -0
  11. package/lib/src/model/Ad4mModel.js +1048 -0
  12. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  13. package/lib/src/{subject → model}/Subject.js +18 -18
  14. package/lib/src/model/decorators.d.ts +502 -0
  15. package/lib/src/model/decorators.js +683 -0
  16. package/lib/src/neighbourhood/NeighbourhoodClient.js +4 -2
  17. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +31 -0
  19. package/lib/src/perspectives/PerspectiveClient.d.ts +18 -11
  20. package/lib/src/perspectives/PerspectiveClient.js +116 -49
  21. package/lib/src/perspectives/PerspectiveProxy.d.ts +471 -54
  22. package/lib/src/perspectives/PerspectiveProxy.js +579 -64
  23. package/lib/src/perspectives/PerspectiveResolver.d.ts +23 -9
  24. package/lib/src/perspectives/PerspectiveResolver.js +140 -46
  25. package/lib/src/schema.gql +19 -9
  26. package/lib/src/typeDefs.js +19 -9
  27. package/package.json +1 -1
  28. package/src/Literal.ts +4 -1
  29. package/src/ai/AIClient.ts +6 -6
  30. package/src/ai/AIResolver.ts +6 -3
  31. package/src/index.ts +3 -3
  32. package/src/model/Ad4mModel.ts +1206 -0
  33. package/src/{subject → model}/Subject.ts +16 -16
  34. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  35. package/src/neighbourhood/NeighbourhoodClient.ts +4 -2
  36. package/src/neighbourhood/NeighbourhoodProxy.test.ts +45 -0
  37. package/src/perspectives/PerspectiveClient.ts +122 -51
  38. package/src/perspectives/PerspectiveProxy.ts +642 -77
  39. package/src/perspectives/PerspectiveResolver.ts +126 -23
  40. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  41. package/lib/src/subject/SDNADecorators.js +0 -360
  42. package/lib/src/subject/SubjectEntity.d.ts +0 -110
  43. package/lib/src/subject/SubjectEntity.js +0 -288
  44. package/src/subject/SubjectEntity.ts +0 -336
  45. /package/lib/src/{subject → model}/util.d.ts +0 -0
  46. /package/lib/src/{subject → model}/util.js +0 -0
  47. /package/src/{subject → model}/util.ts +0 -0
package/lib/index.cjs CHANGED
@@ -4301,7 +4301,7 @@ class Literal {
4301
4301
  toUrl() {
4302
4302
  if (__classPrivateFieldGet$c(this, _Literal_url, "f") && !__classPrivateFieldGet$c(this, _Literal_literal, "f"))
4303
4303
  return __classPrivateFieldGet$c(this, _Literal_url, "f");
4304
- if (!__classPrivateFieldGet$c(this, _Literal_url, "f") && !__classPrivateFieldGet$c(this, _Literal_literal, "f"))
4304
+ if (!__classPrivateFieldGet$c(this, _Literal_url, "f") && (__classPrivateFieldGet$c(this, _Literal_literal, "f") === undefined || __classPrivateFieldGet$c(this, _Literal_literal, "f") === "" || __classPrivateFieldGet$c(this, _Literal_literal, "f") === null))
4305
4305
  throw new Error("Can't turn empty Literal into URL");
4306
4306
  let encoded;
4307
4307
  switch (typeof __classPrivateFieldGet$c(this, _Literal_literal, "f")) {
@@ -4311,6 +4311,9 @@ class Literal {
4311
4311
  case 'number':
4312
4312
  encoded = `number:${encodeRFC3986URIComponent(__classPrivateFieldGet$c(this, _Literal_literal, "f"))}`;
4313
4313
  break;
4314
+ case 'boolean':
4315
+ encoded = `boolean:${encodeRFC3986URIComponent(__classPrivateFieldGet$c(this, _Literal_literal, "f"))}`;
4316
+ break;
4314
4317
  case 'object':
4315
4318
  encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$c(this, _Literal_literal, "f")))}`;
4316
4319
  break;
@@ -4342,12 +4345,12 @@ class Literal {
4342
4345
  }
4343
4346
  _Literal_literal = new WeakMap(), _Literal_url = new WeakMap();
4344
4347
 
4345
- function capitalize(str) {
4348
+ function capitalize$1(str) {
4346
4349
  return str.charAt(0).toUpperCase() + str.slice(1);
4347
4350
  }
4348
4351
  // e.g. "name" -> "setName"
4349
4352
  function propertyNameToSetterName(property) {
4350
- return `set${capitalize(property)}`;
4353
+ return `set${capitalize$1(property)}`;
4351
4354
  }
4352
4355
  function singularToPlural(singular) {
4353
4356
  if (singular.endsWith("y")) {
@@ -4370,7 +4373,7 @@ function pluralToSingular(plural) {
4370
4373
  }
4371
4374
  // e.g. "comments" -> "addComment"
4372
4375
  function collectionToAdderName(collection) {
4373
- return `add${capitalize(pluralToSingular(collection))}`;
4376
+ return `add${capitalize$1(pluralToSingular(collection))}`;
4374
4377
  }
4375
4378
  // e.g. "addEntry" -> "entries"
4376
4379
  function collectionAdderToName(adderName) {
@@ -4380,7 +4383,7 @@ function collectionAdderToName(adderName) {
4380
4383
  }
4381
4384
  // e.g. "comments" -> "removeComment"
4382
4385
  function collectionToRemoverName(collection) {
4383
- return `remove${capitalize(pluralToSingular(collection))}`;
4386
+ return `remove${capitalize$1(pluralToSingular(collection))}`;
4384
4387
  }
4385
4388
  // e.g. "removeEntry" -> "entries"
4386
4389
  function collectionRemoverToName(removerName) {
@@ -4395,7 +4398,7 @@ function collectionSetterToName(adderName) {
4395
4398
  }
4396
4399
  // e.g. "comments" -> "addComment"
4397
4400
  function collectionToSetterName(collection) {
4398
- return `setCollection${capitalize(pluralToSingular(collection))}`;
4401
+ return `setCollection${capitalize$1(pluralToSingular(collection))}`;
4399
4402
  }
4400
4403
  function stringifyObjectLiteral(obj) {
4401
4404
  if (Array.isArray(obj)) {
@@ -4423,7 +4426,7 @@ var __classPrivateFieldGet$b = (undefined && undefined.__classPrivateFieldGet) |
4423
4426
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4424
4427
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
4425
4428
  };
4426
- var _Subject_baseExpression, _Subject_subjectClass, _Subject_perspective;
4429
+ var _Subject_baseExpression, _Subject_subjectClassName, _Subject_perspective;
4427
4430
  /**
4428
4431
  * Represents a subject in the perspective.
4429
4432
  * A subject is an entity that has properties and collections.
@@ -4433,14 +4436,14 @@ class Subject {
4433
4436
  * Constructs a new subject.
4434
4437
  * @param perspective - The perspective that the subject belongs to.
4435
4438
  * @param baseExpression - The base expression of the subject.
4436
- * @param subjectClass - The class of the subject.
4439
+ * @param subjectClassName - The class name of the subject.
4437
4440
  */
4438
- constructor(perspective, baseExpression, subjectClass) {
4441
+ constructor(perspective, baseExpression, subjectClassName) {
4439
4442
  _Subject_baseExpression.set(this, void 0);
4440
- _Subject_subjectClass.set(this, void 0);
4443
+ _Subject_subjectClassName.set(this, void 0);
4441
4444
  _Subject_perspective.set(this, void 0);
4442
4445
  __classPrivateFieldSet$b(this, _Subject_baseExpression, baseExpression, "f");
4443
- __classPrivateFieldSet$b(this, _Subject_subjectClass, subjectClass, "f");
4446
+ __classPrivateFieldSet$b(this, _Subject_subjectClassName, subjectClassName, "f");
4444
4447
  __classPrivateFieldSet$b(this, _Subject_perspective, perspective, "f");
4445
4448
  }
4446
4449
  /**
@@ -4456,19 +4459,19 @@ class Subject {
4456
4459
  */
4457
4460
  async init() {
4458
4461
  // Check if the subject is a valid instance of the subject class
4459
- let isInstance = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").isSubjectInstance(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClass, "f"));
4462
+ let isInstance = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").isSubjectInstance(__classPrivateFieldGet$b(this, _Subject_baseExpression, "f"), __classPrivateFieldGet$b(this, _Subject_subjectClassName, "f"));
4460
4463
  if (!isInstance) {
4461
- throw `Not a valid subject instance of ${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")} for ${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}`;
4464
+ throw `Not a valid subject instance of ${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")} for ${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}`;
4462
4465
  }
4463
4466
  // Define properties and collections dynamically
4464
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), property(C, Property)`);
4467
+ let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property(C, Property)`);
4465
4468
  let properties = results.map(result => result.Property);
4466
4469
  for (let p of properties) {
4467
- const resolveExpressionURI = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), property_resolve(C, "${p}")`);
4470
+ const resolveExpressionURI = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve(C, "${p}")`);
4468
4471
  Object.defineProperty(this, p, {
4469
4472
  configurable: true,
4470
4473
  get: async () => {
4471
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), property_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${p}", Value)`);
4474
+ 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)`);
4472
4475
  if (results && results.length > 0) {
4473
4476
  let expressionURI = results[0].Value;
4474
4477
  if (resolveExpressionURI) {
@@ -4504,12 +4507,12 @@ class Subject {
4504
4507
  });
4505
4508
  }
4506
4509
  // Define setters
4507
- const setters = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), property_setter(C, Property, Setter)`);
4510
+ const setters = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_setter(C, Property, Setter)`);
4508
4511
  for (let setter of (setters ? setters : [])) {
4509
4512
  if (setter) {
4510
4513
  const property = setter.Property;
4511
4514
  const actions = eval(setter.Setter);
4512
- const resolveLanguageResults = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), property_resolve_language(C, "${property}", Language)`);
4515
+ const resolveLanguageResults = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), property_resolve_language(C, "${property}", Language)`);
4513
4516
  let resolveLanguage;
4514
4517
  if (resolveLanguageResults && resolveLanguageResults.length > 0) {
4515
4518
  resolveLanguage = resolveLanguageResults[0].Language;
@@ -4523,7 +4526,7 @@ class Subject {
4523
4526
  }
4524
4527
  }
4525
4528
  // Define collections
4526
- let results2 = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), collection(C, Collection)`);
4529
+ let results2 = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), collection(C, Collection)`);
4527
4530
  if (!results2)
4528
4531
  results2 = [];
4529
4532
  let collections = results2.map(result => result.Collection);
@@ -4531,7 +4534,7 @@ class Subject {
4531
4534
  Object.defineProperty(this, c, {
4532
4535
  configurable: true,
4533
4536
  get: async () => {
4534
- let results = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), collection_getter(C, "${__classPrivateFieldGet$b(this, _Subject_baseExpression, "f")}", "${c}", Value)`);
4537
+ 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)`);
4535
4538
  if (results && results.length > 0 && results[0].Value) {
4536
4539
  let collectionContent = results[0].Value.filter((v) => v !== "" && v !== '');
4537
4540
  return collectionContent;
@@ -4543,7 +4546,7 @@ class Subject {
4543
4546
  });
4544
4547
  }
4545
4548
  // Define collection adders
4546
- let adders = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), collection_adder(C, Collection, Adder)`);
4549
+ let adders = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), collection_adder(C, Collection, Adder)`);
4547
4550
  if (!adders)
4548
4551
  adders = [];
4549
4552
  for (let adder of adders) {
@@ -4561,7 +4564,7 @@ class Subject {
4561
4564
  }
4562
4565
  }
4563
4566
  // Define collection removers
4564
- let removers = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), collection_remover(C, Collection, Remover)`);
4567
+ let removers = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), collection_remover(C, Collection, Remover)`);
4565
4568
  if (!removers)
4566
4569
  removers = [];
4567
4570
  for (let remover of removers) {
@@ -4579,7 +4582,7 @@ class Subject {
4579
4582
  }
4580
4583
  }
4581
4584
  // Define collection setters
4582
- let collectionSetters = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClass, "f")}", C), collection_setter(C, Collection, Setter)`);
4585
+ let collectionSetters = await __classPrivateFieldGet$b(this, _Subject_perspective, "f").infer(`subject_class("${__classPrivateFieldGet$b(this, _Subject_subjectClassName, "f")}", C), collection_setter(C, Collection, Setter)`);
4583
4586
  if (!collectionSetters)
4584
4587
  collectionSetters = [];
4585
4588
  for (let collectionSetter of collectionSetters) {
@@ -4598,7 +4601,7 @@ class Subject {
4598
4601
  }
4599
4602
  }
4600
4603
  }
4601
- _Subject_baseExpression = new WeakMap(), _Subject_subjectClass = new WeakMap(), _Subject_perspective = new WeakMap();
4604
+ _Subject_baseExpression = new WeakMap(), _Subject_subjectClassName = new WeakMap(), _Subject_perspective = new WeakMap();
4602
4605
 
4603
4606
  var __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4604
4607
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -4611,14 +4614,221 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
4611
4614
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4612
4615
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
4613
4616
  };
4614
- var _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
4615
- /** Perspective UI proxy object
4617
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
4618
+ /** Proxy object for a subscribed Prolog query that provides real-time updates
4619
+ *
4620
+ * This class handles:
4621
+ * - Keeping the subscription alive by sending periodic keepalive signals
4622
+ * - Managing callbacks for result updates
4623
+ * - Subscribing to query updates via GraphQL subscriptions
4624
+ * - Maintaining the latest query result
4625
+ * - Ensuring subscription is fully initialized before allowing access
4626
+ *
4627
+ * The subscription will remain active as long as keepalive signals are sent.
4628
+ * Make sure to call dispose() when you're done with the subscription to clean up
4629
+ * resources and stop keepalive signals.
4630
+ *
4631
+ * The subscription goes through an initialization process where it waits for the first
4632
+ * result to come through the subscription channel. You can await the `initialized`
4633
+ * promise to ensure the subscription is ready. The initialization will timeout after
4634
+ * 30 seconds if no result is received.
4635
+ *
4636
+ * Example usage:
4637
+ * ```typescript
4638
+ * const subscription = await perspective.subscribeInfer("my_query(X)");
4639
+ * // At this point the subscription is already initialized since subscribeInfer waits
4640
+ *
4641
+ * // Set up callback for future updates
4642
+ * const removeCallback = subscription.onResult(result => {
4643
+ * console.log("New result:", result);
4644
+ * });
4645
+ *
4646
+ * // Later: clean up
4647
+ * subscription.dispose();
4648
+ * ```
4649
+ */
4650
+ class QuerySubscriptionProxy {
4651
+ /** Creates a new query subscription
4652
+ * @param uuid - The UUID of the perspective
4653
+ * @param subscriptionId - The ID returned by the subscription mutation
4654
+ * @param initialResult - The initial query result
4655
+ * @param client - The PerspectiveClient instance to use for communication
4656
+ */
4657
+ constructor(uuid, subscriptionId, initialResult, client) {
4658
+ _QuerySubscriptionProxy_instances.add(this);
4659
+ _QuerySubscriptionProxy_uuid.set(this, void 0);
4660
+ _QuerySubscriptionProxy_subscriptionId.set(this, void 0);
4661
+ _QuerySubscriptionProxy_client.set(this, void 0);
4662
+ _QuerySubscriptionProxy_callbacks.set(this, void 0);
4663
+ _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
4664
+ _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
4665
+ _QuerySubscriptionProxy_latestResult.set(this, void 0);
4666
+ _QuerySubscriptionProxy_disposed.set(this, false);
4667
+ _QuerySubscriptionProxy_initialized.set(this, void 0);
4668
+ _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
4669
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
4670
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, subscriptionId, "f");
4671
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
4672
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
4673
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult, "f");
4674
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
4675
+ // Add timeout to prevent hanging promises
4676
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
4677
+ reject(new Error('Subscription initialization timed out after 30 seconds'));
4678
+ }, 30000), "f"); // 30 seconds timeout
4679
+ // Subscribe to query updates
4680
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (result) => {
4681
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4682
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4683
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4684
+ }
4685
+ resolve(true);
4686
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, result, "f");
4687
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
4688
+ }), "f");
4689
+ }), "f");
4690
+ // Start keepalive loop using platform-agnostic setTimeout
4691
+ const keepaliveLoop = async () => {
4692
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4693
+ return;
4694
+ try {
4695
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4696
+ }
4697
+ catch (e) {
4698
+ console.error('Error in keepalive:', e);
4699
+ }
4700
+ // Schedule next keepalive if not disposed
4701
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f")) {
4702
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4703
+ }
4704
+ };
4705
+ // Start the first keepalive loop
4706
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4707
+ }
4708
+ /** Promise that resolves when the subscription has received its first result
4709
+ * through the subscription channel. This ensures the subscription is fully
4710
+ * set up before allowing access to results or updates.
4711
+ *
4712
+ * The promise will reject if no result is received within 30 seconds.
4713
+ *
4714
+ * Note: You typically don't need to await this directly since the subscription
4715
+ * creation methods (like subscribeInfer) already wait for initialization.
4716
+ */
4717
+ get initialized() {
4718
+ return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initialized, "f");
4719
+ }
4720
+ /** Get the latest query result
4721
+ *
4722
+ * This returns the most recent result from the query, which could be either:
4723
+ * - The initial result from when the subscription was created
4724
+ * - The latest update received through the subscription
4725
+ *
4726
+ * @returns The latest query result as a string (usually a JSON array of bindings)
4727
+ */
4728
+ get result() {
4729
+ return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, "f");
4730
+ }
4731
+ /** Add a callback that will be called whenever new results arrive
4732
+ *
4733
+ * The callback will be called immediately with the current result,
4734
+ * and then again each time the query results change.
4735
+ *
4736
+ * @param callback - Function that takes a result string and processes it
4737
+ * @returns A function that can be called to remove this callback
4738
+ *
4739
+ * Example:
4740
+ * ```typescript
4741
+ * const removeCallback = subscription.onResult(result => {
4742
+ * const bindings = JSON.parse(result);
4743
+ * console.log("New bindings:", bindings);
4744
+ * });
4745
+ *
4746
+ * // Later: stop receiving updates
4747
+ * removeCallback();
4748
+ * ```
4749
+ */
4750
+ onResult(callback) {
4751
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
4752
+ return () => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
4753
+ }
4754
+ /** Clean up the subscription and stop keepalive signals
4755
+ *
4756
+ * This method:
4757
+ * 1. Stops the keepalive timer
4758
+ * 2. Unsubscribes from GraphQL subscription updates
4759
+ * 3. Clears all registered callbacks
4760
+ * 4. Cleans up any pending initialization timeout
4761
+ *
4762
+ * After calling this method, the subscription is no longer active and
4763
+ * will not receive any more updates. The instance should be discarded.
4764
+ */
4765
+ dispose() {
4766
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, "f");
4767
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4768
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
4769
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
4770
+ }
4771
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4772
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4773
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4774
+ }
4775
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").clear();
4776
+ }
4777
+ }
4778
+ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
4779
+ for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
4780
+ try {
4781
+ callback(result);
4782
+ }
4783
+ catch (e) {
4784
+ console.error('Error in query subscription callback:', e);
4785
+ }
4786
+ }
4787
+ };
4788
+ /**
4789
+ * PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs
4790
+ * that store and organize links between expressions.
4791
+ *
4792
+ * A Perspective is fundamentally a collection of links (subject-predicate-object triples) that represent an agent's view
4793
+ * of their digital world. Through PerspectiveProxy, you can:
4794
+ * - Add, remove, and query links
4795
+ * - Work with Social DNA (subject classes and flows)
4796
+ * - Subscribe to real-time updates
4797
+ * - Share perspectives as Neighbourhoods
4798
+ * - Execute Prolog queries for complex graph patterns
4799
+ *
4616
4800
  *
4617
- * Convenience object for UIs to interact with a perspective.
4618
- * It is created by some of the methods in the PerspectiveClient class and includes
4619
- * a reference to the PerspectiveClient object that created it.
4801
+ * @example
4802
+ * ```typescript
4803
+ * // Create and work with links
4804
+ * const perspective = await ad4m.perspective.add("My Space");
4805
+ * await perspective.add({
4806
+ * source: "did:key:alice",
4807
+ * predicate: "knows",
4808
+ * target: "did:key:bob"
4809
+ * });
4810
+ *
4811
+ * // Query links
4812
+ * const friends = await perspective.get({
4813
+ * source: "did:key:alice",
4814
+ * predicate: "knows"
4815
+ * });
4816
+ *
4817
+ * // Use Social DNA
4818
+ * await perspective.addSdna(todoClass, "subject_class");
4819
+ * const todo = await perspective.createSubject("Todo", "expression://123");
4820
+ *
4821
+ * // Subscribe to changes
4822
+ * perspective.addListener("link-added", (link) => {
4823
+ * console.log("New link added:", link);
4824
+ * });
4825
+ * ```
4620
4826
  */
4621
4827
  class PerspectiveProxy {
4828
+ /**
4829
+ * Creates a new PerspectiveProxy instance.
4830
+ * Note: Don't create this directly, use ad4m.perspective.add() instead.
4831
+ */
4622
4832
  constructor(handle, ad4m) {
4623
4833
  _PerspectiveProxy_handle.set(this, void 0);
4624
4834
  _PerspectiveProxy_client.set(this, void 0);
@@ -4642,52 +4852,255 @@ class PerspectiveProxy {
4642
4852
  __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
4643
4853
  __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
4644
4854
  }
4645
- async executeAction(actions, expression, parameters) {
4646
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters));
4855
+ /**
4856
+ * Executes a set of actions on an expression with optional parameters.
4857
+ * Used internally by Social DNA flows and subject class operations.
4858
+ *
4859
+ * Actions are specified as an array of commands that modify links in the perspective.
4860
+ * Each action is an object with the following format:
4861
+ * ```typescript
4862
+ * {
4863
+ * action: "addLink" | "removeLink" | "setSingleTarget" | "collectionSetter",
4864
+ * source: string, // Usually "this" to reference the current expression
4865
+ * predicate: string, // The predicate URI
4866
+ * target: string // The target value or "value" for parameters
4867
+ * }
4868
+ * ```
4869
+ *
4870
+ * Available commands:
4871
+ * - `addLink`: Creates a new link
4872
+ * - `removeLink`: Removes an existing link
4873
+ * - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one
4874
+ * - `collectionSetter`: Special command for setting collection properties
4875
+ *
4876
+ * When used with parameters, the special value "value" in the target field will be
4877
+ * replaced with the actual parameter value.
4878
+ *
4879
+ * @example
4880
+ * ```typescript
4881
+ * // Add a state link and remove an old one
4882
+ * await perspective.executeAction([
4883
+ * {
4884
+ * action: "addLink",
4885
+ * source: "this",
4886
+ * predicate: "todo://state",
4887
+ * target: "todo://doing"
4888
+ * },
4889
+ * {
4890
+ * action: "removeLink",
4891
+ * source: "this",
4892
+ * predicate: "todo://state",
4893
+ * target: "todo://ready"
4894
+ * }
4895
+ * ], "expression://123");
4896
+ *
4897
+ * // Set a property using a parameter
4898
+ * await perspective.executeAction([
4899
+ * {
4900
+ * action: "setSingleTarget",
4901
+ * source: "this",
4902
+ * predicate: "todo://title",
4903
+ * target: "value"
4904
+ * }
4905
+ * ], "expression://123", [
4906
+ * { name: "title", value: "New Title" }
4907
+ * ]);
4908
+ * ```
4909
+ *
4910
+ * @param actions - Array of action objects to execute
4911
+ * @param expression - Target expression address (replaces "this" in actions)
4912
+ * @param parameters - Optional parameters that replace "value" in actions
4913
+ * @param batchId - Optional batch ID to group this operation with others
4914
+ */
4915
+ async executeAction(actions, expression, parameters, batchId) {
4916
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
4647
4917
  }
4648
- /** Returns all the links of this perspective that matches the LinkQuery */
4918
+ /**
4919
+ * Retrieves links from the perspective that match the given query.
4920
+ *
4921
+ * @param query - Query parameters to filter links
4922
+ * @returns Array of matching LinkExpressions
4923
+ *
4924
+ * @example
4925
+ * ```typescript
4926
+ * // Get all links where Alice knows someone
4927
+ * const links = await perspective.get({
4928
+ * source: "did:key:alice",
4929
+ * predicate: "knows"
4930
+ * });
4931
+ *
4932
+ * // Get all comments on a post
4933
+ * const comments = await perspective.get({
4934
+ * source: "post://123",
4935
+ * predicate: "comment"
4936
+ * });
4937
+ * ```
4938
+ */
4649
4939
  async get(query) {
4650
4940
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4651
4941
  }
4652
- /** Runs a Prolog query on the perspective's Prolog engine */
4942
+ /**
4943
+ * Executes a Prolog query against the perspective's knowledge base.
4944
+ * This is a powerful way to find complex patterns in the graph.
4945
+ *
4946
+ * @param query - Prolog query string
4947
+ * @returns Query results or false if no results
4948
+ *
4949
+ * @example
4950
+ * ```typescript
4951
+ * // Find friends of friends
4952
+ * const results = await perspective.infer(`
4953
+ * triple(A, "knows", B),
4954
+ * triple(B, "knows", C),
4955
+ * A \= C
4956
+ * `);
4957
+ *
4958
+ * // Find all active todos
4959
+ * const todos = await perspective.infer(`
4960
+ * instance(Todo, "Todo"),
4961
+ * property_getter("Todo", Todo, "state", "active")
4962
+ * `);
4963
+ * ```
4964
+ */
4653
4965
  async infer(query) {
4654
4966
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4655
4967
  }
4656
- /** Adds a link to this perspective */
4657
- async add(link, status = 'shared') {
4658
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, status);
4968
+ /**
4969
+ * Adds a new link to the perspective.
4970
+ *
4971
+ * @param link - The link to add
4972
+ * @param status - Whether the link should be shared in a Neighbourhood
4973
+ * @param batchId - Optional batch ID to group this operation with others
4974
+ * @returns The created LinkExpression
4975
+ *
4976
+ * @example
4977
+ * ```typescript
4978
+ * // Add a simple relationship
4979
+ * await perspective.add({
4980
+ * source: "did:key:alice",
4981
+ * predicate: "follows",
4982
+ * target: "did:key:bob"
4983
+ * });
4984
+ *
4985
+ * // Add a local-only link
4986
+ * await perspective.add({
4987
+ * source: "note://123",
4988
+ * predicate: "tag",
4989
+ * target: "private"
4990
+ * }, "local");
4991
+ * ```
4992
+ */
4993
+ async add(link, status = 'shared', batchId) {
4994
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
4659
4995
  }
4660
- /** Adds multiple links to this perspective **/
4661
- async addLinks(links, status = 'shared') {
4662
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, links, status);
4996
+ /**
4997
+ * Adds multiple links to the perspective in a single operation.
4998
+ * More efficient than adding links one by one.
4999
+ *
5000
+ * @param links - Array of links to add
5001
+ * @param status - Whether the links should be shared
5002
+ * @param batchId - Optional batch ID to group this operation with others
5003
+ * @returns Array of created LinkExpressions
5004
+ */
5005
+ async addLinks(links, status = 'shared', batchId) {
5006
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
4663
5007
  }
4664
- /** Removes multiple links from this perspective **/
4665
- async removeLinks(links) {
4666
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, links);
5008
+ /**
5009
+ * Removes multiple links from the perspective.
5010
+ *
5011
+ * @param links - Array of links to remove
5012
+ * @param batchId - Optional batch ID to group this operation with others
5013
+ * @returns Array of removed LinkExpressions
5014
+ */
5015
+ async removeLinks(links, batchId) {
5016
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
4667
5017
  }
4668
- /** Adds and removes multiple links from this perspective **/
5018
+ /**
5019
+ * Applies a set of link mutations (adds and removes) in a single operation.
5020
+ * Useful for atomic updates to the perspective.
5021
+ *
5022
+ * @param mutations - Object containing links to add and remove
5023
+ * @param status - Whether new links should be shared
5024
+ * @returns Object containing results of the mutations
5025
+ */
4669
5026
  async linkMutations(mutations, status = 'shared') {
4670
5027
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
4671
5028
  }
4672
- /** Adds a linkExpression to this perspective */
4673
- async addLinkExpression(link, status = 'shared') {
4674
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, status);
5029
+ /**
5030
+ * Adds a pre-signed LinkExpression to the perspective.
5031
+ *
5032
+ * @param link - The signed LinkExpression to add
5033
+ * @param status - Whether the link should be shared
5034
+ * @param batchId - Optional batch ID to group this operation with others
5035
+ * @returns The added LinkExpression
5036
+ */
5037
+ async addLinkExpression(link, status = 'shared', batchId) {
5038
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
5039
+ }
5040
+ /**
5041
+ * Updates an existing link with new data.
5042
+ *
5043
+ * @param oldLink - The existing link to update
5044
+ * @param newLink - The new link data
5045
+ * @param batchId - Optional batch ID to group this operation with others
5046
+ */
5047
+ async update(oldLink, newLink, batchId) {
5048
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
5049
+ }
5050
+ /**
5051
+ * Removes a link from the perspective.
5052
+ *
5053
+ * @param link - The link to remove
5054
+ * @param batchId - Optional batch ID to group this operation with others
5055
+ */
5056
+ async remove(link, batchId) {
5057
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
4675
5058
  }
4676
- async update(oldLink, newLink) {
4677
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink);
5059
+ /** Creates a new batch for grouping operations */
5060
+ async createBatch() {
5061
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4678
5062
  }
4679
- async remove(link) {
4680
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link);
5063
+ /** Commits a batch of operations */
5064
+ async commitBatch(batchId) {
5065
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, batchId);
4681
5066
  }
5067
+ /**
5068
+ * Retrieves and renders an Expression referenced in this perspective.
5069
+ *
5070
+ * @param expressionURI - URI of the Expression to retrieve
5071
+ * @returns The rendered Expression
5072
+ */
4682
5073
  async getExpression(expressionURI) {
4683
5074
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getExpression(expressionURI);
4684
5075
  }
5076
+ /**
5077
+ * Creates a new Expression in the specified Language.
5078
+ *
5079
+ * @param content - Content for the new Expression
5080
+ * @param languageAddress - Address of the Language to use
5081
+ * @returns URI of the created Expression
5082
+ */
4685
5083
  async createExpression(content, languageAddress) {
4686
5084
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createExpression(content, languageAddress);
4687
5085
  }
4688
- /** Adds a link listener
4689
- * @param type Can be 'link-added' or 'link-removed'
4690
- * @param cb Callback function that is called when a link is added to the perspective
5086
+ /**
5087
+ * Subscribes to link changes in the perspective.
5088
+ *
5089
+ * @param type - Type of change to listen for
5090
+ * @param cb - Callback function
5091
+ *
5092
+ * @example
5093
+ * ```typescript
5094
+ * // Listen for new links
5095
+ * perspective.addListener("link-added", (link) => {
5096
+ * console.log("New link:", link);
5097
+ * });
5098
+ *
5099
+ * // Listen for removed links
5100
+ * perspective.addListener("link-removed", (link) => {
5101
+ * console.log("Link removed:", link);
5102
+ * });
5103
+ * ```
4691
5104
  */
4692
5105
  async addListener(type, cb) {
4693
5106
  if (type === 'link-added') {
@@ -4700,16 +5113,26 @@ class PerspectiveProxy {
4700
5113
  __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").push(cb);
4701
5114
  }
4702
5115
  }
4703
- /** Adds a sync state listener
4704
- * @param cb Callback function that is called when the sync state of the perspective changes
4705
- * @returns A function that can be called to remove the listener
5116
+ /**
5117
+ * Subscribes to sync state changes if this perspective is shared.
5118
+ *
5119
+ * @param cb - Callback function
5120
+ *
5121
+ * @example
5122
+ * ```typescript
5123
+ * perspective.addSyncStateChangeListener((state) => {
5124
+ * console.log("Sync state:", state);
5125
+ * });
5126
+ * ```
4706
5127
  */
4707
5128
  async addSyncStateChangeListener(cb) {
4708
5129
  __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").push(cb);
4709
5130
  }
4710
- /** Removes a previously added link listener
4711
- * @param type Can be 'link-added' or 'link-removed'
4712
- * @param cb Callback function that is called when a link is added to the perspective
5131
+ /**
5132
+ * Unsubscribes from link changes.
5133
+ *
5134
+ * @param type - Type of change to stop listening for
5135
+ * @param cb - The callback function to remove
4713
5136
  */
4714
5137
  async removeListener(type, cb) {
4715
5138
  if (type === 'link-added') {
@@ -4725,13 +5148,20 @@ class PerspectiveProxy {
4725
5148
  __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
4726
5149
  }
4727
5150
  }
4728
- /** Create and return a snapshot of this perspective
4729
- * A snapshot is a rendered Perspectie object that contains all the links of the perspective.
5151
+ /**
5152
+ * Creates a snapshot of the current perspective state.
5153
+ * Useful for backup or sharing.
5154
+ *
5155
+ * @returns Perspective object containing all links
4730
5156
  */
4731
5157
  async snapshot() {
4732
5158
  return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").snapshotByUUID(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4733
5159
  }
4734
- /** Take and load all the links from the given snapshot */
5160
+ /**
5161
+ * Loads a perspective snapshot, replacing current content.
5162
+ *
5163
+ * @param snapshot - Perspective snapshot to load
5164
+ */
4735
5165
  async loadSnapshot(snapshot) {
4736
5166
  //Clean the input data from __typename
4737
5167
  const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));
@@ -4743,11 +5173,21 @@ class PerspectiveProxy {
4743
5173
  await this.addLinkExpression(link);
4744
5174
  }
4745
5175
  }
4746
- /** Convenience function to get the target of the first link that matches the given query
4747
- * This makes sense when the query is expected to return only one link
4748
- * and the target of that link is what you are looking for.
5176
+ /**
5177
+ * Gets a single target value matching a query.
5178
+ * Useful when you expect only one result.
4749
5179
  *
4750
- * Works best together with @member setSingelTarget()
5180
+ * @param query - Query to find the target
5181
+ * @returns Target value or void if not found
5182
+ *
5183
+ * @example
5184
+ * ```typescript
5185
+ * // Get a user's name
5186
+ * const name = await perspective.getSingleTarget({
5187
+ * source: "did:key:alice",
5188
+ * predicate: "name"
5189
+ * });
5190
+ * ```
4751
5191
  */
4752
5192
  async getSingleTarget(query) {
4753
5193
  delete query.target;
@@ -4757,12 +5197,21 @@ class PerspectiveProxy {
4757
5197
  else
4758
5198
  return null;
4759
5199
  }
4760
- /** Convenience function to ensure there is only one link with given source and predicate
4761
- * This function will remove all links with the same source and predicate as the given link,
4762
- * and then add the given link.
4763
- * This ensures there is only one target for the given source and predicate.
5200
+ /**
5201
+ * Sets a single target value, removing any existing targets.
4764
5202
  *
4765
- * Works best together with @member getSingleTarget()
5203
+ * @param link - Link defining the new target
5204
+ * @param status - Whether the link should be shared
5205
+ *
5206
+ * @example
5207
+ * ```typescript
5208
+ * // Set a user's status
5209
+ * await perspective.setSingleTarget({
5210
+ * source: "did:key:alice",
5211
+ * predicate: "status",
5212
+ * target: "online"
5213
+ * });
5214
+ * ```
4766
5215
  */
4767
5216
  async setSingleTarget(link, status = 'shared') {
4768
5217
  const query = new exports.LinkQuery({ source: link.source, predicate: link.predicate });
@@ -4838,7 +5287,7 @@ class PerspectiveProxy {
4838
5287
  return [];
4839
5288
  }
4840
5289
  }
4841
- async stringOrTemplateObjectToSubjectClass(subjectClass) {
5290
+ async stringOrTemplateObjectToSubjectClassName(subjectClass) {
4842
5291
  if (typeof subjectClass === "string")
4843
5292
  return subjectClass;
4844
5293
  else {
@@ -4852,24 +5301,37 @@ class PerspectiveProxy {
4852
5301
  }
4853
5302
  }
4854
5303
  }
4855
- /** Creates a new subject instance by running its (SDNA defined) constructor,
4856
- * which means adding links around the given expression address so that it
4857
- * conforms to the given subject class.
5304
+ /**
5305
+ * Creates a new subject instance of the given subject class
4858
5306
  *
4859
5307
  * @param subjectClass Either a string with the name of the subject class, or an object
4860
- * with the properties of the subject class. In the latter case, the first subject class
4861
- * that matches the given properties will be used.
5308
+ * with the properties of the subject class.
4862
5309
  * @param exprAddr The address of the expression to be turned into a subject instance
5310
+ * @param initialValues Optional initial values for properties. If provided, these will be
5311
+ * merged with constructor actions for better performance.
5312
+ * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
5313
+ * instead of the subject proxy since the subject won't exist until the batch is committed.
5314
+ * @returns A proxy object for the created subject, or just the expression address if in batch mode
4863
5315
  */
4864
- async createSubject(subjectClass, exprAddr) {
5316
+ async createSubject(subjectClass, exprAddr, initialValues, batchId) {
4865
5317
  let className;
4866
5318
  if (typeof subjectClass === "string") {
4867
5319
  className = subjectClass;
4868
- await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className }), exprAddr);
5320
+ await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
5321
+ className,
5322
+ initialValues
5323
+ }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
4869
5324
  }
4870
5325
  else {
4871
5326
  let query = this.buildQueryFromTemplate(subjectClass);
4872
- await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ query }), exprAddr);
5327
+ await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
5328
+ query,
5329
+ initialValues
5330
+ }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
5331
+ }
5332
+ // Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed
5333
+ if (batchId) {
5334
+ return exprAddr;
4873
5335
  }
4874
5336
  return this.getSubjectProxy(exprAddr, subjectClass);
4875
5337
  }
@@ -4887,15 +5349,17 @@ class PerspectiveProxy {
4887
5349
  * with the properties of the subject class. In the latter case, the first subject class
4888
5350
  * that matches the given properties will be used.
4889
5351
  * @param exprAddr The address of the expression to be turned into a subject instance
5352
+ * @param batchId Optional batch ID for grouping operations. If provided, the removal will be part of the batch
5353
+ * and won't be executed until the batch is committed.
4890
5354
  */
4891
- async removeSubject(subjectClass, exprAddr) {
4892
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass);
5355
+ async removeSubject(subjectClass, exprAddr, batchId) {
5356
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
4893
5357
  let result = await this.infer(`subject_class("${className}", C), destructor(C, Actions)`);
4894
5358
  if (!result.length) {
4895
- throw "No constructor found for given subject class: " + className;
5359
+ throw "No destructor found for given subject class: " + className;
4896
5360
  }
4897
5361
  let actions = result.map(x => eval(x.Actions));
4898
- await this.executeAction(actions[0], exprAddr, undefined);
5362
+ await this.executeAction(actions[0], exprAddr, undefined, batchId);
4899
5363
  }
4900
5364
  /** Checks if the given expression is a subject instance of the given subject class
4901
5365
  * @param expression The expression to be checked
@@ -4904,7 +5368,7 @@ class PerspectiveProxy {
4904
5368
  * that matches the given properties will be used.
4905
5369
  */
4906
5370
  async isSubjectInstance(expression, subjectClass) {
4907
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass);
5371
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
4908
5372
  let isInstance = false;
4909
5373
  const maxAttempts = 5;
4910
5374
  let attempts = 0;
@@ -4927,7 +5391,7 @@ class PerspectiveProxy {
4927
5391
  if (!await this.isSubjectInstance(base, subjectClass)) {
4928
5392
  throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`;
4929
5393
  }
4930
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass);
5394
+ let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
4931
5395
  let subject = new Subject(this, base, className);
4932
5396
  await subject.init();
4933
5397
  return subject;
@@ -5088,9 +5552,63 @@ class PerspectiveProxy {
5088
5552
  getNeighbourhoodProxy() {
5089
5553
  return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
5090
5554
  }
5555
+ /**
5556
+ * Returns a proxy object for working with AI capabilities.
5557
+ *
5558
+ * @returns AIClient instance
5559
+ *
5560
+ * @example
5561
+ * ```typescript
5562
+ * // Use AI to analyze perspective content
5563
+ * const summary = await perspective.ai.summarize();
5564
+ *
5565
+ * // Generate new content
5566
+ * const suggestion = await perspective.ai.suggest("next action");
5567
+ * ```
5568
+ */
5091
5569
  get ai() {
5092
5570
  return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").aiClient;
5093
5571
  }
5572
+ /**
5573
+ * Creates a subscription for a Prolog query that updates in real-time.
5574
+ *
5575
+ * This method:
5576
+ * 1. Creates the subscription on the Rust side
5577
+ * 2. Sets up the subscription callback
5578
+ * 3. Waits for the initial result to come through the subscription channel
5579
+ * 4. Returns a fully initialized QuerySubscriptionProxy
5580
+ *
5581
+ * The returned subscription is guaranteed to be ready to receive updates,
5582
+ * as this method waits for the initialization process to complete.
5583
+ *
5584
+ * @param query - Prolog query string
5585
+ * @returns Initialized QuerySubscriptionProxy instance
5586
+ *
5587
+ * @example
5588
+ * ```typescript
5589
+ * // Subscribe to active todos
5590
+ * const subscription = await perspective.subscribeInfer(`
5591
+ * instance(Todo, "Todo"),
5592
+ * property_getter("Todo", Todo, "state", "active")
5593
+ * `);
5594
+ *
5595
+ * // Subscription is already initialized here
5596
+ * console.log("Initial result:", subscription.result);
5597
+ *
5598
+ * // Set up callback for future updates
5599
+ * subscription.onResult((todos) => {
5600
+ * console.log("Active todos:", todos);
5601
+ * });
5602
+ * ```
5603
+ */
5604
+ async subscribeInfer(query) {
5605
+ // Start the subscription on the Rust side first to get the real subscription ID
5606
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").subscribeQuery(this.uuid, query);
5607
+ const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, result.subscriptionId, result.result, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f"));
5608
+ // Wait for the initial result
5609
+ await subscriptionProxy.initialized;
5610
+ return subscriptionProxy;
5611
+ }
5094
5612
  }
5095
5613
  _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
5096
5614
 
@@ -5230,6 +5748,62 @@ class PerspectiveClient {
5230
5748
  }));
5231
5749
  return JSON.parse(perspectiveQueryProlog);
5232
5750
  }
5751
+ async subscribeQuery(uuid, query) {
5752
+ const { perspectiveSubscribeQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5753
+ mutation: gql `mutation perspectiveSubscribeQuery($uuid: String!, $query: String!) {
5754
+ perspectiveSubscribeQuery(uuid: $uuid, query: $query) {
5755
+ subscriptionId
5756
+ result
5757
+ }
5758
+ }`,
5759
+ variables: { uuid, query }
5760
+ }));
5761
+ const { subscriptionId, result } = perspectiveSubscribeQuery;
5762
+ let finalResult = result;
5763
+ try {
5764
+ finalResult = JSON.parse(result);
5765
+ }
5766
+ catch (e) {
5767
+ console.error('Error parsing perspectiveSubscribeQuery result:', e);
5768
+ }
5769
+ return { subscriptionId, result: finalResult };
5770
+ }
5771
+ subscribeToQueryUpdates(subscriptionId, onData) {
5772
+ const subscription = __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").subscribe({
5773
+ query: gql `
5774
+ subscription perspectiveQuerySubscription($subscriptionId: String!) {
5775
+ perspectiveQuerySubscription(subscriptionId: $subscriptionId)
5776
+ }
5777
+ `,
5778
+ variables: {
5779
+ subscriptionId
5780
+ }
5781
+ }).subscribe({
5782
+ next: (result) => {
5783
+ if (result.data && result.data.perspectiveQuerySubscription) {
5784
+ let finalResult = result.data.perspectiveQuerySubscription;
5785
+ try {
5786
+ finalResult = JSON.parse(result.data.perspectiveQuerySubscription);
5787
+ }
5788
+ catch (e) {
5789
+ console.error('Error parsing perspectiveQuerySubscription:', e);
5790
+ }
5791
+ onData(finalResult);
5792
+ }
5793
+ },
5794
+ error: (e) => console.error('Error in query subscription:', e)
5795
+ });
5796
+ return () => subscription.unsubscribe();
5797
+ }
5798
+ async keepAliveQuery(uuid, subscriptionId) {
5799
+ const { perspectiveKeepAliveQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5800
+ mutation: gql `mutation perspectiveKeepAliveQuery($uuid: String!, $subscriptionId: String!) {
5801
+ perspectiveKeepAliveQuery(uuid: $uuid, subscriptionId: $subscriptionId)
5802
+ }`,
5803
+ variables: { uuid, subscriptionId }
5804
+ }));
5805
+ return perspectiveKeepAliveQuery;
5806
+ }
5233
5807
  async add(name) {
5234
5808
  const { perspectiveAdd } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5235
5809
  mutation: gql `mutation perspectiveAdd($name: String!) {
@@ -5260,36 +5834,36 @@ class PerspectiveClient {
5260
5834
  variables: { uuid }
5261
5835
  }));
5262
5836
  }
5263
- async addLink(uuid, link, status) {
5837
+ async addLink(uuid, link, status = 'shared', batchId) {
5264
5838
  const { perspectiveAddLink } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5265
- mutation: gql `mutation perspectiveAddLink($uuid: String!, $link: LinkInput!, $status: String){
5266
- perspectiveAddLink(link: $link, uuid: $uuid, status: $status) {
5839
+ mutation: gql `mutation perspectiveAddLink($uuid: String!, $link: LinkInput!, $status: String!, $batchId: String) {
5840
+ perspectiveAddLink(uuid: $uuid, link: $link, status: $status, batchId: $batchId) {
5267
5841
  ${LINK_EXPRESSION_FIELDS}
5268
5842
  }
5269
5843
  }`,
5270
- variables: { uuid, link, status }
5844
+ variables: { uuid, link, status, batchId }
5271
5845
  }));
5272
5846
  return perspectiveAddLink;
5273
5847
  }
5274
- async addLinks(uuid, links, status) {
5848
+ async addLinks(uuid, links, status = 'shared', batchId) {
5275
5849
  const { perspectiveAddLinks } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5276
- mutation: gql `mutation perspectiveAddLinks($uuid: String!, $links: [LinkInput!]!, $status: String){
5277
- perspectiveAddLinks(links: $links, uuid: $uuid, status: $status) {
5850
+ mutation: gql `mutation perspectiveAddLinks($uuid: String!, $links: [LinkInput!]!, $status: String!, $batchId: String) {
5851
+ perspectiveAddLinks(uuid: $uuid, links: $links, status: $status, batchId: $batchId) {
5278
5852
  ${LINK_EXPRESSION_FIELDS}
5279
5853
  }
5280
5854
  }`,
5281
- variables: { uuid, links, status }
5855
+ variables: { uuid, links, status, batchId }
5282
5856
  }));
5283
5857
  return perspectiveAddLinks;
5284
5858
  }
5285
- async removeLinks(uuid, links) {
5859
+ async removeLinks(uuid, links, batchId) {
5286
5860
  const { perspectiveRemoveLinks } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5287
- mutation: gql `mutation perspectiveRemoveLinks($uuid: String!, $links: [LinkExpressionInput!]!){
5288
- perspectiveRemoveLinks(links: $links, uuid: $uuid) {
5861
+ mutation: gql `mutation perspectiveRemoveLinks($uuid: String!, $links: [LinkExpressionInput!]!, $batchId: String) {
5862
+ perspectiveRemoveLinks(uuid: $uuid, links: $links, batchId: $batchId) {
5289
5863
  ${LINK_EXPRESSION_FIELDS}
5290
5864
  }
5291
5865
  }`,
5292
- variables: { uuid, links }
5866
+ variables: { uuid, links, batchId }
5293
5867
  }));
5294
5868
  return perspectiveRemoveLinks;
5295
5869
  }
@@ -5309,76 +5883,62 @@ class PerspectiveClient {
5309
5883
  }));
5310
5884
  return perspectiveLinkMutations;
5311
5885
  }
5312
- async addLinkExpression(uuid, link, status) {
5886
+ async addLinkExpression(uuid, link, status = 'shared', batchId) {
5313
5887
  const { perspectiveAddLinkExpression } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5314
- mutation: gql `mutation perspectiveAddLinkExpression($uuid: String!, $link: LinkExpressionInput!, $status: String){
5315
- perspectiveAddLinkExpression(link: $link, uuid: $uuid, status: $status) {
5888
+ mutation: gql `mutation perspectiveAddLinkExpression($uuid: String!, $link: LinkExpressionInput!, $status: String!, $batchId: String) {
5889
+ perspectiveAddLinkExpression(uuid: $uuid, link: $link, status: $status, batchId: $batchId) {
5316
5890
  ${LINK_EXPRESSION_FIELDS}
5317
5891
  }
5318
5892
  }`,
5319
- variables: { uuid, link }
5893
+ variables: { uuid, link, status, batchId }
5320
5894
  }));
5321
5895
  return perspectiveAddLinkExpression;
5322
5896
  }
5323
- async updateLink(uuid, oldLink, newLink) {
5324
- delete oldLink.__typename;
5325
- delete oldLink.data.__typename;
5326
- delete oldLink.proof.__typename;
5897
+ async updateLink(uuid, oldLink, newLink, batchId) {
5327
5898
  const { perspectiveUpdateLink } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5328
- mutation: gql `mutation perspectiveUpdateLink(
5329
- $uuid: String!,
5330
- $newLink: LinkInput!
5331
- $oldLink: LinkExpressionInput!
5332
- ){
5333
- perspectiveUpdateLink(
5334
- newLink: $newLink,
5335
- oldLink: $oldLink,
5336
- uuid: $uuid
5337
- ) {
5899
+ mutation: gql `mutation perspectiveUpdateLink($uuid: String!, $oldLink: LinkExpressionInput!, $newLink: LinkInput!, $batchId: String) {
5900
+ perspectiveUpdateLink(uuid: $uuid, oldLink: $oldLink, newLink: $newLink, batchId: $batchId) {
5338
5901
  ${LINK_EXPRESSION_FIELDS}
5339
5902
  }
5340
5903
  }`,
5341
- variables: { uuid, oldLink, newLink }
5904
+ variables: { uuid, oldLink, newLink, batchId }
5342
5905
  }));
5343
- if (!perspectiveUpdateLink.status) {
5344
- delete perspectiveUpdateLink.status;
5345
- }
5346
5906
  return perspectiveUpdateLink;
5347
5907
  }
5348
- async removeLink(uuid, link) {
5908
+ async removeLink(uuid, link, batchId) {
5349
5909
  delete link.__typename;
5350
5910
  delete link.data.__typename;
5351
5911
  delete link.proof.__typename;
5352
5912
  delete link.status;
5353
- return unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5354
- mutation: gql `mutation perspectiveRemoveLink($link: LinkExpressionInput!, $uuid: String!) {
5355
- perspectiveRemoveLink(link: $link, uuid: $uuid)
5913
+ const { perspectiveRemoveLink } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5914
+ mutation: gql `mutation perspectiveRemoveLink($link: LinkExpressionInput!, $uuid: String!, $batchId: String) {
5915
+ perspectiveRemoveLink(link: $link, uuid: $uuid, batchId: $batchId)
5356
5916
  }`,
5357
- variables: { uuid, link }
5917
+ variables: { uuid, link, batchId }
5358
5918
  }));
5919
+ return perspectiveRemoveLink;
5359
5920
  }
5360
5921
  async addSdna(uuid, name, sdnaCode, sdnaType) {
5361
5922
  return unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5362
5923
  mutation: gql `mutation perspectiveAddSdna($uuid: String!, $name: String!, $sdnaCode: String!, $sdnaType: String!) {
5363
5924
  perspectiveAddSdna(uuid: $uuid, name: $name, sdnaCode: $sdnaCode, sdnaType: $sdnaType)
5364
- }`,
5365
- variables: { uuid, name, sdnaCode, sdnaType }
5925
+ }`, variables: { uuid, name, sdnaCode, sdnaType }
5366
5926
  })).perspectiveAddSdna;
5367
5927
  }
5368
- async executeCommands(uuid, commands, expression, parameters) {
5928
+ async executeCommands(uuid, commands, expression, parameters, batchId) {
5369
5929
  return unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5370
- mutation: gql `mutation perspectiveExecuteCommands($uuid: String!, $commands: String!, $expression: String!, $parameters: String) {
5371
- perspectiveExecuteCommands(uuid: $uuid, commands: $commands, expression: $expression, parameters: $parameters)
5930
+ mutation: gql `mutation perspectiveExecuteCommands($uuid: String!, $commands: String!, $expression: String!, $parameters: String, $batchId: String) {
5931
+ perspectiveExecuteCommands(uuid: $uuid, commands: $commands, expression: $expression, parameters: $parameters, batchId: $batchId)
5372
5932
  }`,
5373
- variables: { uuid, commands, expression, parameters }
5933
+ variables: { uuid, commands, expression, parameters, batchId }
5374
5934
  })).perspectiveExecuteCommands;
5375
5935
  }
5376
- async createSubject(uuid, subjectClass, expressionAddress) {
5936
+ async createSubject(uuid, subjectClass, expressionAddress, initialValues, batchId) {
5377
5937
  return unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5378
- mutation: gql `mutation perspectiveCreateSubject($uuid: String!, $subjectClass: String!, $expressionAddress: String!) {
5379
- perspectiveCreateSubject(uuid: $uuid, subjectClass: $subjectClass, expressionAddress: $expressionAddress)
5938
+ mutation: gql `mutation perspectiveCreateSubject($uuid: String!, $subjectClass: String!, $expressionAddress: String!, $initialValues: String, $batchId: String) {
5939
+ perspectiveCreateSubject(uuid: $uuid, subjectClass: $subjectClass, expressionAddress: $expressionAddress, initialValues: $initialValues, batchId: $batchId)
5380
5940
  }`,
5381
- variables: { uuid, subjectClass, expressionAddress }
5941
+ variables: { uuid, subjectClass, expressionAddress, initialValues, batchId }
5382
5942
  })).perspectiveCreateSubject;
5383
5943
  }
5384
5944
  async getSubjectData(uuid, subjectClass, expressionAddress) {
@@ -5537,6 +6097,31 @@ class PerspectiveClient {
5537
6097
  getNeighbourhoodProxy(uuid) {
5538
6098
  return new NeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveClient_neighbourhoodClient, "f"), uuid);
5539
6099
  }
6100
+ async createBatch(uuid) {
6101
+ const { perspectiveCreateBatch } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
6102
+ mutation: gql `mutation perspectiveCreateBatch($uuid: String!) {
6103
+ perspectiveCreateBatch(uuid: $uuid)
6104
+ }`,
6105
+ variables: { uuid }
6106
+ }));
6107
+ return perspectiveCreateBatch;
6108
+ }
6109
+ async commitBatch(uuid, batchId) {
6110
+ const { perspectiveCommitBatch } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
6111
+ mutation: gql `mutation perspectiveCommitBatch($uuid: String!, $batchId: String!) {
6112
+ perspectiveCommitBatch(uuid: $uuid, batchId: $batchId) {
6113
+ additions {
6114
+ ${LINK_EXPRESSION_FIELDS}
6115
+ }
6116
+ removals {
6117
+ ${LINK_EXPRESSION_FIELDS}
6118
+ }
6119
+ }
6120
+ }`,
6121
+ variables: { uuid, batchId }
6122
+ }));
6123
+ return perspectiveCommitBatch;
6124
+ }
5540
6125
  }
5541
6126
  _PerspectiveClient_apolloClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap();
5542
6127
 
@@ -6344,10 +6929,10 @@ class NeighbourhoodClient {
6344
6929
  let handlersForPerspective = __classPrivateFieldGet$6(this, _NeighbourhoodClient_signalHandlers, "f").get(perspectiveUUID);
6345
6930
  if (!handlersForPerspective) {
6346
6931
  handlersForPerspective = [];
6932
+ __classPrivateFieldGet$6(this, _NeighbourhoodClient_signalHandlers, "f").set(perspectiveUUID, handlersForPerspective);
6347
6933
  await this.subscribeToSignals(perspectiveUUID);
6348
6934
  }
6349
6935
  handlersForPerspective.push(handler);
6350
- __classPrivateFieldGet$6(this, _NeighbourhoodClient_signalHandlers, "f").set(perspectiveUUID, handlersForPerspective);
6351
6936
  }
6352
6937
  removeSignalHandler(perspectiveUUID, handler) {
6353
6938
  const handlersForPerspective = __classPrivateFieldGet$6(this, _NeighbourhoodClient_signalHandlers, "f").get(perspectiveUUID);
@@ -6355,9 +6940,11 @@ class NeighbourhoodClient {
6355
6940
  const index = handlersForPerspective.indexOf(handler);
6356
6941
  if (index > -1) {
6357
6942
  handlersForPerspective.splice(index, 1);
6943
+ if (!handlersForPerspective.length) {
6944
+ __classPrivateFieldGet$6(this, _NeighbourhoodClient_signalHandlers, "f").delete(perspectiveUUID);
6945
+ }
6358
6946
  }
6359
6947
  }
6360
- __classPrivateFieldGet$6(this, _NeighbourhoodClient_signalHandlers, "f").set(perspectiveUUID, handlersForPerspective);
6361
6948
  }
6362
6949
  }
6363
6950
  _NeighbourhoodClient_apolloClient = new WeakMap(), _NeighbourhoodClient_signalHandlers = new WeakMap();
@@ -14377,19 +14964,19 @@ class AIClient {
14377
14964
  }
14378
14965
  return aiCloseTranscriptionStream;
14379
14966
  }
14380
- async feedTranscriptionStream(streamId, audio) {
14381
- const { feedTranscriptionStream } = unwrapApolloResult(await __classPrivateFieldGet$3(this, _AIClient_apolloClient, "f").mutate({
14967
+ async feedTranscriptionStream(streamIds, audio) {
14968
+ const { aiFeedTranscriptionStream } = unwrapApolloResult(await __classPrivateFieldGet$3(this, _AIClient_apolloClient, "f").mutate({
14382
14969
  mutation: gql `
14383
- mutation AiFeedTranscriptionStream($streamId: String!, $audio: [Float!]!) {
14384
- aiFeedTranscriptionStream(streamId: $streamId, audio: $audio)
14970
+ mutation AiFeedTranscriptionStream($streamIds: [String!]!, $audio: [Float!]!) {
14971
+ aiFeedTranscriptionStream(streamIds: $streamIds, audio: $audio)
14385
14972
  }
14386
14973
  `,
14387
14974
  variables: {
14388
- streamId,
14975
+ streamIds: Array.isArray(streamIds) ? streamIds : [streamIds],
14389
14976
  audio: audio
14390
14977
  }
14391
14978
  }));
14392
- return feedTranscriptionStream;
14979
+ return aiFeedTranscriptionStream;
14393
14980
  }
14394
14981
  }
14395
14982
  _AIClient_apolloClient = new WeakMap(), _AIClient_transcriptionSubscriptions = new WeakMap();
@@ -14941,23 +15528,44 @@ function hasLink(predicate) {
14941
15528
  return `triple(this, "${predicate}", _)`;
14942
15529
  }
14943
15530
  /**
14944
- * Decorator for querying instances of a subject class.
15531
+ * Decorator for querying instances of a model class.
14945
15532
  *
14946
15533
  * @category Decorators
14947
15534
  *
14948
15535
  * @description
14949
- * NOTE: Only works on methods that return a promise and will throw an error if not used on a method that returns a promise.
14950
- * This will allow you to query for instances of a subject class with custom clauses within the instance clauses.
15536
+ * Allows you to define static query methods on your model class to retrieve instances based on custom conditions.
15537
+ * This decorator can only be applied to static async methods that return a Promise of an array of model instances.
14951
15538
  *
14952
- * @example
14953
- * // Usage with where clause
14954
- * InstanceQuery({ where: { name: "John" }}) // this will return all the properties of the subject class with the name "John"
15539
+ * The query can be constrained using either:
15540
+ * - A `where` clause that matches property values
15541
+ * - A custom Prolog `condition` for more complex queries
14955
15542
  *
14956
15543
  * @example
14957
- * // Usage with condition clause
14958
- * InstanceQuery({ condition: "triple(Instance, 'age', Age), Age > 18" }) // this will return all the properties of the subject class with the age greater than 18
15544
+ * ```typescript
15545
+ * class Recipe extends Ad4mModel {
15546
+ * @Property({ through: "recipe://name" })
15547
+ * name: string = "";
15548
+ *
15549
+ * @Property({ through: "recipe://rating" })
15550
+ * rating: number = 0;
15551
+ *
15552
+ * // Get all recipes
15553
+ * @InstanceQuery()
15554
+ * static async all(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
15555
+ *
15556
+ * // Get recipes by name
15557
+ * @InstanceQuery({ where: { name: "Chocolate Cake" }})
15558
+ * static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
15559
+ *
15560
+ * // Get highly rated recipes using a custom condition
15561
+ * @InstanceQuery({ condition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
15562
+ * static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
15563
+ * }
15564
+ * ```
14959
15565
  *
14960
- * @param {Object} [options] - Query options.
15566
+ * @param {Object} [options] - Query options
15567
+ * @param {object} [options.where] - Object with property-value pairs to match
15568
+ * @param {string} [options.condition] - Custom Prolog condition for more complex queries
14961
15569
  */
14962
15570
  function InstanceQuery(options) {
14963
15571
  return function (target, key, descriptor) {
@@ -14997,28 +15605,89 @@ function InstanceQuery(options) {
14997
15605
  };
14998
15606
  }
14999
15607
  /**
15000
- * Decorator for defining properties of a subject class.
15608
+ * Decorator for defining optional properties on model classes.
15001
15609
  *
15002
15610
  * @category Decorators
15003
15611
  *
15004
15612
  * @description
15005
- * This will allow you to define properties with different conditions and how they would be defined in proflog engine.
15613
+ * The most flexible property decorator that allows you to define properties with full control over:
15614
+ * - Whether the property is required
15615
+ * - Whether the property is writable
15616
+ * - How values are stored and retrieved
15617
+ * - Custom getter/setter logic
15618
+ * - Local vs network storage
15006
15619
  *
15007
- * - All properties must have a `through` option which is the predicate of the property.
15008
- * -e If the property is required, it must have an `initial` option which is the initial value of the property.
15009
- * - If the property is writable, it will have a setter in prolog engine. A custom setter can be defined with the `setter` option.
15010
- * - If resolveLanguage is defined, you can use the default `Literal` Language or use your custom language address that can be used to store the property.
15011
- * - If a custom getter is defined, it will be used to get the value of the property in prolog engine. If not, the default getter will be used.
15012
- * - If local is defined, the property will be stored locally in the perspective and not in the network. This is useful for properties that are not meant to be shared with the network
15620
+ * Both @Property and @ReadOnly are specialized versions of @Optional with preset configurations.
15013
15621
  *
15014
15622
  * @example
15015
- * // Usage
15016
- * SubjectProperty({ through: "ad4m://name", initial: "John", required: true }) // this will define a property with the name "ad4m://name" and the initial value "John"
15623
+ * ```typescript
15624
+ * class Recipe extends Ad4mModel {
15625
+ * // Basic optional property
15626
+ * @Optional({
15627
+ * through: "recipe://description"
15628
+ * })
15629
+ * description?: string;
15630
+ *
15631
+ * // Optional property with custom initial value
15632
+ * @Optional({
15633
+ * through: "recipe://status",
15634
+ * initial: "recipe://draft",
15635
+ * required: true
15636
+ * })
15637
+ * status: string = "";
15638
+ *
15639
+ * // Read-only property with custom getter
15640
+ * @Optional({
15641
+ * through: "recipe://rating",
15642
+ * writable: false,
15643
+ * getter: `
15644
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
15645
+ * sum_list(Ratings, Sum),
15646
+ * length(Ratings, Count),
15647
+ * Value is Sum / Count
15648
+ * `
15649
+ * })
15650
+ * averageRating: number = 0;
15651
+ *
15652
+ * // Property that resolves to a Literal and is stored locally
15653
+ * @Optional({
15654
+ * through: "recipe://notes",
15655
+ * resolveLanguage: "literal",
15656
+ * local: true
15657
+ * })
15658
+ * notes?: string;
15659
+ *
15660
+ * // Property with custom getter and setter logic
15661
+ * @Optional({
15662
+ * through: "recipe://ingredients",
15663
+ * getter: `
15664
+ * triple(Base, "recipe://ingredients", RawValue),
15665
+ * atom_json_term(RawValue, Value)
15666
+ * `,
15667
+ * setter: `
15668
+ * atom_json_term(Value, JsonValue),
15669
+ * Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "recipe://ingredients", "target": JsonValue}]
15670
+ * `
15671
+ * })
15672
+ * ingredients: string[] = [];
15673
+ * }
15674
+ * ```
15017
15675
  *
15018
- * @param {PropertyOptions} [opts] - Property options.
15676
+ * @param {PropertyOptions} opts - Property configuration options
15677
+ * @param {string} opts.through - The predicate URI for the property
15678
+ * @param {string} [opts.initial] - Initial value (required if property is required)
15679
+ * @param {boolean} [opts.required] - Whether the property must have a value
15680
+ * @param {boolean} [opts.writable=true] - Whether the property can be modified
15681
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
15682
+ * @param {string} [opts.getter] - Custom Prolog code for getting the property value
15683
+ * @param {string} [opts.setter] - Custom Prolog code for setting the property value
15684
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
15019
15685
  */
15020
- function SubjectProperty(opts) {
15686
+ function Optional(opts) {
15021
15687
  return function (target, key) {
15688
+ if (typeof opts.writable === "undefined" && opts.through) {
15689
+ opts.writable = true;
15690
+ }
15022
15691
  if (opts.required && !opts.initial) {
15023
15692
  throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
15024
15693
  }
@@ -15030,31 +15699,65 @@ function SubjectProperty(opts) {
15030
15699
  target["__properties"][key] = { ...target["__properties"][key], ...opts };
15031
15700
  if (opts.writable) {
15032
15701
  const value = key;
15033
- target[`set${capitalize(value)}`] = () => { };
15702
+ target[`set${capitalize$1(value)}`] = () => { };
15034
15703
  }
15035
15704
  Object.defineProperty(target, key, { configurable: true, writable: true });
15036
15705
  };
15037
15706
  }
15038
15707
  /**
15039
- * Decorator for defining flags of a subject class
15708
+ * Decorator for defining flags on model classes.
15040
15709
  *
15041
15710
  * @category Decorators
15042
15711
  *
15043
15712
  * @description
15044
- * The idea behind flag decorator is to define a property that is required and has an initial value.
15045
- * This will allow you to define a strict instance query. This behaviour can also be achieved with the `SubjectProperty` decorator but the `SubjectFlag` decorator is a shorthand for that.
15713
+ * A specialized property decorator for defining immutable type flags or markers on model instances.
15714
+ * Flags are always required properties with a fixed value that cannot be changed after creation.
15046
15715
  *
15047
- * NOTE: Use of Flag is discouraged and should be used only when necessary.
15716
+ * Common uses for flags:
15717
+ * - Type discrimination between different kinds of models
15718
+ * - Marking models with specific capabilities or features
15719
+ * - Versioning or compatibility markers
15048
15720
  *
15049
- * - All properties must have a `through` & `initial` option which is the predicate of the property.
15721
+ * Note: Use of Flag is discouraged unless you specifically need type-based filtering or
15722
+ * discrimination between different kinds of models. For most cases, regular properties
15723
+ * with @Property or @Optional are more appropriate.
15050
15724
  *
15051
15725
  * @example
15052
- * // Usage
15053
- * SubjectFlag({ through: "ad4m://name", value: "John" }) // this will define a flag with the name "ad4m://name" and the initial value "John"
15726
+ * ```typescript
15727
+ * class Message extends Ad4mModel {
15728
+ * // Type flag to identify message models
15729
+ * @Flag({
15730
+ * through: "ad4m://type",
15731
+ * value: "ad4m://message"
15732
+ * })
15733
+ * type: string = "";
15734
+ *
15735
+ * // Version flag for compatibility
15736
+ * @Flag({
15737
+ * through: "ad4m://version",
15738
+ * value: "1.0.0"
15739
+ * })
15740
+ * version: string = "";
15741
+ *
15742
+ * // Feature flag
15743
+ * @Flag({
15744
+ * through: "message://feature",
15745
+ * value: "message://encrypted"
15746
+ * })
15747
+ * feature: string = "";
15748
+ * }
15054
15749
  *
15055
- * @param {FlagOptions} [opts] Flag options.
15750
+ * // Later you can query for specific types:
15751
+ * const messages = await Message.query(perspective)
15752
+ * .where({ type: "ad4m://message" })
15753
+ * .run();
15754
+ * ```
15755
+ *
15756
+ * @param {FlagOptions} opts - Flag configuration
15757
+ * @param {string} opts.through - The predicate URI for the flag
15758
+ * @param {string} opts.value - The fixed value for the flag
15056
15759
  */
15057
- function SubjectFlag(opts) {
15760
+ function Flag(opts) {
15058
15761
  return function (target, key) {
15059
15762
  if (!opts.through && !opts.value) {
15060
15763
  throw new Error("SubjectFlag requires a 'through' and 'value' option");
@@ -15080,33 +15783,78 @@ function SubjectFlag(opts) {
15080
15783
  };
15081
15784
  }
15082
15785
  /**
15083
- * Decorator for defining collections of a subject class.
15786
+ * Decorator for defining collections on model classes.
15084
15787
  *
15085
15788
  * @category Decorators
15086
15789
  *
15087
15790
  * @description
15088
- * This will allow you to define collections with different conditions and how they would be defined in proflog engine.
15791
+ * Defines a property that represents a collection of values linked to the model instance.
15792
+ * Collections are always arrays and support operations for adding, removing, and setting values.
15089
15793
  *
15090
- * NOTE: The property needs to be an array for it to picked up during the initialization phase.
15794
+ * For each collection property, the following methods are automatically generated:
15795
+ * - `addX(value)` - Add a value to the collection
15796
+ * - `removeX(value)` - Remove a value from the collection
15797
+ * - `setCollectionX(values)` - Replace all values in the collection
15091
15798
  *
15092
- * - All collections must have a `through` option which is the predicate of the collection.
15093
- * - If the collection has a `where` option, it can be used to define a custom condition for the collection.
15094
- * - If the collection has a `local` option, the collection will be stored locally in the perspective and not in the network. This is useful for collections that are not meant to be shared with the network.
15799
+ * Where X is the capitalized property name.
15800
+ *
15801
+ * Collections can be filtered using the `where` option to only include values that:
15802
+ * - Are instances of a specific model class
15803
+ * - Match a custom Prolog condition
15095
15804
  *
15096
15805
  * @example
15097
- * // Usage
15098
- * SubjectCollection({ through: "ad4m://friends" }) // this will define a collection with the name "ad4m://friends"
15806
+ * ```typescript
15807
+ * class Recipe extends Ad4mModel {
15808
+ * // Basic collection of ingredients
15809
+ * @Collection({
15810
+ * through: "recipe://ingredient"
15811
+ * })
15812
+ * ingredients: string[] = [];
15813
+ *
15814
+ * // Collection that only includes instances of another model
15815
+ * @Collection({
15816
+ * through: "recipe://comment",
15817
+ * where: { isInstance: Comment }
15818
+ * })
15819
+ * comments: string[] = [];
15099
15820
  *
15100
- * @param opts Collection options.
15821
+ * // Collection with custom filter condition
15822
+ * @Collection({
15823
+ * through: "recipe://step",
15824
+ * where: { condition: `triple(Target, "step://order", Order), Order < 3` }
15825
+ * })
15826
+ * firstSteps: string[] = [];
15827
+ *
15828
+ * // Local-only collection not shared with network
15829
+ * @Collection({
15830
+ * through: "recipe://note",
15831
+ * local: true
15832
+ * })
15833
+ * privateNotes: string[] = [];
15834
+ * }
15835
+ *
15836
+ * // Using the generated methods:
15837
+ * const recipe = new Recipe(perspective);
15838
+ * await recipe.addIngredients("ingredient://flour");
15839
+ * await recipe.removeIngredients("ingredient://sugar");
15840
+ * await recipe.setCollectionIngredients(["ingredient://butter", "ingredient://eggs"]);
15841
+ * ```
15842
+ *
15843
+ * @param {CollectionOptions} opts - Collection configuration
15844
+ * @param {string} opts.through - The predicate URI for collection links
15845
+ * @param {WhereOptions} [opts.where] - Filter conditions for collection values
15846
+ * @param {any} [opts.where.isInstance] - Model class to filter instances by
15847
+ * @param {string} [opts.where.condition] - Custom Prolog condition for filtering
15848
+ * @param {boolean} [opts.local] - Whether collection links are stored locally only
15101
15849
  */
15102
- function SubjectCollection(opts) {
15850
+ function Collection(opts) {
15103
15851
  return function (target, key) {
15104
15852
  target["__collections"] = target["__collections"] || {};
15105
15853
  target["__collections"][key] = opts;
15106
15854
  const value = key;
15107
- target[`add${capitalize(value)}`] = () => { };
15108
- target[`remove${capitalize(value)}`] = () => { };
15109
- target[`setCollection${capitalize(value)}`] = () => { };
15855
+ target[`add${capitalize$1(value)}`] = () => { };
15856
+ target[`remove${capitalize$1(value)}`] = () => { };
15857
+ target[`setCollection${capitalize$1(value)}`] = () => { };
15110
15858
  Object.defineProperty(target, key, { configurable: true, writable: true });
15111
15859
  };
15112
15860
  }
@@ -15120,22 +15868,60 @@ function makeRandomPrologAtom(length) {
15120
15868
  return result;
15121
15869
  }
15122
15870
  /**
15123
- * Decorator for defining an SDNA class.
15871
+ * Decorator for defining model classes in AD4M.
15124
15872
  *
15125
15873
  * @category Decorators
15126
15874
  *
15127
15875
  * @description
15128
- * This will create a new SDNA class with the given name and add custom methods to generate the SDNA for the class, for this to work the class need to have the properties defined using the decorators like `SubjectProperty`.
15876
+ * The root decorator that must be applied to any class that represents a model in AD4M.
15877
+ * It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure
15878
+ * for storing and retrieving instances.
15129
15879
  *
15130
- * Note: This decorator is required for the class to be picked up during the initialization phase.
15880
+ * This decorator:
15881
+ * - Registers the class with a unique name in the AD4M system
15882
+ * - Generates the necessary SDNA code for the model's properties and collections
15883
+ * - Enables the use of other model decorators (@Property, @Collection, etc.)
15884
+ * - Provides static query methods through the Ad4mModel base class
15131
15885
  *
15132
15886
  * @example
15133
- * // Usage
15134
- * SDNAClass({ name: "Person" }) // this will create a new SDNA class with the name "Person"
15887
+ * ```typescript
15888
+ * @ModelOptions({ name: "Recipe" })
15889
+ * class Recipe extends Ad4mModel {
15890
+ * @Property({
15891
+ * through: "recipe://name",
15892
+ * resolveLanguage: "literal"
15893
+ * })
15894
+ * name: string = "";
15895
+ *
15896
+ * @Collection({ through: "recipe://ingredient" })
15897
+ * ingredients: string[] = [];
15898
+ *
15899
+ * // Static query methods from Ad4mModel:
15900
+ * static async findByName(perspective: PerspectiveProxy, name: string) {
15901
+ * return Recipe.query(perspective)
15902
+ * .where({ name })
15903
+ * .run();
15904
+ * }
15905
+ * }
15135
15906
  *
15136
- * @param opts SDNA class options.
15907
+ * // Using the model:
15908
+ * const recipe = new Recipe(perspective);
15909
+ * recipe.name = "Chocolate Cake";
15910
+ * await recipe.save();
15911
+ *
15912
+ * // Querying instances:
15913
+ * const recipes = await Recipe.query(perspective)
15914
+ * .where({ name: "Chocolate Cake" })
15915
+ * .run();
15916
+ *
15917
+ * // Using with PerspectiveProxy:
15918
+ * await perspective.ensureSDNASubjectClass(Recipe);
15919
+ * ```
15920
+ *
15921
+ * @param {ModelOptionsOptions} opts - Model configuration
15922
+ * @param {string} opts.name - Unique name for the model class in AD4M
15137
15923
  */
15138
- function SDNAClass(opts) {
15924
+ function ModelOptions(opts) {
15139
15925
  return function (target) {
15140
15926
  target.prototype.className = opts.name;
15141
15927
  target.className = opts.name;
@@ -15180,7 +15966,7 @@ function SDNAClass(opts) {
15180
15966
  if (setter) {
15181
15967
  propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${setter}.\n`;
15182
15968
  }
15183
- else if (writable) {
15969
+ else if (writable && through) {
15184
15970
  let setter = obj[propertyNameToSetterName(property)];
15185
15971
  if (typeof setter === "function") {
15186
15972
  let action = [{
@@ -15205,7 +15991,7 @@ function SDNAClass(opts) {
15205
15991
  action: "removeLink",
15206
15992
  source: "this",
15207
15993
  predicate: through,
15208
- target: initial,
15994
+ target: "*",
15209
15995
  });
15210
15996
  }
15211
15997
  }
@@ -15285,6 +16071,130 @@ function SDNAClass(opts) {
15285
16071
  Object.defineProperty(target, 'type', { configurable: true });
15286
16072
  };
15287
16073
  }
16074
+ /**
16075
+ * Decorator for defining required and writable properties on model classes.
16076
+ *
16077
+ * @category Decorators
16078
+ *
16079
+ * @description
16080
+ * A convenience decorator that defines a required property that must have an initial value and is writable by default.
16081
+ * This is equivalent to using @Optional with `required: true` and `writable: true`.
16082
+ *
16083
+ * Properties defined with this decorator:
16084
+ * - Must have a value (required)
16085
+ * - Can be modified after creation (writable)
16086
+ * - Default to "literal://string:uninitialized" if no initial value is provided
16087
+ *
16088
+ * @example
16089
+ * ```typescript
16090
+ * class User extends Ad4mModel {
16091
+ * // Basic required property with default initial value
16092
+ * @Property({
16093
+ * through: "user://name"
16094
+ * })
16095
+ * name: string = "";
16096
+ *
16097
+ * // Required property with custom initial value
16098
+ * @Property({
16099
+ * through: "user://status",
16100
+ * initial: "user://active"
16101
+ * })
16102
+ * status: string = "";
16103
+ *
16104
+ * // Required property with literal resolution
16105
+ * @Property({
16106
+ * through: "user://bio",
16107
+ * resolveLanguage: "literal"
16108
+ * })
16109
+ * bio: string = "";
16110
+ *
16111
+ * // Required property with custom getter/setter
16112
+ * @Property({
16113
+ * through: "user://age",
16114
+ * getter: `triple(Base, "user://birthYear", Year), Value is 2024 - Year`,
16115
+ * setter: `Year is 2024 - Value, Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "user://birthYear", "target": Year}]`
16116
+ * })
16117
+ * age: number = 0;
16118
+ * }
16119
+ * ```
16120
+ *
16121
+ * @param {PropertyOptions} opts - Property configuration
16122
+ * @param {string} opts.through - The predicate URI for the property
16123
+ * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
16124
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
16125
+ * @param {string} [opts.getter] - Custom Prolog code for getting the property value
16126
+ * @param {string} [opts.setter] - Custom Prolog code for setting the property value
16127
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
16128
+ */
16129
+ function Property(opts) {
16130
+ return Optional({
16131
+ ...opts,
16132
+ required: true,
16133
+ writable: true,
16134
+ initial: opts.initial || "literal://string:uninitialized"
16135
+ });
16136
+ }
16137
+ /**
16138
+ * Decorator for defining read-only properties on model classes.
16139
+ *
16140
+ * @category Decorators
16141
+ *
16142
+ * @description
16143
+ * A convenience decorator that defines a property that can only be read and cannot be modified after initialization.
16144
+ * This is equivalent to using @Optional with `writable: false`.
16145
+ *
16146
+ * Read-only properties are ideal for:
16147
+ * - Computed or derived values
16148
+ * - Properties that should never change after creation
16149
+ * - Properties that are set by the system
16150
+ * - Properties that represent immutable data
16151
+ *
16152
+ * @example
16153
+ * ```typescript
16154
+ * class Post extends Ad4mModel {
16155
+ * // Read-only property with custom getter for computed value
16156
+ * @ReadOnly({
16157
+ * through: "post://likes",
16158
+ * getter: `findall(User, triple(Base, "post://liked_by", User), Users), length(Users, Value)`
16159
+ * })
16160
+ * likeCount: number = 0;
16161
+ *
16162
+ * // Read-only property for creation timestamp
16163
+ * @ReadOnly({
16164
+ * through: "post://created_at",
16165
+ * initial: new Date().toISOString()
16166
+ * })
16167
+ * createdAt: string = "";
16168
+ *
16169
+ * // Read-only property that resolves to a Literal
16170
+ * @ReadOnly({
16171
+ * through: "post://author",
16172
+ * resolveLanguage: "literal"
16173
+ * })
16174
+ * author: string = "";
16175
+ *
16176
+ * // Read-only property for system-managed data
16177
+ * @ReadOnly({
16178
+ * through: "post://version",
16179
+ * initial: "1.0.0"
16180
+ * })
16181
+ * version: string = "";
16182
+ * }
16183
+ * ```
16184
+ *
16185
+ * @param {PropertyOptions} opts - Property configuration
16186
+ * @param {string} opts.through - The predicate URI for the property
16187
+ * @param {string} [opts.initial] - Initial value (if property should have one)
16188
+ * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
16189
+ * @param {string} [opts.getter] - Custom Prolog code for getting the property value
16190
+ * @param {boolean} [opts.local] - Whether the property should only be stored locally
16191
+ */
16192
+ function ReadOnly(opts) {
16193
+ return Optional({
16194
+ ...opts,
16195
+ writable: false
16196
+ });
16197
+ }
15288
16198
 
15289
16199
  const typeDefsString = `
15290
16200
  type AIModelLoadingStatus {
@@ -15596,7 +16506,7 @@ type Mutation {
15596
16506
  aiAddTask(task: AITaskInput!): AITask!
15597
16507
  aiCloseTranscriptionStream(streamId: String!): String!
15598
16508
  aiEmbed(modelId: String!, text: String!): String!
15599
- aiFeedTranscriptionStream(audio: [Float!]!, streamId: String!): String!
16509
+ aiFeedTranscriptionStream(audio: [Float!]!, streamIds: [String!]!): String!
15600
16510
  aiOpenTranscriptionStream(modelId: String!, params: VoiceActivityParamsInput): String!
15601
16511
  aiPrompt(prompt: String!, taskId: String!): String!
15602
16512
  aiRemoveModel(modelId: String!): Boolean!
@@ -15620,20 +16530,24 @@ type Mutation {
15620
16530
  neighbourhoodSetOnlineStatus(perspectiveUUID: String!, status: PerspectiveInput!): Boolean!
15621
16531
  neighbourhoodSetOnlineStatusU(perspectiveUUID: String!, status: PerspectiveUnsignedInput!): Boolean!
15622
16532
  perspectiveAdd(name: String!): PerspectiveHandle!
15623
- perspectiveAddLink(link: LinkInput!, status: String = "shared", uuid: String!): LinkExpression!
15624
- perspectiveAddLinkExpression(link: LinkExpressionInput!, status: String, uuid: String!): LinkExpression!
15625
- perspectiveAddLinks(links: [LinkInput!]!, status: String, uuid: String!): [LinkExpression!]!
16533
+ perspectiveAddLink(batchId: String, link: LinkInput!, status: String = "shared", uuid: String!): LinkExpression!
16534
+ perspectiveAddLinkExpression(batchId: String, link: LinkExpressionInput!, status: String = "shared", uuid: String!): LinkExpression!
16535
+ perspectiveAddLinks(batchId: String, links: [LinkInput!]!, status: String = "shared", uuid: String!): [LinkExpression!]!
15626
16536
  perspectiveAddSdna(name: String!, sdnaCode: String!, sdnaType: String!, uuid: String!): Boolean!
15627
- perspectiveCreateSubject(expressionAddress: String!, subjectClass: String!, uuid: String!): Boolean!
15628
- perspectiveExecuteCommands(commands: String!, expression: String!, parameters: String, uuid: String!): Boolean!
16537
+ perspectiveCommitBatch(batchId: String!, uuid: String!): LinkExpressionMutations!
16538
+ perspectiveCreateBatch(uuid: String!): String!
16539
+ perspectiveCreateSubject(batchId: String, expressionAddress: String!, initialValues: String, subjectClass: String!, uuid: String!): Boolean!
16540
+ perspectiveExecuteCommands(batchId: String, commands: String!, expression: String!, parameters: String, uuid: String!): Boolean!
15629
16541
  perspectiveGetSubjectData(expressionAddress: String!, subjectClass: String!, uuid: String!): String!
16542
+ perspectiveKeepAliveQuery(subscriptionId: String!, uuid: String!): Boolean!
15630
16543
  perspectiveLinkMutations(mutations: LinkMutations!, status: String, uuid: String!): LinkExpressionMutations!
15631
16544
  perspectivePublishSnapshot(uuid: String!): String
15632
16545
  perspectiveRemove(uuid: String!): Boolean!
15633
- perspectiveRemoveLink(link: LinkExpressionInput!, uuid: String!): Boolean!
15634
- perspectiveRemoveLinks(links: [LinkExpressionInput!]!, uuid: String!): [LinkExpression!]!
16546
+ perspectiveRemoveLink(batchId: String, link: LinkExpressionInput!, uuid: String!): Boolean!
16547
+ perspectiveRemoveLinks(batchId: String, links: [LinkExpressionInput!]!, uuid: String!): [LinkExpression!]!
16548
+ perspectiveSubscribeQuery(query: String!, uuid: String!): QuerySubscription!
15635
16549
  perspectiveUpdate(name: String!, uuid: String!): PerspectiveHandle
15636
- perspectiveUpdateLink(newLink: LinkInput!, oldLink: LinkExpressionInput!, uuid: String!): LinkExpression!
16550
+ perspectiveUpdateLink(batchId: String, newLink: LinkInput!, oldLink: LinkExpressionInput!, uuid: String!): LinkExpression!
15637
16551
  runtimeAddFriends(dids: [String!]!): [String!]!
15638
16552
  runtimeAddKnownLinkLanguageTemplates(addresses: [String!]!): [String!]!
15639
16553
  runtimeExportDb(filePath: String!): Boolean!
@@ -15760,6 +16674,11 @@ type Query {
15760
16674
  runtimeVerifyStringSignedByDid(data: String!, did: String!, didSigningKeyId: String!, signedData: String!): Boolean!
15761
16675
  }
15762
16676
 
16677
+ type QuerySubscription {
16678
+ result: String!
16679
+ subscriptionId: String!
16680
+ }
16681
+
15763
16682
  type Resource {
15764
16683
  domain: String!
15765
16684
  pointers: [String!]!
@@ -15792,6 +16711,7 @@ type Subscription {
15792
16711
  perspectiveLinkAdded(uuid: String!): LinkExpression
15793
16712
  perspectiveLinkRemoved(uuid: String!): LinkExpression
15794
16713
  perspectiveLinkUpdated(uuid: String!): LinkExpressionUpdated
16714
+ perspectiveQuerySubscription(subscriptionId: String!): String!
15795
16715
  perspectiveRemoved: String
15796
16716
  perspectiveSyncStateChange(uuid: String!): String!
15797
16717
  perspectiveUpdated: PerspectiveHandle
@@ -15847,291 +16767,6 @@ function capSentence(cap) {
15847
16767
  return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
15848
16768
  }
15849
16769
 
15850
- var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
15851
- if (kind === "m") throw new TypeError("Private method is not writable");
15852
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
15853
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15854
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
15855
- };
15856
- var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
15857
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
15858
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
15859
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15860
- };
15861
- var _SubjectEntity_baseExpression, _SubjectEntity_subjectClass, _SubjectEntity_source, _SubjectEntity_perspective;
15862
- /**
15863
- * Class representing a subject entity.
15864
- * Can extend this class to create a new subject entity to add methods interact with SDNA and much better experience then using the bare bone methods.
15865
- */
15866
- class SubjectEntity {
15867
- /**
15868
- * Constructs a new subject.
15869
- * @param perspective - The perspective that the subject belongs to.
15870
- * @param baseExpression - The base expression of the subject.
15871
- * @param soruce - The source of the subject, the expression this instance is linked too.
15872
- */
15873
- constructor(perspective, baseExpression, source) {
15874
- _SubjectEntity_baseExpression.set(this, void 0);
15875
- _SubjectEntity_subjectClass.set(this, void 0);
15876
- _SubjectEntity_source.set(this, void 0);
15877
- _SubjectEntity_perspective.set(this, void 0);
15878
- __classPrivateFieldSet(this, _SubjectEntity_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
15879
- __classPrivateFieldSet(this, _SubjectEntity_perspective, perspective, "f");
15880
- __classPrivateFieldSet(this, _SubjectEntity_source, source || "ad4m://self", "f");
15881
- }
15882
- /**
15883
- * Gets the base expression of the subject.
15884
- */
15885
- get baseExpression() {
15886
- return __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f");
15887
- }
15888
- /**
15889
- * Protected getter for the perspective.
15890
- * Allows subclasses to access the perspective while keeping it private from external code.
15891
- */
15892
- get perspective() {
15893
- return __classPrivateFieldGet(this, _SubjectEntity_perspective, "f");
15894
- }
15895
- async getData(id) {
15896
- const tempId = id ?? __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f");
15897
- let data = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").getSubjectData(__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f"), tempId);
15898
- Object.assign(this, data);
15899
- __classPrivateFieldSet(this, _SubjectEntity_baseExpression, tempId, "f");
15900
- return this;
15901
- }
15902
- async setProperty(key, value) {
15903
- const setters = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), property_setter(C, "${key}", Setter)`);
15904
- if (setters && setters.length > 0) {
15905
- const actions = eval(setters[0].Setter);
15906
- const resolveLanguageResults = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), property_resolve_language(C, "${key}", Language)`);
15907
- let resolveLanguage;
15908
- if (resolveLanguageResults && resolveLanguageResults.length > 0) {
15909
- resolveLanguage = resolveLanguageResults[0].Language;
15910
- }
15911
- if (resolveLanguage) {
15912
- value = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").createExpression(value, resolveLanguage);
15913
- }
15914
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
15915
- }
15916
- }
15917
- async setCollectionSetter(key, value) {
15918
- let collectionSetters = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
15919
- if (!collectionSetters)
15920
- collectionSetters = [];
15921
- if (collectionSetters.length > 0) {
15922
- const actions = eval(collectionSetters[0].Setter);
15923
- if (value) {
15924
- if (Array.isArray(value)) {
15925
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), value.map(v => ({ name: "value", value: v })));
15926
- }
15927
- else {
15928
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
15929
- }
15930
- }
15931
- }
15932
- }
15933
- async setCollectionAdder(key, value) {
15934
- let adders = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
15935
- if (!adders)
15936
- adders = [];
15937
- if (adders.length > 0) {
15938
- const actions = eval(adders[0].Adder);
15939
- if (value) {
15940
- if (Array.isArray(value)) {
15941
- await Promise.all(value.map(v => __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value: v }])));
15942
- }
15943
- else {
15944
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
15945
- }
15946
- }
15947
- }
15948
- }
15949
- async setCollectionRemover(key, value) {
15950
- let removers = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
15951
- if (!removers)
15952
- removers = [];
15953
- if (removers.length > 0) {
15954
- const actions = eval(removers[0].Remover);
15955
- if (value) {
15956
- if (Array.isArray(value)) {
15957
- await Promise.all(value.map(v => __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value: v }])));
15958
- }
15959
- else {
15960
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
15961
- }
15962
- }
15963
- }
15964
- }
15965
- /**
15966
- * Save the subject entity.
15967
- * This method will create a new subject with the base expression and add a new link from the source to the base expression with the predicate "ad4m://has_child".
15968
- *
15969
- * If a property has an action, it will perform the action (Only for collections).
15970
- * If a property is an array and is not empty, it will set the collection.
15971
- * If a property is not undefined, not null, and not an empty string, it will set the property.
15972
- *
15973
- *
15974
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the subject cannot be created, or if the link cannot be added, or if the subject entity cannot be updated.
15975
- */
15976
- async save() {
15977
- __classPrivateFieldSet(this, _SubjectEntity_subjectClass, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClass(this), "f");
15978
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").createSubject(this, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"));
15979
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").add(new exports.Link({
15980
- source: __classPrivateFieldGet(this, _SubjectEntity_source, "f"),
15981
- predicate: "ad4m://has_child",
15982
- target: this.baseExpression,
15983
- }));
15984
- await this.update();
15985
- }
15986
- /**
15987
- * Update the subject entity.
15988
- *
15989
- * It will iterate over the properties of the subject entity.
15990
- *
15991
- * If a property has an action, it will perform the action (Only for collections).
15992
- * If a property is an array and is not empty, it will set the collection.
15993
- * If a property is not undefined, not null, and not an empty string, it will set the property.
15994
- *
15995
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if a property cannot be set, or if a collection cannot be set, or if the data of the subject entity cannot be gotten.
15996
- */
15997
- async update() {
15998
- __classPrivateFieldSet(this, _SubjectEntity_subjectClass, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClass(this), "f");
15999
- const entries = Object.entries(this);
16000
- for (const [key, value] of entries) {
16001
- if (value !== undefined && value !== null) {
16002
- if (value?.action) {
16003
- switch (value.action) {
16004
- case 'setter':
16005
- await this.setCollectionSetter(key, value.value);
16006
- break;
16007
- case "adder":
16008
- await this.setCollectionAdder(key, value.value);
16009
- break;
16010
- case 'remover':
16011
- await this.setCollectionRemover(key, value.value);
16012
- default:
16013
- await this.setCollectionSetter(key, value.value);
16014
- break;
16015
- }
16016
- }
16017
- else if (Array.isArray(value) && value.length > 0) {
16018
- await this.setCollectionSetter(key, value);
16019
- }
16020
- else if (value !== undefined && value !== null && value !== "") {
16021
- await this.setProperty(key, value);
16022
- }
16023
- }
16024
- }
16025
- await this.getData();
16026
- }
16027
- /**
16028
- * Get the subject entity with all the properties & collection populated.
16029
- *
16030
- * @returns The subject entity.
16031
- *
16032
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the data of the subject entity cannot be gotten.
16033
- */
16034
- async get() {
16035
- __classPrivateFieldSet(this, _SubjectEntity_subjectClass, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClass(this), "f");
16036
- return await this.getData();
16037
- }
16038
- /**
16039
- * Delete the subject entity.
16040
- * This method will remove the subject from the perspective.
16041
- *
16042
- * @throws Will throw an error if the subject entity cannot be removed.
16043
- */
16044
- async delete() {
16045
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"));
16046
- }
16047
- /**
16048
- * Get all the subject entities of the subject class.
16049
- *
16050
- * NOTE: this is a static method and should be called on the class itself.
16051
- *
16052
- * @param perspective - The perspective that the subject belongs to.
16053
- *
16054
- * @returns The subject entities.
16055
- *
16056
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the subject proxies cannot be gotten.
16057
- */
16058
- static async all(perspective) {
16059
- let subjectClass = await perspective.stringOrTemplateObjectToSubjectClass(this);
16060
- const proxies = await perspective.getAllSubjectProxies(subjectClass);
16061
- const instances = [];
16062
- if (proxies) {
16063
- for (const proxy of proxies) {
16064
- // @ts-ignore
16065
- const instance = new this(perspective, proxy.X);
16066
- instances.push(await instance.get());
16067
- }
16068
- return instances;
16069
- }
16070
- return [];
16071
- }
16072
- /**
16073
- * Query the subject entities of the subject class.
16074
- *
16075
- * NOTE: this is a static method and should be called on the class itself.
16076
- *
16077
- * @param perspective - The perspective that the subject belongs to.
16078
- * @param query - The query of the subject entities.
16079
- *
16080
- * @returns The subject entities.
16081
- *
16082
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the query cannot be inferred, or if the data of the subject entities cannot be gotten.
16083
- */
16084
- static async query(perspective, query) {
16085
- const source = query?.source || "ad4m://self";
16086
- let subjectClass = await perspective.stringOrTemplateObjectToSubjectClass(this);
16087
- let res = [];
16088
- let instanceConditions = `subject_class("${subjectClass}", C), instance(C, Base), link("${source}", Predicate, Base, Timestamp, Author)`;
16089
- if (query) {
16090
- if (query.where) {
16091
- if (query.where["condition"]) {
16092
- instanceConditions += ", " + query.where["condition"];
16093
- }
16094
- else {
16095
- const pairs = Object.entries(query.where);
16096
- for (let p of pairs) {
16097
- const propertyName = p[0];
16098
- const propertyValue = p[1];
16099
- instanceConditions += `, property_getter(C, Base, "${propertyName}", "${propertyValue}")`;
16100
- }
16101
- }
16102
- }
16103
- try {
16104
- const queryResponse = (await perspective.infer(`findall([Timestamp, Base], (${instanceConditions}), AllData), sort(AllData, SortedData), length(SortedData, DataLength).`))[0];
16105
- if (queryResponse.DataLength >= query.size) {
16106
- const mainQuery = `findall([Timestamp, Base], (${instanceConditions}), AllData), sort(AllData, SortedData), reverse(SortedData, ReverseSortedData), paginate(ReverseSortedData, ${query.page}, ${query.size}, PageData).`;
16107
- res = await perspective.infer(mainQuery);
16108
- res = res[0].PageData.map(r => ({
16109
- Base: r[1],
16110
- Timestamp: r[0]
16111
- }));
16112
- }
16113
- else {
16114
- res = await perspective.infer(instanceConditions);
16115
- }
16116
- }
16117
- catch (e) {
16118
- console.log("Query failed", e);
16119
- }
16120
- }
16121
- else {
16122
- res = await perspective.infer(instanceConditions);
16123
- }
16124
- if (!res)
16125
- return [];
16126
- const data = await Promise.all(res.map(async (result) => {
16127
- const instance = new this(perspective, result.Base);
16128
- return await instance.get();
16129
- }));
16130
- return data;
16131
- }
16132
- }
16133
- _SubjectEntity_baseExpression = new WeakMap(), _SubjectEntity_subjectClass = new WeakMap(), _SubjectEntity_source = new WeakMap(), _SubjectEntity_perspective = new WeakMap();
16134
-
16135
16770
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
16136
16771
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16137
16772
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -16755,28 +17390,1077 @@ RuntimeResolver = __decorate([
16755
17390
  Resolver()
16756
17391
  ], RuntimeResolver);
16757
17392
 
17393
+ var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
17394
+ if (kind === "m") throw new TypeError("Private method is not writable");
17395
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
17396
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
17397
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
17398
+ };
17399
+ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
17400
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
17401
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
17402
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
17403
+ };
17404
+ var _Ad4mModel_baseExpression, _Ad4mModel_subjectClassName, _Ad4mModel_source, _Ad4mModel_perspective;
17405
+ function capitalize(word) {
17406
+ return word.charAt(0).toUpperCase() + word.slice(1);
17407
+ }
17408
+ function buildSourceQuery(source) {
17409
+ // Constrains the query to instances that have the provided source
17410
+ if (!source)
17411
+ return "";
17412
+ return `triple("${source}", "ad4m://has_child", Base)`;
17413
+ }
17414
+ // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
17415
+ function buildAuthorAndTimestampQuery() {
17416
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
17417
+ return `
17418
+ findall(
17419
+ [T, A],
17420
+ link(Base, _, _, T, A),
17421
+ AllLinks
17422
+ ),
17423
+ sort(AllLinks, SortedLinks),
17424
+ SortedLinks = [[Timestamp, Author]|_]
17425
+ `;
17426
+ }
17427
+ function buildPropertiesQuery(properties) {
17428
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
17429
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
17430
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
17431
+ // If no properties are provided, all are included
17432
+ return `
17433
+ findall([PropertyName, PropertyValue, Resolve], (
17434
+ % Constrain to specified properties if provided
17435
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
17436
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
17437
+ ), Properties)
17438
+ `;
17439
+ }
17440
+ function buildCollectionsQuery(collections) {
17441
+ // Gets the name and array of values for all (or some) collections on a Ad4mModel instance
17442
+ // If no collections are provided, all are included
17443
+ return `
17444
+ findall([CollectionName, CollectionValues], (
17445
+ % Constrain to specified collections if provided
17446
+ ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
17447
+
17448
+ collection(SubjectClass, CollectionName),
17449
+ collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
17450
+ ), Collections)
17451
+ `;
17452
+ }
17453
+ function buildWhereQuery(where = {}) {
17454
+ // Constrains the query to instances that match the provided where conditions
17455
+ function formatValue(value) {
17456
+ // Wrap strings in quotes
17457
+ return typeof value === "string" ? `"${value}"` : value;
17458
+ }
17459
+ return Object.entries(where)
17460
+ .map(([key, value]) => {
17461
+ const isSpecial = ["base", "author", "timestamp"].includes(key);
17462
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
17463
+ // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
17464
+ const field = capitalize(key);
17465
+ // Handle direct array values (for IN conditions)
17466
+ if (Array.isArray(value)) {
17467
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
17468
+ if (isSpecial)
17469
+ return `member(${field}, [${formattedValues}])`;
17470
+ else
17471
+ return `${getter}, member(Value${key}, [${formattedValues}])`;
17472
+ }
17473
+ // Handle operation object
17474
+ if (typeof value === "object" && value !== null) {
17475
+ const { not, between, lt, lte, gt, gte } = value;
17476
+ // Handle NOT operation
17477
+ if (not !== undefined) {
17478
+ if (Array.isArray(not)) {
17479
+ // NOT IN array
17480
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
17481
+ if (isSpecial)
17482
+ return `\\+ member(${field}, [${formattedValues}])`;
17483
+ else
17484
+ return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
17485
+ }
17486
+ else {
17487
+ // NOT EQUAL
17488
+ if (isSpecial)
17489
+ return `${field} \\= ${formatValue(not)}`;
17490
+ else
17491
+ return `${getter}, Value${key} \\= ${formatValue(not)}`;
17492
+ }
17493
+ }
17494
+ // Handle BETWEEN
17495
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
17496
+ if (isSpecial)
17497
+ return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
17498
+ else
17499
+ return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
17500
+ }
17501
+ // Handle lt, lte, gt, & gte operations
17502
+ const operators = [
17503
+ { value: lt, symbol: "<" },
17504
+ { value: lte, symbol: "=<" },
17505
+ { value: gt, symbol: ">" },
17506
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
17507
+ ];
17508
+ for (const { value, symbol } of operators) {
17509
+ if (value !== undefined)
17510
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
17511
+ }
17512
+ }
17513
+ // Default to direct equality
17514
+ if (isSpecial)
17515
+ return `${field} = ${formatValue(value)}`;
17516
+ else
17517
+ return `${getter}, Value${key} = ${formatValue(value)}`;
17518
+ })
17519
+ .join(", ");
17520
+ }
17521
+ function buildCountQuery(count) {
17522
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
17523
+ }
17524
+ function buildOrderQuery(order) {
17525
+ if (!order)
17526
+ return "SortedInstances = UnsortedInstances";
17527
+ const [propertyName, direction] = Object.entries(order)[0];
17528
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
17529
+ }
17530
+ function buildOffsetQuery(offset) {
17531
+ if (!offset || offset < 0)
17532
+ return "InstancesWithOffset = SortedInstances";
17533
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
17534
+ }
17535
+ function buildLimitQuery(limit) {
17536
+ if (!limit || limit < 0)
17537
+ return "AllInstances = InstancesWithOffset";
17538
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
17539
+ }
17540
+ /**
17541
+ * Base class for defining data models in AD4M.
17542
+ *
17543
+ * @description
17544
+ * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
17545
+ * Each model instance is represented as a subgraph in the perspective, with properties and collections
17546
+ * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
17547
+ * instances based on their properties and relationships.
17548
+ *
17549
+ * Key concepts:
17550
+ * - Each model instance has a unique base expression that serves as its identifier
17551
+ * - Properties are stored as links with predicates defined by the `through` option
17552
+ * - Collections represent one-to-many relationships as sets of links
17553
+ * - Queries are translated to Prolog for efficient graph pattern matching
17554
+ * - Changes are tracked through the perspective's subscription system
17555
+ *
17556
+ * @example
17557
+ * ```typescript
17558
+ * // Define a recipe model
17559
+ * @ModelOptions({ name: "Recipe" })
17560
+ * class Recipe extends Ad4mModel {
17561
+ * // Required property with literal value
17562
+ * @Property({
17563
+ * through: "recipe://name",
17564
+ * resolveLanguage: "literal"
17565
+ * })
17566
+ * name: string = "";
17567
+ *
17568
+ * // Optional property with custom initial value
17569
+ * @Optional({
17570
+ * through: "recipe://status",
17571
+ * initial: "recipe://draft"
17572
+ * })
17573
+ * status: string = "";
17574
+ *
17575
+ * // Read-only computed property
17576
+ * @ReadOnly({
17577
+ * through: "recipe://rating",
17578
+ * getter: `
17579
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
17580
+ * sum_list(Ratings, Sum),
17581
+ * length(Ratings, Count),
17582
+ * Value is Sum / Count
17583
+ * `
17584
+ * })
17585
+ * averageRating: number = 0;
17586
+ *
17587
+ * // Collection of ingredients
17588
+ * @Collection({ through: "recipe://ingredient" })
17589
+ * ingredients: string[] = [];
17590
+ *
17591
+ * // Collection of comments that are instances of another model
17592
+ * @Collection({
17593
+ * through: "recipe://comment",
17594
+ * where: { isInstance: Comment }
17595
+ * })
17596
+ * comments: Comment[] = [];
17597
+ * }
17598
+ *
17599
+ * // Create and save a new recipe
17600
+ * const recipe = new Recipe(perspective);
17601
+ * recipe.name = "Chocolate Cake";
17602
+ * recipe.ingredients = ["flour", "sugar", "cocoa"];
17603
+ * await recipe.save();
17604
+ *
17605
+ * // Query recipes in different ways
17606
+ * // Get all recipes
17607
+ * const allRecipes = await Recipe.findAll(perspective);
17608
+ *
17609
+ * // Find recipes with specific criteria
17610
+ * const desserts = await Recipe.findAll(perspective, {
17611
+ * where: {
17612
+ * status: "recipe://published",
17613
+ * averageRating: { gt: 4 }
17614
+ * },
17615
+ * order: { name: "ASC" },
17616
+ * limit: 10
17617
+ * });
17618
+ *
17619
+ * // Use the fluent query builder
17620
+ * const popularRecipes = await Recipe.query(perspective)
17621
+ * .where({ averageRating: { gt: 4.5 } })
17622
+ * .order({ averageRating: "DESC" })
17623
+ * .limit(5)
17624
+ * .get();
17625
+ *
17626
+ * // Subscribe to real-time updates
17627
+ * await Recipe.query(perspective)
17628
+ * .where({ status: "recipe://cooking" })
17629
+ * .subscribe(recipes => {
17630
+ * console.log("Currently being cooked:", recipes);
17631
+ * });
17632
+ *
17633
+ * // Paginate results
17634
+ * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
17635
+ * .where({ status: "recipe://published" })
17636
+ * .paginate(10, 1);
17637
+ * ```
17638
+ */
17639
+ class Ad4mModel {
17640
+ static async getClassName(perspective) {
17641
+ // Get or create the cache for this class
17642
+ let classCache = this.classNamesByClass.get(this);
17643
+ if (!classCache) {
17644
+ classCache = {};
17645
+ this.classNamesByClass.set(this, classCache);
17646
+ }
17647
+ // Get or create the cached name for this perspective
17648
+ const perspectiveID = perspective.uuid;
17649
+ if (!classCache[perspectiveID]) {
17650
+ classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
17651
+ }
17652
+ return classCache[perspectiveID];
17653
+ }
17654
+ /**
17655
+ * Constructs a new model instance.
17656
+ *
17657
+ * @param perspective - The perspective where this model will be stored
17658
+ * @param baseExpression - Optional unique identifier for this instance
17659
+ * @param source - Optional source expression this instance is linked to
17660
+ *
17661
+ * @example
17662
+ * ```typescript
17663
+ * // Create a new recipe with auto-generated base expression
17664
+ * const recipe = new Recipe(perspective);
17665
+ *
17666
+ * // Create with specific base expression
17667
+ * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
17668
+ *
17669
+ * // Create with source link
17670
+ * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
17671
+ * ```
17672
+ */
17673
+ constructor(perspective, baseExpression, source) {
17674
+ _Ad4mModel_baseExpression.set(this, void 0);
17675
+ _Ad4mModel_subjectClassName.set(this, void 0);
17676
+ _Ad4mModel_source.set(this, void 0);
17677
+ _Ad4mModel_perspective.set(this, void 0);
17678
+ __classPrivateFieldSet(this, _Ad4mModel_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
17679
+ __classPrivateFieldSet(this, _Ad4mModel_perspective, perspective, "f");
17680
+ __classPrivateFieldSet(this, _Ad4mModel_source, source || "ad4m://self", "f");
17681
+ }
17682
+ /**
17683
+ * Gets the base expression of the subject.
17684
+ */
17685
+ get baseExpression() {
17686
+ return __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f");
17687
+ }
17688
+ /**
17689
+ * Protected getter for the perspective.
17690
+ * Allows subclasses to access the perspective while keeping it private from external code.
17691
+ */
17692
+ get perspective() {
17693
+ return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
17694
+ }
17695
+ static async assignValuesToInstance(perspective, instance, values) {
17696
+ // Map properties to object
17697
+ const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
17698
+ let finalValue = value;
17699
+ // Resolve the value if necessary
17700
+ if (resolve) {
17701
+ let resolvedExpression = await perspective.getExpression(value);
17702
+ if (resolvedExpression) {
17703
+ finalValue = resolvedExpression.data;
17704
+ }
17705
+ }
17706
+ // Apply transform function if it exists
17707
+ const transform = instance["__properties"]?.[name]?.transform;
17708
+ if (transform && typeof transform === "function") {
17709
+ finalValue = transform(finalValue);
17710
+ }
17711
+ return [name, finalValue];
17712
+ })));
17713
+ // Assign properties to instance
17714
+ Object.assign(instance, propsObject);
17715
+ }
17716
+ async getData() {
17717
+ // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
17718
+ const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
17719
+ const fullQuery = `
17720
+ Base = "${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}",
17721
+ subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", SubjectClass),
17722
+ ${subQueries.join(", ")}
17723
+ `;
17724
+ const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(fullQuery);
17725
+ if (result?.[0]) {
17726
+ const { Properties, Collections, Timestamp, Author } = result?.[0];
17727
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
17728
+ await Ad4mModel.assignValuesToInstance(__classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), this, values);
17729
+ }
17730
+ return this;
17731
+ }
17732
+ // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
17733
+ static async queryToProlog(perspective, query, modelClassName) {
17734
+ const { source, properties, collections, where, order, offset, limit, count } = query;
17735
+ const className = modelClassName || (await this.getClassName(perspective));
17736
+ const instanceQueries = [
17737
+ buildAuthorAndTimestampQuery(),
17738
+ buildSourceQuery(source),
17739
+ buildPropertiesQuery(properties),
17740
+ buildCollectionsQuery(collections),
17741
+ buildWhereQuery(where),
17742
+ ];
17743
+ const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
17744
+ const fullQuery = `
17745
+ findall([Base, Properties, Collections, Timestamp, Author], (
17746
+ subject_class("${className}", SubjectClass),
17747
+ instance(SubjectClass, Base),
17748
+ ${instanceQueries.filter((q) => q).join(", ")}
17749
+ ), UnsortedInstances),
17750
+ ${resultSetQueries.filter((q) => q).join(", ")}
17751
+ `;
17752
+ return fullQuery;
17753
+ }
17754
+ static async instancesFromPrologResult(perspective, query, result) {
17755
+ if (!result?.[0]?.AllInstances)
17756
+ return { results: [], totalCount: 0 };
17757
+ // Map results to instances
17758
+ const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
17759
+ const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
17760
+ try {
17761
+ const instance = new this(perspective, Base);
17762
+ // Remove unrequested attributes from instance
17763
+ if (requestedAttribtes.length) {
17764
+ Object.keys(instance).forEach((key) => {
17765
+ if (!requestedAttribtes.includes(key))
17766
+ delete instance[key];
17767
+ });
17768
+ }
17769
+ // Collect values to assign to instance
17770
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
17771
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
17772
+ return instance;
17773
+ }
17774
+ catch (error) {
17775
+ console.error(`Failed to process instance ${Base}:`, error);
17776
+ // Return null for failed instances - we'll filter these out below
17777
+ return null;
17778
+ }
17779
+ }));
17780
+ return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
17781
+ }
17782
+ /**
17783
+ * Gets all instances of the model in the perspective that match the query params.
17784
+ *
17785
+ * @param perspective - The perspective to search in
17786
+ * @param query - Optional query parameters to filter results
17787
+ * @returns Array of matching models
17788
+ *
17789
+ * @example
17790
+ * ```typescript
17791
+ * // Get all recipes
17792
+ * const allRecipes = await Recipe.findAll(perspective);
17793
+ *
17794
+ * // Get recipes with specific criteria
17795
+ * const recipes = await Recipe.findAll(perspective, {
17796
+ * where: {
17797
+ * name: "Pasta",
17798
+ * rating: { gt: 4 }
17799
+ * },
17800
+ * order: { createdAt: "DESC" },
17801
+ * limit: 10
17802
+ * });
17803
+ * ```
17804
+ */
17805
+ static async findAll(perspective, query = {}) {
17806
+ const prologQuery = await this.queryToProlog(perspective, query);
17807
+ const result = await perspective.infer(prologQuery);
17808
+ const { results } = await this.instancesFromPrologResult(perspective, query, result);
17809
+ return results;
17810
+ }
17811
+ /**
17812
+ * Gets all instances with count of total matches without offset & limit applied.
17813
+ *
17814
+ * @param perspective - The perspective to search in
17815
+ * @param query - Optional query parameters to filter results
17816
+ * @returns Object containing results array and total count
17817
+ *
17818
+ * @example
17819
+ * ```typescript
17820
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
17821
+ * where: { category: "Dessert" },
17822
+ * limit: 10
17823
+ * });
17824
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
17825
+ * ```
17826
+ */
17827
+ static async findAllAndCount(perspective, query = {}) {
17828
+ const prologQuery = await this.queryToProlog(perspective, query);
17829
+ const result = await perspective.infer(prologQuery);
17830
+ return await this.instancesFromPrologResult(perspective, query, result);
17831
+ }
17832
+ /**
17833
+ * Helper function for pagination with explicit page size and number.
17834
+ *
17835
+ * @param perspective - The perspective to search in
17836
+ * @param pageSize - Number of items per page
17837
+ * @param pageNumber - Which page to retrieve (1-based)
17838
+ * @param query - Optional additional query parameters
17839
+ * @returns Paginated results with metadata
17840
+ *
17841
+ * @example
17842
+ * ```typescript
17843
+ * const page = await Recipe.paginate(perspective, 10, 1, {
17844
+ * where: { category: "Main Course" }
17845
+ * });
17846
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
17847
+ * ```
17848
+ */
17849
+ static async paginate(perspective, pageSize, pageNumber, query) {
17850
+ const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
17851
+ const prologQuery = await this.queryToProlog(perspective, paginationQuery);
17852
+ const result = await perspective.infer(prologQuery);
17853
+ const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
17854
+ return { results, totalCount, pageSize, pageNumber };
17855
+ }
17856
+ static async countQueryToProlog(perspective, query = {}, modelClassName) {
17857
+ const { source, where } = query;
17858
+ const className = modelClassName || (await this.getClassName(perspective));
17859
+ const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
17860
+ const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
17861
+ const fullQuery = `
17862
+ findall([Base, Properties, Collections, Timestamp, Author], (
17863
+ subject_class("${className}", SubjectClass),
17864
+ instance(SubjectClass, Base),
17865
+ ${instanceQueries.filter((q) => q).join(", ")}
17866
+ ), UnsortedInstances),
17867
+ ${resultSetQueries.filter((q) => q).join(", ")}
17868
+ `;
17869
+ return fullQuery;
17870
+ }
17871
+ /**
17872
+ * Gets a count of all matching instances.
17873
+ *
17874
+ * @param perspective - The perspective to search in
17875
+ * @param query - Optional query parameters to filter results
17876
+ * @returns Total count of matching entities
17877
+ *
17878
+ * @example
17879
+ * ```typescript
17880
+ * const totalRecipes = await Recipe.count(perspective);
17881
+ * const activeRecipes = await Recipe.count(perspective, {
17882
+ * where: { status: "active" }
17883
+ * });
17884
+ * ```
17885
+ */
17886
+ static async count(perspective, query = {}) {
17887
+ const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
17888
+ return result?.[0]?.TotalCount || 0;
17889
+ }
17890
+ async setProperty(key, value, batchId) {
17891
+ const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
17892
+ if (setters && setters.length > 0) {
17893
+ const actions = eval(setters[0].Setter);
17894
+ const resolveLanguageResults = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_resolve_language(C, "${key}", Language)`);
17895
+ let resolveLanguage;
17896
+ if (resolveLanguageResults && resolveLanguageResults.length > 0) {
17897
+ resolveLanguage = resolveLanguageResults[0].Language;
17898
+ }
17899
+ if (resolveLanguage) {
17900
+ value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
17901
+ }
17902
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
17903
+ }
17904
+ }
17905
+ async setCollectionSetter(key, value, batchId) {
17906
+ let collectionSetters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
17907
+ if (!collectionSetters)
17908
+ collectionSetters = [];
17909
+ if (collectionSetters.length > 0) {
17910
+ const actions = eval(collectionSetters[0].Setter);
17911
+ if (value) {
17912
+ if (Array.isArray(value)) {
17913
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
17914
+ }
17915
+ else {
17916
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
17917
+ }
17918
+ }
17919
+ }
17920
+ }
17921
+ async setCollectionAdder(key, value, batchId) {
17922
+ let adders = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
17923
+ if (!adders)
17924
+ adders = [];
17925
+ if (adders.length > 0) {
17926
+ const actions = eval(adders[0].Adder);
17927
+ if (value) {
17928
+ if (Array.isArray(value)) {
17929
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
17930
+ }
17931
+ else {
17932
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
17933
+ }
17934
+ }
17935
+ }
17936
+ }
17937
+ async setCollectionRemover(key, value, batchId) {
17938
+ let removers = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
17939
+ if (!removers)
17940
+ removers = [];
17941
+ if (removers.length > 0) {
17942
+ const actions = eval(removers[0].Remover);
17943
+ if (value) {
17944
+ if (Array.isArray(value)) {
17945
+ await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
17946
+ }
17947
+ else {
17948
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
17949
+ }
17950
+ }
17951
+ }
17952
+ }
17953
+ /**
17954
+ * Saves the model instance to the perspective.
17955
+ * Creates a new instance with the base expression and links it to the source.
17956
+ *
17957
+ * @param batchId - Optional batch ID for batch operations
17958
+ * @throws Will throw if instance creation, linking, or updating fails
17959
+ *
17960
+ * @example
17961
+ * ```typescript
17962
+ * const recipe = new Recipe(perspective);
17963
+ * recipe.name = "Spaghetti";
17964
+ * recipe.ingredients = ["pasta", "tomato sauce"];
17965
+ * await recipe.save();
17966
+ *
17967
+ * // Or with batch operations:
17968
+ * const batchId = await perspective.createBatch();
17969
+ * await recipe.save(batchId);
17970
+ * await perspective.commitBatch(batchId);
17971
+ * ```
17972
+ */
17973
+ async save(batchId) {
17974
+ // We use createSubject's initialValues to set properties (but not collections)
17975
+ // We then later use innerUpdate to set collections
17976
+ // First filter out the properties that are not collections (arrays)
17977
+ const initialValues = {};
17978
+ for (const [key, value] of Object.entries(this)) {
17979
+ if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
17980
+ initialValues[key] = value;
17981
+ }
17982
+ }
17983
+ // Create the subject with the initial values
17984
+ await this.perspective.createSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), initialValues, batchId);
17985
+ // Link the subject to the source
17986
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").add(new exports.Link({ source: __classPrivateFieldGet(this, _Ad4mModel_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }), 'shared', batchId);
17987
+ // Set collections
17988
+ await this.innerUpdate(false, batchId);
17989
+ // If we're in batch mode, we don't need to do anything else
17990
+ // since the instance won't exist until batch commit
17991
+ if (batchId) {
17992
+ return;
17993
+ }
17994
+ await this.getData();
17995
+ }
17996
+ async innerUpdate(setProperties = true, batchId) {
17997
+ __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
17998
+ const entries = Object.entries(this);
17999
+ for (const [key, value] of entries) {
18000
+ if (value !== undefined && value !== null) {
18001
+ if (value?.action) {
18002
+ switch (value.action) {
18003
+ case "setter":
18004
+ await this.setCollectionSetter(key, value.value, batchId);
18005
+ break;
18006
+ case "adder":
18007
+ await this.setCollectionAdder(key, value.value, batchId);
18008
+ break;
18009
+ case "remover":
18010
+ await this.setCollectionRemover(key, value.value, batchId);
18011
+ break;
18012
+ default:
18013
+ await this.setCollectionSetter(key, value.value, batchId);
18014
+ break;
18015
+ }
18016
+ }
18017
+ else if (Array.isArray(value) && value.length > 0) {
18018
+ await this.setCollectionSetter(key, value, batchId);
18019
+ }
18020
+ else if (value !== undefined && value !== null && value !== "") {
18021
+ if (setProperties) {
18022
+ await this.setProperty(key, value, batchId);
18023
+ }
18024
+ }
18025
+ }
18026
+ }
18027
+ }
18028
+ /**
18029
+ * Updates the model instance's properties and collections.
18030
+ *
18031
+ * @param batchId - Optional batch ID for batch operations
18032
+ * @throws Will throw if property setting or collection updates fail
18033
+ *
18034
+ * @example
18035
+ * ```typescript
18036
+ * const recipe = await Recipe.findAll(perspective)[0];
18037
+ * recipe.rating = 5;
18038
+ * recipe.ingredients.push("garlic");
18039
+ * await recipe.update();
18040
+ *
18041
+ * // Or with batch operations:
18042
+ * const batchId = await perspective.createBatch();
18043
+ * await recipe.update(batchId);
18044
+ * await perspective.commitBatch(batchId);
18045
+ * ```
18046
+ */
18047
+ async update(batchId) {
18048
+ await this.innerUpdate(true, batchId);
18049
+ await this.getData();
18050
+ }
18051
+ /**
18052
+ * Gets the model instance with all properties and collections populated.
18053
+ *
18054
+ * @returns The populated model instance
18055
+ * @throws Will throw if data retrieval fails
18056
+ *
18057
+ * @example
18058
+ * ```typescript
18059
+ * const recipe = new Recipe(perspective, existingId);
18060
+ * await recipe.get();
18061
+ * console.log(recipe.name, recipe.ingredients);
18062
+ * ```
18063
+ */
18064
+ async get() {
18065
+ __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
18066
+ return await this.getData();
18067
+ }
18068
+ /**
18069
+ * Deletes the model instance from the perspective.
18070
+ *
18071
+ * @param batchId - Optional batch ID for batch operations
18072
+ * @throws Will throw if removal fails
18073
+ *
18074
+ * @example
18075
+ * ```typescript
18076
+ * const recipe = await Recipe.findAll(perspective)[0];
18077
+ * await recipe.delete();
18078
+ *
18079
+ * // Or with batch operations:
18080
+ * const batchId = await perspective.createBatch();
18081
+ * await recipe.delete(batchId);
18082
+ * await perspective.commitBatch(batchId);
18083
+ * ```
18084
+ */
18085
+ async delete(batchId) {
18086
+ await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), batchId);
18087
+ }
18088
+ /**
18089
+ * Creates a query builder for fluent query construction.
18090
+ *
18091
+ * @param perspective - The perspective to query
18092
+ * @param query - Optional initial query parameters
18093
+ * @returns A new query builder instance
18094
+ *
18095
+ * @example
18096
+ * ```typescript
18097
+ * const recipes = await Recipe.query(perspective)
18098
+ * .where({ category: "Dessert" })
18099
+ * .order({ rating: "DESC" })
18100
+ * .limit(5)
18101
+ * .run();
18102
+ *
18103
+ * // With real-time updates
18104
+ * await Recipe.query(perspective)
18105
+ * .where({ status: "cooking" })
18106
+ * .subscribe(recipes => {
18107
+ * console.log("Currently cooking:", recipes);
18108
+ * });
18109
+ * ```
18110
+ */
18111
+ static query(perspective, query) {
18112
+ return new ModelQueryBuilder(perspective, this, query);
18113
+ }
18114
+ }
18115
+ _Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
18116
+ Ad4mModel.classNamesByClass = new WeakMap();
18117
+ /** Query builder for Ad4mModel queries.
18118
+ * Allows building queries with a fluent interface and either running them once
18119
+ * or subscribing to updates.
18120
+ *
18121
+ * @example
18122
+ * ```typescript
18123
+ * const builder = Recipe.query(perspective)
18124
+ * .where({ category: "Dessert" })
18125
+ * .order({ rating: "DESC" })
18126
+ * .limit(10);
18127
+ *
18128
+ * // Run once
18129
+ * const recipes = await builder.run();
18130
+ *
18131
+ * // Or subscribe to updates
18132
+ * await builder.subscribe(recipes => {
18133
+ * console.log("Updated recipes:", recipes);
18134
+ * });
18135
+ * ```
18136
+ */
18137
+ class ModelQueryBuilder {
18138
+ constructor(perspective, ctor, query) {
18139
+ this.queryParams = {};
18140
+ this.modelClassName = null;
18141
+ this.perspective = perspective;
18142
+ this.ctor = ctor;
18143
+ if (query)
18144
+ this.queryParams = query;
18145
+ }
18146
+ /**
18147
+ * Adds where conditions to the query.
18148
+ *
18149
+ * @param conditions - The conditions to filter by
18150
+ * @returns The query builder for chaining
18151
+ *
18152
+ * @example
18153
+ * ```typescript
18154
+ * .where({
18155
+ * category: "Dessert",
18156
+ * rating: { gt: 4 },
18157
+ * tags: ["vegan", "quick"],
18158
+ * published: true
18159
+ * })
18160
+ * ```
18161
+ */
18162
+ where(conditions) {
18163
+ this.queryParams.where = conditions;
18164
+ return this;
18165
+ }
18166
+ /**
18167
+ * Sets the order for the query results.
18168
+ *
18169
+ * @param orderBy - The ordering criteria
18170
+ * @returns The query builder for chaining
18171
+ *
18172
+ * @example
18173
+ * ```typescript
18174
+ * .order({ createdAt: "DESC" })
18175
+ * ```
18176
+ */
18177
+ order(orderBy) {
18178
+ this.queryParams.order = orderBy;
18179
+ return this;
18180
+ }
18181
+ /**
18182
+ * Sets the maximum number of results to return.
18183
+ *
18184
+ * @param limit - Maximum number of results
18185
+ * @returns The query builder for chaining
18186
+ *
18187
+ * @example
18188
+ * ```typescript
18189
+ * .limit(10)
18190
+ * ```
18191
+ */
18192
+ limit(limit) {
18193
+ this.queryParams.limit = limit;
18194
+ return this;
18195
+ }
18196
+ /**
18197
+ * Sets the number of results to skip.
18198
+ *
18199
+ * @param offset - Number of results to skip
18200
+ * @returns The query builder for chaining
18201
+ *
18202
+ * @example
18203
+ * ```typescript
18204
+ * .offset(20) // Skip first 20 results
18205
+ * ```
18206
+ */
18207
+ offset(offset) {
18208
+ this.queryParams.offset = offset;
18209
+ return this;
18210
+ }
18211
+ /**
18212
+ * Sets the source filter for the query.
18213
+ *
18214
+ * @param source - The source to filter by
18215
+ * @returns The query builder for chaining
18216
+ *
18217
+ * @example
18218
+ * ```typescript
18219
+ * .source("ad4m://self")
18220
+ * ```
18221
+ */
18222
+ source(source) {
18223
+ this.queryParams.source = source;
18224
+ return this;
18225
+ }
18226
+ /**
18227
+ * Specifies which properties to include in the results.
18228
+ *
18229
+ * @param properties - Array of property names to include
18230
+ * @returns The query builder for chaining
18231
+ *
18232
+ * @example
18233
+ * ```typescript
18234
+ * .properties(["name", "description", "rating"])
18235
+ * ```
18236
+ */
18237
+ properties(properties) {
18238
+ this.queryParams.properties = properties;
18239
+ return this;
18240
+ }
18241
+ /**
18242
+ * Specifies which collections to include in the results.
18243
+ *
18244
+ * @param collections - Array of collection names to include
18245
+ * @returns The query builder for chaining
18246
+ *
18247
+ * @example
18248
+ * ```typescript
18249
+ * .collections(["ingredients", "steps"])
18250
+ * ```
18251
+ */
18252
+ collections(collections) {
18253
+ this.queryParams.collections = collections;
18254
+ return this;
18255
+ }
18256
+ overrideModelClassName(className) {
18257
+ this.modelClassName = className;
18258
+ return this;
18259
+ }
18260
+ /**
18261
+ * Executes the query once and returns the results.
18262
+ *
18263
+ * @returns Array of matching entities
18264
+ *
18265
+ * @example
18266
+ * ```typescript
18267
+ * const recipes = await Recipe.query(perspective)
18268
+ * .where({ category: "Dessert" })
18269
+ * .get();
18270
+ * ```
18271
+ */
18272
+ async get() {
18273
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
18274
+ const result = await this.perspective.infer(query);
18275
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
18276
+ return results;
18277
+ }
18278
+ /**
18279
+ * Subscribes to the query and receives updates when results change.
18280
+ *
18281
+ * This method:
18282
+ * 1. Creates and initializes a Prolog query subscription
18283
+ * 2. Sets up the callback to process future updates
18284
+ * 3. Returns the initial results immediately
18285
+ *
18286
+ * The subscription is guaranteed to be ready when this method returns,
18287
+ * as it waits for the initialization process to complete.
18288
+ *
18289
+ * @param callback - Function to call with updated results
18290
+ * @returns Initial results array
18291
+ *
18292
+ * @example
18293
+ * ```typescript
18294
+ * // Subscribe to cooking recipes
18295
+ * const initialRecipes = await Recipe.query(perspective)
18296
+ * .where({ status: "cooking" })
18297
+ * .subscribe(recipes => {
18298
+ * // This callback will be called with future updates
18299
+ * console.log("Currently cooking:", recipes);
18300
+ * });
18301
+ *
18302
+ * // initialRecipes contains the current state
18303
+ * console.log("Initial recipes:", initialRecipes);
18304
+ * ```
18305
+ */
18306
+ async subscribe(callback) {
18307
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
18308
+ const subscription = await this.perspective.subscribeInfer(query);
18309
+ const processResults = async (result) => {
18310
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
18311
+ callback(results);
18312
+ };
18313
+ subscription.onResult(processResults);
18314
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, subscription.result);
18315
+ return results;
18316
+ }
18317
+ /**
18318
+ * Gets the total count of matching entities.
18319
+ *
18320
+ * @returns Total count
18321
+ *
18322
+ * @example
18323
+ * ```typescript
18324
+ * const totalDesserts = await Recipe.query(perspective)
18325
+ * .where({ category: "Dessert" })
18326
+ * .count();
18327
+ * ```
18328
+ */
18329
+ async count() {
18330
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
18331
+ const result = await this.perspective.infer(query);
18332
+ return result?.[0]?.TotalCount || 0;
18333
+ }
18334
+ /**
18335
+ * Subscribes to count updates for matching entities.
18336
+ *
18337
+ * This method:
18338
+ * 1. Creates and initializes a Prolog query subscription for the count
18339
+ * 2. Sets up the callback to process future count updates
18340
+ * 3. Returns the initial count immediately
18341
+ *
18342
+ * The subscription is guaranteed to be ready when this method returns,
18343
+ * as it waits for the initialization process to complete.
18344
+ *
18345
+ * @param callback - Function to call with updated count
18346
+ * @returns Initial count
18347
+ *
18348
+ * @example
18349
+ * ```typescript
18350
+ * // Subscribe to active recipe count
18351
+ * const initialCount = await Recipe.query(perspective)
18352
+ * .where({ status: "active" })
18353
+ * .countSubscribe(count => {
18354
+ * // This callback will be called when the count changes
18355
+ * console.log("Active items:", count);
18356
+ * });
18357
+ *
18358
+ * // initialCount contains the current count
18359
+ * console.log("Initial count:", initialCount);
18360
+ * ```
18361
+ */
18362
+ async countSubscribe(callback) {
18363
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
18364
+ const subscription = await this.perspective.subscribeInfer(query);
18365
+ const processResults = async (result) => {
18366
+ const newCount = result?.[0]?.TotalCount || 0;
18367
+ callback(newCount);
18368
+ };
18369
+ subscription.onResult(processResults);
18370
+ return subscription.result?.[0]?.TotalCount || 0;
18371
+ }
18372
+ /**
18373
+ * Gets a page of results with pagination metadata.
18374
+ *
18375
+ * @param pageSize - Number of items per page
18376
+ * @param pageNumber - Which page to retrieve (1-based)
18377
+ * @returns Paginated results with metadata
18378
+ *
18379
+ * @example
18380
+ * ```typescript
18381
+ * const page = await Recipe.query(perspective)
18382
+ * .where({ category: "Main" })
18383
+ * .paginate(10, 1);
18384
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
18385
+ * ```
18386
+ */
18387
+ async paginate(pageSize, pageNumber) {
18388
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
18389
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
18390
+ const result = await this.perspective.infer(prologQuery);
18391
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
18392
+ return { results, totalCount, pageSize, pageNumber };
18393
+ }
18394
+ /**
18395
+ * Subscribes to paginated results updates.
18396
+ *
18397
+ * This method:
18398
+ * 1. Creates and initializes a Prolog query subscription for the paginated results
18399
+ * 2. Sets up the callback to process future page updates
18400
+ * 3. Returns the initial page immediately
18401
+ *
18402
+ * The subscription is guaranteed to be ready when this method returns,
18403
+ * as it waits for the initialization process to complete.
18404
+ *
18405
+ * @param pageSize - Number of items per page
18406
+ * @param pageNumber - Which page to retrieve (1-based)
18407
+ * @param callback - Function to call with updated pagination results
18408
+ * @returns Initial pagination results
18409
+ *
18410
+ * @example
18411
+ * ```typescript
18412
+ * // Subscribe to first page of main recipes
18413
+ * const initialPage = await Recipe.query(perspective)
18414
+ * .where({ category: "Main" })
18415
+ * .paginateSubscribe(10, 1, page => {
18416
+ * // This callback will be called when the page content changes
18417
+ * console.log("Updated page:", page.results);
18418
+ * });
18419
+ *
18420
+ * // initialPage contains the current page state
18421
+ * console.log("Initial page:", initialPage.results);
18422
+ * ```
18423
+ */
18424
+ async paginateSubscribe(pageSize, pageNumber, callback) {
18425
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
18426
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
18427
+ const subscription = await this.perspective.subscribeInfer(prologQuery);
18428
+ const processResults = async (r) => {
18429
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
18430
+ callback({ results, totalCount, pageSize, pageNumber });
18431
+ };
18432
+ subscription.onResult(processResults);
18433
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, subscription.result));
18434
+ return { results, totalCount, pageSize, pageNumber };
18435
+ }
18436
+ }
18437
+
16758
18438
  exports.AIClient = AIClient;
16759
18439
  exports.Ad4mClient = Ad4mClient;
18440
+ exports.Ad4mModel = Ad4mModel;
16760
18441
  exports.AgentClient = AgentClient;
18442
+ exports.Collection = Collection;
16761
18443
  exports.Dna = Dna;
16762
18444
  exports.ExpressionGeneric = ExpressionGeneric;
16763
18445
  exports.ExpressionGenericInput = ExpressionGenericInput;
18446
+ exports.Flag = Flag;
16764
18447
  exports.InstanceQuery = InstanceQuery;
16765
18448
  exports.LanguageExpression = LanguageExpression;
16766
18449
  exports.LanguageLanguageInput = LanguageLanguageInput;
16767
18450
  exports.LanguageMetaInternal = LanguageMetaInternal;
16768
18451
  exports.Literal = Literal;
18452
+ exports.ModelOptions = ModelOptions;
18453
+ exports.ModelQueryBuilder = ModelQueryBuilder;
16769
18454
  exports.NeighbourhoodProxy = NeighbourhoodProxy;
18455
+ exports.Optional = Optional;
16770
18456
  exports.PerspectiveAction = PerspectiveAction;
16771
18457
  exports.PerspectiveProxy = PerspectiveProxy;
16772
- exports.SDNAClass = SDNAClass;
18458
+ exports.Property = Property;
18459
+ exports.QuerySubscriptionProxy = QuerySubscriptionProxy;
18460
+ exports.ReadOnly = ReadOnly;
16773
18461
  exports.SMART_LITERAL_CONTENT_PREDICATE = SMART_LITERAL_CONTENT_PREDICATE;
16774
18462
  exports.SmartLiteral = SmartLiteral;
16775
18463
  exports.Subject = Subject;
16776
- exports.SubjectCollection = SubjectCollection;
16777
- exports.SubjectEntity = SubjectEntity;
16778
- exports.SubjectFlag = SubjectFlag;
16779
- exports.SubjectProperty = SubjectProperty;
16780
18464
  exports.addLink = addLink;
16781
18465
  exports.capSentence = capSentence;
16782
18466
  exports.exprRef2String = exprRef2String;