@coasys/ad4m 0.13.0-test-5 → 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 (63) hide show
  1. package/lib/index.cjs +610 -337
  2. package/lib/index.js +608 -338
  3. package/lib/src/Ad4mClient.d.ts +1 -1
  4. package/lib/src/Ad4mClient.js +2 -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.js +29 -57
  14. package/lib/src/model/Ad4mModel.test.js +688 -1434
  15. package/lib/src/model/ModelQueryBuilder.js +0 -9
  16. package/lib/src/model/Subject.js +6 -6
  17. package/lib/src/model/query-surreal.d.ts +44 -0
  18. package/lib/src/model/query-surreal.js +249 -0
  19. package/lib/src/model/relation-filtering.test.js +15 -15
  20. package/lib/src/model/surreal-utils.d.ts +42 -0
  21. package/lib/src/model/surreal-utils.js +128 -0
  22. package/lib/src/model/types.d.ts +0 -1
  23. package/lib/src/perspectives/PerspectiveClient.d.ts +0 -1
  24. package/lib/src/perspectives/PerspectiveClient.js +5 -13
  25. package/lib/src/perspectives/PerspectiveProxy.js +0 -3
  26. package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
  27. package/lib/src/perspectives/PerspectiveResolver.js +11 -0
  28. package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
  29. package/lib/src/runtime/RuntimeResolver.js +4 -197
  30. package/lib/src/schema.gql +1 -27
  31. package/lib/src/shacl/SHACLShape.test.js +0 -82
  32. package/package.json +1 -1
  33. package/src/Ad4mClient.test.ts +14 -4
  34. package/src/Ad4mClient.ts +2 -1
  35. package/src/agent/AgentClient.ts +84 -2
  36. package/src/cache/PersistentCache.ts +145 -0
  37. package/src/cache/cache.test.ts +713 -0
  38. package/src/expression/ExpressionClient.ts +137 -3
  39. package/src/index.ts +1 -0
  40. package/src/model/Ad4mModel.test.ts +1 -61
  41. package/src/model/Ad4mModel.ts +31 -57
  42. package/src/model/ModelQueryBuilder.ts +0 -6
  43. package/src/model/types.ts +1 -1
  44. package/src/perspectives/PerspectiveClient.ts +7 -17
  45. package/src/perspectives/PerspectiveProxy.ts +0 -3
  46. package/lib/src/model/hydration-batch.d.ts +0 -34
  47. package/lib/src/model/hydration-batch.js +0 -147
  48. package/lib/src/model/hydration-batching.test.d.ts +0 -7
  49. package/lib/src/model/hydration-batching.test.js +0 -456
  50. package/lib/src/model/model-manifest.d.ts +0 -41
  51. package/lib/src/model/model-manifest.js +0 -11
  52. package/lib/src/model/query-cache.test.d.ts +0 -1
  53. package/lib/src/model/query-cache.test.js +0 -43
  54. package/lib/src/model/query-sparql-batch.d.ts +0 -17
  55. package/lib/src/model/query-sparql-batch.js +0 -260
  56. package/lib/src/model/query-sparql.test.d.ts +0 -1
  57. package/lib/src/model/query-sparql.test.js +0 -312
  58. package/lib/src/model/subscription-delta.test.d.ts +0 -24
  59. package/lib/src/model/subscription-delta.test.js +0 -180
  60. package/lib/src/model/subscription-pool.d.ts +0 -39
  61. package/lib/src/model/subscription-pool.js +0 -165
  62. package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
  63. 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
  }
@@ -91,8 +91,9 @@ export class Ad4mClient {
91
91
  __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f").subscribeAgentStatusChanged();
92
92
  __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f").subscribeAppsChanged();
93
93
  }
94
- /** Close all event connections */
94
+ /** Close all event connections and clear in-memory caches */
95
95
  close() {
96
+ __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f").clearByDidCache();
96
97
  __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f").closeAll();
97
98
  }
98
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";