tricache 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -0,0 +1,1498 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/edge/index.ts
21
+ var edge_exports = {};
22
+ __export(edge_exports, {
23
+ CloudflareDOStorageAdapter: () => CloudflareDOStorageAdapter,
24
+ CloudflareKVAdapter: () => CloudflareKVAdapter,
25
+ EdgeCacheService: () => EdgeCacheService,
26
+ Murmur3BloomFilter: () => Murmur3BloomFilter,
27
+ UpstashRedisAdapter: () => UpstashRedisAdapter,
28
+ WasmBloomFilter: () => WasmBloomFilter,
29
+ WebCryptoEncryption: () => WebCryptoEncryption,
30
+ base64ToUint8Array: () => base64ToUint8Array,
31
+ buildEdgeDeterministicKey: () => buildEdgeDeterministicKey,
32
+ computeEdgeETag: () => computeEdgeETag,
33
+ honoEdgeCache: () => honoEdgeCache,
34
+ murmur3_32: () => murmur3_32,
35
+ uint8ArrayToBase64: () => uint8ArrayToBase64,
36
+ uint8ArrayToUtf8: () => uint8ArrayToUtf8,
37
+ utf8ToUint8Array: () => utf8ToUint8Array
38
+ });
39
+ module.exports = __toCommonJS(edge_exports);
40
+
41
+ // src/edge/utils/base64.ts
42
+ var CHUNK_SIZE = 8192;
43
+ function uint8ArrayToBase64(bytes) {
44
+ const modernBytes = bytes;
45
+ if (typeof modernBytes.toBase64 === "function") {
46
+ return modernBytes.toBase64();
47
+ }
48
+ let binary = "";
49
+ const len = bytes.length;
50
+ for (let i = 0; i < len; i += CHUNK_SIZE) {
51
+ const chunk = bytes.subarray(i, Math.min(i + CHUNK_SIZE, len));
52
+ binary += String.fromCharCode(...chunk);
53
+ }
54
+ return globalThis.btoa(binary);
55
+ }
56
+ function base64ToUint8Array(base64) {
57
+ const modernU8 = Uint8Array;
58
+ if (typeof modernU8.fromBase64 === "function") {
59
+ return modernU8.fromBase64(base64);
60
+ }
61
+ const binary = globalThis.atob(base64);
62
+ const len = binary.length;
63
+ const bytes = new Uint8Array(len);
64
+ for (let i = 0; i < len; i++) {
65
+ bytes[i] = binary.charCodeAt(i);
66
+ }
67
+ return bytes;
68
+ }
69
+ function utf8ToUint8Array(str) {
70
+ return new TextEncoder().encode(str);
71
+ }
72
+ function uint8ArrayToUtf8(bytes) {
73
+ return new TextDecoder().decode(bytes);
74
+ }
75
+
76
+ // src/edge/crypto.ts
77
+ var PREFIX_256 = "enc:v1:";
78
+ var PREFIX_128 = "a128:v1:";
79
+ var IV_LEN = 12;
80
+ var TAG_LEN = 16;
81
+ var HEADER_LEN = IV_LEN + TAG_LEN;
82
+ var WebCryptoEncryption = class {
83
+ isEnabled;
84
+ mode;
85
+ keyPromise = null;
86
+ prevKeyPromise = null;
87
+ constructor(options) {
88
+ if (!options?.keyBase64) {
89
+ this.isEnabled = false;
90
+ this.mode = "aes-256-gcm";
91
+ return;
92
+ }
93
+ this.isEnabled = true;
94
+ this.mode = options.mode ?? "aes-256-gcm";
95
+ const expectedBytes = this.mode === "aes-256-gcm" ? 32 : 16;
96
+ const rawKey = base64ToUint8Array(options.keyBase64);
97
+ if (rawKey.length !== expectedBytes) {
98
+ throw new Error(
99
+ `WebCryptoEncryption: key length mismatch for ${this.mode}. Expected ${expectedBytes} bytes, received ${rawKey.length} bytes.`
100
+ );
101
+ }
102
+ this.keyPromise = this._importKey(rawKey);
103
+ if (options.prevKeyBase64) {
104
+ const rawPrevKey = base64ToUint8Array(options.prevKeyBase64);
105
+ if (rawPrevKey.length === expectedBytes) {
106
+ this.prevKeyPromise = this._importKey(rawPrevKey);
107
+ }
108
+ }
109
+ }
110
+ async _importKey(rawBytes) {
111
+ const cryptoSubtle = globalThis.crypto?.subtle;
112
+ if (!cryptoSubtle) {
113
+ throw new Error("WebCryptoEncryption: globalThis.crypto.subtle is not available in this environment.");
114
+ }
115
+ const keyBuf = rawBytes.buffer.slice(rawBytes.byteOffset, rawBytes.byteOffset + rawBytes.byteLength);
116
+ return cryptoSubtle.importKey(
117
+ "raw",
118
+ keyBuf,
119
+ { name: "AES-GCM" },
120
+ false,
121
+ ["encrypt", "decrypt"]
122
+ );
123
+ }
124
+ /**
125
+ * Encrypts a plaintext string into a TriCache standard wire envelope.
126
+ * Format: `enc:v1:<base64(IV[12] | Tag[16] | Ciphertext)>`
127
+ */
128
+ async encrypt(plaintext) {
129
+ if (!this.isEnabled || !this.keyPromise) return plaintext;
130
+ const cryptoObj = globalThis.crypto;
131
+ const key = await this.keyPromise;
132
+ const iv = cryptoObj.getRandomValues(new Uint8Array(IV_LEN));
133
+ const plaintextBytes = utf8ToUint8Array(plaintext);
134
+ const encryptedBuf = await cryptoObj.subtle.encrypt(
135
+ {
136
+ name: "AES-GCM",
137
+ iv: iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength),
138
+ tagLength: 128
139
+ },
140
+ key,
141
+ plaintextBytes.buffer.slice(plaintextBytes.byteOffset, plaintextBytes.byteOffset + plaintextBytes.byteLength)
142
+ );
143
+ const encryptedBytes = new Uint8Array(encryptedBuf);
144
+ const ctLen = encryptedBytes.length - TAG_LEN;
145
+ const ciphertext = encryptedBytes.subarray(0, ctLen);
146
+ const tag = encryptedBytes.subarray(ctLen);
147
+ const envelope = new Uint8Array(HEADER_LEN + ctLen);
148
+ envelope.set(iv, 0);
149
+ envelope.set(tag, IV_LEN);
150
+ envelope.set(ciphertext, HEADER_LEN);
151
+ const prefix = this.mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
152
+ return prefix + uint8ArrayToBase64(envelope);
153
+ }
154
+ /**
155
+ * Decrypts a TriCache standard wire envelope into plaintext.
156
+ * Handles envelopes created by both WebCryptoEncryption and Node.js CacheEncryption.
157
+ */
158
+ async decrypt(envelopeStr) {
159
+ if (!this.isEnabled || !this.keyPromise) return envelopeStr;
160
+ let base64Data;
161
+ if (envelopeStr.startsWith(PREFIX_256)) {
162
+ base64Data = envelopeStr.slice(PREFIX_256.length);
163
+ } else if (envelopeStr.startsWith(PREFIX_128)) {
164
+ base64Data = envelopeStr.slice(PREFIX_128.length);
165
+ } else {
166
+ return envelopeStr;
167
+ }
168
+ const envelopeBytes = base64ToUint8Array(base64Data);
169
+ if (envelopeBytes.length < HEADER_LEN) {
170
+ throw new Error(`WebCryptoEncryption: malformed envelope, length ${envelopeBytes.length} < header ${HEADER_LEN}`);
171
+ }
172
+ try {
173
+ const activeKey = await this.keyPromise;
174
+ return await this._decryptWithKey(activeKey, envelopeBytes);
175
+ } catch (primaryErr) {
176
+ if (this.prevKeyPromise) {
177
+ try {
178
+ const prevKey = await this.prevKeyPromise;
179
+ return await this._decryptWithKey(prevKey, envelopeBytes);
180
+ } catch {
181
+ }
182
+ }
183
+ throw primaryErr;
184
+ }
185
+ }
186
+ async _decryptWithKey(key, envelopeBytes) {
187
+ const cryptoSubtle = globalThis.crypto.subtle;
188
+ const iv = envelopeBytes.subarray(0, IV_LEN);
189
+ const tag = envelopeBytes.subarray(IV_LEN, HEADER_LEN);
190
+ const ciphertext = envelopeBytes.subarray(HEADER_LEN);
191
+ const webCryptoInput = new Uint8Array(ciphertext.length + TAG_LEN);
192
+ webCryptoInput.set(ciphertext, 0);
193
+ webCryptoInput.set(tag, ciphertext.length);
194
+ const ivBuf = iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength);
195
+ const dataBuf = webCryptoInput.buffer.slice(webCryptoInput.byteOffset, webCryptoInput.byteOffset + webCryptoInput.byteLength);
196
+ const decryptedBuf = await cryptoSubtle.decrypt(
197
+ {
198
+ name: "AES-GCM",
199
+ iv: ivBuf,
200
+ tagLength: 128
201
+ },
202
+ key,
203
+ dataBuf
204
+ );
205
+ return uint8ArrayToUtf8(new Uint8Array(decryptedBuf));
206
+ }
207
+ };
208
+
209
+ // src/wasm/bloom-filter-wasm.ts
210
+ var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
211
+ var KEY_STAGING_OFFSET = 2e4;
212
+ var MAX_KEY_BYTES = 512;
213
+ var BLOOM_WASM_MODULE = new WebAssembly.Module(
214
+ base64ToUint8Array(BLOOM_WASM_BASE64)
215
+ );
216
+ var WasmBloomFilter = class {
217
+ exports;
218
+ mem;
219
+ stagingTarget;
220
+ encoder = new TextEncoder();
221
+ numBits = 1e5;
222
+ /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
223
+ _maxCapacity;
224
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
225
+ _insertionCount = 0;
226
+ constructor() {
227
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
228
+ this.exports = instance.exports;
229
+ this.mem = new Uint8Array(this.exports.memory.buffer);
230
+ this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
231
+ const k = 7, p = 0.01;
232
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
233
+ }
234
+ writeKey(key) {
235
+ if (key.length === 0) return 0;
236
+ return this.encoder.encodeInto(key, this.stagingTarget).written;
237
+ }
238
+ add(key) {
239
+ const len = this.writeKey(key);
240
+ if (len === 0) return;
241
+ this.exports.add(KEY_STAGING_OFFSET, len);
242
+ this._insertionCount++;
243
+ }
244
+ mightContain(key) {
245
+ const len = this.writeKey(key);
246
+ if (len === 0) return true;
247
+ return this.exports.mightContain(KEY_STAGING_OFFSET, len) === 1;
248
+ }
249
+ reset() {
250
+ this.exports.reset();
251
+ this._insertionCount = 0;
252
+ }
253
+ rebuild(keys) {
254
+ this.reset();
255
+ for (const key of keys) this.add(key);
256
+ }
257
+ get stats() {
258
+ const bitsSet = this.exports.countBits();
259
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
260
+ }
261
+ /** Number of add() calls since last reset/rebuild. */
262
+ get insertions() {
263
+ return this._insertionCount;
264
+ }
265
+ /**
266
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
267
+ * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
268
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
269
+ */
270
+ get maxCapacity() {
271
+ return this._maxCapacity;
272
+ }
273
+ };
274
+
275
+ // src/edge/utils/murmur3.ts
276
+ function murmur3_32(key, seed = 0) {
277
+ const c1 = 3432918353;
278
+ const c2 = 461845907;
279
+ let h1 = seed >>> 0;
280
+ const len = key.length;
281
+ const remainder = len & 1;
282
+ const bytes = len - remainder;
283
+ for (let i = 0; i < bytes; i += 2) {
284
+ let k1 = key.charCodeAt(i) & 65535 | (key.charCodeAt(i + 1) & 65535) << 16;
285
+ k1 = Math.imul(k1, c1);
286
+ k1 = k1 << 15 | k1 >>> 17;
287
+ k1 = Math.imul(k1, c2);
288
+ h1 ^= k1;
289
+ h1 = h1 << 13 | h1 >>> 19;
290
+ h1 = Math.imul(h1, 5) + 3864292196 >>> 0;
291
+ }
292
+ if (remainder === 1) {
293
+ let k1 = key.charCodeAt(bytes) & 65535;
294
+ k1 = Math.imul(k1, c1);
295
+ k1 = k1 << 15 | k1 >>> 17;
296
+ k1 = Math.imul(k1, c2);
297
+ h1 ^= k1;
298
+ }
299
+ h1 ^= len;
300
+ h1 ^= h1 >>> 16;
301
+ h1 = Math.imul(h1, 2246822507);
302
+ h1 ^= h1 >>> 13;
303
+ h1 = Math.imul(h1, 3266489909);
304
+ h1 ^= h1 >>> 16;
305
+ return h1 >>> 0;
306
+ }
307
+ var Murmur3BloomFilter = class {
308
+ bits;
309
+ numBits;
310
+ k;
311
+ _maxCapacity;
312
+ _insertionCount = 0;
313
+ /**
314
+ * @param numBits Total bits in the filter (default: 100,000 bits = 12.5 KB)
315
+ * @param k Number of hash probes per key (default: 7, targeting ~1% FPR at 2,000 items)
316
+ */
317
+ constructor(numBits = 1e5, k = 7) {
318
+ this.numBits = Math.max(64, numBits);
319
+ this.k = Math.max(1, k);
320
+ this.bits = new Uint8Array(Math.ceil(this.numBits / 8));
321
+ const p = 0.01;
322
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / this.k)) / this.k);
323
+ }
324
+ setBit(bitIndex) {
325
+ const byteIndex = bitIndex >>> 3;
326
+ this.bits[byteIndex] |= 1 << (bitIndex & 7);
327
+ }
328
+ getBit(bitIndex) {
329
+ const byteIndex = bitIndex >>> 3;
330
+ return (this.bits[byteIndex] & 1 << (bitIndex & 7)) !== 0;
331
+ }
332
+ /**
333
+ * Adds a key to the Bloom filter.
334
+ */
335
+ add(key) {
336
+ if (key.length === 0) return;
337
+ const h1 = murmur3_32(key, 0);
338
+ const h2 = murmur3_32(key, 2538058380) || 1;
339
+ const m = this.numBits;
340
+ for (let i = 0; i < this.k; i++) {
341
+ const bit = (h1 + Math.imul(i, h2) >>> 0) % m;
342
+ this.setBit(bit);
343
+ }
344
+ this._insertionCount++;
345
+ }
346
+ /**
347
+ * Tests whether a key might be in the set.
348
+ * Returns `false` for guaranteed misses, `true` for possible hits.
349
+ */
350
+ mightContain(key) {
351
+ if (key.length === 0) return true;
352
+ const h1 = murmur3_32(key, 0);
353
+ const h2 = murmur3_32(key, 2538058380) || 1;
354
+ const m = this.numBits;
355
+ for (let i = 0; i < this.k; i++) {
356
+ const bit = (h1 + Math.imul(i, h2) >>> 0) % m;
357
+ if (!this.getBit(bit)) return false;
358
+ }
359
+ return true;
360
+ }
361
+ /**
362
+ * Clears all set bits in the filter.
363
+ */
364
+ reset() {
365
+ this.bits.fill(0);
366
+ this._insertionCount = 0;
367
+ }
368
+ /**
369
+ * Rebuilds the filter from a collection of keys.
370
+ */
371
+ rebuild(keys) {
372
+ this.reset();
373
+ for (const key of keys) {
374
+ this.add(key);
375
+ }
376
+ }
377
+ /**
378
+ * Total add() calls since creation or last reset.
379
+ */
380
+ get insertions() {
381
+ return this._insertionCount;
382
+ }
383
+ /**
384
+ * Maximum safe insertions before false positive rate exceeds target ~1%.
385
+ */
386
+ get maxCapacity() {
387
+ return this._maxCapacity;
388
+ }
389
+ /**
390
+ * Returns current bit saturation metrics.
391
+ */
392
+ get stats() {
393
+ let bitsSet = 0;
394
+ const len = this.bits.length;
395
+ for (let i = 0; i < len; i++) {
396
+ let b = this.bits[i];
397
+ while (b) {
398
+ bitsSet++;
399
+ b &= b - 1;
400
+ }
401
+ }
402
+ return {
403
+ bitsSet,
404
+ fillFactor: bitsSet / this.numBits
405
+ };
406
+ }
407
+ };
408
+
409
+ // src/edge/cache.ts
410
+ var EdgeCacheService = class {
411
+ maxKeys;
412
+ maxBytes;
413
+ defaultTtl;
414
+ namespace;
415
+ remoteStorage;
416
+ enc;
417
+ tracer;
418
+ bloomFilter;
419
+ // L1 Dual-bounded LRU
420
+ l1 = /* @__PURE__ */ new Map();
421
+ currentBytes = 0;
422
+ // Single-flight in-flight stampede coalescing map
423
+ inflight = /* @__PURE__ */ new Map();
424
+ // Tag indexing for edge
425
+ tagIndex = /* @__PURE__ */ new Map();
426
+ // Tag version in-isolate cache with 800ms micro-TTL (prevents HTTP fetch amplification on L1 hits)
427
+ tagVersionCache = /* @__PURE__ */ new Map();
428
+ tagVersionTtlMs = 800;
429
+ constructor(options) {
430
+ this.maxKeys = options?.maxKeys ?? 1e4;
431
+ this.maxBytes = options?.maxBytes ?? 32 * 1024 * 1024;
432
+ this.defaultTtl = options?.defaultTtlSeconds ?? 300;
433
+ this.namespace = options?.namespace?.trim() ?? "";
434
+ this.remoteStorage = options?.remoteStorage ?? null;
435
+ this.tracer = options?.tracer ?? null;
436
+ this.enc = new WebCryptoEncryption(options?.encryption);
437
+ if (options?.bloomFilter === true) {
438
+ try {
439
+ this.bloomFilter = new WasmBloomFilter();
440
+ } catch {
441
+ this.bloomFilter = new Murmur3BloomFilter();
442
+ }
443
+ } else if (options?.bloomFilter) {
444
+ this.bloomFilter = options.bloomFilter;
445
+ } else {
446
+ this.bloomFilter = null;
447
+ }
448
+ }
449
+ /**
450
+ * Active Bloom filter instance defending against cold miss penetration, or null.
451
+ */
452
+ get bloom() {
453
+ return this.bloomFilter;
454
+ }
455
+ nk(key) {
456
+ return this.namespace ? `${this.namespace}:${key}` : key;
457
+ }
458
+ _estimateBytes(key, serialized) {
459
+ return (key.length + serialized.length) * 2 + 64;
460
+ }
461
+ _evictIfNeeded(newBytes) {
462
+ while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
463
+ const oldestKey = this.l1.keys().next().value;
464
+ if (oldestKey === void 0) break;
465
+ this._deleteL1(oldestKey);
466
+ }
467
+ while (this.l1.size >= this.maxKeys) {
468
+ const oldestKey = this.l1.keys().next().value;
469
+ if (oldestKey === void 0) break;
470
+ this._deleteL1(oldestKey);
471
+ }
472
+ }
473
+ _deleteL1(k) {
474
+ const entry = this.l1.get(k);
475
+ if (entry) {
476
+ this.currentBytes = Math.max(0, this.currentBytes - entry.bytes);
477
+ this.l1.delete(k);
478
+ if (entry.tags) {
479
+ for (const tag of entry.tags) {
480
+ const s = this.tagIndex.get(tag);
481
+ if (s) {
482
+ s.delete(k);
483
+ if (s.size === 0) this.tagIndex.delete(tag);
484
+ }
485
+ }
486
+ }
487
+ }
488
+ }
489
+ _startSpan(name) {
490
+ if (this.tracer) {
491
+ const span = this.tracer.startSpan(name);
492
+ if (this.namespace) span.setAttribute("cache.namespace", this.namespace);
493
+ return span;
494
+ }
495
+ return {
496
+ setAttribute() {
497
+ return this;
498
+ },
499
+ setStatus() {
500
+ return this;
501
+ },
502
+ recordException() {
503
+ return this;
504
+ },
505
+ end() {
506
+ }
507
+ };
508
+ }
509
+ async _getTagVersion(tag) {
510
+ const cached = this.tagVersionCache.get(tag);
511
+ const now = Date.now();
512
+ if (cached && cached.expiresAt > now) {
513
+ return cached.version;
514
+ }
515
+ let version = 1;
516
+ if (this.remoteStorage) {
517
+ try {
518
+ if (typeof this.remoteStorage.getTagVersion === "function") {
519
+ version = await this.remoteStorage.getTagVersion(this.nk(tag));
520
+ } else {
521
+ const raw = await this.remoteStorage.get(this.nk(`tag_ver:${tag}`));
522
+ version = raw ? parseInt(raw, 10) || 1 : 1;
523
+ }
524
+ } catch {
525
+ version = cached?.version ?? 1;
526
+ }
527
+ } else {
528
+ version = cached?.version ?? 1;
529
+ }
530
+ this.tagVersionCache.set(tag, { version, expiresAt: now + this.tagVersionTtlMs });
531
+ return version;
532
+ }
533
+ async _batchGetTagVersions(tags) {
534
+ const now = Date.now();
535
+ const result = {};
536
+ const missingTags = [];
537
+ for (const t of tags) {
538
+ const c = this.tagVersionCache.get(t);
539
+ if (c && c.expiresAt > now) {
540
+ result[t] = c.version;
541
+ } else {
542
+ missingTags.push(t);
543
+ }
544
+ }
545
+ if (missingTags.length > 0 && this.remoteStorage) {
546
+ try {
547
+ if (typeof this.remoteStorage.batchGetTagVersions === "function") {
548
+ const nsTags = missingTags.map((t) => this.nk(t));
549
+ const remoteVersions = await this.remoteStorage.batchGetTagVersions(nsTags);
550
+ for (let i = 0; i < missingTags.length; i++) {
551
+ const t = missingTags[i];
552
+ const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
553
+ result[t] = v;
554
+ this.tagVersionCache.set(t, { version: v, expiresAt: now + this.tagVersionTtlMs });
555
+ }
556
+ } else {
557
+ await Promise.all(missingTags.map(async (t) => {
558
+ const v = await this._getTagVersion(t);
559
+ result[t] = v;
560
+ }));
561
+ }
562
+ } catch {
563
+ for (const t of missingTags) {
564
+ result[t] = this.tagVersionCache.get(t)?.version ?? 1;
565
+ }
566
+ }
567
+ } else {
568
+ for (const t of missingTags) {
569
+ result[t] = this.tagVersionCache.get(t)?.version ?? 1;
570
+ }
571
+ }
572
+ return result;
573
+ }
574
+ /**
575
+ * Reads or fetches a value by key.
576
+ */
577
+ async get(key, fetchFn, ttlSeconds, options) {
578
+ const span = this._startSpan("tricache.get");
579
+ span.setAttribute("cache.key", key);
580
+ const nsKey = this.nk(key);
581
+ const now = Date.now();
582
+ const resolvedTtl = ttlSeconds ?? this.defaultTtl;
583
+ try {
584
+ const l1Entry = this.l1.get(nsKey);
585
+ if (l1Entry) {
586
+ let isTagStale = false;
587
+ if (l1Entry.tagVersions) {
588
+ const tagNames = Object.keys(l1Entry.tagVersions);
589
+ const currentVers = await this._batchGetTagVersions(tagNames);
590
+ for (const tag of tagNames) {
591
+ if (currentVers[tag] > l1Entry.tagVersions[tag]) {
592
+ isTagStale = true;
593
+ break;
594
+ }
595
+ }
596
+ }
597
+ if (isTagStale) {
598
+ this._deleteL1(nsKey);
599
+ } else {
600
+ this.l1.delete(nsKey);
601
+ this.l1.set(nsKey, l1Entry);
602
+ if (l1Entry.expiresAt > now) {
603
+ span.setAttribute("cache.hit", true);
604
+ span.setAttribute("cache.item.tier", "memory");
605
+ span.setAttribute("cache.hit_tier", "l1");
606
+ return l1Entry.value;
607
+ }
608
+ if (l1Entry.staleUntil > now && fetchFn) {
609
+ span.setAttribute("cache.hit", true);
610
+ span.setAttribute("cache.item.tier", "memory");
611
+ span.setAttribute("cache.hit_tier", "l1");
612
+ span.setAttribute("cache.stale", true);
613
+ const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
614
+ if (options?.ctx?.waitUntil) {
615
+ options.ctx.waitUntil(revalPromise);
616
+ }
617
+ return l1Entry.value;
618
+ }
619
+ this._deleteL1(nsKey);
620
+ }
621
+ }
622
+ if (this.remoteStorage) {
623
+ if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
624
+ span.setAttribute("cache.bloom.filtered", true);
625
+ } else {
626
+ try {
627
+ const rawRemote = await this.remoteStorage.get(nsKey);
628
+ if (rawRemote !== null) {
629
+ const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
630
+ const parsedJson = JSON.parse(plain);
631
+ let parsed;
632
+ let activeTagVersions;
633
+ let isStaleRemote = false;
634
+ if (parsedJson && typeof parsedJson === "object" && "__t_val" in parsedJson && "__t_tv" in parsedJson) {
635
+ parsed = parsedJson.__t_val;
636
+ activeTagVersions = parsedJson.__t_tv;
637
+ const tagNames = Object.keys(activeTagVersions);
638
+ const currentVers = await this._batchGetTagVersions(tagNames);
639
+ for (const tag of tagNames) {
640
+ if (currentVers[tag] > activeTagVersions[tag]) {
641
+ isStaleRemote = true;
642
+ break;
643
+ }
644
+ }
645
+ } else {
646
+ parsed = parsedJson;
647
+ }
648
+ if (!isStaleRemote) {
649
+ await this.set(key, parsed, resolvedTtl, options);
650
+ span.setAttribute("cache.hit", true);
651
+ span.setAttribute("cache.item.tier", "remote");
652
+ span.setAttribute("cache.hit_tier", "l2");
653
+ return parsed;
654
+ }
655
+ }
656
+ } catch (remoteErr) {
657
+ span.recordException?.(remoteErr);
658
+ }
659
+ }
660
+ }
661
+ if (!fetchFn) {
662
+ span.setAttribute("cache.hit", false);
663
+ span.setAttribute("cache.hit_tier", "miss");
664
+ return null;
665
+ }
666
+ let inflightPromise = this.inflight.get(nsKey);
667
+ let coalesced = false;
668
+ if (inflightPromise) {
669
+ coalesced = true;
670
+ } else {
671
+ inflightPromise = (async () => {
672
+ try {
673
+ const fresh = await fetchFn();
674
+ await this.set(key, fresh, resolvedTtl, options);
675
+ return fresh;
676
+ } finally {
677
+ this.inflight.delete(nsKey);
678
+ }
679
+ })();
680
+ this.inflight.set(nsKey, inflightPromise);
681
+ }
682
+ span.setAttribute("cache.hit", coalesced);
683
+ span.setAttribute("cache.hit_tier", coalesced ? "l1" : "miss");
684
+ span.setAttribute("cache.stampede_coalesced", coalesced);
685
+ const result = await inflightPromise;
686
+ return result;
687
+ } catch (err) {
688
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
689
+ span.recordException?.(err);
690
+ throw err;
691
+ } finally {
692
+ span.end();
693
+ }
694
+ }
695
+ async _revalidate(key, fetchFn, ttl, options) {
696
+ const nsKey = this.nk(key);
697
+ if (this.inflight.has(nsKey)) return;
698
+ const task = (async () => {
699
+ try {
700
+ const fresh = await fetchFn();
701
+ await this.set(key, fresh, ttl, options);
702
+ } catch {
703
+ } finally {
704
+ this.inflight.delete(nsKey);
705
+ }
706
+ })();
707
+ this.inflight.set(nsKey, task);
708
+ await task;
709
+ }
710
+ /**
711
+ * Sets a value in the cache with an optional TTL and tags.
712
+ */
713
+ async set(key, value, ttlSeconds, options) {
714
+ const span = this._startSpan("tricache.set");
715
+ span.setAttribute("cache.key", key);
716
+ const nsKey = this.nk(key);
717
+ const resolvedTtl = ttlSeconds ?? this.defaultTtl;
718
+ const now = Date.now();
719
+ const swrSeconds = options?.swr ?? 0;
720
+ try {
721
+ let activeTagVersions;
722
+ if (options?.tags?.length) {
723
+ activeTagVersions = await this._batchGetTagVersions(options.tags);
724
+ }
725
+ const serialized = JSON.stringify(value);
726
+ const bytes = this._estimateBytes(nsKey, serialized);
727
+ this._deleteL1(nsKey);
728
+ this._evictIfNeeded(bytes);
729
+ const entry = {
730
+ value,
731
+ serialized,
732
+ bytes,
733
+ expiresAt: now + resolvedTtl * 1e3,
734
+ staleUntil: now + (resolvedTtl + swrSeconds) * 1e3,
735
+ tags: options?.tags,
736
+ tagVersions: activeTagVersions
737
+ };
738
+ this.l1.set(nsKey, entry);
739
+ this.currentBytes += bytes;
740
+ if (options?.tags) {
741
+ for (const tag of options.tags) {
742
+ let s = this.tagIndex.get(tag);
743
+ if (!s) {
744
+ s = /* @__PURE__ */ new Set();
745
+ this.tagIndex.set(tag, s);
746
+ }
747
+ s.add(nsKey);
748
+ }
749
+ }
750
+ if (this.remoteStorage) {
751
+ const toStoreRaw = activeTagVersions ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions }) : serialized;
752
+ const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
753
+ await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
754
+ }
755
+ if (this.bloomFilter) {
756
+ this.bloomFilter.add(nsKey);
757
+ }
758
+ } catch (err) {
759
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
760
+ span.recordException?.(err);
761
+ throw err;
762
+ } finally {
763
+ span.end();
764
+ }
765
+ }
766
+ /**
767
+ * Deletes a key from all tiers.
768
+ */
769
+ async delete(key) {
770
+ const span = this._startSpan("tricache.delete");
771
+ span.setAttribute("cache.key", key);
772
+ const nsKey = this.nk(key);
773
+ try {
774
+ this._deleteL1(nsKey);
775
+ if (this.remoteStorage) {
776
+ await this.remoteStorage.delete(nsKey);
777
+ }
778
+ } catch (err) {
779
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
780
+ span.recordException?.(err);
781
+ throw err;
782
+ } finally {
783
+ span.end();
784
+ }
785
+ }
786
+ /**
787
+ * Invalidates all cached entries associated with a tag.
788
+ */
789
+ async invalidateTag(tag) {
790
+ const span = this._startSpan("tricache.invalidate_tag");
791
+ span.setAttribute("cache.tag", tag);
792
+ try {
793
+ let newVer = 1;
794
+ if (this.remoteStorage) {
795
+ try {
796
+ if (typeof this.remoteStorage.incrementTagVersion === "function") {
797
+ newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
798
+ } else {
799
+ const key = this.nk(`tag_ver:${tag}`);
800
+ const current = await this._getTagVersion(tag);
801
+ newVer = Math.max(current + 1, Date.now());
802
+ await this.remoteStorage.set(key, String(newVer));
803
+ }
804
+ } catch {
805
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
806
+ newVer = current + 1;
807
+ }
808
+ } else {
809
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
810
+ newVer = current + 1;
811
+ }
812
+ this.tagVersionCache.set(tag, { version: newVer, expiresAt: Date.now() + 6e4 });
813
+ const keys = this.tagIndex.get(tag);
814
+ if (keys) {
815
+ const keysArr = Array.from(keys);
816
+ for (const k of keysArr) {
817
+ this._deleteL1(k);
818
+ }
819
+ this.tagIndex.delete(tag);
820
+ }
821
+ } catch (err) {
822
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
823
+ span.recordException?.(err);
824
+ throw err;
825
+ } finally {
826
+ span.end();
827
+ }
828
+ }
829
+ /**
830
+ * Clears all entries from the edge cache.
831
+ */
832
+ async clear() {
833
+ const span = this._startSpan("tricache.clear");
834
+ try {
835
+ this.l1.clear();
836
+ this.currentBytes = 0;
837
+ this.tagIndex.clear();
838
+ this.tagVersionCache.clear();
839
+ if (this.bloomFilter) {
840
+ this.bloomFilter.reset();
841
+ }
842
+ if (this.remoteStorage) {
843
+ await this.remoteStorage.clear?.(this.namespace || void 0);
844
+ }
845
+ } catch (err) {
846
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
847
+ span.recordException?.(err);
848
+ throw err;
849
+ } finally {
850
+ span.end();
851
+ }
852
+ }
853
+ /**
854
+ * Batch get with miss-fetching.
855
+ */
856
+ async mget(keys, fetchFn, ttlSeconds) {
857
+ const span = this._startSpan("tricache.mget");
858
+ span.setAttribute("cache.batch.size", keys.length);
859
+ try {
860
+ const results = Array.from({ length: keys.length }, () => null);
861
+ const missIndices = [];
862
+ const missKeys = [];
863
+ for (let i = 0; i < keys.length; i++) {
864
+ const val = await this.get(keys[i]);
865
+ if (val !== null) {
866
+ results[i] = val;
867
+ } else {
868
+ missIndices.push(i);
869
+ missKeys.push(keys[i]);
870
+ }
871
+ }
872
+ span.setAttribute("cache.hits", keys.length - missKeys.length);
873
+ span.setAttribute("cache.misses", missKeys.length);
874
+ if (missKeys.length > 0 && fetchFn) {
875
+ const fetchedMap = await fetchFn(missKeys);
876
+ for (let j = 0; j < missKeys.length; j++) {
877
+ const k = missKeys[j];
878
+ const fetchedVal = fetchedMap[k];
879
+ if (fetchedVal !== void 0) {
880
+ results[missIndices[j]] = fetchedVal;
881
+ await this.set(k, fetchedVal, ttlSeconds);
882
+ }
883
+ }
884
+ }
885
+ return results;
886
+ } catch (err) {
887
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
888
+ span.recordException?.(err);
889
+ throw err;
890
+ } finally {
891
+ span.end();
892
+ }
893
+ }
894
+ /**
895
+ * Serializes active, unexpired L1 entries into a snapshot string (encrypted if WebCrypto encryption is enabled).
896
+ * Ideal for persisting Edge state to Cloudflare R2 before worker restart.
897
+ */
898
+ async exportSnapshot(options) {
899
+ const now = Date.now();
900
+ const entries = [];
901
+ for (const [nsKey, entry] of this.l1.entries()) {
902
+ if (entry.expiresAt > now || entry.staleUntil > now) {
903
+ const cleanKey = this.namespace && nsKey.startsWith(this.namespace + ":") ? nsKey.slice(this.namespace.length + 1) : nsKey;
904
+ entries.push({
905
+ key: cleanKey,
906
+ value: entry.value,
907
+ expiresAt: entry.expiresAt,
908
+ staleUntil: entry.staleUntil,
909
+ tags: entry.tags,
910
+ tagVersions: entry.tagVersions
911
+ });
912
+ }
913
+ }
914
+ const payload = {
915
+ version: 1,
916
+ writtenAt: now,
917
+ entries
918
+ };
919
+ const jsonStr = JSON.stringify(payload);
920
+ const shouldEncrypt = options?.encrypt ?? this.enc.isEnabled;
921
+ if (shouldEncrypt && this.enc.isEnabled) {
922
+ return await this.enc.encrypt(jsonStr);
923
+ }
924
+ return jsonStr;
925
+ }
926
+ /**
927
+ * Hydrates L1 memory and primes the Bloom filter directly from Cloudflare R2 or snapshot sources on edge isolate initialization.
928
+ *
929
+ * @param source Cloudflare R2 bucket binding (env.MY_BUCKET), reader object, snapshot string, or ArrayBuffer.
930
+ * @param options Configuration options (key, maxAgeMs, clockSkewToleranceMs).
931
+ * @returns Number of cache entries successfully restored into L1.
932
+ *
933
+ * @example
934
+ * // In Cloudflare Worker:
935
+ * export default {
936
+ * async fetch(request, env, ctx) {
937
+ * await edgeCache.hydrate(env.CACHE_R2_BUCKET);
938
+ * return handleRequest(request);
939
+ * }
940
+ * }
941
+ */
942
+ async hydrate(source, options) {
943
+ let rawStr = null;
944
+ if (source && typeof source === "object") {
945
+ if ("get" in source && typeof source.get === "function") {
946
+ const key = options?.key ?? "tricache-edge.snap";
947
+ const obj = await source.get(key);
948
+ if (!obj) return 0;
949
+ if (typeof obj === "string") {
950
+ rawStr = obj;
951
+ } else if (obj instanceof ArrayBuffer || typeof Uint8Array !== "undefined" && obj instanceof Uint8Array) {
952
+ rawStr = new TextDecoder().decode(obj);
953
+ } else if (typeof obj.text === "function") {
954
+ rawStr = await obj.text();
955
+ } else if (typeof obj.arrayBuffer === "function") {
956
+ const ab = await obj.arrayBuffer();
957
+ rawStr = new TextDecoder().decode(ab);
958
+ }
959
+ } else if (source instanceof ArrayBuffer) {
960
+ rawStr = new TextDecoder().decode(source);
961
+ } else if (typeof Uint8Array !== "undefined" && source instanceof Uint8Array) {
962
+ rawStr = new TextDecoder().decode(source);
963
+ }
964
+ } else if (typeof source === "string") {
965
+ rawStr = source;
966
+ }
967
+ if (!rawStr) return 0;
968
+ if (rawStr.startsWith("enc:v1:") || rawStr.startsWith("a128:v1:")) {
969
+ try {
970
+ rawStr = await this.enc.decrypt(rawStr);
971
+ } catch {
972
+ return 0;
973
+ }
974
+ }
975
+ let payload;
976
+ try {
977
+ payload = JSON.parse(rawStr);
978
+ } catch {
979
+ return 0;
980
+ }
981
+ if (!payload || !Array.isArray(payload.entries)) {
982
+ return 0;
983
+ }
984
+ const now = Date.now();
985
+ const maxAgeMs = options?.maxAgeMs ?? 72e5;
986
+ const tolerance = options?.clockSkewToleranceMs ?? 250;
987
+ const writtenAt = payload.writtenAt ?? 0;
988
+ if (writtenAt - now > tolerance) {
989
+ return 0;
990
+ }
991
+ const ageMs = Math.max(0, now - writtenAt);
992
+ if (ageMs > maxAgeMs) {
993
+ return 0;
994
+ }
995
+ let imported = 0;
996
+ for (const item of payload.entries) {
997
+ if (!item || typeof item.key !== "string") continue;
998
+ if (item.expiresAt <= now && item.staleUntil <= now) continue;
999
+ const nsKey = this.nk(item.key);
1000
+ const serialized = JSON.stringify(item.value);
1001
+ const bytes = this._estimateBytes(nsKey, serialized);
1002
+ this._deleteL1(nsKey);
1003
+ this._evictIfNeeded(bytes);
1004
+ const entry = {
1005
+ value: item.value,
1006
+ serialized,
1007
+ bytes,
1008
+ expiresAt: item.expiresAt,
1009
+ staleUntil: item.staleUntil,
1010
+ tags: item.tags,
1011
+ tagVersions: item.tagVersions
1012
+ };
1013
+ this.l1.set(nsKey, entry);
1014
+ this.currentBytes += bytes;
1015
+ if (item.tags) {
1016
+ for (const tag of item.tags) {
1017
+ let s = this.tagIndex.get(tag);
1018
+ if (!s) {
1019
+ s = /* @__PURE__ */ new Set();
1020
+ this.tagIndex.set(tag, s);
1021
+ }
1022
+ s.add(nsKey);
1023
+ }
1024
+ }
1025
+ if (this.bloomFilter) {
1026
+ this.bloomFilter.add(item.key);
1027
+ }
1028
+ imported++;
1029
+ }
1030
+ return imported;
1031
+ }
1032
+ /**
1033
+ * Diagnostic snapshot of edge cache memory usage.
1034
+ */
1035
+ stats() {
1036
+ return {
1037
+ keys: this.l1.size,
1038
+ bytes: this.currentBytes,
1039
+ maxKeys: this.maxKeys,
1040
+ maxBytes: this.maxBytes,
1041
+ tags: this.tagIndex.size
1042
+ };
1043
+ }
1044
+ };
1045
+
1046
+ // src/edge/adapters/upstash.ts
1047
+ var UpstashRedisAdapter = class {
1048
+ baseUrl;
1049
+ token;
1050
+ customFetch;
1051
+ constructor(options) {
1052
+ if (!options?.url || !options?.token) {
1053
+ throw new Error("UpstashRedisAdapter: url and token are required.");
1054
+ }
1055
+ this.baseUrl = options.url.replace(/\/+$/, "");
1056
+ this.token = options.token;
1057
+ this.customFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1058
+ }
1059
+ async _executeCommand(command) {
1060
+ const res = await this.customFetch(this.baseUrl, {
1061
+ method: "POST",
1062
+ headers: {
1063
+ Authorization: `Bearer ${this.token}`,
1064
+ "Content-Type": "application/json"
1065
+ },
1066
+ body: JSON.stringify(command)
1067
+ });
1068
+ if (!res.ok) {
1069
+ const text = await res.text().catch(() => "");
1070
+ throw new Error(`Upstash HTTP error (${res.status} ${res.statusText}): ${text}`);
1071
+ }
1072
+ const json = await res.json();
1073
+ if (json.error) {
1074
+ throw new Error(`Upstash Redis command error: ${json.error}`);
1075
+ }
1076
+ return json.result;
1077
+ }
1078
+ async _executePipeline(commands) {
1079
+ const res = await this.customFetch(`${this.baseUrl}/pipeline`, {
1080
+ method: "POST",
1081
+ headers: {
1082
+ Authorization: `Bearer ${this.token}`,
1083
+ "Content-Type": "application/json"
1084
+ },
1085
+ body: JSON.stringify(commands)
1086
+ });
1087
+ if (!res.ok) {
1088
+ const text = await res.text().catch(() => "");
1089
+ throw new Error(`Upstash Pipeline error (${res.status} ${res.statusText}): ${text}`);
1090
+ }
1091
+ const json = await res.json();
1092
+ return json.map((item) => {
1093
+ if (item.error) {
1094
+ throw new Error(`Upstash Redis pipeline item error: ${item.error}`);
1095
+ }
1096
+ return item.result;
1097
+ });
1098
+ }
1099
+ async get(key) {
1100
+ const res = await this._executeCommand(["GET", key]);
1101
+ return res ?? null;
1102
+ }
1103
+ async set(key, value, ttlSeconds) {
1104
+ if (typeof ttlSeconds === "number" && ttlSeconds > 0) {
1105
+ await this._executeCommand(["SET", key, value, "EX", Math.round(ttlSeconds)]);
1106
+ } else {
1107
+ await this._executeCommand(["SET", key, value]);
1108
+ }
1109
+ }
1110
+ async delete(key) {
1111
+ await this._executeCommand(["DEL", key]);
1112
+ }
1113
+ async mget(keys) {
1114
+ if (keys.length === 0) return [];
1115
+ const res = await this._executeCommand(["MGET", ...keys]);
1116
+ return Array.isArray(res) ? res : [];
1117
+ }
1118
+ async mset(entries, ttlSeconds) {
1119
+ const keys = Object.keys(entries);
1120
+ if (keys.length === 0) return;
1121
+ if (typeof ttlSeconds === "number" && ttlSeconds > 0) {
1122
+ const roundedTtl = Math.round(ttlSeconds);
1123
+ const commands = keys.map((k) => ["SET", k, entries[k], "EX", roundedTtl]);
1124
+ await this._executePipeline(commands);
1125
+ } else {
1126
+ const args = [];
1127
+ for (const k of keys) {
1128
+ args.push(k, entries[k]);
1129
+ }
1130
+ await this._executeCommand(["MSET", ...args]);
1131
+ }
1132
+ }
1133
+ async clear(prefix) {
1134
+ if (prefix) {
1135
+ const pattern = prefix.endsWith("*") ? prefix : `${prefix}*`;
1136
+ const keys = await this._executeCommand(["KEYS", pattern]);
1137
+ if (Array.isArray(keys) && keys.length > 0) {
1138
+ await this._executeCommand(["DEL", ...keys]);
1139
+ }
1140
+ } else {
1141
+ await this._executeCommand(["FLUSHDB"]);
1142
+ }
1143
+ }
1144
+ async incrementTagVersion(tag) {
1145
+ const res = await this._executeCommand(["INCR", `tag_ver:${tag}`]);
1146
+ return typeof res === "number" ? res : 1;
1147
+ }
1148
+ async getTagVersion(tag) {
1149
+ const res = await this._executeCommand(["GET", `tag_ver:${tag}`]);
1150
+ return res ? parseInt(res, 10) || 1 : 1;
1151
+ }
1152
+ async batchGetTagVersions(tags) {
1153
+ if (tags.length === 0) return {};
1154
+ const keys = tags.map((t) => `tag_ver:${t}`);
1155
+ const res = await this.mget(keys);
1156
+ const result = {};
1157
+ for (let i = 0; i < tags.length; i++) {
1158
+ const raw = res[i];
1159
+ result[tags[i]] = raw ? parseInt(raw, 10) || 1 : 1;
1160
+ }
1161
+ return result;
1162
+ }
1163
+ };
1164
+
1165
+ // src/edge/adapters/cloudflare-kv.ts
1166
+ var MIN_CF_KV_TTL = 60;
1167
+ var CloudflareKVAdapter = class {
1168
+ kv;
1169
+ constructor(kv) {
1170
+ if (!kv) {
1171
+ throw new Error("CloudflareKVAdapter: KVNamespace instance is required.");
1172
+ }
1173
+ this.kv = kv;
1174
+ }
1175
+ async get(key) {
1176
+ const raw = await this.kv.get(key, { type: "text" });
1177
+ if (raw === null) return null;
1178
+ if (raw.startsWith('{"exp":') && raw.includes('"val":')) {
1179
+ try {
1180
+ const parsed = JSON.parse(raw);
1181
+ if (typeof parsed.exp === "number" && typeof parsed.val === "string") {
1182
+ if (Date.now() >= parsed.exp) {
1183
+ void this.kv.delete(key).catch(() => {
1184
+ });
1185
+ return null;
1186
+ }
1187
+ return parsed.val;
1188
+ }
1189
+ } catch {
1190
+ }
1191
+ }
1192
+ return raw;
1193
+ }
1194
+ async set(key, value, ttlSeconds) {
1195
+ if (typeof ttlSeconds === "number" && ttlSeconds > 0) {
1196
+ if (ttlSeconds < MIN_CF_KV_TTL) {
1197
+ const envelope = {
1198
+ exp: Date.now() + Math.round(ttlSeconds * 1e3),
1199
+ val: value
1200
+ };
1201
+ await this.kv.put(key, JSON.stringify(envelope), { expirationTtl: MIN_CF_KV_TTL });
1202
+ } else {
1203
+ await this.kv.put(key, value, { expirationTtl: Math.round(ttlSeconds) });
1204
+ }
1205
+ } else {
1206
+ await this.kv.put(key, value);
1207
+ }
1208
+ }
1209
+ async delete(key) {
1210
+ await this.kv.delete(key);
1211
+ }
1212
+ async mget(keys) {
1213
+ return Promise.all(keys.map((k) => this.get(k)));
1214
+ }
1215
+ async mset(entries, ttlSeconds) {
1216
+ const keys = Object.keys(entries);
1217
+ await Promise.all(keys.map((k) => this.set(k, entries[k], ttlSeconds)));
1218
+ }
1219
+ async clear(prefix) {
1220
+ if (!this.kv.list) return;
1221
+ let cursor;
1222
+ do {
1223
+ const res = await this.kv.list({ prefix, cursor });
1224
+ if (res.keys.length > 0) {
1225
+ await Promise.all(res.keys.map((item) => this.kv.delete(item.name)));
1226
+ }
1227
+ cursor = res.list_complete ? void 0 : res.cursor;
1228
+ } while (cursor);
1229
+ }
1230
+ async incrementTagVersion(tag) {
1231
+ const key = `tag_ver:${tag}`;
1232
+ const raw = await this.kv.get(key);
1233
+ const prev = raw ? parseInt(raw, 10) || 0 : 0;
1234
+ const nextVer = Math.max(prev + 1, Date.now());
1235
+ await this.kv.put(key, String(nextVer));
1236
+ return nextVer;
1237
+ }
1238
+ async getTagVersion(tag) {
1239
+ const raw = await this.kv.get(`tag_ver:${tag}`);
1240
+ return raw ? parseInt(raw, 10) || 1 : 1;
1241
+ }
1242
+ async batchGetTagVersions(tags) {
1243
+ const vers = await Promise.all(tags.map((t) => this.getTagVersion(t)));
1244
+ const res = {};
1245
+ for (let i = 0; i < tags.length; i++) {
1246
+ res[tags[i]] = vers[i];
1247
+ }
1248
+ return res;
1249
+ }
1250
+ };
1251
+
1252
+ // src/edge/adapters/cloudflare-do.ts
1253
+ var CloudflareDOStorageAdapter = class {
1254
+ storage;
1255
+ constructor(storage) {
1256
+ if (!storage) {
1257
+ throw new Error("CloudflareDOStorageAdapter: DurableObjectStorage instance is required.");
1258
+ }
1259
+ this.storage = storage;
1260
+ }
1261
+ async get(key) {
1262
+ const entry = await this.storage.get(key);
1263
+ if (entry === void 0 || entry === null) return null;
1264
+ if (typeof entry === "object" && "val" in entry && "exp" in entry) {
1265
+ if (entry.exp > 0 && Date.now() >= entry.exp) {
1266
+ void this.storage.delete(key).catch(() => {
1267
+ });
1268
+ return null;
1269
+ }
1270
+ return entry.val;
1271
+ }
1272
+ return String(entry);
1273
+ }
1274
+ async set(key, value, ttlSeconds) {
1275
+ const exp = typeof ttlSeconds === "number" && ttlSeconds > 0 ? Date.now() + Math.round(ttlSeconds * 1e3) : 0;
1276
+ const entry = { val: value, exp };
1277
+ await this.storage.put(key, entry);
1278
+ }
1279
+ async delete(key) {
1280
+ await this.storage.delete(key);
1281
+ }
1282
+ async mget(keys) {
1283
+ if (keys.length === 0) return [];
1284
+ const map = await this.storage.get(keys);
1285
+ const now = Date.now();
1286
+ const result = [];
1287
+ for (const k of keys) {
1288
+ const entry = map.get(k);
1289
+ if (entry === void 0 || entry === null) {
1290
+ result.push(null);
1291
+ } else if (typeof entry === "object" && "val" in entry && "exp" in entry) {
1292
+ if (entry.exp > 0 && now >= entry.exp) {
1293
+ void this.storage.delete(k).catch(() => {
1294
+ });
1295
+ result.push(null);
1296
+ } else {
1297
+ result.push(entry.val);
1298
+ }
1299
+ } else {
1300
+ result.push(String(entry));
1301
+ }
1302
+ }
1303
+ return result;
1304
+ }
1305
+ async mset(entries, ttlSeconds) {
1306
+ const exp = typeof ttlSeconds === "number" && ttlSeconds > 0 ? Date.now() + Math.round(ttlSeconds * 1e3) : 0;
1307
+ const record = {};
1308
+ for (const [k, v] of Object.entries(entries)) {
1309
+ record[k] = { val: v, exp };
1310
+ }
1311
+ await this.storage.put(record);
1312
+ }
1313
+ async clear(prefix) {
1314
+ if (!this.storage.list) return;
1315
+ const map = await this.storage.list({ prefix });
1316
+ const keysToDelete = Array.from(map.keys());
1317
+ if (keysToDelete.length > 0) {
1318
+ await this.storage.delete(keysToDelete);
1319
+ }
1320
+ }
1321
+ async incrementTagVersion(tag) {
1322
+ const key = `tag_ver:${tag}`;
1323
+ const raw = await this.storage.get(key);
1324
+ const prev = raw && typeof raw === "object" && "val" in raw ? parseInt(raw.val, 10) || 0 : typeof raw === "string" ? parseInt(raw, 10) || 0 : 0;
1325
+ const nextVer = prev + 1;
1326
+ await this.storage.put(key, { val: String(nextVer), exp: 0 });
1327
+ return nextVer;
1328
+ }
1329
+ async getTagVersion(tag) {
1330
+ const raw = await this.storage.get(`tag_ver:${tag}`);
1331
+ if (raw && typeof raw === "object" && "val" in raw) {
1332
+ return parseInt(raw.val, 10) || 1;
1333
+ }
1334
+ return typeof raw === "string" ? parseInt(raw, 10) || 1 : 1;
1335
+ }
1336
+ async batchGetTagVersions(tags) {
1337
+ const keys = tags.map((t) => `tag_ver:${t}`);
1338
+ const map = await this.storage.get(keys);
1339
+ const result = {};
1340
+ for (const tag of tags) {
1341
+ const entry = map.get(`tag_ver:${tag}`);
1342
+ if (entry && typeof entry === "object" && "val" in entry) {
1343
+ result[tag] = parseInt(entry.val, 10) || 1;
1344
+ } else {
1345
+ result[tag] = typeof entry === "string" ? parseInt(entry, 10) || 1 : 1;
1346
+ }
1347
+ }
1348
+ return result;
1349
+ }
1350
+ };
1351
+
1352
+ // src/edge/hono.ts
1353
+ async function computeEdgeETag(text) {
1354
+ try {
1355
+ if (typeof crypto !== "undefined" && crypto.subtle) {
1356
+ const encoder = new TextEncoder();
1357
+ const data = encoder.encode(text);
1358
+ const hashBuf = await crypto.subtle.digest("SHA-1", data);
1359
+ const hashArr = Array.from(new Uint8Array(hashBuf));
1360
+ const hashHex = hashArr.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
1361
+ return `W/"${text.length.toString(16)}-${hashHex}"`;
1362
+ }
1363
+ } catch {
1364
+ }
1365
+ let h = 0;
1366
+ for (let i = 0; i < text.length; i++) {
1367
+ h = Math.imul(31, h) + text.charCodeAt(i) | 0;
1368
+ }
1369
+ return `W/"${text.length.toString(16)}-${Math.abs(h).toString(16)}"`;
1370
+ }
1371
+ function buildEdgeDeterministicKey(c, options) {
1372
+ if (options?.keyGenerator) {
1373
+ return options.keyGenerator(c);
1374
+ }
1375
+ const req = c.req;
1376
+ const method = (req.method || "GET").toUpperCase();
1377
+ const rawUrl = req.url || "/";
1378
+ const qIdx = rawUrl.indexOf("?");
1379
+ const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
1380
+ let queryString = "";
1381
+ if (qIdx >= 0) {
1382
+ const rawQuery = rawUrl.slice(qIdx + 1);
1383
+ try {
1384
+ const params = new URLSearchParams(rawQuery);
1385
+ params.sort();
1386
+ queryString = params.toString();
1387
+ } catch {
1388
+ queryString = rawQuery;
1389
+ }
1390
+ }
1391
+ let key = `edge:http:${method}:${path}`;
1392
+ if (queryString) {
1393
+ key += `?${queryString}`;
1394
+ }
1395
+ if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.header) {
1396
+ const sortedHeaders = [...options.headerWhitelist].sort();
1397
+ for (const h of sortedHeaders) {
1398
+ const val = req.header(h);
1399
+ if (val !== void 0 && val !== null && val !== "") {
1400
+ key += `|h:${h.toLowerCase()}=${val}`;
1401
+ }
1402
+ }
1403
+ }
1404
+ return key;
1405
+ }
1406
+ function honoEdgeCache(options = {}) {
1407
+ const {
1408
+ cache,
1409
+ etag = true,
1410
+ ttl = 300,
1411
+ swr,
1412
+ tags,
1413
+ skipCache,
1414
+ keyGenerator,
1415
+ headerWhitelist
1416
+ } = options;
1417
+ return async (c, next) => {
1418
+ const method = c.req.method;
1419
+ if (method !== "GET" && method !== "HEAD") {
1420
+ return await next();
1421
+ }
1422
+ if (skipCache && skipCache(c)) {
1423
+ return await next();
1424
+ }
1425
+ const cc = c.req.header?.("cache-control") || c.req.header?.("Cache-Control");
1426
+ if (typeof cc === "string") {
1427
+ const lower = cc.toLowerCase();
1428
+ if (lower.includes("no-cache") || lower.includes("no-store")) {
1429
+ return await next();
1430
+ }
1431
+ }
1432
+ if (!cache) {
1433
+ return await next();
1434
+ }
1435
+ const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
1436
+ const ifNoneMatch = c.req.header?.("if-none-match") || c.req.header?.("If-None-Match");
1437
+ const resolvedTags = typeof tags === "function" ? tags(c) : tags;
1438
+ const cached = await cache.get(
1439
+ key,
1440
+ async () => {
1441
+ await next();
1442
+ const res = c.res;
1443
+ if (!res) {
1444
+ return null;
1445
+ }
1446
+ const clone = res.clone();
1447
+ const text = await clone.text();
1448
+ const statusCode = res.status ?? 200;
1449
+ const bodyEtag = etag ? await computeEdgeETag(text) : void 0;
1450
+ const contentType = res.headers.get("content-type") || "text/plain; charset=utf-8";
1451
+ return {
1452
+ body: text,
1453
+ contentType,
1454
+ etag: bodyEtag,
1455
+ status: statusCode
1456
+ };
1457
+ },
1458
+ ttl,
1459
+ {
1460
+ swr,
1461
+ tags: resolvedTags,
1462
+ ctx: c.executionCtx
1463
+ }
1464
+ );
1465
+ if (!cached) {
1466
+ return;
1467
+ }
1468
+ if (typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300)) {
1469
+ await cache.delete?.(key);
1470
+ return;
1471
+ }
1472
+ if (cached.etag && ifNoneMatch === cached.etag) {
1473
+ return c.body(null, 304, { ETag: cached.etag });
1474
+ }
1475
+ const headers = {};
1476
+ if (cached.etag) headers["ETag"] = cached.etag;
1477
+ if (cached.contentType) headers["Content-Type"] = cached.contentType;
1478
+ return c.body(cached.body, cached.status ?? 200, headers);
1479
+ };
1480
+ }
1481
+ // Annotate the CommonJS export names for ESM import in node:
1482
+ 0 && (module.exports = {
1483
+ CloudflareDOStorageAdapter,
1484
+ CloudflareKVAdapter,
1485
+ EdgeCacheService,
1486
+ Murmur3BloomFilter,
1487
+ UpstashRedisAdapter,
1488
+ WasmBloomFilter,
1489
+ WebCryptoEncryption,
1490
+ base64ToUint8Array,
1491
+ buildEdgeDeterministicKey,
1492
+ computeEdgeETag,
1493
+ honoEdgeCache,
1494
+ murmur3_32,
1495
+ uint8ArrayToBase64,
1496
+ uint8ArrayToUtf8,
1497
+ utf8ToUint8Array
1498
+ });