@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
@@ -27,6 +27,6 @@ export declare class Ad4mClient {
27
27
  /** Start event subscriptions (agent-updated, agent-status-changed, apps-changed).
28
28
  * Safe to call if subscriptions were deferred at construction (subscribe=false). */
29
29
  startSubscriptions(): void;
30
- /** Close all event connections */
30
+ /** Close all event connections and clear in-memory caches */
31
31
  close(): void;
32
32
  }
@@ -18,6 +18,7 @@ import { RuntimeClient } from './runtime/RuntimeClient';
18
18
  import { ExpressionClient } from './expression/ExpressionClient';
19
19
  import { AIClient } from './ai/AIClient';
20
20
  import { ApiClient } from './apiClient';
21
+ import { Ad4mModel } from './model/Ad4mModel';
21
22
  /**
22
23
  * Client for the Ad4m interface wrapping WebSocket RPC calls
23
24
  * for convenient use in user facing code.
@@ -52,6 +53,15 @@ export class Ad4mClient {
52
53
  __classPrivateFieldGet(this, _Ad4mClient_perspectiveClient, "f").setNeighbourhoodClient(__classPrivateFieldGet(this, _Ad4mClient_neighbourhoodClient, "f"));
53
54
  __classPrivateFieldGet(this, _Ad4mClient_perspectiveClient, "f").setAIClient(__classPrivateFieldGet(this, _Ad4mClient_aiClient, "f"));
54
55
  __classPrivateFieldSet(this, _Ad4mClient_runtimeClient, new RuntimeClient(baseUrl, token, subscribe, __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f")), "f");
56
+ // Register with AD4M DevTools if the bridge is installed (e.g. browser extension)
57
+ try {
58
+ const dt = globalThis.__AD4M_DEVTOOLS__;
59
+ if (dt) {
60
+ dt._client = this;
61
+ dt._Ad4mModel = Ad4mModel;
62
+ }
63
+ }
64
+ catch { }
55
65
  }
56
66
  get agent() {
57
67
  return __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f");
@@ -81,8 +91,9 @@ export class Ad4mClient {
81
91
  __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f").subscribeAgentStatusChanged();
82
92
  __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f").subscribeAppsChanged();
83
93
  }
84
- /** Close all event connections */
94
+ /** Close all event connections and clear in-memory caches */
85
95
  close() {
96
+ __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f").clearByDidCache();
86
97
  __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f").closeAll();
87
98
  }
88
99
  }
@@ -18,6 +18,8 @@ export type HostingUserInfoChangedCallback = (info: HostingUserInfo) => void;
18
18
  export type ComputeLogUpdatedCallback = (entry: ComputeLogEntry) => void;
19
19
  export declare class AgentClient {
20
20
  #private;
21
+ /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
22
+ static REMOTE_AGENT_TTL_MS: number;
21
23
  constructor(baseUrl: string, token?: string, subscribe?: boolean, sharedApiClient?: ApiClient);
22
24
  me(): Promise<Agent>;
23
25
  status(): Promise<AgentStatus>;
@@ -26,6 +28,20 @@ export declare class AgentClient {
26
28
  lock(passphrase: string): Promise<AgentStatus>;
27
29
  unlock(passphrase: string, holochain?: boolean): Promise<AgentStatus>;
28
30
  byDID(did: string): Promise<Agent>;
31
+ /**
32
+ * Set the current agent's own DID.
33
+ * The self-DID receives event-driven invalidation and is never TTL-expired.
34
+ */
35
+ setSelfDid(did: string): void;
36
+ /**
37
+ * Invalidate a specific DID's cache entry in both L1 and L2.
38
+ */
39
+ invalidateByDid(did: string): void;
40
+ /**
41
+ * Clear the entire L1 (memory) byDID cache.
42
+ * L2 (IndexedDB) is preserved — agent data remains valid across sessions.
43
+ */
44
+ clearByDidCache(): void;
29
45
  updatePublicPerspective(perspective: PerspectiveInput): Promise<Agent>;
30
46
  mutatePublicPerspective(mutations: LinkMutations): Promise<Agent>;
31
47
  updateDirectMessageLanguage(directMessageLanguage: string): Promise<Agent>;
@@ -9,12 +9,13 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _AgentClient_apiClient, _AgentClient_baseUrl, _AgentClient_token, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks, _AgentClient_unsubscribers;
12
+ var _AgentClient_apiClient, _AgentClient_baseUrl, _AgentClient_token, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks, _AgentClient_unsubscribers, _AgentClient_memCache, _AgentClient_persistent, _AgentClient_selfDid;
13
13
  import { ApiClient } from "../apiClient";
14
14
  import { Agent, } from "./Agent";
15
15
  import { HostingUserInfo } from "../runtime/RuntimeTypes";
16
16
  import { AgentStatus } from "./AgentStatus";
17
17
  import { PerspectiveClient } from "../perspectives/PerspectiveClient";
18
+ import { createPersistentCache } from "../cache/PersistentCache";
18
19
  export class AgentClient {
19
20
  constructor(baseUrl, token, subscribe = true, sharedApiClient) {
20
21
  _AgentClient_apiClient.set(this, void 0);
@@ -26,6 +27,13 @@ export class AgentClient {
26
27
  _AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);
27
28
  _AgentClient_computeLogUpdatedCallbacks.set(this, void 0);
28
29
  _AgentClient_unsubscribers.set(this, void 0);
30
+ // ── byDID cache ────────────────────────────────────────────────────
31
+ // L1: in-memory promise cache with timestamps for TTL
32
+ _AgentClient_memCache.set(this, new Map());
33
+ // L2: persistent cache (IndexedDB in browser, NullCache in Node)
34
+ _AgentClient_persistent.set(this, void 0);
35
+ // Self-DID for event-driven invalidation (no TTL for own profile)
36
+ _AgentClient_selfDid.set(this, null);
29
37
  __classPrivateFieldSet(this, _AgentClient_baseUrl, baseUrl, "f");
30
38
  __classPrivateFieldSet(this, _AgentClient_token, token, "f");
31
39
  __classPrivateFieldSet(this, _AgentClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
@@ -35,6 +43,7 @@ export class AgentClient {
35
43
  __classPrivateFieldSet(this, _AgentClient_hostingUserInfoChangedCallbacks, [], "f");
36
44
  __classPrivateFieldSet(this, _AgentClient_computeLogUpdatedCallbacks, [], "f");
37
45
  __classPrivateFieldSet(this, _AgentClient_unsubscribers, [], "f");
46
+ __classPrivateFieldSet(this, _AgentClient_persistent, createPersistentCache('ad4m-agent-cache', 'agents'), "f");
38
47
  if (subscribe) {
39
48
  this.subscribeAgentUpdated();
40
49
  this.subscribeAgentStatusChanged();
@@ -68,7 +77,57 @@ export class AgentClient {
68
77
  return new AgentStatus(result);
69
78
  }
70
79
  async byDID(did) {
71
- return __classPrivateFieldGet(this, _AgentClient_apiClient, "f").call('agent.byDid', { did });
80
+ const now = Date.now();
81
+ const cached = __classPrivateFieldGet(this, _AgentClient_memCache, "f").get(did);
82
+ if (cached) {
83
+ const isSelf = did === __classPrivateFieldGet(this, _AgentClient_selfDid, "f");
84
+ // Self-DID: L1 always valid (event-driven invalidation)
85
+ // Remote DID: L1 valid within TTL
86
+ if (isSelf || (now - cached.ts) < AgentClient.REMOTE_AGENT_TTL_MS) {
87
+ return cached.promise;
88
+ }
89
+ }
90
+ // Deduplicate: store the promise immediately so concurrent calls share one RPC
91
+ const promise = (async () => {
92
+ // L2: check persistent cache before network
93
+ const persisted = await __classPrivateFieldGet(this, _AgentClient_persistent, "f").get(did);
94
+ if (persisted) {
95
+ return persisted;
96
+ }
97
+ // L3: network fetch
98
+ const result = await __classPrivateFieldGet(this, _AgentClient_apiClient, "f").call('agent.byDid', { did });
99
+ __classPrivateFieldGet(this, _AgentClient_persistent, "f").put(did, result); // fire-and-forget write to L2
100
+ return result;
101
+ })();
102
+ __classPrivateFieldGet(this, _AgentClient_memCache, "f").set(did, { promise, ts: now });
103
+ // Clean up on failure so next call retries
104
+ promise.catch(() => {
105
+ if (__classPrivateFieldGet(this, _AgentClient_memCache, "f").get(did)?.promise === promise) {
106
+ __classPrivateFieldGet(this, _AgentClient_memCache, "f").delete(did);
107
+ }
108
+ });
109
+ return promise;
110
+ }
111
+ /**
112
+ * Set the current agent's own DID.
113
+ * The self-DID receives event-driven invalidation and is never TTL-expired.
114
+ */
115
+ setSelfDid(did) {
116
+ __classPrivateFieldSet(this, _AgentClient_selfDid, did, "f");
117
+ }
118
+ /**
119
+ * Invalidate a specific DID's cache entry in both L1 and L2.
120
+ */
121
+ invalidateByDid(did) {
122
+ __classPrivateFieldGet(this, _AgentClient_memCache, "f").delete(did);
123
+ __classPrivateFieldGet(this, _AgentClient_persistent, "f").delete(did); // fire-and-forget
124
+ }
125
+ /**
126
+ * Clear the entire L1 (memory) byDID cache.
127
+ * L2 (IndexedDB) is preserved — agent data remains valid across sessions.
128
+ */
129
+ clearByDidCache() {
130
+ __classPrivateFieldGet(this, _AgentClient_memCache, "f").clear();
72
131
  }
73
132
  async updatePublicPerspective(perspective) {
74
133
  const cleanedPerspective = JSON.parse(JSON.stringify(perspective));
@@ -129,7 +188,16 @@ export class AgentClient {
129
188
  subscribeAgentUpdated() {
130
189
  const unsub = __classPrivateFieldGet(this, _AgentClient_apiClient, "f").subscribe((data) => {
131
190
  if (data.type === 'agent-updated') {
132
- __classPrivateFieldGet(this, _AgentClient_updatedCallbacks, "f").forEach((cb) => cb((data.agent || data)));
191
+ const agent = (data.agent || data);
192
+ // Update L1 and L2 cache from the event payload
193
+ if (agent.did) {
194
+ __classPrivateFieldGet(this, _AgentClient_memCache, "f").set(agent.did, {
195
+ promise: Promise.resolve(agent),
196
+ ts: Date.now(),
197
+ });
198
+ __classPrivateFieldGet(this, _AgentClient_persistent, "f").put(agent.did, agent); // fire-and-forget
199
+ }
200
+ __classPrivateFieldGet(this, _AgentClient_updatedCallbacks, "f").forEach((cb) => cb(agent));
133
201
  }
134
202
  });
135
203
  __classPrivateFieldGet(this, _AgentClient_unsubscribers, "f").push(unsub);
@@ -228,4 +296,6 @@ export class AgentClient {
228
296
  return __classPrivateFieldGet(this, _AgentClient_apiClient, "f").call('hosting.requestPayment', { amountHOT });
229
297
  }
230
298
  }
231
- _AgentClient_apiClient = new WeakMap(), _AgentClient_baseUrl = new WeakMap(), _AgentClient_token = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap(), _AgentClient_unsubscribers = new WeakMap();
299
+ _AgentClient_apiClient = new WeakMap(), _AgentClient_baseUrl = new WeakMap(), _AgentClient_token = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap(), _AgentClient_unsubscribers = new WeakMap(), _AgentClient_memCache = new WeakMap(), _AgentClient_persistent = new WeakMap(), _AgentClient_selfDid = new WeakMap();
300
+ /** TTL for remote (non-self) agent profiles in L1 cache (ms). */
301
+ AgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes
@@ -0,0 +1,40 @@
1
+ /**
2
+ * PersistentCache — two-tier persistent key-value cache abstraction.
3
+ *
4
+ * Provides an IndexedDB-backed implementation for browsers and a no-op
5
+ * NullCache fallback for Node.js / environments without IndexedDB.
6
+ *
7
+ * Design goals:
8
+ * - Lazy open: IDB connection is deferred until first access
9
+ * - Fire-and-forget writes: put() resolves immediately (best-effort persistence)
10
+ * - Graceful degradation: all IDB errors resolve (never reject), so callers
11
+ * never need try/catch around cache operations
12
+ * - Tree-shakeable: import only what you need
13
+ */
14
+ export interface PersistentCache<T = unknown> {
15
+ get(key: string): Promise<T | undefined>;
16
+ put(key: string, value: T): Promise<void>;
17
+ delete(key: string): Promise<void>;
18
+ clear(): Promise<void>;
19
+ }
20
+ export declare class IDBCache<T = unknown> implements PersistentCache<T> {
21
+ #private;
22
+ constructor(dbName: string, storeName: string);
23
+ get(key: string): Promise<T | undefined>;
24
+ put(key: string, value: T): Promise<void>;
25
+ delete(key: string): Promise<void>;
26
+ clear(): Promise<void>;
27
+ }
28
+ export declare class NullCache<T = unknown> implements PersistentCache<T> {
29
+ get(_key: string): Promise<T | undefined>;
30
+ put(_key: string, _value: T): Promise<void>;
31
+ delete(_key: string): Promise<void>;
32
+ clear(): Promise<void>;
33
+ }
34
+ /**
35
+ * Create a PersistentCache backed by IndexedDB (browser) or NullCache (Node.js).
36
+ *
37
+ * @param dbName - IndexedDB database name
38
+ * @param storeName - IndexedDB object store name
39
+ */
40
+ export declare function createPersistentCache<T = unknown>(dbName: string, storeName: string): PersistentCache<T>;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * PersistentCache — two-tier persistent key-value cache abstraction.
3
+ *
4
+ * Provides an IndexedDB-backed implementation for browsers and a no-op
5
+ * NullCache fallback for Node.js / environments without IndexedDB.
6
+ *
7
+ * Design goals:
8
+ * - Lazy open: IDB connection is deferred until first access
9
+ * - Fire-and-forget writes: put() resolves immediately (best-effort persistence)
10
+ * - Graceful degradation: all IDB errors resolve (never reject), so callers
11
+ * never need try/catch around cache operations
12
+ * - Tree-shakeable: import only what you need
13
+ */
14
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
15
+ if (kind === "m") throw new TypeError("Private method is not writable");
16
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
17
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
18
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
19
+ };
20
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
21
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
22
+ 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");
23
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
24
+ };
25
+ var _IDBCache_instances, _IDBCache_dbName, _IDBCache_storeName, _IDBCache_dbPromise, _IDBCache_version, _IDBCache_open;
26
+ // ── IndexedDB Implementation ─────────────────────────────────────────
27
+ export class IDBCache {
28
+ constructor(dbName, storeName) {
29
+ _IDBCache_instances.add(this);
30
+ _IDBCache_dbName.set(this, void 0);
31
+ _IDBCache_storeName.set(this, void 0);
32
+ _IDBCache_dbPromise.set(this, null);
33
+ _IDBCache_version.set(this, 1);
34
+ __classPrivateFieldSet(this, _IDBCache_dbName, dbName, "f");
35
+ __classPrivateFieldSet(this, _IDBCache_storeName, storeName, "f");
36
+ }
37
+ async get(key) {
38
+ try {
39
+ const db = await __classPrivateFieldGet(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
40
+ return new Promise((resolve) => {
41
+ const tx = db.transaction(__classPrivateFieldGet(this, _IDBCache_storeName, "f"), 'readonly');
42
+ const store = tx.objectStore(__classPrivateFieldGet(this, _IDBCache_storeName, "f"));
43
+ const req = store.get(key);
44
+ req.onsuccess = () => resolve(req.result ?? undefined);
45
+ req.onerror = () => resolve(undefined);
46
+ });
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ async put(key, value) {
53
+ try {
54
+ const db = await __classPrivateFieldGet(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
55
+ return new Promise((resolve) => {
56
+ const tx = db.transaction(__classPrivateFieldGet(this, _IDBCache_storeName, "f"), 'readwrite');
57
+ const store = tx.objectStore(__classPrivateFieldGet(this, _IDBCache_storeName, "f"));
58
+ store.put(value, key);
59
+ tx.oncomplete = () => resolve();
60
+ tx.onerror = () => resolve(); // fire-and-forget
61
+ });
62
+ }
63
+ catch {
64
+ // degrade gracefully
65
+ }
66
+ }
67
+ async delete(key) {
68
+ try {
69
+ const db = await __classPrivateFieldGet(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
70
+ return new Promise((resolve) => {
71
+ const tx = db.transaction(__classPrivateFieldGet(this, _IDBCache_storeName, "f"), 'readwrite');
72
+ const store = tx.objectStore(__classPrivateFieldGet(this, _IDBCache_storeName, "f"));
73
+ store.delete(key);
74
+ tx.oncomplete = () => resolve();
75
+ tx.onerror = () => resolve();
76
+ });
77
+ }
78
+ catch {
79
+ // degrade gracefully
80
+ }
81
+ }
82
+ async clear() {
83
+ try {
84
+ const db = await __classPrivateFieldGet(this, _IDBCache_instances, "m", _IDBCache_open).call(this);
85
+ return new Promise((resolve) => {
86
+ const tx = db.transaction(__classPrivateFieldGet(this, _IDBCache_storeName, "f"), 'readwrite');
87
+ const store = tx.objectStore(__classPrivateFieldGet(this, _IDBCache_storeName, "f"));
88
+ store.clear();
89
+ tx.oncomplete = () => resolve();
90
+ tx.onerror = () => resolve();
91
+ });
92
+ }
93
+ catch {
94
+ // degrade gracefully
95
+ }
96
+ }
97
+ }
98
+ _IDBCache_dbName = new WeakMap(), _IDBCache_storeName = new WeakMap(), _IDBCache_dbPromise = new WeakMap(), _IDBCache_version = new WeakMap(), _IDBCache_instances = new WeakSet(), _IDBCache_open = function _IDBCache_open() {
99
+ if (!__classPrivateFieldGet(this, _IDBCache_dbPromise, "f")) {
100
+ __classPrivateFieldSet(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {
101
+ const storeName = __classPrivateFieldGet(this, _IDBCache_storeName, "f");
102
+ const req = indexedDB.open(__classPrivateFieldGet(this, _IDBCache_dbName, "f"), __classPrivateFieldGet(this, _IDBCache_version, "f"));
103
+ req.onupgradeneeded = () => {
104
+ const db = req.result;
105
+ if (!db.objectStoreNames.contains(storeName)) {
106
+ db.createObjectStore(storeName);
107
+ }
108
+ };
109
+ req.onsuccess = () => resolve(req.result);
110
+ req.onerror = () => reject(req.error);
111
+ }), "f");
112
+ }
113
+ return __classPrivateFieldGet(this, _IDBCache_dbPromise, "f");
114
+ };
115
+ // ── NullCache (no-op fallback for Node.js) ───────────────────────────
116
+ export class NullCache {
117
+ async get(_key) { return undefined; }
118
+ async put(_key, _value) { }
119
+ async delete(_key) { }
120
+ async clear() { }
121
+ }
122
+ // ── Factory ──────────────────────────────────────────────────────────
123
+ /**
124
+ * Create a PersistentCache backed by IndexedDB (browser) or NullCache (Node.js).
125
+ *
126
+ * @param dbName - IndexedDB database name
127
+ * @param storeName - IndexedDB object store name
128
+ */
129
+ export function createPersistentCache(dbName, storeName) {
130
+ try {
131
+ if (typeof indexedDB !== 'undefined') {
132
+ return new IDBCache(dbName, storeName);
133
+ }
134
+ }
135
+ catch {
136
+ // indexedDB access threw (e.g. in a worker with restricted globals)
137
+ }
138
+ return new NullCache();
139
+ }
@@ -3,9 +3,17 @@ import { InteractionCall, InteractionMeta } from "../language/Language";
3
3
  import { ExpressionRendered } from "./Expression";
4
4
  export declare class ExpressionClient {
5
5
  #private;
6
+ /** Maximum number of entries in the L1 memory cache. */
7
+ static MAX_MEM_ENTRIES: number;
8
+ /** Maximum total size (in bytes) of L1 memory cache values. */
9
+ static MAX_MEM_BYTES: number;
6
10
  constructor(baseUrl: string, token?: string, sharedApiClient?: ApiClient);
7
11
  get(url: string, alwaysGet?: boolean): Promise<ExpressionRendered>;
8
12
  getMany(urls: string[]): Promise<ExpressionRendered[]>;
13
+ /**
14
+ * Clear both L1 (memory) and L2 (persistent) expression caches.
15
+ */
16
+ clearCache(): void;
9
17
  getRaw(url: string): Promise<string>;
10
18
  create(content: unknown, languageAddress: string): Promise<string>;
11
19
  interactions(url: string): Promise<InteractionMeta[]>;
@@ -9,15 +9,25 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _ExpressionClient_apiClient;
12
+ var _ExpressionClient_instances, _ExpressionClient_apiClient, _ExpressionClient_memCache, _ExpressionClient_inflight, _ExpressionClient_totalMemBytes, _ExpressionClient_persistent, _ExpressionClient_memCacheResult;
13
13
  import { ApiClient } from "../apiClient";
14
14
  import { Literal } from "../Literal";
15
+ import { createPersistentCache } from "../cache/PersistentCache";
15
16
  export class ExpressionClient {
16
17
  constructor(baseUrl, token, sharedApiClient) {
18
+ _ExpressionClient_instances.add(this);
17
19
  _ExpressionClient_apiClient.set(this, void 0);
20
+ // L1: in-memory LRU cache (hot path, sub-ms)
21
+ _ExpressionClient_memCache.set(this, new Map());
22
+ _ExpressionClient_inflight.set(this, new Map());
23
+ _ExpressionClient_totalMemBytes.set(this, 0);
24
+ // L2: persistent cache (IndexedDB in browser, NullCache in Node)
25
+ _ExpressionClient_persistent.set(this, void 0);
18
26
  __classPrivateFieldSet(this, _ExpressionClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), "f");
27
+ __classPrivateFieldSet(this, _ExpressionClient_persistent, createPersistentCache('ad4m-expression-cache', 'expressions'), "f");
19
28
  }
20
29
  async get(url, alwaysGet = false) {
30
+ // Existing literal fast-path
21
31
  if (!alwaysGet) {
22
32
  try {
23
33
  let literalValue = Literal.fromUrl(url).get();
@@ -29,10 +39,85 @@ export class ExpressionClient {
29
39
  }
30
40
  catch (e) { }
31
41
  }
32
- return __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.get', { url });
42
+ // L1: memory hit
43
+ if (!alwaysGet) {
44
+ const memHit = __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").get(url);
45
+ if (memHit)
46
+ return memHit.data;
47
+ }
48
+ // Deduplicate in-flight requests
49
+ if (!alwaysGet) {
50
+ const existing = __classPrivateFieldGet(this, _ExpressionClient_inflight, "f").get(url);
51
+ if (existing)
52
+ return existing;
53
+ }
54
+ // L2 check + L3 network
55
+ const promise = (async () => {
56
+ if (!alwaysGet) {
57
+ const persisted = await __classPrivateFieldGet(this, _ExpressionClient_persistent, "f").get(url);
58
+ if (persisted) {
59
+ __classPrivateFieldGet(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, persisted); // promote to L1
60
+ return persisted;
61
+ }
62
+ }
63
+ // L3: network fetch
64
+ const result = await __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.get', { url });
65
+ __classPrivateFieldGet(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, url, result);
66
+ __classPrivateFieldGet(this, _ExpressionClient_persistent, "f").put(url, result); // fire-and-forget write to L2
67
+ return result;
68
+ })();
69
+ __classPrivateFieldGet(this, _ExpressionClient_inflight, "f").set(url, promise);
70
+ try {
71
+ return await promise;
72
+ }
73
+ finally {
74
+ __classPrivateFieldGet(this, _ExpressionClient_inflight, "f").delete(url);
75
+ }
33
76
  }
34
77
  async getMany(urls) {
35
- return __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.getMany', { urls });
78
+ // Check L1 first
79
+ const results = urls.map(u => __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").get(u)?.data ?? null);
80
+ let uncachedIndices = results
81
+ .map((r, i) => r === null ? i : -1)
82
+ .filter(i => i >= 0);
83
+ if (uncachedIndices.length === 0)
84
+ return results;
85
+ // Check L2 for remaining misses
86
+ const l2Results = await Promise.all(uncachedIndices.map(i => __classPrivateFieldGet(this, _ExpressionClient_persistent, "f").get(urls[i])));
87
+ const stillMissing = [];
88
+ for (let j = 0; j < uncachedIndices.length; j++) {
89
+ const idx = uncachedIndices[j];
90
+ if (l2Results[j]) {
91
+ results[idx] = l2Results[j];
92
+ __classPrivateFieldGet(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, urls[idx], l2Results[j]); // promote to L1
93
+ }
94
+ else {
95
+ stillMissing.push(idx);
96
+ }
97
+ }
98
+ if (stillMissing.length === 0)
99
+ return results;
100
+ // L3: fetch only truly uncached URLs
101
+ const uncachedUrls = stillMissing.map(i => urls[i]);
102
+ const fetched = await __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.getMany', { urls: uncachedUrls });
103
+ for (let i = 0; i < stillMissing.length; i++) {
104
+ const idx = stillMissing[i];
105
+ results[idx] = fetched[i];
106
+ if (fetched[i]) {
107
+ __classPrivateFieldGet(this, _ExpressionClient_instances, "m", _ExpressionClient_memCacheResult).call(this, uncachedUrls[i], fetched[i]);
108
+ __classPrivateFieldGet(this, _ExpressionClient_persistent, "f").put(uncachedUrls[i], fetched[i]); // fire-and-forget
109
+ }
110
+ }
111
+ return results;
112
+ }
113
+ /**
114
+ * Clear both L1 (memory) and L2 (persistent) expression caches.
115
+ */
116
+ clearCache() {
117
+ __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").clear();
118
+ __classPrivateFieldGet(this, _ExpressionClient_inflight, "f").clear();
119
+ __classPrivateFieldSet(this, _ExpressionClient_totalMemBytes, 0, "f");
120
+ __classPrivateFieldGet(this, _ExpressionClient_persistent, "f").clear(); // fire-and-forget
36
121
  }
37
122
  async getRaw(url) {
38
123
  return __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.get', { url, raw: true });
@@ -45,7 +130,30 @@ export class ExpressionClient {
45
130
  return __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.interactions', { url });
46
131
  }
47
132
  async interact(url, interactionCall) {
48
- return __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.interact', { url, interactionCall });
133
+ const result = await __classPrivateFieldGet(this, _ExpressionClient_apiClient, "f").call('expression.interact', { url, interactionCall });
134
+ // Interactions can mutate the expression — invalidate cache so next get() fetches fresh
135
+ __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").delete(url);
136
+ __classPrivateFieldGet(this, _ExpressionClient_inflight, "f").delete(url);
137
+ __classPrivateFieldGet(this, _ExpressionClient_persistent, "f").delete(url); // fire-and-forget
138
+ return result;
49
139
  }
50
140
  }
51
- _ExpressionClient_apiClient = new WeakMap();
141
+ _ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_memCache = new WeakMap(), _ExpressionClient_inflight = new WeakMap(), _ExpressionClient_totalMemBytes = new WeakMap(), _ExpressionClient_persistent = new WeakMap(), _ExpressionClient_instances = new WeakSet(), _ExpressionClient_memCacheResult = function _ExpressionClient_memCacheResult(url, data) {
142
+ const size = JSON.stringify(data).length;
143
+ // Evict oldest entries if we'd exceed limits
144
+ while (__classPrivateFieldGet(this, _ExpressionClient_memCache, "f").size >= ExpressionClient.MAX_MEM_ENTRIES ||
145
+ __classPrivateFieldGet(this, _ExpressionClient_totalMemBytes, "f") + size > ExpressionClient.MAX_MEM_BYTES) {
146
+ const oldest = __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").keys().next().value;
147
+ if (!oldest)
148
+ break;
149
+ const entry = __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").get(oldest);
150
+ __classPrivateFieldSet(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet(this, _ExpressionClient_totalMemBytes, "f") - entry.size, "f");
151
+ __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").delete(oldest);
152
+ }
153
+ __classPrivateFieldGet(this, _ExpressionClient_memCache, "f").set(url, { data, size });
154
+ __classPrivateFieldSet(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet(this, _ExpressionClient_totalMemBytes, "f") + size, "f");
155
+ };
156
+ /** Maximum number of entries in the L1 memory cache. */
157
+ ExpressionClient.MAX_MEM_ENTRIES = 200;
158
+ /** Maximum total size (in bytes) of L1 memory cache values. */
159
+ ExpressionClient.MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB
@@ -2,6 +2,7 @@ export * from "./Ad4mClient";
2
2
  export * from "./Address";
3
3
  export * from "./agent/Agent";
4
4
  export * from "./agent/AgentStatus";
5
+ export * from "./cache/PersistentCache";
5
6
  export * from "./Exception";
6
7
  export * from "./expression/Expression";
7
8
  export * from "./expression/ExpressionRef";
package/lib/src/index.js CHANGED
@@ -2,6 +2,7 @@ export * from "./Ad4mClient";
2
2
  export * from "./Address";
3
3
  export * from "./agent/Agent";
4
4
  export * from "./agent/AgentStatus";
5
+ export * from "./cache/PersistentCache";
5
6
  export * from "./Exception";
6
7
  export * from "./expression/Expression";
7
8
  export * from "./expression/ExpressionRef";
@@ -474,10 +474,10 @@ export declare class Ad4mModel {
474
474
  /**
475
475
  * Evaluate SPARQL getters for a batch of instances on demand.
476
476
  *
477
- * Use after a shallow collection query (the default) to resolve
478
- * getter-backed properties for visible items only. This avoids the
479
- * O(N × getters) cost of evaluating every getter on every instance in
480
- * a large collection query.
477
+ * Since deepQuery defaults to true, property getters are evaluated
478
+ * automatically during collection queries. Use this method when
479
+ * deepQuery was explicitly set to false and you want to lazily
480
+ * resolve getter-backed properties for a subset of instances.
481
481
  *
482
482
  * @param instances - Array of model instances to evaluate getters on
483
483
  * @param perspective - The perspective to query against
@@ -486,8 +486,8 @@ export declare class Ad4mModel {
486
486
  *
487
487
  * @example
488
488
  * ```typescript
489
- * const messages = await Message.findAll(perspective, { parent: channel, limit: 30 });
490
- * // messages[i].replyingTo is undefined (getter skipped by default)
489
+ * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
490
+ * // messages[i].replyingTo is undefined (getter skipped)
491
491
  *
492
492
  * // Evaluate getters for the visible subset
493
493
  * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
@@ -766,5 +766,18 @@ export declare class Ad4mModel {
766
766
  * @param name - Class name to assign (e.g. "Channel")
767
767
  * @returns Generated Ad4mModel subclass, ready for querying
768
768
  */
769
- static fromSHACL(shape: SHACLShape, name: string): typeof Ad4mModel;
769
+ /**
770
+ * Synthesise an `Ad4mModel` subclass from a SHACL shape.
771
+ *
772
+ * @param shape - The SHACL shape to synthesise from.
773
+ * @param name - The model name (e.g. "Channel").
774
+ * @param classResolver - Optional thunk factory. When provided, any collection
775
+ * property that carries a `sh:class` URI will have its `target` wired up lazily:
776
+ * `target: () => classResolver(localName)`. Because `target` is only called at
777
+ * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
778
+ * resolver just needs to return the correct class by the time a query runs —
779
+ * making it safe to pass a closure over a registry object that is still being
780
+ * populated (e.g. the `result` record inside `getModelClasses`).
781
+ */
782
+ static fromSHACL(shape: SHACLShape, name: string, classResolver?: (localName: string) => typeof Ad4mModel | undefined): typeof Ad4mModel;
770
783
  }