@coasys/ad4m 0.10.1-release-candidate-5 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -4610,7 +4610,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
4610
4610
  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");
4611
4611
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
4612
4612
  };
4613
- var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
4613
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
4614
4614
  /** Proxy object for a subscribed Prolog query that provides real-time updates
4615
4615
  *
4616
4616
  * This class handles:
@@ -4661,56 +4661,119 @@ class QuerySubscriptionProxy {
4661
4661
  _QuerySubscriptionProxy_latestResult.set(this, void 0);
4662
4662
  _QuerySubscriptionProxy_disposed.set(this, false);
4663
4663
  _QuerySubscriptionProxy_initialized.set(this, void 0);
4664
+ _QuerySubscriptionProxy_initResolve.set(this, void 0);
4665
+ _QuerySubscriptionProxy_initReject.set(this, void 0);
4664
4666
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
4665
4667
  _QuerySubscriptionProxy_query.set(this, void 0);
4668
+ this.isSurrealDB = false;
4666
4669
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
4667
4670
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, "f");
4668
4671
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
4669
4672
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
4670
4673
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, null, "f");
4674
+ // Create the promise once and store its resolve/reject
4675
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
4676
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
4677
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, reject, "f");
4678
+ }), "f");
4671
4679
  }
4672
4680
  async subscribe() {
4673
- // initialize the query subscription
4674
- const result = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4675
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, result.subscriptionId, "f");
4676
- // Subscribe to query updates
4677
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
4678
- // Add timeout to prevent hanging promises
4681
+ // Clean up previous subscription attempt if retrying
4682
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
4683
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
4684
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, undefined, "f");
4685
+ }
4686
+ // Clear any existing timeout
4687
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4688
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4689
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4690
+ }
4691
+ // Clear any existing keepalive timer to prevent accumulation
4692
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f")) {
4693
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4694
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, "f");
4695
+ }
4696
+ try {
4697
+ // Initialize the query subscription
4698
+ let initialResult;
4699
+ if (this.isSurrealDB) {
4700
+ initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4701
+ }
4702
+ else {
4703
+ initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4704
+ }
4705
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
4706
+ // Process the initial result immediately for fast UX
4707
+ if (initialResult.result) {
4708
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
4709
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
4710
+ }
4711
+ else {
4712
+ console.warn('⚠️ No initial result returned from subscribeQuery!');
4713
+ }
4714
+ // Set up timeout for retry
4679
4715
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
4680
- reject(new Error('Subscription initialization timed out after 30 seconds. Resubscribing...'));
4681
- this.subscribe();
4682
- }, 30000), "f"); // 30 seconds timeout
4716
+ console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
4717
+ // Recursively retry subscription, catching any errors
4718
+ this.subscribe().catch(error => {
4719
+ console.error('Error during subscription retry after timeout:', error);
4720
+ });
4721
+ }, 30000), "f");
4683
4722
  // Subscribe to query updates
4684
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (result) => {
4723
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
4724
+ // Clear timeout on first message
4685
4725
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4686
4726
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4687
4727
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4688
4728
  }
4689
- resolve(true);
4690
- // if the result is one of those repeated initialization results
4691
- // and we got a result before, we don't notify the callbacks
4692
- // so they don't get confused (we could have gotten another
4693
- // more recent result in between)
4694
- if (result.isInit && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, "f")) {
4695
- return;
4729
+ // Resolve the initialization promise (only resolves once)
4730
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
4731
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
4732
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
4733
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
4696
4734
  }
4697
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, result, "f");
4698
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
4735
+ // Skip duplicate init messages
4736
+ if (updateResult.isInit && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, "f"))
4737
+ return;
4738
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
4739
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
4699
4740
  }), "f");
4700
- }), "f");
4741
+ }
4742
+ catch (error) {
4743
+ console.error('Error setting up subscription:', error);
4744
+ // Reject the promise if this is the first attempt
4745
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, "f")) {
4746
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, "f").call(this, error);
4747
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
4748
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
4749
+ }
4750
+ throw error; // Re-throw so caller knows it failed
4751
+ }
4701
4752
  // Start keepalive loop using platform-agnostic setTimeout
4702
4753
  const keepaliveLoop = async () => {
4703
4754
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4704
4755
  return;
4705
4756
  try {
4706
- await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4757
+ if (this.isSurrealDB) {
4758
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4759
+ }
4760
+ else {
4761
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4762
+ }
4707
4763
  }
4708
4764
  catch (e) {
4709
4765
  console.error('Error in keepalive:', e);
4710
4766
  // try to reinitialize the subscription
4711
4767
  console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4712
- await this.subscribe();
4713
- console.log('Subscription reinitialized');
4768
+ try {
4769
+ await this.subscribe();
4770
+ console.log('Subscription reinitialized');
4771
+ }
4772
+ catch (resubscribeError) {
4773
+ console.error('Error during resubscription from keepalive:', resubscribeError);
4774
+ // Don't schedule another keepalive on resubscribe failure
4775
+ return;
4776
+ }
4714
4777
  }
4715
4778
  // Schedule next keepalive if not disposed
4716
4779
  if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f")) {
@@ -4735,7 +4798,9 @@ class QuerySubscriptionProxy {
4735
4798
  * through the subscription channel. This ensures the subscription is fully
4736
4799
  * set up before allowing access to results or updates.
4737
4800
  *
4738
- * The promise will reject if no result is received within 30 seconds.
4801
+ * If no result is received within 30 seconds, the subscription will automatically
4802
+ * retry. The promise will remain pending until a subscription message successfully
4803
+ * arrives, or until a fatal error occurs during subscription setup.
4739
4804
  *
4740
4805
  * Note: You typically don't need to await this directly since the subscription
4741
4806
  * creation methods (like subscribeInfer) already wait for initialization.
@@ -4801,12 +4866,18 @@ class QuerySubscriptionProxy {
4801
4866
  }
4802
4867
  // Tell the backend to dispose of the subscription
4803
4868
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
4804
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"))
4805
- .catch(e => console.error('Error disposing query subscription:', e));
4869
+ if (this.isSurrealDB) {
4870
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"))
4871
+ .catch(e => console.error('Error disposing surreal query subscription:', e));
4872
+ }
4873
+ else {
4874
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"))
4875
+ .catch(e => console.error('Error disposing query subscription:', e));
4876
+ }
4806
4877
  }
4807
4878
  }
4808
4879
  }
4809
- _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_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
4880
+ _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_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
4810
4881
  for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
4811
4882
  try {
4812
4883
  callback(result);
@@ -4996,6 +5067,36 @@ class PerspectiveProxy {
4996
5067
  async infer(query) {
4997
5068
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4998
5069
  }
5070
+ /**
5071
+ * Executes a SurrealQL query against the perspective's link cache.
5072
+ * This allows powerful SQL-like queries on the link data stored in SurrealDB.
5073
+ *
5074
+ * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
5075
+ * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
5076
+ * blocked for security reasons. Use the perspective's add/remove methods to modify links.
5077
+ *
5078
+ * @param query - SurrealQL query string (read-only operations only)
5079
+ * @returns Query results as parsed JSON
5080
+ *
5081
+ * @example
5082
+ * ```typescript
5083
+ * // Get all links
5084
+ * const links = await perspective.querySurrealDB('SELECT * FROM link');
5085
+ *
5086
+ * // Filter links by predicate
5087
+ * const follows = await perspective.querySurrealDB(
5088
+ * "SELECT * FROM link WHERE predicate = 'follows'"
5089
+ * );
5090
+ *
5091
+ * // Complex aggregation query
5092
+ * const stats = await perspective.querySurrealDB(
5093
+ * "SELECT predicate, count() as total FROM link GROUP BY predicate"
5094
+ * );
5095
+ * ```
5096
+ */
5097
+ async querySurrealDB(query) {
5098
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
5099
+ }
4999
5100
  /**
5000
5101
  * Adds a new link to the perspective.
5001
5102
  *
@@ -5704,6 +5805,34 @@ class PerspectiveProxy {
5704
5805
  await subscriptionProxy.initialized;
5705
5806
  return subscriptionProxy;
5706
5807
  }
5808
+ /**
5809
+ * Creates a subscription for a SurrealQL query that updates in real-time.
5810
+ *
5811
+ * This method:
5812
+ * 1. Creates the subscription on the Rust side
5813
+ * 2. Sets up the subscription callback
5814
+ * 3. Waits for the initial result to come through the subscription channel
5815
+ * 4. Returns a fully initialized QuerySubscriptionProxy
5816
+ *
5817
+ * The returned subscription is guaranteed to be ready to receive updates,
5818
+ * as this method waits for the initialization process to complete.
5819
+ *
5820
+ * The subscription will be automatically cleaned up on both frontend and backend
5821
+ * when dispose() is called. Make sure to call dispose() when you're done to
5822
+ * prevent memory leaks and ensure proper cleanup of resources.
5823
+ *
5824
+ * @param query - SurrealQL query string
5825
+ * @returns Initialized QuerySubscriptionProxy instance
5826
+ */
5827
+ async subscribeSurrealDB(query) {
5828
+ const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f"));
5829
+ subscriptionProxy.isSurrealDB = true;
5830
+ // Start the subscription on the Rust side first to get the real subscription ID
5831
+ await subscriptionProxy.subscribe();
5832
+ // Wait for the initial result
5833
+ await subscriptionProxy.initialized;
5834
+ return subscriptionProxy;
5835
+ }
5707
5836
  }
5708
5837
  _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
5709
5838
 
@@ -5843,6 +5972,24 @@ class PerspectiveClient {
5843
5972
  }));
5844
5973
  return JSON.parse(perspectiveQueryProlog);
5845
5974
  }
5975
+ /**
5976
+ * Executes a read-only SurrealQL query against a perspective's link cache.
5977
+ *
5978
+ * Security: Only SELECT, RETURN, and other read-only queries are permitted.
5979
+ * Mutating operations (DELETE, UPDATE, INSERT, etc.) are blocked.
5980
+ *
5981
+ * Note: GraphQL field name is "perspectiveQuerySurrealDb" (lowercase "b" in "Db")
5982
+ * as generated from Rust method "perspective_query_surreal_db"
5983
+ */
5984
+ async querySurrealDB(uuid, query) {
5985
+ const { perspectiveQuerySurrealDb } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").query({
5986
+ query: gql `query perspectiveQuerySurrealDb($uuid: String!, $query: String!) {
5987
+ perspectiveQuerySurrealDb(uuid: $uuid, query: $query)
5988
+ }`,
5989
+ variables: { uuid, query }
5990
+ }));
5991
+ return JSON.parse(perspectiveQuerySurrealDb);
5992
+ }
5846
5993
  async subscribeQuery(uuid, query) {
5847
5994
  const { perspectiveSubscribeQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
5848
5995
  mutation: gql `mutation perspectiveSubscribeQuery($uuid: String!, $query: String!) {
@@ -5868,6 +6015,49 @@ class PerspectiveClient {
5868
6015
  }
5869
6016
  return { subscriptionId, result: finalResult, isInit };
5870
6017
  }
6018
+ async perspectiveSubscribeSurrealQuery(uuid, query) {
6019
+ const { perspectiveSubscribeSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
6020
+ mutation: gql `mutation perspectiveSubscribeSurrealQuery($uuid: String!, $query: String!) {
6021
+ perspectiveSubscribeSurrealQuery(uuid: $uuid, query: $query) {
6022
+ subscriptionId
6023
+ result
6024
+ }
6025
+ }`,
6026
+ variables: { uuid, query }
6027
+ }));
6028
+ const { subscriptionId, result } = perspectiveSubscribeSurrealQuery;
6029
+ let finalResult = result;
6030
+ let isInit = false;
6031
+ if (finalResult.startsWith("#init#")) {
6032
+ finalResult = finalResult.substring(6);
6033
+ isInit = true;
6034
+ }
6035
+ try {
6036
+ finalResult = JSON.parse(finalResult);
6037
+ }
6038
+ catch (e) {
6039
+ console.error('Error parsing perspectiveSubscribeSurrealQuery result:', e);
6040
+ }
6041
+ return { subscriptionId, result: finalResult, isInit };
6042
+ }
6043
+ async perspectiveKeepAliveSurrealQuery(uuid, subscriptionId) {
6044
+ const { perspectiveKeepAliveSurrealQuery } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
6045
+ mutation: gql `mutation perspectiveKeepAliveSurrealQuery($uuid: String!, $subscriptionId: String!) {
6046
+ perspectiveKeepAliveSurrealQuery(uuid: $uuid, subscriptionId: $subscriptionId)
6047
+ }`,
6048
+ variables: { uuid, subscriptionId }
6049
+ }));
6050
+ return perspectiveKeepAliveSurrealQuery;
6051
+ }
6052
+ async perspectiveDisposeSurrealQuerySubscription(uuid, subscriptionId) {
6053
+ const { perspectiveDisposeSurrealQuerySubscription } = unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
6054
+ mutation: gql `mutation perspectiveDisposeSurrealQuerySubscription($uuid: String!, $subscriptionId: String!) {
6055
+ perspectiveDisposeSurrealQuerySubscription(uuid: $uuid, subscriptionId: $subscriptionId)
6056
+ }`,
6057
+ variables: { uuid, subscriptionId }
6058
+ }));
6059
+ return perspectiveDisposeSurrealQuerySubscription;
6060
+ }
5871
6061
  subscribeToQueryUpdates(subscriptionId, onData) {
5872
6062
  const subscription = __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").subscribe({
5873
6063
  query: gql `
@@ -16793,6 +16983,7 @@ type Query {
16793
16983
  perspective(uuid: String!): PerspectiveHandle
16794
16984
  perspectiveQueryLinks(query: LinkQuery!, uuid: String!): [LinkExpression!]
16795
16985
  perspectiveQueryProlog(query: String!, uuid: String!): String!
16986
+ perspectiveQuerySurrealDB(query: String!, uuid: String!): String!
16796
16987
  perspectiveSnapshot(uuid: String!): Perspective
16797
16988
  perspectives: [PerspectiveHandle!]!
16798
16989
  runtimeFriendStatus(did: String!): PerspectiveExpression
@@ -17691,6 +17882,42 @@ function buildLimitQuery(limit) {
17691
17882
  return "AllInstances = InstancesWithOffset";
17692
17883
  return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
17693
17884
  }
17885
+ function normalizeNamespaceString(namespace) {
17886
+ if (!namespace)
17887
+ return '';
17888
+ if (namespace.includes('://')) {
17889
+ const [scheme, rest] = namespace.split('://');
17890
+ const path = (rest || '').replace(/\/+$/, '');
17891
+ return `${scheme}://${path}`;
17892
+ }
17893
+ else {
17894
+ return namespace.replace(/\/+$/, '');
17895
+ }
17896
+ }
17897
+ function normalizeSchemaType(type) {
17898
+ if (!type)
17899
+ return undefined;
17900
+ if (typeof type === "string")
17901
+ return type;
17902
+ if (Array.isArray(type) && type.length > 0) {
17903
+ const nonNull = type.find((t) => t !== "null");
17904
+ return nonNull || type[0];
17905
+ }
17906
+ return undefined;
17907
+ }
17908
+ function isSchemaType(schema, expectedType) {
17909
+ return normalizeSchemaType(schema.type) === expectedType;
17910
+ }
17911
+ function isArrayType(schema) {
17912
+ return isSchemaType(schema, "array");
17913
+ }
17914
+ function isObjectType(schema) {
17915
+ return isSchemaType(schema, "object");
17916
+ }
17917
+ function isNumericType(schema) {
17918
+ const normalized = normalizeSchemaType(schema.type);
17919
+ return normalized === "number" || normalized === "integer";
17920
+ }
17694
17921
  /**
17695
17922
  * Base class for defining data models in AD4M.
17696
17923
  *
@@ -17811,6 +18038,126 @@ class Ad4mModel {
17811
18038
  }
17812
18039
  return classCache[perspectiveID];
17813
18040
  }
18041
+ /**
18042
+ * Extracts metadata from decorators for query building.
18043
+ *
18044
+ * @description
18045
+ * This method reads the metadata stored by decorators (@Property, @Collection, etc.)
18046
+ * and returns it in a structured format that's easier to work with for query builders
18047
+ * and other systems that need to introspect model structure.
18048
+ *
18049
+ * The metadata includes:
18050
+ * - Class name from @ModelOptions
18051
+ * - Property metadata (predicates, types, constraints, etc.)
18052
+ * - Collection metadata (predicates, filters, etc.)
18053
+ *
18054
+ * For models created via `fromJSONSchema()`, this method will derive metadata from
18055
+ * the stored `__properties` and `__collections` structures that were populated during
18056
+ * the dynamic class creation. If these structures are empty but a JSON schema was
18057
+ * attached to the class, it can fall back to deriving metadata from that schema.
18058
+ *
18059
+ * @returns Structured metadata object containing className, properties, and collections
18060
+ * @throws Error if the class doesn't have @ModelOptions decorator
18061
+ *
18062
+ * @example
18063
+ * ```typescript
18064
+ * @ModelOptions({ name: "Recipe" })
18065
+ * class Recipe extends Ad4mModel {
18066
+ * @Property({ through: "recipe://name", resolveLanguage: "literal" })
18067
+ * name: string = "";
18068
+ *
18069
+ * @Collection({ through: "recipe://ingredient" })
18070
+ * ingredients: string[] = [];
18071
+ * }
18072
+ *
18073
+ * const metadata = Recipe.getModelMetadata();
18074
+ * console.log(metadata.className); // "Recipe"
18075
+ * console.log(metadata.properties.name.predicate); // "recipe://name"
18076
+ * console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
18077
+ * ```
18078
+ */
18079
+ static getModelMetadata() {
18080
+ // Access the prototype with any type to access decorator-added properties
18081
+ const prototype = this.prototype;
18082
+ // Validate that the class has @ModelOptions decorator
18083
+ // The decorator sets prototype.className, so we check for its existence
18084
+ if (!prototype.className || prototype.className === 'Ad4mModel') {
18085
+ throw new Error("Model class must be decorated with @ModelOptions");
18086
+ }
18087
+ // Extract className
18088
+ const className = prototype.className;
18089
+ // Extract properties from prototype.__properties
18090
+ const propertiesMetadata = {};
18091
+ const prototypeProperties = prototype.__properties || {};
18092
+ for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
18093
+ const options = opts;
18094
+ propertiesMetadata[propertyName] = {
18095
+ name: propertyName,
18096
+ predicate: options.through || "",
18097
+ required: options.required || false,
18098
+ writable: options.writable || false,
18099
+ ...(options.initial !== undefined && { initial: options.initial }),
18100
+ ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
18101
+ ...(options.getter !== undefined && { getter: options.getter }),
18102
+ ...(options.setter !== undefined && { setter: options.setter }),
18103
+ ...(options.local !== undefined && { local: options.local }),
18104
+ ...(options.transform !== undefined && { transform: options.transform }),
18105
+ ...(options.flag !== undefined && { flag: options.flag })
18106
+ };
18107
+ }
18108
+ // Extract collections from prototype.__collections
18109
+ const collectionsMetadata = {};
18110
+ const prototypeCollections = prototype.__collections || {};
18111
+ for (const [collectionName, opts] of Object.entries(prototypeCollections)) {
18112
+ const options = opts;
18113
+ collectionsMetadata[collectionName] = {
18114
+ name: collectionName,
18115
+ predicate: options.through || "",
18116
+ ...(options.where !== undefined && { where: options.where }),
18117
+ ...(options.local !== undefined && { local: options.local })
18118
+ };
18119
+ }
18120
+ // Fallback: If both structures are empty but a JSON schema is attached, derive from it
18121
+ // This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
18122
+ const hasProperties = Object.keys(propertiesMetadata).length > 0;
18123
+ const hasCollections = Object.keys(collectionsMetadata).length > 0;
18124
+ const hasMetadata = hasProperties || hasCollections;
18125
+ if (!hasMetadata && prototype.__jsonSchema) {
18126
+ // Derive metadata from the attached JSON schema
18127
+ const schema = prototype.__jsonSchema;
18128
+ const options = prototype.__jsonSchemaOptions || {};
18129
+ if (schema.properties) {
18130
+ for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
18131
+ const isArray = isArrayType(propertySchema);
18132
+ const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
18133
+ if (isArray) {
18134
+ collectionsMetadata[propertyName] = {
18135
+ name: propertyName,
18136
+ predicate: predicate,
18137
+ ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
18138
+ };
18139
+ }
18140
+ else {
18141
+ const isRequired = schema.required?.includes(propertyName) || false;
18142
+ propertiesMetadata[propertyName] = {
18143
+ name: propertyName,
18144
+ predicate: predicate,
18145
+ required: isRequired,
18146
+ writable: propertySchema["x-ad4m"]?.writable !== false,
18147
+ ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
18148
+ ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
18149
+ ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
18150
+ };
18151
+ }
18152
+ }
18153
+ }
18154
+ }
18155
+ return {
18156
+ className,
18157
+ properties: propertiesMetadata,
18158
+ collections: collectionsMetadata
18159
+ };
18160
+ }
17814
18161
  /**
17815
18162
  * Constructs a new model instance.
17816
18163
  *
@@ -17938,6 +18285,477 @@ class Ad4mModel {
17938
18285
  `;
17939
18286
  return fullQuery;
17940
18287
  }
18288
+ /**
18289
+ * Generates a SurrealQL query from a Query object.
18290
+ *
18291
+ * @description
18292
+ * This method translates high-level query parameters into a SurrealQL query string
18293
+ * that can be executed against the SurrealDB backend. Unlike Prolog queries which
18294
+ * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
18295
+ * stored in SurrealDB.
18296
+ *
18297
+ * The generated query uses a CTE (Common Table Expression) pattern:
18298
+ * 1. First, identify candidate base expressions by filtering links based on where conditions
18299
+ * 2. Then, for each candidate base, resolve properties and collections via subqueries
18300
+ * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
18301
+ *
18302
+ * Key architectural notes:
18303
+ * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
18304
+ * - No SDNA knowledge at the database level
18305
+ * - Properties are resolved via subqueries that look for links with specific predicates
18306
+ * - Collections are similar but return multiple values instead of one
18307
+ * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
18308
+ *
18309
+ * @param perspective - The perspective to query (used for metadata extraction)
18310
+ * @param query - Query parameters (where, order, limit, offset, properties, collections)
18311
+ * @returns Complete SurrealQL query string ready for execution
18312
+ *
18313
+ * @example
18314
+ * ```typescript
18315
+ * const query = Recipe.queryToSurrealQL(perspective, {
18316
+ * where: { name: "Pasta", rating: { gt: 4 } },
18317
+ * order: { timestamp: "DESC" },
18318
+ * limit: 10
18319
+ * });
18320
+ * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
18321
+ * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
18322
+ * ```
18323
+ */
18324
+ static async queryToSurrealQL(perspective, query) {
18325
+ const metadata = this.getModelMetadata();
18326
+ const { source, where, order, offset, limit } = query;
18327
+ // Build list of graph traversal filters for required predicates
18328
+ const graphTraversalFilters = [];
18329
+ // Add source filter if specified (filter to nodes that are children of this source)
18330
+ // Source filter means: find targets of 'ad4m://has_child' links from the specified source
18331
+ if (source) {
18332
+ // Use graph traversal: node must be target of has_child link from source
18333
+ graphTraversalFilters.push(`count(<-link[WHERE perspective = $perspective AND in.uri = ${this.formatSurrealValue(source)} AND predicate = 'ad4m://has_child']) > 0`);
18334
+ }
18335
+ // Add filters for required properties
18336
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
18337
+ if (propMeta.required) {
18338
+ // For flag properties, also filter by the target value
18339
+ if (propMeta.flag && propMeta.initial) {
18340
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
18341
+ }
18342
+ else {
18343
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
18344
+ }
18345
+ }
18346
+ }
18347
+ // If no required properties, we need at least one property to define the model
18348
+ // Use any property with an initial value as the defining characteristic
18349
+ if (graphTraversalFilters.length === 0) {
18350
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
18351
+ if (propMeta.initial) {
18352
+ // For flag properties, also filter by the target value
18353
+ if (propMeta.flag) {
18354
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}' AND out.uri = '${propMeta.initial}']) > 0`);
18355
+ }
18356
+ else {
18357
+ graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${propMeta.predicate}']) > 0`);
18358
+ }
18359
+ break; // Just need one defining property
18360
+ }
18361
+ }
18362
+ }
18363
+ // Build user WHERE clause filters using graph traversal
18364
+ const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
18365
+ // Build complete WHERE clause using graph traversal filters
18366
+ const whereConditions = [];
18367
+ // Add all graph traversal filters for required properties
18368
+ whereConditions.push(...graphTraversalFilters);
18369
+ // Add user where conditions if any
18370
+ if (userWhereClause) {
18371
+ whereConditions.push(userWhereClause);
18372
+ }
18373
+ // Always ensure node has at least one link in this perspective
18374
+ whereConditions.push(`count(->link[WHERE perspective = $perspective]) > 0`);
18375
+ // Build the query FROM node using direct graph traversal in WHERE
18376
+ // This avoids slow subqueries and uses graph indexes for fast traversal
18377
+ const fullQuery = `
18378
+ SELECT
18379
+ id AS source,
18380
+ uri AS source_uri,
18381
+ ->link[WHERE perspective = $perspective] AS links
18382
+ FROM node
18383
+ WHERE ${whereConditions.join(' AND ')}
18384
+ `.trim();
18385
+ return fullQuery;
18386
+ }
18387
+ /**
18388
+ * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
18389
+ *
18390
+ * @description
18391
+ * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
18392
+ * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
18393
+ *
18394
+ * Handles several condition types:
18395
+ * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
18396
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
18397
+ * - NOT operators: Use `NOT` prefix
18398
+ * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
18399
+ * - Special fields: base uses `uri` directly, author/timestamp handled post-query
18400
+ *
18401
+ * @param metadata - Model metadata containing property predicates
18402
+ * @param where - Where conditions from the query
18403
+ * @returns Graph traversal WHERE clause filters, or empty string if no conditions
18404
+ *
18405
+ * @private
18406
+ */
18407
+ static buildGraphTraversalWhereClause(metadata, where) {
18408
+ if (!where)
18409
+ return '';
18410
+ const conditions = [];
18411
+ for (const [propertyName, condition] of Object.entries(where)) {
18412
+ // Check if this is a special field (base, author, timestamp)
18413
+ // Note: author and timestamp filtering is done in JavaScript after query
18414
+ const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
18415
+ if (isSpecial) {
18416
+ // Skip author and timestamp - they'll be filtered in JavaScript
18417
+ // Only handle 'base' (which maps to 'uri') here
18418
+ if (propertyName === 'author' || propertyName === 'timestamp') {
18419
+ continue; // Skip - will be filtered post-query
18420
+ }
18421
+ const columnName = 'uri'; // base maps to uri in node table
18422
+ // Handle base/uri field directly
18423
+ if (Array.isArray(condition)) {
18424
+ // Array values (IN clause)
18425
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
18426
+ conditions.push(`${columnName} IN [${formattedValues}]`);
18427
+ }
18428
+ else if (typeof condition === 'object' && condition !== null) {
18429
+ // Operator object
18430
+ const ops = condition;
18431
+ if (ops.not !== undefined) {
18432
+ if (Array.isArray(ops.not)) {
18433
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
18434
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
18435
+ }
18436
+ else {
18437
+ conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
18438
+ }
18439
+ }
18440
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
18441
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
18442
+ }
18443
+ if (ops.gt !== undefined) {
18444
+ conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
18445
+ }
18446
+ if (ops.gte !== undefined) {
18447
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
18448
+ }
18449
+ if (ops.lt !== undefined) {
18450
+ conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
18451
+ }
18452
+ if (ops.lte !== undefined) {
18453
+ conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
18454
+ }
18455
+ if (ops.contains !== undefined) {
18456
+ conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
18457
+ }
18458
+ }
18459
+ else {
18460
+ // Simple equality
18461
+ conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
18462
+ }
18463
+ }
18464
+ else {
18465
+ // Handle regular properties via graph traversal
18466
+ const propMeta = metadata.properties[propertyName];
18467
+ if (!propMeta)
18468
+ continue; // Skip if property not found in metadata
18469
+ const predicate = propMeta.predicate;
18470
+ // Use fn::parse_literal() for properties with resolveLanguage
18471
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
18472
+ if (Array.isArray(condition)) {
18473
+ // Array values (IN clause)
18474
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
18475
+ conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
18476
+ }
18477
+ else if (typeof condition === 'object' && condition !== null) {
18478
+ // Operator object
18479
+ const ops = condition;
18480
+ if (ops.not !== undefined) {
18481
+ if (Array.isArray(ops.not)) {
18482
+ // For NOT IN with array: must NOT have a link with value in the array
18483
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
18484
+ conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
18485
+ }
18486
+ else {
18487
+ // For NOT with single value: must NOT have this value
18488
+ conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
18489
+ }
18490
+ }
18491
+ // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
18492
+ // post-query because fn::parse_literal() comparisons in SurrealDB
18493
+ // don't work reliably with numeric comparisons.
18494
+ // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
18495
+ // However, we still need to ensure the property exists
18496
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
18497
+ ops.lt !== undefined || ops.lte !== undefined ||
18498
+ ops.between !== undefined || ops.contains !== undefined;
18499
+ if (hasComparisonOps) {
18500
+ // Ensure we only get nodes that have this property
18501
+ conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}']) > 0`);
18502
+ }
18503
+ }
18504
+ else {
18505
+ // Simple equality
18506
+ conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
18507
+ }
18508
+ }
18509
+ }
18510
+ return conditions.join(' AND ');
18511
+ }
18512
+ /**
18513
+ * Builds the WHERE clause for SurrealQL queries.
18514
+ *
18515
+ * @description
18516
+ * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
18517
+ * For each property filter, generates a subquery that checks for links with the appropriate
18518
+ * predicate and target value.
18519
+ *
18520
+ * Handles several condition types:
18521
+ * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
18522
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
18523
+ * - Operators: `{ rating: { gt: 4 } }` → target > '4'
18524
+ * - gt, gte, lt, lte: comparison operators
18525
+ * - not: negation (single value or array)
18526
+ * - between: range check
18527
+ * - contains: substring/element check (uses SurrealQL CONTAINS)
18528
+ * - Special fields: base, author, timestamp are accessed directly, not via subqueries
18529
+ *
18530
+ * All conditions are joined with AND.
18531
+ *
18532
+ * @param metadata - Model metadata containing property predicates
18533
+ * @param where - Where conditions from the query
18534
+ * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
18535
+ *
18536
+ * @private
18537
+ */
18538
+ static buildSurrealWhereClause(metadata, where) {
18539
+ if (!where)
18540
+ return '';
18541
+ const conditions = [];
18542
+ for (const [propertyName, condition] of Object.entries(where)) {
18543
+ // Check if this is a special field (base, author, timestamp)
18544
+ // Note: author and timestamp filtering is done in JavaScript after GROUP BY
18545
+ // because they need to be computed from the grouped links first
18546
+ const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
18547
+ if (isSpecial) {
18548
+ // Skip author and timestamp - they'll be filtered in JavaScript
18549
+ // Only handle 'base' (which maps to 'source') here
18550
+ if (propertyName === 'author' || propertyName === 'timestamp') {
18551
+ continue; // Skip - will be filtered post-query
18552
+ }
18553
+ const columnName = 'source'; // base maps to source
18554
+ // Handle base/source field directly
18555
+ if (Array.isArray(condition)) {
18556
+ // Array values (IN clause)
18557
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
18558
+ conditions.push(`${columnName} IN [${formattedValues}]`);
18559
+ }
18560
+ else if (typeof condition === 'object' && condition !== null) {
18561
+ // Operator object
18562
+ const ops = condition;
18563
+ if (ops.not !== undefined) {
18564
+ if (Array.isArray(ops.not)) {
18565
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
18566
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
18567
+ }
18568
+ else {
18569
+ conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
18570
+ }
18571
+ }
18572
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
18573
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
18574
+ }
18575
+ if (ops.gt !== undefined) {
18576
+ conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
18577
+ }
18578
+ if (ops.gte !== undefined) {
18579
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
18580
+ }
18581
+ if (ops.lt !== undefined) {
18582
+ conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
18583
+ }
18584
+ if (ops.lte !== undefined) {
18585
+ conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
18586
+ }
18587
+ if (ops.contains !== undefined) {
18588
+ conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
18589
+ }
18590
+ }
18591
+ else {
18592
+ // Simple equality
18593
+ conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
18594
+ }
18595
+ }
18596
+ else {
18597
+ // Handle regular properties via subqueries
18598
+ const propMeta = metadata.properties[propertyName];
18599
+ if (!propMeta)
18600
+ continue; // Skip if property not found in metadata
18601
+ const predicate = propMeta.predicate;
18602
+ // Use fn::parse_literal() for properties with resolveLanguage
18603
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
18604
+ if (Array.isArray(condition)) {
18605
+ // Array values (IN clause)
18606
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
18607
+ conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
18608
+ }
18609
+ else if (typeof condition === 'object' && condition !== null) {
18610
+ // Operator object
18611
+ const ops = condition;
18612
+ if (ops.not !== undefined) {
18613
+ if (Array.isArray(ops.not)) {
18614
+ // For NOT IN with array: exclude sources that HAVE a value in the array
18615
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
18616
+ conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
18617
+ }
18618
+ else {
18619
+ // For NOT with single value: exclude sources that HAVE this value
18620
+ conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
18621
+ }
18622
+ }
18623
+ // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
18624
+ // post-query because fn::parse_literal() comparisons in SurrealDB subqueries
18625
+ // don't work reliably with numeric comparisons.
18626
+ // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
18627
+ // However, we still need to ensure the property exists by filtering on the predicate
18628
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
18629
+ ops.lt !== undefined || ops.lte !== undefined ||
18630
+ ops.between !== undefined || ops.contains !== undefined;
18631
+ if (hasComparisonOps) {
18632
+ // Ensure we only get instances that have this property
18633
+ conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
18634
+ }
18635
+ }
18636
+ else {
18637
+ // Simple equality
18638
+ conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
18639
+ }
18640
+ }
18641
+ }
18642
+ return conditions.join(' AND ');
18643
+ }
18644
+ /**
18645
+ * Builds the SELECT fields for SurrealQL queries.
18646
+ *
18647
+ * @description
18648
+ * Generates the field list for the SELECT clause, resolving properties and collections
18649
+ * via subqueries. Each property is fetched with a subquery that finds the link with the
18650
+ * appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
18651
+ *
18652
+ * Field types:
18653
+ * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
18654
+ * - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
18655
+ * - Author/Timestamp: Always included to provide metadata about each instance
18656
+ *
18657
+ * If properties or collections arrays are provided, only those fields are included.
18658
+ * Otherwise, all properties/collections from metadata are included.
18659
+ *
18660
+ * @param metadata - Model metadata containing property and collection predicates
18661
+ * @param properties - Optional array of property names to include (default: all)
18662
+ * @param collections - Optional array of collection names to include (default: all)
18663
+ * @returns Comma-separated SELECT field list
18664
+ *
18665
+ * @private
18666
+ */
18667
+ static buildSurrealSelectFields(metadata, properties, collections) {
18668
+ const fields = [];
18669
+ // Determine properties to fetch
18670
+ const propsToFetch = properties || Object.keys(metadata.properties);
18671
+ for (const propName of propsToFetch) {
18672
+ const propMeta = metadata.properties[propName];
18673
+ if (!propMeta)
18674
+ continue; // Skip if not found
18675
+ // Reference source directly since we're selecting from link table
18676
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${propMeta.predicate}' LIMIT 1) AS ${propName}`);
18677
+ }
18678
+ // Determine collections to fetch
18679
+ const collsToFetch = collections || Object.keys(metadata.collections);
18680
+ for (const collName of collsToFetch) {
18681
+ const collMeta = metadata.collections[collName];
18682
+ if (!collMeta)
18683
+ continue; // Skip if not found
18684
+ // Reference source directly since we're selecting from link table
18685
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${collMeta.predicate}') AS ${collName}`);
18686
+ }
18687
+ // Always add author and timestamp fields
18688
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
18689
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
18690
+ return fields.join(',\n ');
18691
+ }
18692
+ /**
18693
+ * Builds the SELECT fields for SurrealQL queries using aggregation functions.
18694
+ * Compatible with GROUP BY source queries.
18695
+ *
18696
+ * @private
18697
+ */
18698
+ static buildSurrealSelectFieldsWithAggregation(metadata, properties, collections) {
18699
+ const fields = [];
18700
+ // Determine properties to fetch
18701
+ const propsToFetch = properties || Object.keys(metadata.properties);
18702
+ for (const propName of propsToFetch) {
18703
+ const propMeta = metadata.properties[propName];
18704
+ if (!propMeta)
18705
+ continue; // Skip if not found
18706
+ // Use array::first to get the first target value for this predicate
18707
+ fields.push(`array::first(target[WHERE predicate = '${propMeta.predicate}']) AS ${propName}`);
18708
+ }
18709
+ // Determine collections to fetch
18710
+ const collsToFetch = collections || Object.keys(metadata.collections);
18711
+ for (const collName of collsToFetch) {
18712
+ const collMeta = metadata.collections[collName];
18713
+ if (!collMeta)
18714
+ continue; // Skip if not found
18715
+ // Use array filtering to get all target values for this predicate
18716
+ fields.push(`target[WHERE predicate = '${collMeta.predicate}'] AS ${collName}`);
18717
+ }
18718
+ // Always add author and timestamp fields using array::first
18719
+ fields.push(`array::first(author) AS author`);
18720
+ fields.push(`array::first(timestamp) AS timestamp`);
18721
+ return fields.join(',\n ');
18722
+ }
18723
+ /**
18724
+ * Formats a value for use in SurrealQL queries.
18725
+ *
18726
+ * @description
18727
+ * Handles different value types:
18728
+ * - Strings: Wrapped in single quotes with backslash-escaped special characters
18729
+ * - Numbers/booleans: Converted to string
18730
+ * - Arrays: Recursively formatted and wrapped in brackets
18731
+ *
18732
+ * @param value - The value to format
18733
+ * @returns Formatted value string ready for SurrealQL
18734
+ *
18735
+ * @private
18736
+ */
18737
+ static formatSurrealValue(value) {
18738
+ if (typeof value === 'string') {
18739
+ // Escape backslashes first, then single quotes and other special characters
18740
+ const escaped = value
18741
+ .replace(/\\/g, '\\\\') // Backslash -> \\
18742
+ .replace(/'/g, "\\'") // Single quote -> \'
18743
+ .replace(/"/g, '\\"') // Double quote -> \"
18744
+ .replace(/\n/g, '\\n') // Newline -> \n
18745
+ .replace(/\r/g, '\\r') // Carriage return -> \r
18746
+ .replace(/\t/g, '\\t'); // Tab -> \t
18747
+ return `'${escaped}'`;
18748
+ }
18749
+ else if (typeof value === 'number' || typeof value === 'boolean') {
18750
+ return String(value);
18751
+ }
18752
+ else if (Array.isArray(value)) {
18753
+ return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
18754
+ }
18755
+ else {
18756
+ return String(value);
18757
+ }
18758
+ }
17941
18759
  static async instancesFromPrologResult(perspective, query, result) {
17942
18760
  if (!result?.[0]?.AllInstances)
17943
18761
  return { results: [], totalCount: 0 };
@@ -17966,19 +18784,339 @@ class Ad4mModel {
17966
18784
  }));
17967
18785
  return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
17968
18786
  }
18787
+ /**
18788
+ * Converts SurrealDB query results to Ad4mModel instances.
18789
+ *
18790
+ * @param perspective - The perspective context
18791
+ * @param query - The query parameters used
18792
+ * @param result - Array of result objects from SurrealDB
18793
+ * @returns Promise resolving to results with total count
18794
+ *
18795
+ * @internal
18796
+ */
18797
+ static async instancesFromSurrealResult(perspective, query, result) {
18798
+ if (!result || result.length === 0)
18799
+ return { results: [], totalCount: 0 };
18800
+ const metadata = this.getModelMetadata();
18801
+ const requestedProperties = query?.properties || [];
18802
+ const requestedCollections = query?.collections || [];
18803
+ // The query used GROUP BY with graph traversal, so each row has:
18804
+ // - source: the node ID (e.g., "node:abc123")
18805
+ // - source_uri: the actual URI (the base expression)
18806
+ // - links: array of link objects with {predicate, target, author, timestamp}
18807
+ const instances = [];
18808
+ for (const row of result) {
18809
+ let base;
18810
+ try {
18811
+ // Use source_uri as the base (the actual URI), not the node ID
18812
+ base = row.source_uri;
18813
+ // Skip rows without a source_uri field
18814
+ if (!base) {
18815
+ continue;
18816
+ }
18817
+ const links = row.links || [];
18818
+ const instance = new this(perspective, base);
18819
+ // Track the most recent timestamp and corresponding author
18820
+ let maxTimestamp = null;
18821
+ let latestAuthor = null;
18822
+ // Process each link (track index for collection ordering)
18823
+ for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
18824
+ const link = links[linkIndex];
18825
+ const predicate = link.predicate;
18826
+ const target = link.target;
18827
+ // Skip 'None' values
18828
+ if (target === 'None')
18829
+ continue;
18830
+ // Track the most recent timestamp and its author
18831
+ if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
18832
+ maxTimestamp = link.timestamp;
18833
+ latestAuthor = link.author;
18834
+ }
18835
+ // Find matching property
18836
+ let foundProperty = false;
18837
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
18838
+ if (propMeta.predicate === predicate) {
18839
+ // For properties, take the first value (or we could use timestamp to get latest)
18840
+ // Note: Empty objects {} are truthy, so we need to check for them explicitly
18841
+ const currentValue = instance[propName];
18842
+ const isEmptyObject = typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue) && Object.keys(currentValue).length === 0;
18843
+ if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
18844
+ let convertedValue = target;
18845
+ // Parse literal URLs if property has resolveLanguage
18846
+ if (propMeta.resolveLanguage === 'literal' && typeof target === 'string' && target.startsWith('literal://')) {
18847
+ try {
18848
+ convertedValue = Literal.fromUrl(target).get();
18849
+ if (convertedValue.data !== undefined) {
18850
+ convertedValue = convertedValue.data;
18851
+ }
18852
+ }
18853
+ catch (e) {
18854
+ console.warn(`Failed to parse literal URL for ${propName}:`, e);
18855
+ convertedValue = target; // Fall back to raw value
18856
+ }
18857
+ }
18858
+ else {
18859
+ // Type conversion: check the instance property's current type
18860
+ const expectedType = typeof instance[propName];
18861
+ if (expectedType === 'number' && typeof target === 'string') {
18862
+ convertedValue = Number(target);
18863
+ }
18864
+ else if (expectedType === 'boolean' && typeof target === 'string') {
18865
+ convertedValue = target === 'true' || target === '1';
18866
+ }
18867
+ }
18868
+ // Apply transform function if it exists
18869
+ if (propMeta.transform && typeof propMeta.transform === 'function') {
18870
+ convertedValue = propMeta.transform(convertedValue);
18871
+ }
18872
+ instance[propName] = convertedValue;
18873
+ }
18874
+ foundProperty = true;
18875
+ break;
18876
+ }
18877
+ }
18878
+ // If not a property, check if it's a collection
18879
+ if (!foundProperty) {
18880
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
18881
+ if (collMeta.predicate === predicate) {
18882
+ // For collections, accumulate all values with their timestamps and indices for sorting
18883
+ if (!instance[collName]) {
18884
+ instance[collName] = [];
18885
+ }
18886
+ // Initialize timestamp tracking array if not already done
18887
+ const timestampsKey = `__${collName}_timestamps`;
18888
+ const indicesKey = `__${collName}_indices`;
18889
+ if (!instance[timestampsKey]) {
18890
+ instance[timestampsKey] = [];
18891
+ }
18892
+ if (!instance[indicesKey]) {
18893
+ instance[indicesKey] = [];
18894
+ }
18895
+ if (!instance[collName].includes(target)) {
18896
+ instance[collName].push(target);
18897
+ instance[timestampsKey].push(link.timestamp || '');
18898
+ // Track original position in the links array for stable sorting
18899
+ instance[indicesKey].push(linkIndex);
18900
+ }
18901
+ break;
18902
+ }
18903
+ }
18904
+ }
18905
+ }
18906
+ // Set author and timestamp from the most recent link
18907
+ if (latestAuthor && maxTimestamp) {
18908
+ instance.author = latestAuthor;
18909
+ // Convert timestamp to number (milliseconds) if it's an ISO string
18910
+ if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
18911
+ instance.timestamp = new Date(maxTimestamp).getTime();
18912
+ }
18913
+ else if (typeof maxTimestamp === 'string') {
18914
+ // Try to parse as number string
18915
+ const parsed = parseInt(maxTimestamp, 10);
18916
+ instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
18917
+ }
18918
+ else {
18919
+ instance.timestamp = maxTimestamp;
18920
+ }
18921
+ }
18922
+ // Sort collections by timestamp to maintain insertion order
18923
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
18924
+ const timestampsKey = `__${collName}_timestamps`;
18925
+ const indicesKey = `__${collName}_indices`;
18926
+ if (instance[collName] && instance[timestampsKey]) {
18927
+ // Create array of [value, timestamp, index] tuples
18928
+ const pairs = instance[collName].map((value, index) => ({
18929
+ value,
18930
+ timestamp: instance[timestampsKey][index] || '',
18931
+ originalIndex: instance[indicesKey]?.[index] ?? index
18932
+ }));
18933
+ // Sort by timestamp first, then by original index for stable sorting
18934
+ pairs.sort((a, b) => {
18935
+ const tsA = String(a.timestamp || '');
18936
+ const tsB = String(b.timestamp || '');
18937
+ const tsCompare = tsA.localeCompare(tsB);
18938
+ if (tsCompare !== 0)
18939
+ return tsCompare;
18940
+ // Use original index as tiebreaker for stable sorting
18941
+ return a.originalIndex - b.originalIndex;
18942
+ });
18943
+ // Replace collection with sorted values
18944
+ instance[collName] = pairs.map(p => p.value);
18945
+ // Clean up temporary arrays
18946
+ delete instance[timestampsKey];
18947
+ delete instance[indicesKey];
18948
+ }
18949
+ }
18950
+ // Filter by requested attributes if specified
18951
+ if (requestedProperties.length > 0 || requestedCollections.length > 0) {
18952
+ const requestedAttributes = [...requestedProperties, ...requestedCollections];
18953
+ Object.keys(instance).forEach((key) => {
18954
+ // Keep only requested attributes, plus always keep timestamp and author
18955
+ if (!requestedAttributes.includes(key) && key !== 'timestamp' && key !== 'author' && key !== 'baseExpression') {
18956
+ delete instance[key];
18957
+ }
18958
+ });
18959
+ }
18960
+ instances.push(instance);
18961
+ }
18962
+ catch (error) {
18963
+ console.error(`Failed to process SurrealDB instance ${base}:`, error);
18964
+ }
18965
+ }
18966
+ // Filter by where conditions that couldn't be filtered in SQL
18967
+ // This includes:
18968
+ // - author/timestamp (computed from grouped links)
18969
+ // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
18970
+ // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
18971
+ let filteredInstances = instances;
18972
+ if (query.where) {
18973
+ filteredInstances = instances.filter(instance => {
18974
+ for (const [propertyName, condition] of Object.entries(query.where)) {
18975
+ // Skip 'base' as it's filtered in SQL
18976
+ if (propertyName === 'base')
18977
+ continue;
18978
+ // For author and timestamp, always filter in JS
18979
+ if (propertyName === 'author' || propertyName === 'timestamp') {
18980
+ if (!this.matchesCondition(instance[propertyName], condition)) {
18981
+ return false;
18982
+ }
18983
+ continue;
18984
+ }
18985
+ // For regular properties, only filter comparison operators in JS
18986
+ // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
18987
+ if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
18988
+ const ops = condition;
18989
+ // Check if any comparison operators are present
18990
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
18991
+ ops.lt !== undefined || ops.lte !== undefined ||
18992
+ ops.between !== undefined || ops.contains !== undefined;
18993
+ if (hasComparisonOps) {
18994
+ if (!this.matchesCondition(instance[propertyName], condition)) {
18995
+ return false;
18996
+ }
18997
+ }
18998
+ }
18999
+ }
19000
+ return true;
19001
+ });
19002
+ }
19003
+ // Apply ordering in JavaScript
19004
+ // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
19005
+ // This ensures consistent pagination behavior
19006
+ const effectiveOrder = query.order ||
19007
+ (query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' } : null);
19008
+ if (effectiveOrder) {
19009
+ const orderPropName = Object.keys(effectiveOrder)[0];
19010
+ const orderDirection = Object.values(effectiveOrder)[0];
19011
+ filteredInstances.sort((a, b) => {
19012
+ let aVal = a[orderPropName];
19013
+ let bVal = b[orderPropName];
19014
+ // Handle undefined values - push them to the end
19015
+ if (aVal === undefined && bVal === undefined)
19016
+ return 0;
19017
+ if (aVal === undefined)
19018
+ return orderDirection === 'ASC' ? 1 : -1;
19019
+ if (bVal === undefined)
19020
+ return orderDirection === 'ASC' ? -1 : 1;
19021
+ // Compare values
19022
+ let comparison = 0;
19023
+ if (typeof aVal === 'number' && typeof bVal === 'number') {
19024
+ comparison = aVal - bVal;
19025
+ }
19026
+ else if (typeof aVal === 'string' && typeof bVal === 'string') {
19027
+ comparison = aVal.localeCompare(bVal);
19028
+ }
19029
+ else {
19030
+ // Convert to strings for comparison
19031
+ comparison = String(aVal).localeCompare(String(bVal));
19032
+ }
19033
+ return orderDirection === 'DESC' ? -comparison : comparison;
19034
+ });
19035
+ }
19036
+ // Calculate totalCount BEFORE applying limit/offset
19037
+ const totalCount = filteredInstances.length;
19038
+ // Apply offset and limit in JavaScript
19039
+ let paginatedInstances = filteredInstances;
19040
+ if (query.offset !== undefined || query.limit !== undefined) {
19041
+ const start = query.offset || 0;
19042
+ const end = query.limit ? start + query.limit : undefined;
19043
+ paginatedInstances = filteredInstances.slice(start, end);
19044
+ }
19045
+ return {
19046
+ results: paginatedInstances,
19047
+ totalCount
19048
+ };
19049
+ }
19050
+ /**
19051
+ * Checks if a value matches a condition (for post-query filtering).
19052
+ * @private
19053
+ */
19054
+ static matchesCondition(value, condition) {
19055
+ // Handle array values (IN clause)
19056
+ if (Array.isArray(condition)) {
19057
+ return condition.includes(value);
19058
+ }
19059
+ // Handle operator object
19060
+ if (typeof condition === 'object' && condition !== null) {
19061
+ const ops = condition;
19062
+ // Special case: 'not' operator (exclusive with other operators)
19063
+ if (ops.not !== undefined) {
19064
+ if (Array.isArray(ops.not)) {
19065
+ return !ops.not.includes(value);
19066
+ }
19067
+ else {
19068
+ return value !== ops.not;
19069
+ }
19070
+ }
19071
+ // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
19072
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
19073
+ return value >= ops.between[0] && value <= ops.between[1];
19074
+ }
19075
+ // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
19076
+ // and return true only if ALL conditions are satisfied
19077
+ let allConditionsMet = true;
19078
+ if (ops.gt !== undefined) {
19079
+ allConditionsMet = allConditionsMet && (value > ops.gt);
19080
+ }
19081
+ if (ops.gte !== undefined) {
19082
+ allConditionsMet = allConditionsMet && (value >= ops.gte);
19083
+ }
19084
+ if (ops.lt !== undefined) {
19085
+ allConditionsMet = allConditionsMet && (value < ops.lt);
19086
+ }
19087
+ if (ops.lte !== undefined) {
19088
+ allConditionsMet = allConditionsMet && (value <= ops.lte);
19089
+ }
19090
+ if (ops.contains !== undefined) {
19091
+ if (typeof value === 'string') {
19092
+ allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
19093
+ }
19094
+ else if (Array.isArray(value)) {
19095
+ allConditionsMet = allConditionsMet && value.includes(ops.contains);
19096
+ }
19097
+ else {
19098
+ allConditionsMet = false;
19099
+ }
19100
+ }
19101
+ return allConditionsMet;
19102
+ }
19103
+ // Simple equality
19104
+ return value === condition;
19105
+ }
17969
19106
  /**
17970
19107
  * Gets all instances of the model in the perspective that match the query params.
17971
19108
  *
17972
19109
  * @param perspective - The perspective to search in
17973
19110
  * @param query - Optional query parameters to filter results
19111
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
17974
19112
  * @returns Array of matching models
17975
19113
  *
17976
19114
  * @example
17977
19115
  * ```typescript
17978
- * // Get all recipes
19116
+ * // Get all recipes (uses SurrealDB by default)
17979
19117
  * const allRecipes = await Recipe.findAll(perspective);
17980
19118
  *
17981
- * // Get recipes with specific criteria
19119
+ * // Get recipes with specific criteria (uses SurrealDB)
17982
19120
  * const recipes = await Recipe.findAll(perspective, {
17983
19121
  * where: {
17984
19122
  * name: "Pasta",
@@ -17987,19 +19125,31 @@ class Ad4mModel {
17987
19125
  * order: { createdAt: "DESC" },
17988
19126
  * limit: 10
17989
19127
  * });
19128
+ *
19129
+ * // Explicitly use Prolog (legacy, for backward compatibility)
19130
+ * const recipesProlog = await Recipe.findAll(perspective, {}, false);
17990
19131
  * ```
17991
19132
  */
17992
- static async findAll(perspective, query = {}) {
17993
- const prologQuery = await this.queryToProlog(perspective, query);
17994
- const result = await perspective.infer(prologQuery);
17995
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
17996
- return results;
19133
+ static async findAll(perspective, query = {}, useSurrealDB = true) {
19134
+ if (useSurrealDB) {
19135
+ const surrealQuery = await this.queryToSurrealQL(perspective, query);
19136
+ const result = await perspective.querySurrealDB(surrealQuery);
19137
+ const { results } = await this.instancesFromSurrealResult(perspective, query, result);
19138
+ return results;
19139
+ }
19140
+ else {
19141
+ const prologQuery = await this.queryToProlog(perspective, query);
19142
+ const result = await perspective.infer(prologQuery);
19143
+ const { results } = await this.instancesFromPrologResult(perspective, query, result);
19144
+ return results;
19145
+ }
17997
19146
  }
17998
19147
  /**
17999
19148
  * Gets all instances with count of total matches without offset & limit applied.
18000
19149
  *
18001
19150
  * @param perspective - The perspective to search in
18002
19151
  * @param query - Optional query parameters to filter results
19152
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
18003
19153
  * @returns Object containing results array and total count
18004
19154
  *
18005
19155
  * @example
@@ -18009,12 +19159,22 @@ class Ad4mModel {
18009
19159
  * limit: 10
18010
19160
  * });
18011
19161
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
19162
+ *
19163
+ * // Use Prolog explicitly (legacy)
19164
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
18012
19165
  * ```
18013
19166
  */
18014
- static async findAllAndCount(perspective, query = {}) {
18015
- const prologQuery = await this.queryToProlog(perspective, query);
18016
- const result = await perspective.infer(prologQuery);
18017
- return await this.instancesFromPrologResult(perspective, query, result);
19167
+ static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
19168
+ if (useSurrealDB) {
19169
+ const surrealQuery = await this.queryToSurrealQL(perspective, query);
19170
+ const result = await perspective.querySurrealDB(surrealQuery);
19171
+ return await this.instancesFromSurrealResult(perspective, query, result);
19172
+ }
19173
+ else {
19174
+ const prologQuery = await this.queryToProlog(perspective, query);
19175
+ const result = await perspective.infer(prologQuery);
19176
+ return await this.instancesFromPrologResult(perspective, query, result);
19177
+ }
18018
19178
  }
18019
19179
  /**
18020
19180
  * Helper function for pagination with explicit page size and number.
@@ -18023,6 +19183,7 @@ class Ad4mModel {
18023
19183
  * @param pageSize - Number of items per page
18024
19184
  * @param pageNumber - Which page to retrieve (1-based)
18025
19185
  * @param query - Optional additional query parameters
19186
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
18026
19187
  * @returns Paginated results with metadata
18027
19188
  *
18028
19189
  * @example
@@ -18031,14 +19192,25 @@ class Ad4mModel {
18031
19192
  * where: { category: "Main Course" }
18032
19193
  * });
18033
19194
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
19195
+ *
19196
+ * // Use Prolog explicitly (legacy)
19197
+ * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
18034
19198
  * ```
18035
19199
  */
18036
- static async paginate(perspective, pageSize, pageNumber, query) {
19200
+ static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
18037
19201
  const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
18038
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
18039
- const result = await perspective.infer(prologQuery);
18040
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
18041
- return { results, totalCount, pageSize, pageNumber };
19202
+ if (useSurrealDB) {
19203
+ const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
19204
+ const result = await perspective.querySurrealDB(surrealQuery);
19205
+ const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
19206
+ return { results, totalCount, pageSize, pageNumber };
19207
+ }
19208
+ else {
19209
+ const prologQuery = await this.queryToProlog(perspective, paginationQuery);
19210
+ const result = await perspective.infer(prologQuery);
19211
+ const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
19212
+ return { results, totalCount, pageSize, pageNumber };
19213
+ }
18042
19214
  }
18043
19215
  static async countQueryToProlog(perspective, query = {}, modelClassName) {
18044
19216
  const { source, where } = query;
@@ -18055,11 +19227,29 @@ class Ad4mModel {
18055
19227
  `;
18056
19228
  return fullQuery;
18057
19229
  }
19230
+ /**
19231
+ * Generates a SurrealQL COUNT query for the model.
19232
+ *
19233
+ * @param perspective - The perspective context
19234
+ * @param query - Query parameters to filter the count
19235
+ * @returns SurrealQL COUNT query string
19236
+ *
19237
+ * @private
19238
+ */
19239
+ static async countQueryToSurrealQL(perspective, query) {
19240
+ // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
19241
+ // We'll count the number of rows returned (one row per source)
19242
+ const countQuery = { ...query };
19243
+ delete countQuery.limit;
19244
+ delete countQuery.offset;
19245
+ return await this.queryToSurrealQL(perspective, countQuery);
19246
+ }
18058
19247
  /**
18059
19248
  * Gets a count of all matching instances.
18060
19249
  *
18061
19250
  * @param perspective - The perspective to search in
18062
19251
  * @param query - Optional query parameters to filter results
19252
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
18063
19253
  * @returns Total count of matching entities
18064
19254
  *
18065
19255
  * @example
@@ -18068,11 +19258,25 @@ class Ad4mModel {
18068
19258
  * const activeRecipes = await Recipe.count(perspective, {
18069
19259
  * where: { status: "active" }
18070
19260
  * });
19261
+ *
19262
+ * // Use Prolog explicitly (legacy)
19263
+ * const countProlog = await Recipe.count(perspective, {}, false);
18071
19264
  * ```
18072
19265
  */
18073
- static async count(perspective, query = {}) {
18074
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
18075
- return result?.[0]?.TotalCount || 0;
19266
+ static async count(perspective, query = {}, useSurrealDB = true) {
19267
+ if (useSurrealDB) {
19268
+ const surrealQuery = await this.queryToSurrealQL(perspective, query);
19269
+ const result = await perspective.querySurrealDB(surrealQuery);
19270
+ // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
19271
+ // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
19272
+ // This ensures count() returns the same number as findAll().length
19273
+ const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
19274
+ return totalCount;
19275
+ }
19276
+ else {
19277
+ const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
19278
+ return result?.[0]?.TotalCount || 0;
19279
+ }
18076
19280
  }
18077
19281
  async setProperty(key, value, batchId) {
18078
19282
  const setters = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _Ad4mModel_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
@@ -18314,6 +19518,318 @@ class Ad4mModel {
18314
19518
  static query(perspective, query) {
18315
19519
  return new ModelQueryBuilder(perspective, this, query);
18316
19520
  }
19521
+ /**
19522
+ * Creates an Ad4mModel class from a JSON Schema definition.
19523
+ *
19524
+ * @description
19525
+ * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
19526
+ * enabling integration with systems that use JSON Schema for type definitions.
19527
+ *
19528
+ * The method follows a cascading approach for determining predicates:
19529
+ * 1. Explicit configuration in options parameter (highest precedence)
19530
+ * 2. x-ad4m metadata in the JSON Schema
19531
+ * 3. Inference from schema title and property names
19532
+ * 4. Error if no namespace can be determined
19533
+ *
19534
+ * @example
19535
+ * ```typescript
19536
+ * // With explicit configuration
19537
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
19538
+ * name: "Person",
19539
+ * namespace: "person://",
19540
+ * resolveLanguage: "literal"
19541
+ * });
19542
+ *
19543
+ * // With property mapping
19544
+ * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
19545
+ * name: "Contact",
19546
+ * namespace: "contact://",
19547
+ * propertyMapping: {
19548
+ * "name": "foaf://name",
19549
+ * "email": "foaf://mbox"
19550
+ * }
19551
+ * });
19552
+ *
19553
+ * // With x-ad4m metadata in schema
19554
+ * const schema = {
19555
+ * "title": "Product",
19556
+ * "x-ad4m": { "namespace": "product://" },
19557
+ * "properties": {
19558
+ * "name": {
19559
+ * "type": "string",
19560
+ * "x-ad4m": { "through": "product://title" }
19561
+ * }
19562
+ * }
19563
+ * };
19564
+ * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
19565
+ * ```
19566
+ *
19567
+ * @param schema - JSON Schema definition
19568
+ * @param options - Configuration options
19569
+ * @returns Generated Ad4mModel subclass
19570
+ * @throws Error when namespace cannot be inferred
19571
+ */
19572
+ static fromJSONSchema(schema, options) {
19573
+ // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
19574
+ if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
19575
+ throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
19576
+ }
19577
+ // Determine namespace with cascading precedence
19578
+ const namespace = this.determineNamespace(schema, options);
19579
+ // Create the dynamic class
19580
+ const DynamicModelClass = class extends Ad4mModel {
19581
+ };
19582
+ // Set up class metadata
19583
+ if (!options.name || options.name.trim() === '') {
19584
+ throw new Error("options.name is required and cannot be empty");
19585
+ }
19586
+ DynamicModelClass.className = options.name;
19587
+ DynamicModelClass.prototype.className = options.name;
19588
+ // Generate properties and collections metadata
19589
+ const properties = {};
19590
+ const collections = {};
19591
+ if (schema.properties) {
19592
+ for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
19593
+ const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
19594
+ const isRequired = schema.required?.includes(propertyName) || false;
19595
+ const propertyType = normalizeSchemaType(propertySchema.type);
19596
+ const isArray = isArrayType(propertySchema);
19597
+ if (isArray) {
19598
+ // Handle arrays as collections
19599
+ // Store the singular form as the collection key since SDNA generation expects singular
19600
+ collections[propertyName] = {
19601
+ through: predicate,
19602
+ local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
19603
+ };
19604
+ // Define the property on prototype
19605
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
19606
+ configurable: true,
19607
+ writable: true,
19608
+ value: []
19609
+ });
19610
+ // Add collection methods
19611
+ const adderName = `add${capitalize(propertyName)}`;
19612
+ const removerName = `remove${capitalize(propertyName)}`;
19613
+ const setterName = `setCollection${capitalize(propertyName)}`;
19614
+ DynamicModelClass.prototype[adderName] = function () {
19615
+ // Placeholder function for SDNA generation
19616
+ };
19617
+ DynamicModelClass.prototype[removerName] = function () {
19618
+ // Placeholder function for SDNA generation
19619
+ };
19620
+ DynamicModelClass.prototype[setterName] = function () {
19621
+ // Placeholder function for SDNA generation
19622
+ };
19623
+ }
19624
+ else {
19625
+ // Handle regular properties
19626
+ let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
19627
+ // If no specific resolveLanguage for this property, use the global one
19628
+ if (!resolveLanguage && options.resolveLanguage) {
19629
+ resolveLanguage = options.resolveLanguage;
19630
+ }
19631
+ const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
19632
+ const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
19633
+ let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
19634
+ // Handle nested objects by serializing to JSON
19635
+ if (isObjectType(propertySchema) && !resolveLanguage) {
19636
+ resolveLanguage = 'literal';
19637
+ console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
19638
+ }
19639
+ // Ensure numeric properties use literal language for correct typing
19640
+ if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
19641
+ resolveLanguage = 'literal';
19642
+ }
19643
+ // If property is required, ensure it has an initial value
19644
+ if (isRequired && !initial) {
19645
+ if (isObjectType(propertySchema)) {
19646
+ initial = 'literal://json:{}';
19647
+ }
19648
+ else {
19649
+ initial = "ad4m://undefined";
19650
+ }
19651
+ }
19652
+ properties[propertyName] = {
19653
+ through: predicate,
19654
+ required: isRequired,
19655
+ writable: writable,
19656
+ ...(resolveLanguage && { resolveLanguage }),
19657
+ ...(local !== undefined && { local }),
19658
+ ...(initial && { initial })
19659
+ };
19660
+ // Define the property on prototype
19661
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
19662
+ configurable: true,
19663
+ writable: true,
19664
+ value: this.getDefaultValueForType(propertyType)
19665
+ });
19666
+ // Add setter function if writable
19667
+ if (writable) {
19668
+ const setterName = propertyNameToSetterName(propertyName);
19669
+ DynamicModelClass.prototype[setterName] = function () {
19670
+ // This is a placeholder function that the SDNA generation looks for
19671
+ // The actual setter logic is handled by the Ad4mModel base class
19672
+ };
19673
+ }
19674
+ }
19675
+ }
19676
+ }
19677
+ // Validate that at least one property has an initial value (needed for valid SDNA constructor)
19678
+ // Collections don't create constructor actions, only properties with initial values do
19679
+ const hasPropertyWithInitial = Object.values(properties).some((prop) => prop.initial);
19680
+ if (!hasPropertyWithInitial) {
19681
+ // If no properties have initial values, add a type identifier automatically
19682
+ const typeProperty = `ad4m://type`;
19683
+ let typeValue;
19684
+ if (namespace.includes('://')) {
19685
+ const [scheme, rest] = namespace.split('://');
19686
+ const path = (rest || '').replace(/\/+$/, '');
19687
+ if (path) {
19688
+ typeValue = `${scheme}://${path}/instance`;
19689
+ }
19690
+ else {
19691
+ typeValue = `${scheme}://instance`;
19692
+ }
19693
+ }
19694
+ else {
19695
+ const path = namespace.replace(/\/+$/, '');
19696
+ typeValue = `${path}/instance`;
19697
+ }
19698
+ properties['__ad4m_type'] = {
19699
+ through: typeProperty,
19700
+ required: true,
19701
+ writable: false,
19702
+ initial: typeValue,
19703
+ flag: true
19704
+ };
19705
+ // Add the type property to the prototype
19706
+ Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
19707
+ configurable: true,
19708
+ writable: false,
19709
+ value: typeValue
19710
+ });
19711
+ console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
19712
+ }
19713
+ // Attach metadata to prototype
19714
+ DynamicModelClass.prototype.__properties = properties;
19715
+ DynamicModelClass.prototype.__collections = collections;
19716
+ // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
19717
+ DynamicModelClass.prototype.__jsonSchema = schema;
19718
+ DynamicModelClass.prototype.__jsonSchemaOptions = options;
19719
+ // Apply the ModelOptions decorator to set up the generateSDNA method
19720
+ const ModelOptionsDecorator = ModelOptions({ name: options.name });
19721
+ ModelOptionsDecorator(DynamicModelClass);
19722
+ return DynamicModelClass;
19723
+ }
19724
+ /**
19725
+ * Determines the namespace for predicates using cascading precedence
19726
+ */
19727
+ static determineNamespace(schema, options) {
19728
+ // 1. Explicit namespace in options (highest precedence)
19729
+ if (options.namespace) {
19730
+ return options.namespace;
19731
+ }
19732
+ // 2. x-ad4m metadata in schema
19733
+ if (schema["x-ad4m"]?.namespace) {
19734
+ return schema["x-ad4m"].namespace;
19735
+ }
19736
+ // 3. Infer from schema title
19737
+ if (schema.title) {
19738
+ return `${schema.title.toLowerCase()}://`;
19739
+ }
19740
+ // 4. Try to extract from $id if it's a URL
19741
+ if (schema.$id) {
19742
+ try {
19743
+ const url = new URL(schema.$id);
19744
+ const pathParts = url.pathname.split('/').filter(p => p);
19745
+ if (pathParts.length > 0) {
19746
+ const lastPart = pathParts[pathParts.length - 1];
19747
+ const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
19748
+ return `${baseName.toLowerCase()}://`;
19749
+ }
19750
+ }
19751
+ catch {
19752
+ // If $id is not a valid URL, continue to error
19753
+ }
19754
+ }
19755
+ // 5. Error if no namespace can be determined
19756
+ throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
19757
+ - options.namespace
19758
+ - schema["x-ad4m"].namespace
19759
+ - schema.title
19760
+ - valid schema.$id`);
19761
+ }
19762
+ /**
19763
+ * Determines the predicate for a specific property using cascading precedence
19764
+ */
19765
+ static determinePredicate(schema, propertyName, propertySchema, namespace, options) {
19766
+ // 1. Explicit property mapping (highest precedence)
19767
+ if (options.propertyMapping?.[propertyName]) {
19768
+ return options.propertyMapping[propertyName];
19769
+ }
19770
+ // 2. x-ad4m metadata in property schema
19771
+ if (propertySchema["x-ad4m"]?.through) {
19772
+ return propertySchema["x-ad4m"].through;
19773
+ }
19774
+ // 3. Generate from namespace + property name
19775
+ if (options.predicateTemplate) {
19776
+ const normalizedNs = normalizeNamespaceString(namespace);
19777
+ const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
19778
+ const nsNoScheme = rest || '';
19779
+ return options.predicateTemplate
19780
+ .replace('${namespace}', nsNoScheme)
19781
+ .replace('${scheme}', scheme)
19782
+ .replace('${ns}', nsNoScheme)
19783
+ .replace('${title}', schema.title || '')
19784
+ .replace('${property}', propertyName);
19785
+ }
19786
+ // 4. Custom predicate generator
19787
+ if (options.predicateGenerator) {
19788
+ return options.predicateGenerator(schema.title || '', propertyName);
19789
+ }
19790
+ // 5. Default: namespace + property name
19791
+ const normalizedNs = normalizeNamespaceString(namespace);
19792
+ if (normalizedNs.includes('://')) {
19793
+ // For namespaces like "product://", append property directly
19794
+ return `${normalizedNs}${propertyName}`;
19795
+ }
19796
+ else {
19797
+ return `${normalizedNs}://${propertyName}`;
19798
+ }
19799
+ }
19800
+ /**
19801
+ * Gets property-specific options using cascading precedence
19802
+ */
19803
+ static getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
19804
+ // 1. Property-specific options
19805
+ if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
19806
+ return options.propertyOptions[propertyName][optionName];
19807
+ }
19808
+ // 2. x-ad4m metadata in property
19809
+ if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
19810
+ return propertySchema["x-ad4m"][optionName];
19811
+ }
19812
+ // 3. Global option
19813
+ if (options[optionName] !== undefined) {
19814
+ return options[optionName];
19815
+ }
19816
+ // 4. Default value
19817
+ return defaultValue;
19818
+ }
19819
+ /**
19820
+ * Gets default value for a JSON Schema type
19821
+ */
19822
+ static getDefaultValueForType(type) {
19823
+ switch (type) {
19824
+ case 'string': return '';
19825
+ case 'number': return 0;
19826
+ case 'integer': return 0;
19827
+ case 'boolean': return false;
19828
+ case 'array': return [];
19829
+ case 'object': return {};
19830
+ default: return '';
19831
+ }
19832
+ }
18317
19833
  }
18318
19834
  _Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
18319
19835
  Ad4mModel.classNamesByClass = new WeakMap();
@@ -18341,6 +19857,7 @@ class ModelQueryBuilder {
18341
19857
  constructor(perspective, ctor, query) {
18342
19858
  this.queryParams = {};
18343
19859
  this.modelClassName = null;
19860
+ this.useSurrealDBFlag = true;
18344
19861
  this.perspective = perspective;
18345
19862
  this.ctor = ctor;
18346
19863
  if (query)
@@ -18478,6 +19995,35 @@ class ModelQueryBuilder {
18478
19995
  this.modelClassName = className;
18479
19996
  return this;
18480
19997
  }
19998
+ /**
19999
+ * Enables or disables SurrealDB query path.
20000
+ *
20001
+ * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
20002
+ * @returns The query builder for chaining
20003
+ *
20004
+ * @example
20005
+ * ```typescript
20006
+ * // Use SurrealDB (default)
20007
+ * const recipes = await Recipe.query(perspective)
20008
+ * .where({ category: "Dessert" })
20009
+ * .useSurrealDB(true)
20010
+ * .get();
20011
+ *
20012
+ * // Use Prolog (legacy)
20013
+ * const recipesProlog = await Recipe.query(perspective)
20014
+ * .where({ category: "Dessert" })
20015
+ * .useSurrealDB(false)
20016
+ * .get();
20017
+ * ```
20018
+ *
20019
+ * @remarks
20020
+ * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
20021
+ * if useSurrealDB(true) is set (default).
20022
+ */
20023
+ useSurrealDB(enabled = true) {
20024
+ this.useSurrealDBFlag = enabled;
20025
+ return this;
20026
+ }
18481
20027
  /**
18482
20028
  * Executes the query once and returns the results.
18483
20029
  *
@@ -18491,16 +20037,24 @@ class ModelQueryBuilder {
18491
20037
  * ```
18492
20038
  */
18493
20039
  async get() {
18494
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
18495
- const result = await this.perspective.infer(query);
18496
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
18497
- return results;
20040
+ if (this.useSurrealDBFlag) {
20041
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20042
+ const result = await this.perspective.querySurrealDB(surrealQuery);
20043
+ const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20044
+ return results;
20045
+ }
20046
+ else {
20047
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
20048
+ const result = await this.perspective.infer(query);
20049
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
20050
+ return results;
20051
+ }
18498
20052
  }
18499
20053
  /**
18500
20054
  * Subscribes to the query and receives updates when results change.
18501
20055
  *
18502
20056
  * This method:
18503
- * 1. Creates and initializes a Prolog query subscription
20057
+ * 1. Creates and initializes a SurrealDB live query subscription (default)
18504
20058
  * 2. Sets up the callback to process future updates
18505
20059
  * 3. Returns the initial results immediately
18506
20060
  *
@@ -18522,19 +20076,41 @@ class ModelQueryBuilder {
18522
20076
  * // When done with subscription:
18523
20077
  * builder.dispose();
18524
20078
  * ```
20079
+ *
20080
+ * @remarks
20081
+ * By default, this uses SurrealDB live queries for real-time updates.
20082
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
18525
20083
  */
18526
20084
  async subscribe(callback) {
18527
20085
  // Clean up any existing subscription
18528
20086
  this.dispose();
18529
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
18530
- this.currentSubscription = await this.perspective.subscribeInfer(query);
18531
- const processResults = async (result) => {
18532
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
18533
- callback(results);
18534
- };
18535
- this.currentSubscription.onResult(processResults);
18536
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
18537
- return results;
20087
+ if (this.useSurrealDBFlag) {
20088
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20089
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20090
+ const processResults = async (result) => {
20091
+ // The result from live query subscription update (handled in PerspectiveInstance listener)
20092
+ // is the new full set of results (because we re-query in Rust).
20093
+ // So we just need to map it to instances.
20094
+ const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20095
+ callback(results);
20096
+ };
20097
+ this.currentSubscription.onResult(processResults);
20098
+ // Process initial result
20099
+ const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20100
+ return results;
20101
+ }
20102
+ else {
20103
+ // Note: Subscriptions currently only work with Prolog
20104
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
20105
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
20106
+ const processResults = async (result) => {
20107
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
20108
+ callback(results);
20109
+ };
20110
+ this.currentSubscription.onResult(processResults);
20111
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
20112
+ return results;
20113
+ }
18538
20114
  }
18539
20115
  /**
18540
20116
  * Gets the total count of matching entities.
@@ -18549,15 +20125,26 @@ class ModelQueryBuilder {
18549
20125
  * ```
18550
20126
  */
18551
20127
  async count() {
18552
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
18553
- const result = await this.perspective.infer(query);
18554
- return result?.[0]?.TotalCount || 0;
20128
+ if (this.useSurrealDBFlag) {
20129
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20130
+ const result = await this.perspective.querySurrealDB(surrealQuery);
20131
+ // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
20132
+ // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
20133
+ // This ensures count() returns the same number as get().length
20134
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20135
+ return totalCount;
20136
+ }
20137
+ else {
20138
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
20139
+ const result = await this.perspective.infer(query);
20140
+ return result?.[0]?.TotalCount || 0;
20141
+ }
18555
20142
  }
18556
20143
  /**
18557
20144
  * Subscribes to count updates for matching entities.
18558
20145
  *
18559
20146
  * This method:
18560
- * 1. Creates and initializes a Prolog query subscription for the count
20147
+ * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
18561
20148
  * 2. Sets up the callback to process future count updates
18562
20149
  * 3. Returns the initial count immediately
18563
20150
  *
@@ -18579,18 +20166,35 @@ class ModelQueryBuilder {
18579
20166
  * // When done with subscription:
18580
20167
  * builder.dispose();
18581
20168
  * ```
20169
+ *
20170
+ * @remarks
20171
+ * By default, this uses SurrealDB live queries for real-time updates.
20172
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
18582
20173
  */
18583
20174
  async countSubscribe(callback) {
18584
20175
  // Clean up any existing subscription
18585
20176
  this.dispose();
18586
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
18587
- this.currentSubscription = await this.perspective.subscribeInfer(query);
18588
- const processResults = async (result) => {
18589
- const newCount = result?.[0]?.TotalCount || 0;
18590
- callback(newCount);
18591
- };
18592
- this.currentSubscription.onResult(processResults);
18593
- return this.currentSubscription.result?.[0]?.TotalCount || 0;
20177
+ if (this.useSurrealDBFlag) {
20178
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
20179
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20180
+ const processResults = async (result) => {
20181
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
20182
+ callback(totalCount);
20183
+ };
20184
+ this.currentSubscription.onResult(processResults);
20185
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
20186
+ return totalCount;
20187
+ }
20188
+ else {
20189
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
20190
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
20191
+ const processResults = async (result) => {
20192
+ const newCount = result?.[0]?.TotalCount || 0;
20193
+ callback(newCount);
20194
+ };
20195
+ this.currentSubscription.onResult(processResults);
20196
+ return this.currentSubscription.result?.[0]?.TotalCount || 0;
20197
+ }
18594
20198
  }
18595
20199
  /**
18596
20200
  * Gets a page of results with pagination metadata.
@@ -18609,16 +20213,24 @@ class ModelQueryBuilder {
18609
20213
  */
18610
20214
  async paginate(pageSize, pageNumber) {
18611
20215
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
18612
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
18613
- const result = await this.perspective.infer(prologQuery);
18614
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
18615
- return { results, totalCount, pageSize, pageNumber };
20216
+ if (this.useSurrealDBFlag) {
20217
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20218
+ const result = await this.perspective.querySurrealDB(surrealQuery);
20219
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
20220
+ return { results, totalCount, pageSize, pageNumber };
20221
+ }
20222
+ else {
20223
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
20224
+ const result = await this.perspective.infer(prologQuery);
20225
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
20226
+ return { results, totalCount, pageSize, pageNumber };
20227
+ }
18616
20228
  }
18617
20229
  /**
18618
20230
  * Subscribes to paginated results updates.
18619
20231
  *
18620
20232
  * This method:
18621
- * 1. Creates and initializes a Prolog query subscription for the paginated results
20233
+ * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
18622
20234
  * 2. Sets up the callback to process future page updates
18623
20235
  * 3. Returns the initial page immediately
18624
20236
  *
@@ -18642,20 +20254,37 @@ class ModelQueryBuilder {
18642
20254
  * // When done with subscription:
18643
20255
  * builder.dispose();
18644
20256
  * ```
20257
+ *
20258
+ * @remarks
20259
+ * By default, this uses SurrealDB live queries for real-time updates.
20260
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
18645
20261
  */
18646
20262
  async paginateSubscribe(pageSize, pageNumber, callback) {
18647
20263
  // Clean up any existing subscription
18648
20264
  this.dispose();
18649
20265
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
18650
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
18651
- this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
18652
- const processResults = async (r) => {
18653
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
18654
- callback({ results, totalCount, pageSize, pageNumber });
18655
- };
18656
- this.currentSubscription.onResult(processResults);
18657
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
18658
- return { results, totalCount, pageSize, pageNumber };
20266
+ if (this.useSurrealDBFlag) {
20267
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
20268
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
20269
+ const processResults = async (result) => {
20270
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
20271
+ callback({ results, totalCount, pageSize, pageNumber });
20272
+ };
20273
+ this.currentSubscription.onResult(processResults);
20274
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
20275
+ return { results, totalCount, pageSize, pageNumber };
20276
+ }
20277
+ else {
20278
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
20279
+ this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
20280
+ const processResults = async (r) => {
20281
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
20282
+ callback({ results, totalCount, pageSize, pageNumber });
20283
+ };
20284
+ this.currentSubscription.onResult(processResults);
20285
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
20286
+ return { results, totalCount, pageSize, pageNumber };
20287
+ }
18659
20288
  }
18660
20289
  }
18661
20290