@open-mercato/cache-provider-memory 0.0.0-stage → 0.11.1-develop.8687.1.adb16f62b3

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.
@@ -0,0 +1,2 @@
1
+ [build:cache-provider-memory] found 1 entry points
2
+ [build:cache-provider-memory] built successfully
package/build.mjs ADDED
@@ -0,0 +1,10 @@
1
+ import { dirname } from 'node:path'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { buildPackage } from '../../scripts/build-package.mjs'
4
+
5
+ const packageDir = dirname(fileURLToPath(import.meta.url))
6
+
7
+ await buildPackage(packageDir, {
8
+ name: 'cache-provider-memory',
9
+ entryPoints: 'src/**/*.ts',
10
+ })
package/dist/index.js ADDED
@@ -0,0 +1,197 @@
1
+ import { matchCacheKeyPattern } from "@open-mercato/cache-provider-kit/patterns";
2
+ const EXPIRED_SWEEP_WRITE_INTERVAL = 256;
3
+ const EXPIRED_SWEEP_MAX_SCAN = 1e3;
4
+ const DEFAULT_MEMORY_MAX_ENTRIES = 5e4;
5
+ function normalizeMaxEntries(raw) {
6
+ if (raw === void 0) return DEFAULT_MEMORY_MAX_ENTRIES;
7
+ if (!Number.isFinite(raw) || raw <= 0) return Number.POSITIVE_INFINITY;
8
+ return Math.floor(raw);
9
+ }
10
+ function createMemoryStrategy(options) {
11
+ const store = /* @__PURE__ */ new Map();
12
+ const tagIndex = /* @__PURE__ */ new Map();
13
+ const defaultTtl = options?.defaultTtl;
14
+ const maxEntries = normalizeMaxEntries(options?.maxEntries);
15
+ let writesSinceSweep = 0;
16
+ let evictions = 0;
17
+ let sweeps = 0;
18
+ let lastSweepReclaimed = 0;
19
+ function isExpired(entry) {
20
+ if (entry.expiresAt === null) return false;
21
+ return Date.now() > entry.expiresAt;
22
+ }
23
+ function touchKey(key, entry) {
24
+ if (maxEntries === Number.POSITIVE_INFINITY) return;
25
+ store.delete(key);
26
+ store.set(key, entry);
27
+ }
28
+ function evictIfNeeded() {
29
+ if (maxEntries === Number.POSITIVE_INFINITY) return;
30
+ while (store.size > maxEntries) {
31
+ const oldest = store.keys().next().value;
32
+ if (typeof oldest !== "string") break;
33
+ const entry = store.get(oldest);
34
+ store.delete(oldest);
35
+ if (entry) removeFromTagIndex(oldest, entry.tags);
36
+ evictions++;
37
+ }
38
+ }
39
+ function cleanupExpiredEntry(key, entry) {
40
+ store.delete(key);
41
+ for (const tag of entry.tags) {
42
+ const keys2 = tagIndex.get(tag);
43
+ if (keys2) {
44
+ keys2.delete(key);
45
+ if (keys2.size === 0) {
46
+ tagIndex.delete(tag);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ function addToTagIndex(key, tags) {
52
+ for (const tag of tags) {
53
+ if (!tagIndex.has(tag)) {
54
+ tagIndex.set(tag, /* @__PURE__ */ new Set());
55
+ }
56
+ tagIndex.get(tag).add(key);
57
+ }
58
+ }
59
+ function removeFromTagIndex(key, tags) {
60
+ for (const tag of tags) {
61
+ const keys2 = tagIndex.get(tag);
62
+ if (keys2) {
63
+ keys2.delete(key);
64
+ if (keys2.size === 0) {
65
+ tagIndex.delete(tag);
66
+ }
67
+ }
68
+ }
69
+ }
70
+ function sweepExpiredIfDue() {
71
+ if (++writesSinceSweep < EXPIRED_SWEEP_WRITE_INTERVAL) return;
72
+ writesSinceSweep = 0;
73
+ sweeps++;
74
+ let scanned = 0;
75
+ let reclaimed = 0;
76
+ for (const [key, entry] of store.entries()) {
77
+ if (scanned >= EXPIRED_SWEEP_MAX_SCAN) break;
78
+ scanned++;
79
+ if (isExpired(entry)) {
80
+ cleanupExpiredEntry(key, entry);
81
+ reclaimed++;
82
+ }
83
+ }
84
+ lastSweepReclaimed = reclaimed;
85
+ }
86
+ const get = async (key, options2) => {
87
+ const entry = store.get(key);
88
+ if (!entry) return null;
89
+ if (isExpired(entry)) {
90
+ if (options2?.returnExpired) {
91
+ return entry.value;
92
+ }
93
+ cleanupExpiredEntry(key, entry);
94
+ return null;
95
+ }
96
+ touchKey(key, entry);
97
+ return entry.value;
98
+ };
99
+ const set = async (key, value, options2) => {
100
+ const oldEntry = store.get(key);
101
+ if (oldEntry) {
102
+ removeFromTagIndex(key, oldEntry.tags);
103
+ }
104
+ const ttl = options2?.ttl ?? defaultTtl;
105
+ const tags = options2?.tags || [];
106
+ const expiresAt = ttl ? Date.now() + ttl : null;
107
+ const entry = {
108
+ key,
109
+ value,
110
+ tags,
111
+ expiresAt,
112
+ createdAt: Date.now()
113
+ };
114
+ store.set(key, entry);
115
+ addToTagIndex(key, tags);
116
+ sweepExpiredIfDue();
117
+ evictIfNeeded();
118
+ };
119
+ const has = async (key) => {
120
+ const entry = store.get(key);
121
+ if (!entry) return false;
122
+ if (isExpired(entry)) {
123
+ cleanupExpiredEntry(key, entry);
124
+ return false;
125
+ }
126
+ return true;
127
+ };
128
+ const deleteKey = async (key) => {
129
+ const entry = store.get(key);
130
+ if (!entry) return false;
131
+ removeFromTagIndex(key, entry.tags);
132
+ return store.delete(key);
133
+ };
134
+ const deleteByTags = async (tags) => {
135
+ const keysToDelete = /* @__PURE__ */ new Set();
136
+ for (const tag of tags) {
137
+ const keys2 = tagIndex.get(tag);
138
+ if (keys2) {
139
+ for (const key of keys2) {
140
+ keysToDelete.add(key);
141
+ }
142
+ }
143
+ }
144
+ let deleted = 0;
145
+ for (const key of keysToDelete) {
146
+ const success = await deleteKey(key);
147
+ if (success) deleted++;
148
+ }
149
+ return deleted;
150
+ };
151
+ const clear = async () => {
152
+ const size = store.size;
153
+ store.clear();
154
+ tagIndex.clear();
155
+ return size;
156
+ };
157
+ const keys = async (pattern) => {
158
+ const allKeys = Array.from(store.keys());
159
+ if (!pattern) return allKeys;
160
+ return allKeys.filter((key) => matchCacheKeyPattern(key, pattern));
161
+ };
162
+ const stats = async () => {
163
+ let expired = 0;
164
+ for (const entry of store.values()) {
165
+ if (isExpired(entry)) {
166
+ expired++;
167
+ }
168
+ }
169
+ return { size: store.size, expired, evictions, sweeps, lastSweepReclaimed };
170
+ };
171
+ const cleanup = async () => {
172
+ let removed = 0;
173
+ for (const [key, entry] of store.entries()) {
174
+ if (isExpired(entry)) {
175
+ cleanupExpiredEntry(key, entry);
176
+ removed++;
177
+ }
178
+ }
179
+ return removed;
180
+ };
181
+ return {
182
+ get,
183
+ set,
184
+ has,
185
+ delete: deleteKey,
186
+ deleteByTags,
187
+ clear,
188
+ keys,
189
+ stats,
190
+ cleanup
191
+ };
192
+ }
193
+ export {
194
+ DEFAULT_MEMORY_MAX_ENTRIES,
195
+ createMemoryStrategy
196
+ };
197
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["import type { CacheStrategy, CacheEntry, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'\nimport { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'\n\nconst EXPIRED_SWEEP_WRITE_INTERVAL = 256\n\n/**\n * Upper bound on entries scanned by a single amortized sweep pass. Keeps the\n * sweep O(budget) instead of O(store size) so a large, hot store never pays a\n * full-store scan latency spike on the `set()` that crosses the sweep interval.\n * The scan walks from the LRU head, where expired-and-cold entries accumulate;\n * anything beyond the budget is reclaimed on a later sweep, on access, by LRU\n * eviction once the cap is exceeded, or by an explicit `cleanup()`.\n */\nconst EXPIRED_SWEEP_MAX_SCAN = 1_000\n\n/**\n * Default upper bound on the number of entries a memory cache retains.\n * Bounds memory for long-lived (process-wide) instances; LRU eviction drops\n * the least-recently-used entries once the cap is exceeded. Override via the\n * `maxEntries` option (or `CACHE_MEMORY_MAX_ENTRIES`); a non-positive value\n * disables the cap (unbounded \u2014 only safe for short-lived instances).\n */\nexport const DEFAULT_MEMORY_MAX_ENTRIES = 50_000\n\nfunction normalizeMaxEntries(raw?: number): number {\n if (raw === undefined) return DEFAULT_MEMORY_MAX_ENTRIES\n if (!Number.isFinite(raw) || raw <= 0) return Number.POSITIVE_INFINITY\n return Math.floor(raw)\n}\n\n/**\n * In-memory cache strategy with tag support.\n * Fast but data is lost when process restarts.\n *\n * Bounded by an LRU cap (`maxEntries`, default {@link DEFAULT_MEMORY_MAX_ENTRIES},\n * env-tunable via `CACHE_MEMORY_MAX_ENTRIES` resolved in the cache service) so a\n * process-shared instance (OM_BOOTSTRAP_CACHE, long-lived workers, memory-backed\n * CRUD list cache) cannot grow without limit on user-controllable key\n * cardinality. Recency is refreshed on read (Map re-insertion), the oldest\n * entries are evicted on write, and expired entries are reclaimed by an\n * amortized sweep every N writes \u2014 no per-instance timer, so the per-request\n * default stays leak-free (a per-instance setInterval would pin every request's\n * Maps for the process lifetime).\n */\nexport function createMemoryStrategy(options?: { defaultTtl?: number; maxEntries?: number }): CacheStrategy {\n const store = new Map<string, CacheEntry>()\n const tagIndex = new Map<string, Set<string>>() // tag -> Set of keys\n const defaultTtl = options?.defaultTtl\n const maxEntries = normalizeMaxEntries(options?.maxEntries)\n let writesSinceSweep = 0\n // Lightweight observability counters so operators can tell whether the bound\n // is actively protecting the process. Process-global for this instance, not\n // tenant-scoped; surfaced via stats().\n let evictions = 0\n let sweeps = 0\n let lastSweepReclaimed = 0\n\n function isExpired(entry: CacheEntry): boolean {\n if (entry.expiresAt === null) return false\n return Date.now() > entry.expiresAt\n }\n\n // LRU bookkeeping: re-insert on read so the most-recently-used entry moves\n // to the tail (Map preserves insertion order), mirroring the rbacDefaultCache\n // precedent; evictIfNeeded then drops from the head (least-recently-used).\n function touchKey(key: string, entry: CacheEntry): void {\n if (maxEntries === Number.POSITIVE_INFINITY) return\n store.delete(key)\n store.set(key, entry)\n }\n\n function evictIfNeeded(): void {\n if (maxEntries === Number.POSITIVE_INFINITY) return\n while (store.size > maxEntries) {\n const oldest = store.keys().next().value\n if (typeof oldest !== 'string') break\n const entry = store.get(oldest)\n store.delete(oldest)\n if (entry) removeFromTagIndex(oldest, entry.tags)\n evictions++\n }\n }\n\n function cleanupExpiredEntry(key: string, entry: CacheEntry): void {\n store.delete(key)\n // Remove from tag index\n for (const tag of entry.tags) {\n const keys = tagIndex.get(tag)\n if (keys) {\n keys.delete(key)\n if (keys.size === 0) {\n tagIndex.delete(tag)\n }\n }\n }\n }\n\n function addToTagIndex(key: string, tags: string[]): void {\n for (const tag of tags) {\n if (!tagIndex.has(tag)) {\n tagIndex.set(tag, new Set())\n }\n tagIndex.get(tag)!.add(key)\n }\n }\n\n function removeFromTagIndex(key: string, tags: string[]): void {\n for (const tag of tags) {\n const keys = tagIndex.get(tag)\n if (keys) {\n keys.delete(key)\n if (keys.size === 0) {\n tagIndex.delete(tag)\n }\n }\n }\n }\n\n // Amortized reclamation of already-expired entries. Runs every N writes\n // instead of on a timer, keeping the no-shared-state property that makes the\n // per-request default safe. Independent of the LRU cap so expired-but-cold\n // entries are reclaimed even when the store stays under `maxEntries`. The\n // scan is budgeted (EXPIRED_SWEEP_MAX_SCAN entries from the LRU head per pass)\n // so it stays O(budget) on large stores instead of scanning every entry.\n function sweepExpiredIfDue(): void {\n if (++writesSinceSweep < EXPIRED_SWEEP_WRITE_INTERVAL) return\n writesSinceSweep = 0\n sweeps++\n let scanned = 0\n let reclaimed = 0\n for (const [key, entry] of store.entries()) {\n if (scanned >= EXPIRED_SWEEP_MAX_SCAN) break\n scanned++\n if (isExpired(entry)) {\n cleanupExpiredEntry(key, entry)\n reclaimed++\n }\n }\n lastSweepReclaimed = reclaimed\n }\n\n const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {\n const entry = store.get(key)\n if (!entry) return null\n\n if (isExpired(entry)) {\n if (options?.returnExpired) {\n return entry.value\n }\n cleanupExpiredEntry(key, entry)\n return null\n }\n\n touchKey(key, entry)\n return entry.value\n }\n\n const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {\n // Remove old entry from tag index if it exists\n const oldEntry = store.get(key)\n if (oldEntry) {\n removeFromTagIndex(key, oldEntry.tags)\n }\n\n const ttl = options?.ttl ?? defaultTtl\n const tags = options?.tags || []\n const expiresAt = ttl ? Date.now() + ttl : null\n\n const entry: CacheEntry = {\n key,\n value,\n tags,\n expiresAt,\n createdAt: Date.now(),\n }\n\n store.set(key, entry)\n addToTagIndex(key, tags)\n sweepExpiredIfDue()\n evictIfNeeded()\n }\n\n const has = async (key: string): Promise<boolean> => {\n const entry = store.get(key)\n if (!entry) return false\n if (isExpired(entry)) {\n cleanupExpiredEntry(key, entry)\n return false\n }\n return true\n }\n\n const deleteKey = async (key: string): Promise<boolean> => {\n const entry = store.get(key)\n if (!entry) return false\n\n removeFromTagIndex(key, entry.tags)\n return store.delete(key)\n }\n\n const deleteByTags = async (tags: string[]): Promise<number> => {\n const keysToDelete = new Set<string>()\n\n // Collect all keys that have any of the specified tags\n for (const tag of tags) {\n const keys = tagIndex.get(tag)\n if (keys) {\n for (const key of keys) {\n keysToDelete.add(key)\n }\n }\n }\n\n // Delete all collected keys\n let deleted = 0\n for (const key of keysToDelete) {\n const success = await deleteKey(key)\n if (success) deleted++\n }\n\n return deleted\n }\n\n const clear = async (): Promise<number> => {\n const size = store.size\n store.clear()\n tagIndex.clear()\n return size\n }\n\n const keys = async (pattern?: string): Promise<string[]> => {\n const allKeys = Array.from(store.keys())\n if (!pattern) return allKeys\n return allKeys.filter((key) => matchCacheKeyPattern(key, pattern))\n }\n\n const stats = async (): Promise<{\n size: number\n expired: number\n evictions: number\n sweeps: number\n lastSweepReclaimed: number\n }> => {\n let expired = 0\n for (const entry of store.values()) {\n if (isExpired(entry)) {\n expired++\n }\n }\n return { size: store.size, expired, evictions, sweeps, lastSweepReclaimed }\n }\n\n const cleanup = async (): Promise<number> => {\n let removed = 0\n for (const [key, entry] of store.entries()) {\n if (isExpired(entry)) {\n cleanupExpiredEntry(key, entry)\n removed++\n }\n }\n return removed\n }\n\n return {\n get,\n set,\n has,\n delete: deleteKey,\n deleteByTags,\n clear,\n keys,\n stats,\n cleanup,\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,4BAA4B;AAErC,MAAM,+BAA+B;AAUrC,MAAM,yBAA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AK,MAAM,KAAK,CAAC;AACvC,QAAI,CAAC,QAAS,QAAO;AACrB,WAAO,QAAQ,OAAO,CAAC,QAAQ,qBAAqB,KAAK,OAAO,CAAC;AAAA,EACnE;AAEA,QAAM,QAAQ,YAMR;AACJ,QAAI,UAAU;AACd,eAAW,SAAS,MAAM,OAAO,GAAG;AAClC,UAAI,UAAU,KAAK,GAAG;AACpB;AAAA,MACF;AAAA,IACF;AACA,WAAO,EAAE,MAAM,MAAM,MAAM,SAAS,WAAW,QAAQ,mBAAmB;AAAA,EAC5E;AAEA,QAAM,UAAU,YAA6B;AAC3C,QAAI,UAAU;AACd,eAAW,CAAC,KAAK,KAAK,KAAK,MAAM,QAAQ,GAAG;AAC1C,UAAI,UAAU,KAAK,GAAG;AACpB,4BAAoB,KAAK,KAAK;AAC9B;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
+ "names": ["keys", "options"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@open-mercato/cache-provider-memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.11.1-develop.8687.1.adb16f62b3",
4
+ "description": "Stock memory cache factory for Open Mercato",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "node build.mjs",
16
+ "watch": "node watch.mjs",
17
+ "typecheck": "tsc --noEmit"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "^26.4.0",
21
+ "typescript": "7.0.2"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/open-mercato/open-mercato",
29
+ "directory": "packages/cache-provider-memory"
30
+ },
31
+ "dependencies": {
32
+ "@open-mercato/cache-provider-kit": "0.11.1-develop.8687.1.adb16f62b3"
33
+ },
34
+ "stableVersion": "0.11.0"
6
35
  }
package/src/index.ts ADDED
@@ -0,0 +1,275 @@
1
+ import type { CacheStrategy, CacheEntry, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'
2
+ import { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'
3
+
4
+ const EXPIRED_SWEEP_WRITE_INTERVAL = 256
5
+
6
+ /**
7
+ * Upper bound on entries scanned by a single amortized sweep pass. Keeps the
8
+ * sweep O(budget) instead of O(store size) so a large, hot store never pays a
9
+ * full-store scan latency spike on the `set()` that crosses the sweep interval.
10
+ * The scan walks from the LRU head, where expired-and-cold entries accumulate;
11
+ * anything beyond the budget is reclaimed on a later sweep, on access, by LRU
12
+ * eviction once the cap is exceeded, or by an explicit `cleanup()`.
13
+ */
14
+ const EXPIRED_SWEEP_MAX_SCAN = 1_000
15
+
16
+ /**
17
+ * Default upper bound on the number of entries a memory cache retains.
18
+ * Bounds memory for long-lived (process-wide) instances; LRU eviction drops
19
+ * the least-recently-used entries once the cap is exceeded. Override via the
20
+ * `maxEntries` option (or `CACHE_MEMORY_MAX_ENTRIES`); a non-positive value
21
+ * disables the cap (unbounded — only safe for short-lived instances).
22
+ */
23
+ export const DEFAULT_MEMORY_MAX_ENTRIES = 50_000
24
+
25
+ function normalizeMaxEntries(raw?: number): number {
26
+ if (raw === undefined) return DEFAULT_MEMORY_MAX_ENTRIES
27
+ if (!Number.isFinite(raw) || raw <= 0) return Number.POSITIVE_INFINITY
28
+ return Math.floor(raw)
29
+ }
30
+
31
+ /**
32
+ * In-memory cache strategy with tag support.
33
+ * Fast but data is lost when process restarts.
34
+ *
35
+ * Bounded by an LRU cap (`maxEntries`, default {@link DEFAULT_MEMORY_MAX_ENTRIES},
36
+ * env-tunable via `CACHE_MEMORY_MAX_ENTRIES` resolved in the cache service) so a
37
+ * process-shared instance (OM_BOOTSTRAP_CACHE, long-lived workers, memory-backed
38
+ * CRUD list cache) cannot grow without limit on user-controllable key
39
+ * cardinality. Recency is refreshed on read (Map re-insertion), the oldest
40
+ * entries are evicted on write, and expired entries are reclaimed by an
41
+ * amortized sweep every N writes — no per-instance timer, so the per-request
42
+ * default stays leak-free (a per-instance setInterval would pin every request's
43
+ * Maps for the process lifetime).
44
+ */
45
+ export function createMemoryStrategy(options?: { defaultTtl?: number; maxEntries?: number }): CacheStrategy {
46
+ const store = new Map<string, CacheEntry>()
47
+ const tagIndex = new Map<string, Set<string>>() // tag -> Set of keys
48
+ const defaultTtl = options?.defaultTtl
49
+ const maxEntries = normalizeMaxEntries(options?.maxEntries)
50
+ let writesSinceSweep = 0
51
+ // Lightweight observability counters so operators can tell whether the bound
52
+ // is actively protecting the process. Process-global for this instance, not
53
+ // tenant-scoped; surfaced via stats().
54
+ let evictions = 0
55
+ let sweeps = 0
56
+ let lastSweepReclaimed = 0
57
+
58
+ function isExpired(entry: CacheEntry): boolean {
59
+ if (entry.expiresAt === null) return false
60
+ return Date.now() > entry.expiresAt
61
+ }
62
+
63
+ // LRU bookkeeping: re-insert on read so the most-recently-used entry moves
64
+ // to the tail (Map preserves insertion order), mirroring the rbacDefaultCache
65
+ // precedent; evictIfNeeded then drops from the head (least-recently-used).
66
+ function touchKey(key: string, entry: CacheEntry): void {
67
+ if (maxEntries === Number.POSITIVE_INFINITY) return
68
+ store.delete(key)
69
+ store.set(key, entry)
70
+ }
71
+
72
+ function evictIfNeeded(): void {
73
+ if (maxEntries === Number.POSITIVE_INFINITY) return
74
+ while (store.size > maxEntries) {
75
+ const oldest = store.keys().next().value
76
+ if (typeof oldest !== 'string') break
77
+ const entry = store.get(oldest)
78
+ store.delete(oldest)
79
+ if (entry) removeFromTagIndex(oldest, entry.tags)
80
+ evictions++
81
+ }
82
+ }
83
+
84
+ function cleanupExpiredEntry(key: string, entry: CacheEntry): void {
85
+ store.delete(key)
86
+ // Remove from tag index
87
+ for (const tag of entry.tags) {
88
+ const keys = tagIndex.get(tag)
89
+ if (keys) {
90
+ keys.delete(key)
91
+ if (keys.size === 0) {
92
+ tagIndex.delete(tag)
93
+ }
94
+ }
95
+ }
96
+ }
97
+
98
+ function addToTagIndex(key: string, tags: string[]): void {
99
+ for (const tag of tags) {
100
+ if (!tagIndex.has(tag)) {
101
+ tagIndex.set(tag, new Set())
102
+ }
103
+ tagIndex.get(tag)!.add(key)
104
+ }
105
+ }
106
+
107
+ function removeFromTagIndex(key: string, tags: string[]): void {
108
+ for (const tag of tags) {
109
+ const keys = tagIndex.get(tag)
110
+ if (keys) {
111
+ keys.delete(key)
112
+ if (keys.size === 0) {
113
+ tagIndex.delete(tag)
114
+ }
115
+ }
116
+ }
117
+ }
118
+
119
+ // Amortized reclamation of already-expired entries. Runs every N writes
120
+ // instead of on a timer, keeping the no-shared-state property that makes the
121
+ // per-request default safe. Independent of the LRU cap so expired-but-cold
122
+ // entries are reclaimed even when the store stays under `maxEntries`. The
123
+ // scan is budgeted (EXPIRED_SWEEP_MAX_SCAN entries from the LRU head per pass)
124
+ // so it stays O(budget) on large stores instead of scanning every entry.
125
+ function sweepExpiredIfDue(): void {
126
+ if (++writesSinceSweep < EXPIRED_SWEEP_WRITE_INTERVAL) return
127
+ writesSinceSweep = 0
128
+ sweeps++
129
+ let scanned = 0
130
+ let reclaimed = 0
131
+ for (const [key, entry] of store.entries()) {
132
+ if (scanned >= EXPIRED_SWEEP_MAX_SCAN) break
133
+ scanned++
134
+ if (isExpired(entry)) {
135
+ cleanupExpiredEntry(key, entry)
136
+ reclaimed++
137
+ }
138
+ }
139
+ lastSweepReclaimed = reclaimed
140
+ }
141
+
142
+ const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {
143
+ const entry = store.get(key)
144
+ if (!entry) return null
145
+
146
+ if (isExpired(entry)) {
147
+ if (options?.returnExpired) {
148
+ return entry.value
149
+ }
150
+ cleanupExpiredEntry(key, entry)
151
+ return null
152
+ }
153
+
154
+ touchKey(key, entry)
155
+ return entry.value
156
+ }
157
+
158
+ const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {
159
+ // Remove old entry from tag index if it exists
160
+ const oldEntry = store.get(key)
161
+ if (oldEntry) {
162
+ removeFromTagIndex(key, oldEntry.tags)
163
+ }
164
+
165
+ const ttl = options?.ttl ?? defaultTtl
166
+ const tags = options?.tags || []
167
+ const expiresAt = ttl ? Date.now() + ttl : null
168
+
169
+ const entry: CacheEntry = {
170
+ key,
171
+ value,
172
+ tags,
173
+ expiresAt,
174
+ createdAt: Date.now(),
175
+ }
176
+
177
+ store.set(key, entry)
178
+ addToTagIndex(key, tags)
179
+ sweepExpiredIfDue()
180
+ evictIfNeeded()
181
+ }
182
+
183
+ const has = async (key: string): Promise<boolean> => {
184
+ const entry = store.get(key)
185
+ if (!entry) return false
186
+ if (isExpired(entry)) {
187
+ cleanupExpiredEntry(key, entry)
188
+ return false
189
+ }
190
+ return true
191
+ }
192
+
193
+ const deleteKey = async (key: string): Promise<boolean> => {
194
+ const entry = store.get(key)
195
+ if (!entry) return false
196
+
197
+ removeFromTagIndex(key, entry.tags)
198
+ return store.delete(key)
199
+ }
200
+
201
+ const deleteByTags = async (tags: string[]): Promise<number> => {
202
+ const keysToDelete = new Set<string>()
203
+
204
+ // Collect all keys that have any of the specified tags
205
+ for (const tag of tags) {
206
+ const keys = tagIndex.get(tag)
207
+ if (keys) {
208
+ for (const key of keys) {
209
+ keysToDelete.add(key)
210
+ }
211
+ }
212
+ }
213
+
214
+ // Delete all collected keys
215
+ let deleted = 0
216
+ for (const key of keysToDelete) {
217
+ const success = await deleteKey(key)
218
+ if (success) deleted++
219
+ }
220
+
221
+ return deleted
222
+ }
223
+
224
+ const clear = async (): Promise<number> => {
225
+ const size = store.size
226
+ store.clear()
227
+ tagIndex.clear()
228
+ return size
229
+ }
230
+
231
+ const keys = async (pattern?: string): Promise<string[]> => {
232
+ const allKeys = Array.from(store.keys())
233
+ if (!pattern) return allKeys
234
+ return allKeys.filter((key) => matchCacheKeyPattern(key, pattern))
235
+ }
236
+
237
+ const stats = async (): Promise<{
238
+ size: number
239
+ expired: number
240
+ evictions: number
241
+ sweeps: number
242
+ lastSweepReclaimed: number
243
+ }> => {
244
+ let expired = 0
245
+ for (const entry of store.values()) {
246
+ if (isExpired(entry)) {
247
+ expired++
248
+ }
249
+ }
250
+ return { size: store.size, expired, evictions, sweeps, lastSweepReclaimed }
251
+ }
252
+
253
+ const cleanup = async (): Promise<number> => {
254
+ let removed = 0
255
+ for (const [key, entry] of store.entries()) {
256
+ if (isExpired(entry)) {
257
+ cleanupExpiredEntry(key, entry)
258
+ removed++
259
+ }
260
+ }
261
+ return removed
262
+ }
263
+
264
+ return {
265
+ get,
266
+ set,
267
+ has,
268
+ delete: deleteKey,
269
+ deleteByTags,
270
+ clear,
271
+ keys,
272
+ stats,
273
+ cleanup,
274
+ }
275
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "../../tsconfig.base.json",
4
+ "compilerOptions": {
5
+ "noEmit": true,
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src/**/*"],
9
+ "exclude": ["node_modules", "dist", "**/__tests__/**"]
10
+ }
package/watch.mjs ADDED
@@ -0,0 +1,6 @@
1
+ import { watch } from '../../scripts/watch.mjs'
2
+ import { dirname } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const __dirname = dirname(fileURLToPath(import.meta.url))
6
+ watch(__dirname)
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.