tricache 1.0.1 → 2.0.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 (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,103 @@
1
+ import { K as KeyDerivationOptions } from '../utils-Bvzn-rKS.cjs';
2
+ export { b as buildDeterministicKey, g as generateETag, s as shouldSkipCache } from '../utils-Bvzn-rKS.cjs';
3
+ import { C as CacheService } from '../cache-service-BV5T8-20.cjs';
4
+ import { W as WrapOptions } from '../types-F8vRWMrE.cjs';
5
+ export { C as CachedEdgeHttpResponse, H as HonoEdgeCacheOptions, b as buildEdgeDeterministicKey, c as computeEdgeETag, h as honoCache } from '../hono-CMv2VdQ6.cjs';
6
+ import 'crypto';
7
+
8
+ interface ExpressCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOptions {
9
+ /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
10
+ cache?: CacheService;
11
+ /** Whether to generate and evaluate weak ETags. Default: true. */
12
+ etag?: boolean;
13
+ /** Custom predicate to skip caching dynamically for this request (e.g. authenticated sessions). */
14
+ skipCache?: (req: any) => boolean;
15
+ /** Dynamic tags derivation from request. */
16
+ tags?: string[] | ((req: any) => string[]);
17
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
18
+ swr?: number;
19
+ }
20
+ interface CachedHttpResponse {
21
+ body: unknown;
22
+ contentType?: string;
23
+ etag?: string;
24
+ status: number;
25
+ binary?: boolean;
26
+ headers?: Record<string, string | string[]>;
27
+ }
28
+ /**
29
+ * Creates an Express / Connect middleware that provides deterministic response caching,
30
+ * weak ETag generation, conditional 304 Not Modified short-circuiting, and Cache-Control bypass controls.
31
+ *
32
+ * @example
33
+ * import express from 'express';
34
+ * import { CacheService } from 'tricache';
35
+ * import { createExpressMiddleware } from 'tricache/http';
36
+ *
37
+ * const app = express();
38
+ * const cache = CacheService.create();
39
+ *
40
+ * app.get(
41
+ * '/api/products',
42
+ * createExpressMiddleware({
43
+ * cache,
44
+ * ttl: 120,
45
+ * tags: ['products'],
46
+ * headerWhitelist: ['accept-language'],
47
+ * }),
48
+ * async (req, res) => {
49
+ * const data = await getProducts();
50
+ * res.json(data);
51
+ * }
52
+ * );
53
+ */
54
+ declare function createExpressMiddleware(options?: ExpressCacheOptions): (req: any, res: any, next: any) => Promise<any>;
55
+ /** Alias matching legacy nomenclature */
56
+ declare const expressCache: typeof createExpressMiddleware;
57
+
58
+ interface FastifyCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOptions {
59
+ /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
60
+ cache?: CacheService;
61
+ /** Whether to generate and evaluate weak ETags. Default: true. */
62
+ etag?: boolean;
63
+ /** Custom predicate to skip caching dynamically for this request. */
64
+ skipCache?: (req: any) => boolean;
65
+ /** Dynamic tags derivation from request. */
66
+ tags?: string[] | ((req: any) => string[]);
67
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
68
+ swr?: number;
69
+ }
70
+ interface CachedFastifyResponse {
71
+ body: unknown;
72
+ contentType?: string;
73
+ etag?: string;
74
+ status: number;
75
+ binary?: boolean;
76
+ headers?: Record<string, string | string[]>;
77
+ }
78
+ /**
79
+ * Creates a Fastify plugin that registers `onRequest` and `onSend` lifecycle hooks.
80
+ *
81
+ * Designed to bypass Fastify's route encapsulation barrier (`skip-override`),
82
+ * allowing caching across global and nested route scopes.
83
+ *
84
+ * @example
85
+ * import Fastify from 'fastify';
86
+ * import { fastifyCachePlugin } from 'tricache/http';
87
+ *
88
+ * const app = Fastify();
89
+ * await app.register(fastifyCachePlugin, {
90
+ * ttl: 300,
91
+ * tags: ['api'],
92
+ * });
93
+ */
94
+ declare function createFastifyPlugin(options?: FastifyCacheOptions): (fastify: any, pluginOpts?: FastifyCacheOptions) => Promise<void>;
95
+ /** Standard Fastify plugin export */
96
+ declare const fastifyCachePlugin: (fastify: any, pluginOpts?: FastifyCacheOptions) => Promise<void>;
97
+ /**
98
+ * Universal Fastify middleware: functions both as a Fastify plugin (`fastify.register(fastifyCache(options))`)
99
+ * and as a route preHandler hook (`fastify.get('/route', { preHandler: fastifyCache(options) })`).
100
+ */
101
+ declare function fastifyCache(options?: FastifyCacheOptions): (first: any, second?: any) => Promise<any>;
102
+
103
+ export { type CachedFastifyResponse, type CachedHttpResponse, type ExpressCacheOptions, type FastifyCacheOptions, type ExpressCacheOptions as HttpCacheOptions, KeyDerivationOptions, createExpressMiddleware, createFastifyPlugin, expressCache, fastifyCache, fastifyCachePlugin };
@@ -1,8 +1,8 @@
1
- import { K as KeyDerivationOptions } from '../utils-CEsU_Z0s.js';
2
- export { b as buildDeterministicKey, g as generateETag, s as shouldSkipCache } from '../utils-CEsU_Z0s.js';
3
- import { C as CacheService } from '../cache-service-CREOp7MM.js';
4
- import { W as WrapOptions } from '../types-Dyip5wAl.js';
5
- export { C as CachedEdgeHttpResponse, H as HonoEdgeCacheOptions, b as buildEdgeDeterministicKey, c as computeEdgeETag, h as honoCache } from '../hono-DSV2ve66.js';
1
+ import { K as KeyDerivationOptions } from '../utils-Bvzn-rKS.js';
2
+ export { b as buildDeterministicKey, g as generateETag, s as shouldSkipCache } from '../utils-Bvzn-rKS.js';
3
+ import { C as CacheService } from '../cache-service-tpyrXvlH.js';
4
+ import { W as WrapOptions } from '../types-F8vRWMrE.js';
5
+ export { C as CachedEdgeHttpResponse, H as HonoEdgeCacheOptions, b as buildEdgeDeterministicKey, c as computeEdgeETag, h as honoCache } from '../hono-Dvq04kX9.js';
6
6
  import 'crypto';
7
7
 
8
8
  interface ExpressCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOptions {
@@ -14,12 +14,16 @@ interface ExpressCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOp
14
14
  skipCache?: (req: any) => boolean;
15
15
  /** Dynamic tags derivation from request. */
16
16
  tags?: string[] | ((req: any) => string[]);
17
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
18
+ swr?: number;
17
19
  }
18
20
  interface CachedHttpResponse {
19
21
  body: unknown;
20
22
  contentType?: string;
21
23
  etag?: string;
22
24
  status: number;
25
+ binary?: boolean;
26
+ headers?: Record<string, string | string[]>;
23
27
  }
24
28
  /**
25
29
  * Creates an Express / Connect middleware that provides deterministic response caching,
@@ -60,12 +64,16 @@ interface FastifyCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOp
60
64
  skipCache?: (req: any) => boolean;
61
65
  /** Dynamic tags derivation from request. */
62
66
  tags?: string[] | ((req: any) => string[]);
67
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
68
+ swr?: number;
63
69
  }
64
70
  interface CachedFastifyResponse {
65
71
  body: unknown;
66
72
  contentType?: string;
67
73
  etag?: string;
68
74
  status: number;
75
+ binary?: boolean;
76
+ headers?: Record<string, string | string[]>;
69
77
  }
70
78
  /**
71
79
  * Creates a Fastify plugin that registers `onRequest` and `onSend` lifecycle hooks.
@@ -2,38 +2,51 @@ import {
2
2
  buildEdgeDeterministicKey,
3
3
  computeEdgeETag,
4
4
  honoEdgeCache
5
- } from "../chunk-IITRFWHY.js";
5
+ } from "../chunk-EUKB7RKP.js";
6
6
  import {
7
7
  buildDeterministicKey,
8
8
  generateETag,
9
+ isCacheableHttpResponse,
10
+ isShareableHttpResponse,
11
+ matchesETag,
9
12
  shouldSkipCache
10
- } from "../chunk-BQRURGGD.js";
13
+ } from "../chunk-RBJRTGFK.js";
11
14
 
12
15
  // src/http/express.ts
16
+ var UncacheableHttpResponse = class extends Error {
17
+ constructor(response, shareable) {
18
+ super("Response is not cacheable");
19
+ this.response = response;
20
+ this.shareable = shareable;
21
+ }
22
+ response;
23
+ shareable;
24
+ };
13
25
  function createExpressMiddleware(options = {}) {
14
26
  const {
15
27
  cache,
16
28
  etag = true,
17
29
  ttl = 300,
18
- swr,
19
30
  tags,
20
31
  skipCache,
21
32
  keyGenerator,
22
- headerWhitelist
33
+ headerWhitelist,
34
+ cacheAuthenticated
23
35
  } = options;
24
36
  return async (req, res, next) => {
25
37
  if (req.method !== "GET" && req.method !== "HEAD") {
26
38
  return next();
27
39
  }
28
- if (shouldSkipCache(req, skipCache)) {
40
+ if (shouldSkipCache(req, skipCache, options)) {
29
41
  return next();
30
42
  }
31
43
  let activeCache = cache;
32
44
  if (!activeCache) {
33
- const { CacheService } = await import("../cache-service-MG7PN6MX.js");
45
+ const { CacheService } = await import("../cache-service-UZXOQGEY.js");
34
46
  activeCache = CacheService.create();
35
47
  }
36
- const key = buildDeterministicKey(req, { keyGenerator, headerWhitelist });
48
+ const keyOptions = { keyGenerator, headerWhitelist, cacheAuthenticated };
49
+ const key = buildDeterministicKey(req, keyOptions);
37
50
  const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
38
51
  const resolvedTags = typeof tags === "function" ? tags(req) : tags;
39
52
  let respondedLocally = false;
@@ -45,22 +58,37 @@ function createExpressMiddleware(options = {}) {
45
58
  const rawJson = res.json;
46
59
  const rawSend = res.send;
47
60
  const rawEnd = res.end;
61
+ const rawWrite = res.write;
48
62
  const origJson = rawJson?.bind(res);
49
63
  const origSend = rawSend?.bind(res);
50
64
  const origEnd = rawEnd?.bind(res);
51
65
  let settled = false;
66
+ let streamed = false;
52
67
  const cleanup = () => {
53
68
  if (rawJson !== void 0) res.json = rawJson;
54
69
  if (rawSend !== void 0) res.send = rawSend;
55
70
  if (rawEnd !== void 0) res.end = rawEnd;
71
+ if (rawWrite !== void 0) res.write = rawWrite;
56
72
  res.removeListener?.("close", onClose);
57
73
  };
58
74
  const settle = (response) => {
59
75
  if (settled) return;
60
76
  settled = true;
61
77
  respondedLocally = true;
78
+ response.binary = Buffer.isBuffer(response.body);
79
+ if (typeof res.getHeaders === "function") {
80
+ const headers = {};
81
+ for (const [name, value] of Object.entries(res.getHeaders())) {
82
+ if (!["content-length", "transfer-encoding", "connection", "set-cookie", "etag", "content-type"].includes(name.toLowerCase()) && value != null) {
83
+ headers[name] = Array.isArray(value) ? value : String(value);
84
+ }
85
+ }
86
+ response.headers = headers;
87
+ }
88
+ const header = (name) => res.getHeader?.(name);
62
89
  cleanup();
63
- resolve(response);
90
+ if (!streamed && isCacheableHttpResponse(response.status, header, keyOptions)) resolve(response);
91
+ else reject(new UncacheableHttpResponse(response, !streamed && isShareableHttpResponse(response.status, header, keyOptions)));
64
92
  };
65
93
  const onClose = () => {
66
94
  if (settled) return;
@@ -70,6 +98,10 @@ function createExpressMiddleware(options = {}) {
70
98
  reject(new Error("Express response closed before completion"));
71
99
  };
72
100
  res.once?.("close", onClose);
101
+ if (rawWrite) res.write = (...args) => {
102
+ streamed = true;
103
+ return rawWrite.apply(res, args);
104
+ };
73
105
  const getStatusCode = () => res.statusCode ?? 200;
74
106
  if (origJson) {
75
107
  res.json = (body) => {
@@ -77,7 +109,7 @@ function createExpressMiddleware(options = {}) {
77
109
  const bodyEtag = etag ? generateETag(body) : void 0;
78
110
  const contentType = res.getHeader?.("content-type") || "application/json; charset=utf-8";
79
111
  settle({ body, contentType, etag: bodyEtag, status });
80
- if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
112
+ if (isCacheableHttpResponse(status, (name) => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
81
113
  res.status?.(304);
82
114
  origEnd?.();
83
115
  return;
@@ -94,7 +126,7 @@ function createExpressMiddleware(options = {}) {
94
126
  const bodyEtag = etag ? generateETag(body) : void 0;
95
127
  const contentType = res.getHeader?.("content-type");
96
128
  settle({ body, contentType, etag: bodyEtag, status });
97
- if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
129
+ if (isCacheableHttpResponse(status, (name) => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
98
130
  res.status?.(304);
99
131
  origEnd?.();
100
132
  return;
@@ -106,12 +138,12 @@ function createExpressMiddleware(options = {}) {
106
138
  };
107
139
  }
108
140
  if (origEnd) {
109
- res.end = (body) => {
141
+ res.end = (body, ...args) => {
110
142
  const status = getStatusCode();
111
143
  const bodyEtag = etag && body != null ? generateETag(body) : void 0;
112
144
  const contentType = res.getHeader?.("content-type");
113
145
  settle({ body, contentType, etag: bodyEtag, status });
114
- return origEnd(body);
146
+ return origEnd(body, ...args);
115
147
  };
116
148
  }
117
149
  try {
@@ -126,17 +158,14 @@ function createExpressMiddleware(options = {}) {
126
158
  });
127
159
  },
128
160
  ttl,
129
- { swr, tags: resolvedTags }
161
+ // res/next belong to this request and cannot be reused for background SWR.
162
+ { swr: 0, tags: resolvedTags }
130
163
  );
131
- const isNon2xx = typeof cached.status === "number" && (cached.status < 200 || cached.status >= 300);
132
- if (isNon2xx) {
133
- await activeCache.delete(key).catch(() => {
134
- });
135
- }
136
164
  if (!respondedLocally && !res.headersSent) {
137
- if (!isNon2xx && cached.etag) {
165
+ for (const [name, value] of Object.entries(cached.headers ?? {})) res.setHeader?.(name, value);
166
+ if (cached.etag) {
138
167
  if (res.setHeader) res.setHeader("ETag", cached.etag);
139
- if (ifNoneMatch === cached.etag) {
168
+ if (matchesETag(ifNoneMatch, cached.etag)) {
140
169
  return res.status(304).end();
141
170
  }
142
171
  }
@@ -146,6 +175,11 @@ function createExpressMiddleware(options = {}) {
146
175
  if (cached.status && res.status) {
147
176
  res.status(cached.status);
148
177
  }
178
+ if (req.method === "HEAD") return res.end?.();
179
+ if (cached.binary) {
180
+ const body = Buffer.isBuffer(cached.body) ? cached.body : Buffer.from(cached.body.data);
181
+ return res.send ? res.send(body) : res.end?.(body);
182
+ }
149
183
  if (typeof cached.body === "object" && cached.body !== null && res.json) {
150
184
  return res.json(cached.body);
151
185
  } else if (res.send) {
@@ -155,6 +189,14 @@ function createExpressMiddleware(options = {}) {
155
189
  }
156
190
  }
157
191
  } catch (err) {
192
+ if (err instanceof UncacheableHttpResponse) {
193
+ if (respondedLocally || res.headersSent) return;
194
+ if (!err.shareable) return next();
195
+ const response = err.response;
196
+ if (response.contentType) res.setHeader?.("Content-Type", response.contentType);
197
+ res.status?.(response.status);
198
+ return typeof response.body === "object" && response.body !== null && !response.binary && res.json ? res.json(response.body) : res.send ? res.send(response.body) : res.end?.(response.body);
199
+ }
158
200
  next(err);
159
201
  }
160
202
  };
@@ -162,6 +204,9 @@ function createExpressMiddleware(options = {}) {
162
204
  var expressCache = createExpressMiddleware;
163
205
 
164
206
  // src/http/fastify.ts
207
+ function responseBody(entry) {
208
+ return entry.binary && !Buffer.isBuffer(entry.body) ? Buffer.from(entry.body.data) : entry.body;
209
+ }
165
210
  function createFastifyPlugin(options = {}) {
166
211
  const plugin = async function(fastify, pluginOpts = {}) {
167
212
  const mergedOpts = { ...options, ...pluginOpts };
@@ -169,14 +214,14 @@ function createFastifyPlugin(options = {}) {
169
214
  const ttl = mergedOpts.ttl ?? 300;
170
215
  let activeCache = mergedOpts.cache;
171
216
  if (!activeCache) {
172
- const { CacheService } = await import("../cache-service-MG7PN6MX.js");
217
+ const { CacheService } = await import("../cache-service-UZXOQGEY.js");
173
218
  activeCache = CacheService.create();
174
219
  }
175
220
  fastify.addHook("onRequest", async (req, reply) => {
176
221
  if (req.method !== "GET" && req.method !== "HEAD") {
177
222
  return;
178
223
  }
179
- if (shouldSkipCache(req, mergedOpts.skipCache)) {
224
+ if (shouldSkipCache(req, mergedOpts.skipCache, mergedOpts)) {
180
225
  return;
181
226
  }
182
227
  const key = buildDeterministicKey(req, {
@@ -186,9 +231,10 @@ function createFastifyPlugin(options = {}) {
186
231
  const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
187
232
  const cached = await activeCache.peek(key);
188
233
  if (cached && typeof cached === "object" && cached.body !== null) {
234
+ for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header(name, value);
189
235
  if (cached.etag) {
190
236
  reply.header("ETag", cached.etag);
191
- if (ifNoneMatch === cached.etag) {
237
+ if (matchesETag(ifNoneMatch, cached.etag)) {
192
238
  reply.code(304);
193
239
  return reply.send();
194
240
  }
@@ -197,9 +243,10 @@ function createFastifyPlugin(options = {}) {
197
243
  reply.header("Content-Type", cached.contentType);
198
244
  }
199
245
  reply.code(cached.status ?? 200);
200
- return reply.send(cached.body);
246
+ return reply.send(req.method === "HEAD" ? void 0 : responseBody(cached));
201
247
  }
202
248
  req._tricacheKey = key;
249
+ req._tricacheCanCommit = activeCache.captureMutationFence(key);
203
250
  const resolvedTags = typeof mergedOpts.tags === "function" ? mergedOpts.tags(req) : mergedOpts.tags;
204
251
  req._tricacheTags = resolvedTags;
205
252
  });
@@ -209,27 +256,29 @@ function createFastifyPlugin(options = {}) {
209
256
  return payload;
210
257
  }
211
258
  const statusCode = reply.statusCode ?? reply.raw?.statusCode ?? 200;
212
- if (statusCode >= 200 && statusCode < 300 && payload !== void 0 && payload !== null) {
259
+ if (req._tricacheCanCommit?.() && isCacheableHttpResponse(statusCode, (name) => reply.getHeader(name), mergedOpts) && payload !== void 0 && payload !== null && !(typeof payload === "object" && typeof payload.pipe === "function")) {
213
260
  const payloadEtag = etag ? generateETag(payload) : void 0;
214
261
  const contentType = reply.getHeader("content-type") || (typeof payload === "object" ? "application/json" : "text/plain");
215
262
  if (payloadEtag) {
216
263
  reply.header("ETag", payloadEtag);
217
264
  }
218
265
  const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
219
- if (ifNoneMatch && payloadEtag && ifNoneMatch === payloadEtag) {
220
- reply.code(304);
221
- return "";
222
- }
223
266
  const entry = {
224
267
  body: payload,
225
268
  contentType,
226
269
  etag: payloadEtag,
227
- status: statusCode
270
+ status: statusCode,
271
+ binary: Buffer.isBuffer(payload),
272
+ headers: reply.getHeaders ? Object.fromEntries(Object.entries(reply.getHeaders()).filter(([name]) => !["content-length", "transfer-encoding", "connection", "set-cookie", "content-type", "etag"].includes(name.toLowerCase()))) : void 0
228
273
  };
229
274
  void activeCache.set(key, entry, mergedOpts.ttl ?? ttl, void 0, {
230
275
  tags: req._tricacheTags
231
276
  }).catch(() => {
232
277
  });
278
+ if (payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
279
+ reply.code(304);
280
+ return "";
281
+ }
233
282
  }
234
283
  return payload;
235
284
  });
@@ -247,10 +296,10 @@ function fastifyCache(options = {}) {
247
296
  const req = first;
248
297
  const reply = second;
249
298
  if (req.method !== "GET" && req.method !== "HEAD") return;
250
- if (shouldSkipCache(req, options.skipCache)) return;
299
+ if (shouldSkipCache(req, options.skipCache, options)) return;
251
300
  let activeCache = options.cache;
252
301
  if (!activeCache) {
253
- const { CacheService } = await import("../cache-service-MG7PN6MX.js");
302
+ const { CacheService } = await import("../cache-service-UZXOQGEY.js");
254
303
  activeCache = CacheService.create();
255
304
  }
256
305
  const key = buildDeterministicKey(req, {
@@ -258,15 +307,12 @@ function fastifyCache(options = {}) {
258
307
  headerWhitelist: options.headerWhitelist
259
308
  });
260
309
  const ifNoneMatch = req.headers ? req.headers["if-none-match"] || req.headers["If-None-Match"] : void 0;
261
- const cached = await activeCache.get(
262
- key,
263
- async () => null,
264
- 0
265
- );
310
+ const cached = await activeCache.peek(key);
266
311
  if (cached && typeof cached === "object" && cached.body !== null) {
312
+ for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header?.(name, value);
267
313
  if (cached.etag) {
268
314
  if (reply.header) reply.header("ETag", cached.etag);
269
- if (ifNoneMatch === cached.etag) {
315
+ if (matchesETag(ifNoneMatch, cached.etag)) {
270
316
  if (reply.code) reply.code(304);
271
317
  else if (reply.status) reply.status(304);
272
318
  if (reply.send) return reply.send();
@@ -280,9 +326,10 @@ function fastifyCache(options = {}) {
280
326
  if (reply.code) reply.code(cached.status);
281
327
  else if (reply.status) reply.status(cached.status);
282
328
  }
283
- if (reply.send) return reply.send(cached.body);
329
+ if (reply.send) return reply.send(req.method === "HEAD" ? void 0 : responseBody(cached));
284
330
  return;
285
331
  }
332
+ const canCommit = activeCache.captureMutationFence(key);
286
333
  const origSend = reply.send?.bind(reply);
287
334
  if (origSend) {
288
335
  reply.send = function(resPayload) {
@@ -290,17 +337,19 @@ function fastifyCache(options = {}) {
290
337
  const payloadEtag = options.etag !== false ? generateETag(resPayload) : void 0;
291
338
  const contentType = reply.getHeader && reply.getHeader("content-type") || (typeof resPayload === "object" ? "application/json" : "text/plain");
292
339
  const respStatus = reply.statusCode ?? reply.raw?.statusCode ?? 200;
293
- if (respStatus >= 200 && respStatus < 300) {
340
+ const cacheable = isCacheableHttpResponse(respStatus, (name) => reply.getHeader?.(name), options);
341
+ if (cacheable && canCommit() && !(typeof resPayload === "object" && typeof resPayload.pipe === "function")) {
294
342
  const resolvedTags = typeof options.tags === "function" ? options.tags(req) : options.tags;
295
343
  void activeCache.set(
296
344
  key,
297
- { body: resPayload, contentType, etag: payloadEtag, status: respStatus },
345
+ { body: resPayload, contentType, etag: payloadEtag, status: respStatus, binary: Buffer.isBuffer(resPayload) },
298
346
  options.ttl ?? 300,
299
347
  void 0,
300
348
  { tags: resolvedTags }
301
- );
349
+ ).catch(() => {
350
+ });
302
351
  }
303
- if (ifNoneMatch && ifNoneMatch === payloadEtag) {
352
+ if (cacheable && payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
304
353
  if (reply.code) reply.code(304);
305
354
  else if (reply.status) reply.status(304);
306
355
  return origSend();