@coasys/ad4m 0.13.0-test-4 → 0.13.0-test-6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/lib/index.cjs +1507 -1372
  2. package/lib/index.js +1505 -1370
  3. package/lib/src/Ad4mClient.d.ts +1 -1
  4. package/lib/src/Ad4mClient.js +12 -1
  5. package/lib/src/agent/AgentClient.d.ts +16 -0
  6. package/lib/src/agent/AgentClient.js +74 -4
  7. package/lib/src/cache/PersistentCache.d.ts +40 -0
  8. package/lib/src/cache/PersistentCache.js +139 -0
  9. package/lib/src/expression/ExpressionClient.d.ts +8 -0
  10. package/lib/src/expression/ExpressionClient.js +113 -5
  11. package/lib/src/index.d.ts +1 -0
  12. package/lib/src/index.js +1 -0
  13. package/lib/src/model/Ad4mModel.d.ts +20 -7
  14. package/lib/src/model/Ad4mModel.js +102 -108
  15. package/lib/src/model/Ad4mModel.test.js +688 -1434
  16. package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
  17. package/lib/src/model/ModelQueryBuilder.js +29 -20
  18. package/lib/src/model/Subject.js +6 -6
  19. package/lib/src/model/hydration.d.ts +2 -39
  20. package/lib/src/model/hydration.js +2 -260
  21. package/lib/src/model/query-surreal.d.ts +44 -0
  22. package/lib/src/model/query-surreal.js +249 -0
  23. package/lib/src/model/query-utils.d.ts +1 -0
  24. package/lib/src/model/query-utils.js +46 -1
  25. package/lib/src/model/relation-filtering.test.js +15 -15
  26. package/lib/src/model/surreal-utils.d.ts +42 -0
  27. package/lib/src/model/surreal-utils.js +128 -0
  28. package/lib/src/model/types.d.ts +4 -6
  29. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  30. package/lib/src/perspectives/PerspectiveClient.js +15 -13
  31. package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
  32. package/lib/src/perspectives/PerspectiveProxy.js +16 -3
  33. package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
  34. package/lib/src/perspectives/PerspectiveResolver.js +11 -0
  35. package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
  36. package/lib/src/runtime/RuntimeResolver.js +4 -197
  37. package/lib/src/schema.gql +1 -27
  38. package/lib/src/shacl/SHACLShape.test.js +0 -82
  39. package/package.json +11 -8
  40. package/src/Ad4mClient.test.ts +14 -4
  41. package/src/Ad4mClient.ts +12 -1
  42. package/src/agent/AgentClient.ts +84 -2
  43. package/src/cache/PersistentCache.ts +145 -0
  44. package/src/cache/cache.test.ts +713 -0
  45. package/src/expression/ExpressionClient.ts +137 -3
  46. package/src/index.ts +1 -0
  47. package/src/model/Ad4mModel.test.ts +59 -358
  48. package/src/model/Ad4mModel.ts +112 -108
  49. package/src/model/ModelQueryBuilder.ts +29 -17
  50. package/src/model/hydration.ts +2 -279
  51. package/src/model/query-utils.ts +47 -2
  52. package/src/model/types.ts +5 -6
  53. package/src/perspectives/PerspectiveClient.ts +26 -17
  54. package/src/perspectives/PerspectiveProxy.ts +24 -3
  55. package/lib/src/model/hydration-batch.d.ts +0 -34
  56. package/lib/src/model/hydration-batch.js +0 -147
  57. package/lib/src/model/hydration-batching.test.d.ts +0 -7
  58. package/lib/src/model/hydration-batching.test.js +0 -456
  59. package/lib/src/model/model-manifest.d.ts +0 -41
  60. package/lib/src/model/model-manifest.js +0 -11
  61. package/lib/src/model/query-cache.test.d.ts +0 -1
  62. package/lib/src/model/query-cache.test.js +0 -43
  63. package/lib/src/model/query-sparql-batch.d.ts +0 -17
  64. package/lib/src/model/query-sparql-batch.js +0 -260
  65. package/lib/src/model/query-sparql.test.d.ts +0 -1
  66. package/lib/src/model/query-sparql.test.js +0 -312
  67. package/lib/src/model/subscription-delta.test.d.ts +0 -24
  68. package/lib/src/model/subscription-delta.test.js +0 -180
  69. package/lib/src/model/subscription-pool.d.ts +0 -39
  70. package/lib/src/model/subscription-pool.js +0 -165
  71. package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
  72. package/lib/src/perspectives/PerspectiveClient.test.js +0 -224
@@ -15,7 +15,6 @@ import { buildSPARQLQuery } from "./query-sparql";
15
15
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
16
16
  import {
17
17
  normalizeValue,
18
- evaluateCustomGettersForInstance,
19
18
  } from "./hydration";
20
19
  import type {
21
20
  ParentScope, IncludeMap, Query,
@@ -745,6 +744,7 @@ export class Ad4mModel {
745
744
  const query: Query = {
746
745
  where: { id: this._baseExpression },
747
746
  limit: 1,
747
+ deepQuery: true, // Single-instance get() always evaluates property getters
748
748
  };
749
749
  if (opts?.properties) query.properties = opts.properties;
750
750
  if (opts?.include) query.include = opts.include;
@@ -850,13 +850,18 @@ export class Ad4mModel {
850
850
  if (query.offset !== undefined) queryInput.offset = query.offset;
851
851
  if (query.limit !== undefined) queryInput.limit = query.limit;
852
852
  if (query.count !== undefined) queryInput.count = query.count;
853
+ queryInput.deepQuery = query.deepQuery ?? true;
853
854
 
854
855
  if (query.include) {
855
856
  const allRelMeta = getRelationsMetadata(this as any);
856
857
  enrichShapeForIncludes(metadata, query.include, allRelMeta);
857
858
  }
858
859
 
859
- // Pre-compute conformance getters (with where-clause support)
860
+ // Pre-compute conformance getters for Rust-side evaluation.
861
+ // Where clauses are NOT compiled into getter SPARQL because stored
862
+ // property values are signed expression envelopes (literal:json:...),
863
+ // not simple literal:string:X values. Instead, where clauses are
864
+ // attached as metadata for Rust-side post-evaluation filtering.
860
865
  {
861
866
  const allRelMeta = getRelationsMetadata(this as any);
862
867
  for (const [relName, relMeta] of Object.entries(metadata.relations)) {
@@ -868,43 +873,30 @@ export class Ad4mModel {
868
873
  const TargetClass = meta.target();
869
874
  const filter = buildConformanceFilter(meta.predicate, TargetClass);
870
875
 
871
- // Only compile where clauses to SPARQL when the target properties
872
- // are stored as plain IRIs (not signed expressions). Properties
873
- // without resolveLanguage or with resolveLanguage='literal' store
874
- // values as signed JSON envelopes, so SPARQL exact-match fails.
875
- let whereConditions: string[] = [];
876
+ if (filter) {
877
+ rel.getter = filter.getter;
878
+ }
879
+
880
+ // Attach where-clause metadata for Rust-side post-getter filtering
876
881
  if (rel.where) {
877
882
  try {
878
883
  const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
879
- let allSparqlFilterable = true;
880
884
  if (targetMetadata) {
885
+ const predicates: Record<string, string> = {};
881
886
  for (const propName of Object.keys(rel.where)) {
882
887
  if (['id', 'author', 'timestamp'].includes(propName)) continue;
883
888
  const propMeta = targetMetadata.properties[propName];
884
- if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
885
- allSparqlFilterable = false;
886
- break;
889
+ if (propMeta?.predicate) {
890
+ predicates[propName] = propMeta.predicate;
887
891
  }
888
892
  }
889
- } else {
890
- allSparqlFilterable = false;
891
- }
892
- if (allSparqlFilterable) {
893
- whereConditions = compileWhereClause(rel.where, targetMetadata);
893
+ if (Object.keys(predicates).length > 0) {
894
+ rel.whereFilter = rel.where;
895
+ rel.wherePredicates = predicates;
896
+ }
894
897
  }
895
898
  } catch (_) {}
896
899
  }
897
-
898
- if (filter) {
899
- let getter = filter.getter;
900
- if (whereConditions.length > 0) {
901
- getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
902
- }
903
- rel.getter = getter;
904
- } else if (whereConditions.length > 0) {
905
- const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
906
- rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
907
- }
908
900
  } catch (_) {}
909
901
  }
910
902
  }
@@ -1014,6 +1006,7 @@ export class Ad4mModel {
1014
1006
  if (query.offset !== undefined) queryInput.offset = query.offset;
1015
1007
  if (query.limit !== undefined) queryInput.limit = query.limit;
1016
1008
  if (query.count !== undefined) queryInput.count = query.count;
1009
+ queryInput.deepQuery = query.deepQuery ?? true;
1017
1010
 
1018
1011
  // Enrich relation metadata with target class shapes for Rust-side
1019
1012
  // include resolution. This eliminates per-relation GraphQL round-trips
@@ -1044,45 +1037,32 @@ export class Ad4mModel {
1044
1037
  const TargetClass = meta.target();
1045
1038
  const filter = buildConformanceFilter(meta.predicate, TargetClass);
1046
1039
 
1047
- // Only compile where clauses to SPARQL when the target properties
1048
- // are stored as plain IRIs (not signed expressions). Properties
1049
- // without resolveLanguage or with resolveLanguage='literal' store
1050
- // values as signed JSON envelopes, so SPARQL exact-match fails.
1051
- let whereConditions: string[] = [];
1040
+ if (filter) {
1041
+ rel.getter = filter.getter;
1042
+ }
1043
+
1044
+ // Attach where-clause metadata for Rust-side post-getter filtering.
1045
+ // Property values are signed expression envelopes (literal:json:...)
1046
+ // and cannot be matched by SPARQL FILTER on the raw IRI.
1052
1047
  if (rel.where) {
1053
1048
  try {
1054
1049
  const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
1055
- let allSparqlFilterable = true;
1056
1050
  if (targetMetadata) {
1051
+ const predicates: Record<string, string> = {};
1057
1052
  for (const propName of Object.keys(rel.where)) {
1058
1053
  if (['id', 'author', 'timestamp'].includes(propName)) continue;
1059
1054
  const propMeta = targetMetadata.properties[propName];
1060
- if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
1061
- allSparqlFilterable = false;
1062
- break;
1055
+ if (propMeta?.predicate) {
1056
+ predicates[propName] = propMeta.predicate;
1063
1057
  }
1064
1058
  }
1065
- } else {
1066
- allSparqlFilterable = false;
1067
- }
1068
- if (allSparqlFilterable) {
1069
- whereConditions = compileWhereClause(rel.where, targetMetadata);
1059
+ if (Object.keys(predicates).length > 0) {
1060
+ rel.whereFilter = rel.where;
1061
+ rel.wherePredicates = predicates;
1062
+ }
1070
1063
  }
1071
1064
  } catch (_) { /* target metadata unavailable */ }
1072
1065
  }
1073
-
1074
- if (filter) {
1075
- let getter = filter.getter;
1076
- if (whereConditions.length > 0) {
1077
- // Append where conditions before the closing }
1078
- getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
1079
- }
1080
- rel.getter = getter;
1081
- } else if (whereConditions.length > 0) {
1082
- // No conformance filter but where clause exists — build getter from where alone
1083
- const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
1084
- rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
1085
- }
1086
1066
  } catch (e) {
1087
1067
  // Target class may not be available; skip silently
1088
1068
  }
@@ -1132,43 +1112,6 @@ export class Ad4mModel {
1132
1112
  );
1133
1113
  }
1134
1114
 
1135
- // Relation conformance getters are evaluated Rust-side via evaluate_getters()
1136
- // in model_query.rs. However, for relations with non-SPARQL-filterable where
1137
- // clauses (e.g. properties stored as signed expressions), we still need
1138
- // TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
1139
- // with skipPropertyGetters ensures conformance + JS post-filtering for
1140
- // where clauses that couldn't be compiled to SPARQL.
1141
- const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set<string>();
1142
- for (const inst of instances) {
1143
- // Save included relation values that came from Rust hydration
1144
- const savedIncluded: Record<string, any> = {};
1145
- for (const relName of includedRelNames) {
1146
- if ((inst as any)[relName] !== undefined) {
1147
- savedIncluded[relName] = (inst as any)[relName];
1148
- }
1149
- }
1150
-
1151
- await evaluateCustomGettersForInstance(inst, perspective, metadata, {
1152
- skipPropertyGetters: true,
1153
- });
1154
-
1155
- // Restore hydrated include objects that were overwritten by conformance getters
1156
- for (const [relName, value] of Object.entries(savedIncluded)) {
1157
- (inst as any)[relName] = value;
1158
- }
1159
-
1160
- // Fix cardinality for non-included HasOne/BelongsToOne relations:
1161
- // The conformance getter always produces arrays; unwrap to scalar.
1162
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1163
- if (includedRelNames.has(relName)) continue;
1164
- const kind = (relMeta as any).kind;
1165
- if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray((inst as any)[relName])) {
1166
- const arr = (inst as any)[relName] as any[];
1167
- (inst as any)[relName] = arr.length > 0 ? arr[0] : null;
1168
- }
1169
- }
1170
- }
1171
-
1172
1115
  // Take snapshots for dirty tracking
1173
1116
  const snapshotRelations = queryInput.include;
1174
1117
  for (const inst of instances) {
@@ -1675,10 +1618,10 @@ export class Ad4mModel {
1675
1618
  /**
1676
1619
  * Evaluate SPARQL getters for a batch of instances on demand.
1677
1620
  *
1678
- * Use after a shallow collection query (the default) to resolve
1679
- * getter-backed properties for visible items only. This avoids the
1680
- * O(N × getters) cost of evaluating every getter on every instance in
1681
- * a large collection query.
1621
+ * Since deepQuery defaults to true, property getters are evaluated
1622
+ * automatically during collection queries. Use this method when
1623
+ * deepQuery was explicitly set to false and you want to lazily
1624
+ * resolve getter-backed properties for a subset of instances.
1682
1625
  *
1683
1626
  * @param instances - Array of model instances to evaluate getters on
1684
1627
  * @param perspective - The perspective to query against
@@ -1687,8 +1630,8 @@ export class Ad4mModel {
1687
1630
  *
1688
1631
  * @example
1689
1632
  * ```typescript
1690
- * const messages = await Message.findAll(perspective, { parent: channel, limit: 30 });
1691
- * // messages[i].replyingTo is undefined (getter skipped by default)
1633
+ * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
1634
+ * // messages[i].replyingTo is undefined (getter skipped)
1692
1635
  *
1693
1636
  * // Evaluate getters for the visible subset
1694
1637
  * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
@@ -1702,11 +1645,33 @@ export class Ad4mModel {
1702
1645
  ): Promise<void> {
1703
1646
  if (instances.length === 0) return;
1704
1647
  const metadata = this.getModelMetadata();
1705
- const opts = propertyNames && propertyNames.length > 0
1706
- ? { requestedProperties: propertyNames }
1707
- : undefined;
1708
1648
 
1709
- // Determine which property names will actually be evaluated
1649
+ // Pre-compute conformance getters so the shape sent to Rust includes them
1650
+ const allRelMeta = getRelationsMetadata(this as any);
1651
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1652
+ const rel = relMeta as any;
1653
+ if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
1654
+ const meta = allRelMeta[relName];
1655
+ if (!meta?.target) continue;
1656
+ try {
1657
+ const TargetClass = meta.target();
1658
+ const filter = buildConformanceFilter(meta.predicate, TargetClass);
1659
+ if (filter) rel.getter = filter.getter;
1660
+ } catch (_) { /* target class may not be available */ }
1661
+ }
1662
+
1663
+ const shapeJson = JSON.stringify(metadata);
1664
+ const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
1665
+
1666
+ // Single RPC call evaluates all getters in-process on the executor
1667
+ const result = await perspective.evaluateGetters(
1668
+ metadata.className,
1669
+ instanceIds,
1670
+ shapeJson,
1671
+ propertyNames,
1672
+ );
1673
+
1674
+ // Determine which property names were evaluated for snapshot sync
1710
1675
  const evaluatedPropertyNames: string[] = [];
1711
1676
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1712
1677
  if ((propMeta as any).getter) {
@@ -1715,14 +1680,25 @@ export class Ad4mModel {
1715
1680
  }
1716
1681
  }
1717
1682
  }
1683
+ // Also include relation getters
1684
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1685
+ if ((relMeta as any).getter) {
1686
+ if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
1687
+ evaluatedPropertyNames.push(relName);
1688
+ }
1689
+ }
1690
+ }
1718
1691
 
1692
+ // Apply results to instances and sync snapshots
1719
1693
  for (const instance of instances) {
1720
- await evaluateCustomGettersForInstance(instance, perspective, metadata, opts);
1721
- // Sync snapshot so isDirty() doesn't flag getter-only changes.
1722
- // evaluateGetters() mutates instances in place, but their snapshots
1723
- // were already taken during hydration. Without this sync, the computed
1724
- // getter values would make isDirty() return true and save() would try
1725
- // to write read-only computed properties.
1694
+ const id = (instance as any).id || (instance as any)._baseExpression;
1695
+ const props = result[id];
1696
+ if (props) {
1697
+ for (const [key, value] of Object.entries(props)) {
1698
+ (instance as any)[key] = value;
1699
+ }
1700
+ }
1701
+ // Sync snapshot so isDirty() doesn't flag getter-only changes
1726
1702
  const modelInstance = instance as Ad4mModel;
1727
1703
  if (modelInstance._snapshot) {
1728
1704
  for (const propName of evaluatedPropertyNames) {
@@ -2171,7 +2147,24 @@ export class Ad4mModel {
2171
2147
  * @param name - Class name to assign (e.g. "Channel")
2172
2148
  * @returns Generated Ad4mModel subclass, ready for querying
2173
2149
  */
2174
- static fromSHACL(shape: SHACLShape, name: string): typeof Ad4mModel {
2150
+ /**
2151
+ * Synthesise an `Ad4mModel` subclass from a SHACL shape.
2152
+ *
2153
+ * @param shape - The SHACL shape to synthesise from.
2154
+ * @param name - The model name (e.g. "Channel").
2155
+ * @param classResolver - Optional thunk factory. When provided, any collection
2156
+ * property that carries a `sh:class` URI will have its `target` wired up lazily:
2157
+ * `target: () => classResolver(localName)`. Because `target` is only called at
2158
+ * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
2159
+ * resolver just needs to return the correct class by the time a query runs —
2160
+ * making it safe to pass a closure over a registry object that is still being
2161
+ * populated (e.g. the `result` record inside `getModelClasses`).
2162
+ */
2163
+ static fromSHACL(
2164
+ shape: SHACLShape,
2165
+ name: string,
2166
+ classResolver?: (localName: string) => typeof Ad4mModel | undefined,
2167
+ ): typeof Ad4mModel {
2175
2168
  const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
2176
2169
  (DynamicModelClass as any).className = name;
2177
2170
  (DynamicModelClass.prototype as any).className = name;
@@ -2216,9 +2209,20 @@ export class Ad4mModel {
2216
2209
  const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
2217
2210
 
2218
2211
  if (isCollection) {
2212
+ // Derive a lazy `target` thunk when a sh:class URI is present and a
2213
+ // classResolver was supplied. The thunk is evaluated at query time so
2214
+ // it is safe even if the target class hasn't been registered yet.
2215
+ let targetThunk: (() => typeof Ad4mModel) | undefined;
2216
+ if (prop.class && classResolver) {
2217
+ const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
2218
+ const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
2219
+ targetThunk = () => classResolver(localName) as typeof Ad4mModel;
2220
+ }
2221
+
2219
2222
  setRelationRegistryEntry(DynamicModelClass, prop.name, {
2220
2223
  predicate: prop.path,
2221
2224
  kind: 'hasMany',
2225
+ ...(targetThunk !== undefined && { target: targetThunk }),
2222
2226
  ...(prop.local !== undefined && { local: prop.local }),
2223
2227
  ...(prop.getter !== undefined && { getter: prop.getter }),
2224
2228
  });
@@ -224,25 +224,25 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
224
224
  }
225
225
 
226
226
  /**
227
- * Opts in to evaluating SPARQL property getters during collection hydration.
227
+ * Controls whether SPARQL property getters are evaluated during hydration.
228
228
  *
229
- * By default, collection queries skip getter evaluation for performance.
230
- * Call `.deepQuery()` when you need getter-backed properties in the result set.
229
+ * By default, collection queries evaluate property getters (deepQuery=true).
230
+ * Call `.deepQuery(false)` to skip getter evaluation for performance.
231
231
  *
232
+ * @param enabled - Whether to evaluate property getters (default: true)
232
233
  * @returns The query builder for chaining
233
234
  *
234
235
  * @example
235
236
  * ```typescript
236
237
  * const messages = await Message.query(perspective)
237
238
  * .parent(channel)
238
- * .deepQuery()
239
+ * .deepQuery(false) // skip property getters for performance
239
240
  * .limit(30)
240
241
  * .get();
241
- * // messages[i].replyingTo is populated
242
242
  * ```
243
243
  */
244
- deepQuery(): ModelQueryBuilder<T> {
245
- (this.queryParams as any).deepQuery = true;
244
+ deepQuery(enabled: boolean = true): ModelQueryBuilder<T> {
245
+ this.queryParams.deepQuery = enabled;
246
246
  return this;
247
247
  }
248
248
 
@@ -409,10 +409,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
409
409
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
410
410
  subscriptionId,
411
411
  (rawResult: any) => {
412
- // Skip delayed #init# messages — initial data was already returned
413
- // synchronously from modelSubscribe(). Late init messages contain stale
414
- // data that would overwrite real subscription updates.
415
- if (rawResult && rawResult.isInit) return;
416
412
  try {
417
413
  const results = parseResults(rawResult);
418
414
  const fp = buildFingerprint(results);
@@ -425,9 +421,15 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
425
421
  },
426
422
  );
427
423
 
428
- // Set up keepalive
424
+ // Set up keepalive with failure tracking
425
+ let keepaliveFailures = 0;
429
426
  const keepaliveTimer = setInterval(() => {
430
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).catch(() => {});
427
+ this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
428
+ keepaliveFailures = 0;
429
+ }).catch((e: any) => {
430
+ keepaliveFailures++;
431
+ console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
432
+ });
431
433
  }, 30000);
432
434
 
433
435
  // Store dispose function
@@ -531,7 +533,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
531
533
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
532
534
  subscriptionId,
533
535
  (rawResult: any) => {
534
- if (rawResult && rawResult.isInit) return;
535
536
  try {
536
537
  callback(parseCount(rawResult));
537
538
  } catch (e) {
@@ -540,8 +541,14 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
540
541
  },
541
542
  );
542
543
 
544
+ let keepaliveFailures = 0;
543
545
  const keepaliveTimer = setInterval(() => {
544
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).catch(() => {});
546
+ this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
547
+ keepaliveFailures = 0;
548
+ }).catch((e: any) => {
549
+ keepaliveFailures++;
550
+ console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
551
+ });
545
552
  }, 30000);
546
553
 
547
554
  this.currentSubscription = {
@@ -662,13 +669,18 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
662
669
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
663
670
  subscriptionId,
664
671
  (rawResult: any) => {
665
- if (rawResult && rawResult.isInit) return;
666
672
  processResults().catch(e => console.error('Paginate subscription error:', e));
667
673
  },
668
674
  );
669
675
 
676
+ let keepaliveFailures = 0;
670
677
  const keepaliveTimer = setInterval(() => {
671
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).catch(() => {});
678
+ this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
679
+ keepaliveFailures = 0;
680
+ }).catch((e: any) => {
681
+ keepaliveFailures++;
682
+ console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
683
+ });
672
684
  }, 30000);
673
685
 
674
686
  this.currentSubscription = {