tricache 0.7.0 → 0.7.1

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 (40) hide show
  1. package/README.md +1428 -1428
  2. package/bin/tricache.js +8 -8
  3. package/dist/cache-service-5GATUYAK.js +7 -0
  4. package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
  5. package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
  6. package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
  7. package/dist/cli.cjs +113 -56
  8. package/dist/cli.js +3 -3
  9. package/dist/drizzle/index.cjs +114 -57
  10. package/dist/drizzle/index.d.ts +1 -1
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/http/index.cjs +149 -64
  13. package/dist/http/index.d.ts +1 -1
  14. package/dist/http/index.js +38 -10
  15. package/dist/index.cjs +112 -55
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/nestjs/index.cjs +112 -55
  19. package/dist/nestjs/index.d.ts +1 -1
  20. package/dist/nestjs/index.js +2 -2
  21. package/dist/next/index.cjs +143 -63
  22. package/dist/next/index.d.ts +10 -6
  23. package/dist/next/index.js +33 -10
  24. package/dist/prisma/index.cjs +2 -1
  25. package/dist/prisma/index.d.ts +1 -1
  26. package/dist/prisma/index.js +2 -1
  27. package/dist/serialize-worker.cjs +26 -15
  28. package/dist/serialize-worker.js +1 -1
  29. package/package.json +4 -2
  30. package/src/cache-service.ts +3294 -3226
  31. package/src/cli.ts +143 -143
  32. package/src/compression.ts +56 -63
  33. package/src/disk-tier.ts +821 -821
  34. package/src/encryption.ts +513 -493
  35. package/src/http/index.ts +265 -223
  36. package/src/next/cache-handler.ts +268 -244
  37. package/src/prisma/index.ts +154 -151
  38. package/src/smart-memory-cache.ts +1026 -1024
  39. package/src/types.ts +911 -902
  40. package/dist/cache-service-AJASH5FX.js +0 -7
@@ -1,4 +1,4 @@
1
- import { W as WrapOptions, C as CacheService } from '../cache-service-BblHuF3i.js';
1
+ import { W as WrapOptions, C as CacheService } from '../cache-service-D8tIXmzb.js';
2
2
 
3
3
  /**
4
4
  * tricache/drizzle — First-class Drizzle ORM query caching wrapper for TriCache.
@@ -9,7 +9,7 @@ async function withCache(query, options = {}) {
9
9
  const { cache, key, ttl = 300, swr, priority, tags, dependsOn, refreshAhead, xfetchBeta, notFoundTtl } = options;
10
10
  let activeCache = cache;
11
11
  if (!activeCache) {
12
- const { CacheService } = await import("../cache-service-AJASH5FX.js");
12
+ const { CacheService } = await import("../cache-service-5GATUYAK.js");
13
13
  activeCache = CacheService.create();
14
14
  }
15
15
  let cacheKey = key;
@@ -283,6 +283,8 @@ var init_encryption = __esm({
283
283
  _keyObj = null;
284
284
  // parsed KeyObject — used for all AES modes
285
285
  _mode;
286
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
287
+ _strictKeyValidation;
286
288
  _prevKey = null;
287
289
  _prevKeyObj = null;
288
290
  _prevMode = "aes-256-gcm";
@@ -348,11 +350,12 @@ var init_encryption = __esm({
348
350
  }
349
351
  return out;
350
352
  }
351
- constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
353
+ constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode, opts) {
352
354
  const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
353
355
  const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
356
+ this._strictKeyValidation = opts?.strictKeyValidation ?? false;
354
357
  this._mode = resolvedMode;
355
- if (!keyBase64) {
358
+ if (keyBase64 === void 0 || keyBase64 === null) {
356
359
  if (process.env.NODE_ENV === "production") {
357
360
  logger.warn(
358
361
  "SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
@@ -361,11 +364,17 @@ var init_encryption = __esm({
361
364
  }
362
365
  return;
363
366
  }
367
+ if (keyBase64 === "") {
368
+ const err = new Error("Encryption key is empty \u2014 set encryptionKey option or CACHE_ENCRYPTION_KEY");
369
+ if (this._strictKeyValidation) throw err;
370
+ logger.error("Empty encryption key \u2014 falling back to plaintext", {}, err);
371
+ return;
372
+ }
364
373
  try {
365
374
  const buf = Buffer.from(keyBase64, "base64");
366
375
  const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
367
376
  if (requiredLen > 0 && buf.length !== requiredLen) {
368
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
377
+ throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
369
378
  }
370
379
  if (buf.length < 1) {
371
380
  throw new Error("XOR key must be at least 1 byte");
@@ -389,6 +398,9 @@ var init_encryption = __esm({
389
398
  logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
390
399
  }
391
400
  } catch (err) {
401
+ if (this._strictKeyValidation) {
402
+ throw err;
403
+ }
392
404
  logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
393
405
  }
394
406
  if (previousKeyBase64) {
@@ -755,13 +767,12 @@ function globMatchParts(parts, first, last, key) {
755
767
  }
756
768
  return true;
757
769
  }
758
- var import_msgpackr, _hit, LARGE_VALUE_BYTES, EVICTION_BATCH_PERCENT, EVICTION_SAMPLE, EVICT_COUNT, JsBloomFilter, SKETCH_ROWS, SKETCH_WIDTH, SKETCH_MASK, SKETCH_DECAY_THRESHOLD, CountMinSketch, SmartMemoryCache;
770
+ var import_msgpackr, LARGE_VALUE_BYTES, EVICTION_BATCH_PERCENT, EVICTION_SAMPLE, EVICT_COUNT, JsBloomFilter, SKETCH_ROWS, SKETCH_WIDTH, SKETCH_MASK, SKETCH_DECAY_THRESHOLD, CountMinSketch, SmartMemoryCache;
759
771
  var init_smart_memory_cache = __esm({
760
772
  "src/smart-memory-cache.ts"() {
761
773
  "use strict";
762
774
  import_msgpackr = require("msgpackr");
763
775
  init_bloom_filter_wasm();
764
- _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
765
776
  LARGE_VALUE_BYTES = 16384;
766
777
  EVICTION_BATCH_PERCENT = 0.2;
767
778
  EVICTION_SAMPLE = 16;
@@ -1129,15 +1140,17 @@ var init_smart_memory_cache = __esm({
1129
1140
  entry.lastAccess = now;
1130
1141
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
1131
1142
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
1132
- _hit.value = value;
1133
- _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
1134
- _hit.expiresAt = entry.expiresAt;
1135
- _hit.ttlMs = entry.ttlMs;
1136
- _hit.delta = entry.delta;
1137
- _hit.fetchedAt = now;
1138
- _hit.tagVersions = entry.tagVersions;
1139
- _hit.setAt = entry.setAt;
1140
- return _hit;
1143
+ const hit = {
1144
+ value,
1145
+ isStale: entry.staleAt !== void 0 && now > entry.staleAt,
1146
+ expiresAt: entry.expiresAt,
1147
+ ttlMs: entry.ttlMs,
1148
+ delta: entry.delta,
1149
+ fetchedAt: now,
1150
+ tagVersions: entry.tagVersions,
1151
+ setAt: entry.setAt
1152
+ };
1153
+ return hit;
1141
1154
  }
1142
1155
  set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1143
1156
  const packed = (0, import_msgpackr.pack)(data);
@@ -1584,26 +1597,25 @@ function compressBuffer(buf, algorithm) {
1584
1597
  return buf;
1585
1598
  }
1586
1599
  function decompressBuffer(buf, algorithm = "brotli") {
1587
- if (algorithm === "gzip") {
1600
+ const tryBrotli = () => {
1588
1601
  try {
1589
- return import_zlib.default.gunzipSync(buf);
1602
+ return import_zlib.default.brotliDecompressSync(buf);
1590
1603
  } catch {
1591
- try {
1592
- return import_zlib.default.brotliDecompressSync(buf);
1593
- } catch {
1594
- return buf;
1595
- }
1604
+ return null;
1596
1605
  }
1597
- }
1598
- try {
1599
- return import_zlib.default.brotliDecompressSync(buf);
1600
- } catch {
1606
+ };
1607
+ const tryGzip = () => {
1601
1608
  try {
1602
1609
  return import_zlib.default.gunzipSync(buf);
1603
1610
  } catch {
1604
- return buf;
1611
+ return null;
1605
1612
  }
1613
+ };
1614
+ const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
1615
+ if (result === null) {
1616
+ throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1606
1617
  }
1618
+ return result;
1607
1619
  }
1608
1620
  function compressWithHeader(buf, algorithm) {
1609
1621
  if (algorithm === "none") return buf;
@@ -2136,6 +2148,7 @@ var init_disk_tier = __esm({
2136
2148
  dec = this.decrypt(raw);
2137
2149
  } catch {
2138
2150
  import_fs2.default.unlinkSync(filePath);
2151
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2139
2152
  this.fileCount = Math.max(0, this.fileCount - 1);
2140
2153
  purged++;
2141
2154
  continue;
@@ -2299,6 +2312,7 @@ var init_disk_tier = __esm({
2299
2312
  dec = this.decrypt(raw);
2300
2313
  } catch {
2301
2314
  import_fs2.default.unlinkSync(filePath);
2315
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2302
2316
  this.fileCount = Math.max(0, this.fileCount - 1);
2303
2317
  purged++;
2304
2318
  continue;
@@ -2411,7 +2425,7 @@ function detectServerlessRuntime() {
2411
2425
  if (process.env["VERCEL"]) return "Vercel";
2412
2426
  return null;
2413
2427
  }
2414
- var import_ioredis, import_msgpackr3, import_crypto3, import_os2, import_node_v8, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, CacheService;
2428
+ var import_ioredis, import_msgpackr3, import_crypto3, import_os2, import_node_v8, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, CacheService;
2415
2429
  var init_cache_service = __esm({
2416
2430
  "src/cache-service.ts"() {
2417
2431
  "use strict";
@@ -2437,6 +2451,7 @@ return 0
2437
2451
  `;
2438
2452
  SNAPSHOT_VERSION = 1;
2439
2453
  DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
2454
+ INDEFINITE_TTL_SECONDS = 31536e3;
2440
2455
  SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
2441
2456
  DEFAULT_CATEGORY_LIMITS = {
2442
2457
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
@@ -2673,7 +2688,8 @@ return 0
2673
2688
  logger,
2674
2689
  options.encryptionMode,
2675
2690
  options.previousEncryptionKey,
2676
- options.previousEncryptionMode
2691
+ options.previousEncryptionMode,
2692
+ { strictKeyValidation: options.strictKeyValidation ?? false }
2677
2693
  );
2678
2694
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
2679
2695
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
@@ -2695,8 +2711,14 @@ return 0
2695
2711
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
2696
2712
  redisPort: options.redisPort ?? 6379,
2697
2713
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2698
- disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
2714
+ disableRedis: options.disableRedis ?? (() => {
2715
+ const explicitConfig = Boolean(
2716
+ options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2717
+ );
2718
+ return !explicitConfig && process.env.NODE_ENV !== "production";
2719
+ })(),
2699
2720
  encryptionKey: encKeyRaw,
2721
+ encryptionMode: options.encryptionMode,
2700
2722
  snapshotPath: options.snapshotPath ?? import_path3.default.join(
2701
2723
  import_os2.default.tmpdir(),
2702
2724
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
@@ -2802,7 +2824,6 @@ return 0
2802
2824
  }
2803
2825
  this._shutdownHandler = () => {
2804
2826
  if (!this._diskDisabled) this.writeSnapshot();
2805
- process.exit(0);
2806
2827
  };
2807
2828
  process.once("SIGTERM", this._shutdownHandler);
2808
2829
  process.once("SIGINT", this._shutdownHandler);
@@ -2981,7 +3002,10 @@ return 0
2981
3002
  disableRedis: this._redisDisabled,
2982
3003
  redisClusterNodes: o.redisClusterNodes,
2983
3004
  redisSentinel: o.redisSentinel,
2984
- encryptionKey: o.encryptionKey,
3005
+ // Never surface key material through diagnostics — a JSON.stringify of
3006
+ // this object previously leaked the raw encryption key.
3007
+ encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
3008
+ encryptionMode: o.encryptionMode,
2985
3009
  l2WriteMode: o.l2WriteMode,
2986
3010
  instanceName: o.instanceName,
2987
3011
  frozen: o.frozen,
@@ -3186,24 +3210,7 @@ return 0
3186
3210
  for (const [id, fields] of entries) {
3187
3211
  this._lastStreamId = id;
3188
3212
  this.counters.streamEntriesReceived++;
3189
- let op = "";
3190
- let key = "";
3191
- let src = "";
3192
- let tagVersion;
3193
- for (let i = 0; i < fields.length; i += 2) {
3194
- const f = fields[i];
3195
- const v = fields[i + 1];
3196
- if (f === "op") op = v;
3197
- else if (f === "key") key = v;
3198
- else if (f === "src") src = v;
3199
- else if (f === "tagVersion") tagVersion = parseInt(v, 10);
3200
- }
3201
- if (src === this.instanceId) {
3202
- this.counters.invSkipped++;
3203
- continue;
3204
- }
3205
- this.counters.invReceived++;
3206
- this._applyInvalidationEvent(op, key, tagVersion);
3213
+ this._processStreamEntry(fields);
3207
3214
  }
3208
3215
  }
3209
3216
  }
@@ -3224,6 +3231,51 @@ return 0
3224
3231
  };
3225
3232
  void runLoop();
3226
3233
  }
3234
+ /**
3235
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
3236
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
3237
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
3238
+ * key/src must be non-empty strings, tagVersion must parse to a finite
3239
+ * number. Invalid entries are logged and dropped — never applied.
3240
+ */
3241
+ /** @internal Exposed for testing. */
3242
+ _processStreamEntry(fields) {
3243
+ let op = "";
3244
+ let key = "";
3245
+ let src = "";
3246
+ let tagVersionRaw;
3247
+ for (let i = 0; i + 1 < fields.length; i += 2) {
3248
+ const f = fields[i];
3249
+ const v = fields[i + 1];
3250
+ if (f === "op") op = v;
3251
+ else if (f === "key") key = v;
3252
+ else if (f === "src") src = v;
3253
+ else if (f === "tagVersion") tagVersionRaw = v;
3254
+ }
3255
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
3256
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
3257
+ this.logger.warn("Backplane: rejected invalid stream entry", {
3258
+ op: String(op).slice(0, 40),
3259
+ key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
3260
+ });
3261
+ return;
3262
+ }
3263
+ let tagVersion;
3264
+ if (tagVersionRaw !== void 0) {
3265
+ const parsed = parseInt(tagVersionRaw, 10);
3266
+ if (!Number.isFinite(parsed)) {
3267
+ this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
3268
+ return;
3269
+ }
3270
+ tagVersion = parsed;
3271
+ }
3272
+ if (src === this.instanceId) {
3273
+ this.counters.invSkipped++;
3274
+ return;
3275
+ }
3276
+ this.counters.invReceived++;
3277
+ this._applyInvalidationEvent(op, key, tagVersion);
3278
+ }
3227
3279
  _applyInvalidationEvent(op, key, tagVersion) {
3228
3280
  if (op === "del") {
3229
3281
  this.l1.delete(key);
@@ -3910,7 +3962,8 @@ return 0
3910
3962
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3911
3963
  const span = this._startSpan("tricache.set");
3912
3964
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3913
- const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3965
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
3966
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
3914
3967
  const p = priority ?? inferPriority(cacheKey);
3915
3968
  const k = this.nk(cacheKey);
3916
3969
  this.counters.sets++;
@@ -4752,8 +4805,9 @@ return 0
4752
4805
  const deadline = Date.now() + acquireTimeout;
4753
4806
  let acquired = false;
4754
4807
  if (!this._redisDisabled) {
4808
+ let client = null;
4755
4809
  try {
4756
- const client = await this.getRedis();
4810
+ client = await this.getRedis();
4757
4811
  while (Date.now() <= deadline) {
4758
4812
  const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4759
4813
  if (res === "OK") {
@@ -4767,6 +4821,15 @@ return 0
4767
4821
  if (!acquired) {
4768
4822
  throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4769
4823
  }
4824
+ } catch (err) {
4825
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
4826
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4827
+ resourceKey,
4828
+ error: err.message
4829
+ });
4830
+ client = null;
4831
+ }
4832
+ if (client !== null && acquired) {
4770
4833
  try {
4771
4834
  return await fn();
4772
4835
  } finally {
@@ -4782,12 +4845,6 @@ return 0
4782
4845
  } catch {
4783
4846
  }
4784
4847
  }
4785
- } catch (err) {
4786
- if (err.message.startsWith("Failed to acquire lock")) throw err;
4787
- this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4788
- resourceKey,
4789
- error: err.message
4790
- });
4791
4848
  }
4792
4849
  }
4793
4850
  let unlock = () => {
@@ -5141,12 +5198,16 @@ function expressCache(options = {}) {
5141
5198
  return new Promise((resolve) => {
5142
5199
  const origJson = res.json?.bind(res);
5143
5200
  const origSend = res.send?.bind(res);
5201
+ const origEnd = res.end?.bind(res);
5202
+ const statusOf = () => res.statusCode;
5144
5203
  if (origJson) {
5145
5204
  res.json = (body) => {
5146
5205
  const bodyEtag = etag ? generateETag(body) : void 0;
5147
- resolve({ body, contentType: "application/json; charset=utf-8", etag: bodyEtag });
5206
+ resolve({ body, contentType: "application/json; charset=utf-8", etag: bodyEtag, status: statusOf() });
5148
5207
  if (ifNoneMatch && ifNoneMatch === bodyEtag) {
5149
- return res.status(304).end();
5208
+ res.status?.(304);
5209
+ origEnd?.();
5210
+ return;
5150
5211
  }
5151
5212
  if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
5152
5213
  return origJson(body);
@@ -5155,20 +5216,35 @@ function expressCache(options = {}) {
5155
5216
  if (origSend) {
5156
5217
  res.send = (body) => {
5157
5218
  const bodyEtag = etag ? generateETag(body) : void 0;
5158
- resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag });
5219
+ resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag, status: statusOf() });
5159
5220
  if (ifNoneMatch && ifNoneMatch === bodyEtag) {
5160
- return res.status(304).end();
5221
+ res.status?.(304);
5222
+ origEnd?.();
5223
+ return;
5161
5224
  }
5162
5225
  if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
5163
5226
  return origSend(body);
5164
5227
  };
5165
5228
  }
5229
+ if (origEnd) {
5230
+ res.end = (body) => {
5231
+ const bodyEtag = etag && body != null ? generateETag(body) : void 0;
5232
+ resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag, status: statusOf() });
5233
+ return origEnd(body);
5234
+ };
5235
+ }
5166
5236
  next();
5167
5237
  });
5168
5238
  },
5169
5239
  ttl,
5170
5240
  { swr, tags }
5171
5241
  );
5242
+ const respStatus = cached.status;
5243
+ if (typeof respStatus === "number" && (respStatus < 200 || respStatus >= 300)) {
5244
+ await activeCache.delete(key).catch(() => {
5245
+ });
5246
+ return;
5247
+ }
5172
5248
  if (!res.headersSent) {
5173
5249
  if (cached.etag) {
5174
5250
  if (res.setHeader) res.setHeader("ETag", cached.etag);
@@ -5213,12 +5289,18 @@ function honoCache(options = {}) {
5213
5289
  return {
5214
5290
  body: text,
5215
5291
  contentType: res.headers.get("content-type") ?? "text/plain",
5216
- etag: bodyEtag
5292
+ etag: bodyEtag,
5293
+ status: typeof res.status === "number" ? res.status : void 0
5217
5294
  };
5218
5295
  },
5219
5296
  ttl,
5220
5297
  { swr, tags }
5221
5298
  );
5299
+ if (typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300)) {
5300
+ await activeCache.delete(key).catch(() => {
5301
+ });
5302
+ return;
5303
+ }
5222
5304
  if (cached.etag && ifNoneMatch === cached.etag) {
5223
5305
  return c.body(null, 304, { ETag: cached.etag });
5224
5306
  }
@@ -5266,8 +5348,11 @@ function fastifyCache(options = {}) {
5266
5348
  if (payload !== void 0 && payload !== null) {
5267
5349
  const payloadEtag = etag ? generateETag(payload) : void 0;
5268
5350
  const contentType = reply.getHeader && reply.getHeader("content-type") || (typeof payload === "object" ? "application/json" : "text/plain");
5269
- activeCache.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, void 0, { tags }).catch(() => {
5270
- });
5351
+ const respStatus = reply.statusCode ?? reply.raw?.statusCode;
5352
+ if (respStatus === void 0 || respStatus >= 200 && respStatus < 300) {
5353
+ activeCache.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, void 0, { tags }).catch(() => {
5354
+ });
5355
+ }
5271
5356
  if (ifNoneMatch && ifNoneMatch === payloadEtag) {
5272
5357
  if (reply.code) reply.code(304);
5273
5358
  else if (reply.status) reply.status(304);
@@ -1,4 +1,4 @@
1
- import { W as WrapOptions, C as CacheService } from '../cache-service-BblHuF3i.js';
1
+ import { W as WrapOptions, C as CacheService } from '../cache-service-D8tIXmzb.js';
2
2
 
3
3
  /**
4
4
  * tricache/http — Universal HTTP Caching, ETag generation, and 304 Not Modified middleware
@@ -13,7 +13,7 @@ function expressCache(options = {}) {
13
13
  }
14
14
  let activeCache = cache;
15
15
  if (!activeCache) {
16
- const { CacheService } = await import("../cache-service-AJASH5FX.js");
16
+ const { CacheService } = await import("../cache-service-5GATUYAK.js");
17
17
  activeCache = CacheService.create();
18
18
  }
19
19
  const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.originalUrl || req.url}`;
@@ -25,12 +25,16 @@ function expressCache(options = {}) {
25
25
  return new Promise((resolve) => {
26
26
  const origJson = res.json?.bind(res);
27
27
  const origSend = res.send?.bind(res);
28
+ const origEnd = res.end?.bind(res);
29
+ const statusOf = () => res.statusCode;
28
30
  if (origJson) {
29
31
  res.json = (body) => {
30
32
  const bodyEtag = etag ? generateETag(body) : void 0;
31
- resolve({ body, contentType: "application/json; charset=utf-8", etag: bodyEtag });
33
+ resolve({ body, contentType: "application/json; charset=utf-8", etag: bodyEtag, status: statusOf() });
32
34
  if (ifNoneMatch && ifNoneMatch === bodyEtag) {
33
- return res.status(304).end();
35
+ res.status?.(304);
36
+ origEnd?.();
37
+ return;
34
38
  }
35
39
  if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
36
40
  return origJson(body);
@@ -39,20 +43,35 @@ function expressCache(options = {}) {
39
43
  if (origSend) {
40
44
  res.send = (body) => {
41
45
  const bodyEtag = etag ? generateETag(body) : void 0;
42
- resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag });
46
+ resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag, status: statusOf() });
43
47
  if (ifNoneMatch && ifNoneMatch === bodyEtag) {
44
- return res.status(304).end();
48
+ res.status?.(304);
49
+ origEnd?.();
50
+ return;
45
51
  }
46
52
  if (bodyEtag && res.setHeader) res.setHeader("ETag", bodyEtag);
47
53
  return origSend(body);
48
54
  };
49
55
  }
56
+ if (origEnd) {
57
+ res.end = (body) => {
58
+ const bodyEtag = etag && body != null ? generateETag(body) : void 0;
59
+ resolve({ body, contentType: res.getHeader ? res.getHeader("content-type") : void 0, etag: bodyEtag, status: statusOf() });
60
+ return origEnd(body);
61
+ };
62
+ }
50
63
  next();
51
64
  });
52
65
  },
53
66
  ttl,
54
67
  { swr, tags }
55
68
  );
69
+ const respStatus = cached.status;
70
+ if (typeof respStatus === "number" && (respStatus < 200 || respStatus >= 300)) {
71
+ await activeCache.delete(key).catch(() => {
72
+ });
73
+ return;
74
+ }
56
75
  if (!res.headersSent) {
57
76
  if (cached.etag) {
58
77
  if (res.setHeader) res.setHeader("ETag", cached.etag);
@@ -82,7 +101,7 @@ function honoCache(options = {}) {
82
101
  }
83
102
  let activeCache = cache;
84
103
  if (!activeCache) {
85
- const { CacheService } = await import("../cache-service-AJASH5FX.js");
104
+ const { CacheService } = await import("../cache-service-5GATUYAK.js");
86
105
  activeCache = CacheService.create();
87
106
  }
88
107
  const key = keyGenerator ? keyGenerator(c.req) : `http:${c.req.method}:${c.req.url}`;
@@ -97,12 +116,18 @@ function honoCache(options = {}) {
97
116
  return {
98
117
  body: text,
99
118
  contentType: res.headers.get("content-type") ?? "text/plain",
100
- etag: bodyEtag
119
+ etag: bodyEtag,
120
+ status: typeof res.status === "number" ? res.status : void 0
101
121
  };
102
122
  },
103
123
  ttl,
104
124
  { swr, tags }
105
125
  );
126
+ if (typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300)) {
127
+ await activeCache.delete(key).catch(() => {
128
+ });
129
+ return;
130
+ }
106
131
  if (cached.etag && ifNoneMatch === cached.etag) {
107
132
  return c.body(null, 304, { ETag: cached.etag });
108
133
  }
@@ -118,7 +143,7 @@ function fastifyCache(options = {}) {
118
143
  if (req.method !== "GET" && req.method !== "HEAD") return;
119
144
  let activeCache = cache;
120
145
  if (!activeCache) {
121
- const { CacheService } = await import("../cache-service-AJASH5FX.js");
146
+ const { CacheService } = await import("../cache-service-5GATUYAK.js");
122
147
  activeCache = CacheService.create();
123
148
  }
124
149
  const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.url}`;
@@ -150,8 +175,11 @@ function fastifyCache(options = {}) {
150
175
  if (payload !== void 0 && payload !== null) {
151
176
  const payloadEtag = etag ? generateETag(payload) : void 0;
152
177
  const contentType = reply.getHeader && reply.getHeader("content-type") || (typeof payload === "object" ? "application/json" : "text/plain");
153
- activeCache.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, void 0, { tags }).catch(() => {
154
- });
178
+ const respStatus = reply.statusCode ?? reply.raw?.statusCode;
179
+ if (respStatus === void 0 || respStatus >= 200 && respStatus < 300) {
180
+ activeCache.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, void 0, { tags }).catch(() => {
181
+ });
182
+ }
155
183
  if (ifNoneMatch && ifNoneMatch === payloadEtag) {
156
184
  if (reply.code) reply.code(304);
157
185
  else if (reply.status) reply.status(304);