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
package/src/http/index.ts CHANGED
@@ -1,223 +1,265 @@
1
- /**
2
- * tricache/http — Universal HTTP Caching, ETag generation, and 304 Not Modified middleware
3
- * for Express, Fastify, and Hono.
4
- *
5
- * Usage with Express:
6
- * import { expressCache } from 'tricache/http';
7
- * app.get('/api/users', expressCache({ cache, ttl: 300, tags: ['users'] }), handler);
8
- *
9
- * Usage with Hono:
10
- * import { honoCache } from 'tricache/http';
11
- * app.get('/api/users', honoCache({ cache, ttl: 300, tags: ['users'] }), handler);
12
- */
13
-
14
- import type { CacheService } from '../cache-service.js';
15
- import type { WrapOptions } from '../types.js';
16
- import crypto from 'crypto';
17
-
18
- export interface HttpCacheOptions extends WrapOptions {
19
- /** TriCache instance. If omitted, uses singleton CacheService.create(). */
20
- cache?: CacheService;
21
- /** Custom key derivation function. Defaults to `${method}:${url}`. */
22
- keyGenerator?: (req: any) => string;
23
- /** Whether to emit weak ETags (default: true). */
24
- etag?: boolean;
25
- }
26
-
27
- /** Compute a weak ETag from a string, Buffer, or object */
28
- export function generateETag(data: unknown): string {
29
- const str = typeof data === 'string'
30
- ? data
31
- : Buffer.isBuffer(data)
32
- ? data.toString('utf8')
33
- : JSON.stringify(data);
34
- const hash = crypto.createHash('sha1').update(str).digest('hex').slice(0, 16);
35
- return `W/"${str.length.toString(16)}-${hash}"`;
36
- }
37
-
38
- /** Express / Connect middleware */
39
- export function expressCache(options: HttpCacheOptions = {}) {
40
- const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
41
-
42
- return async (req: any, res: any, next: any) => {
43
- if (req.method !== 'GET' && req.method !== 'HEAD') {
44
- return next();
45
- }
46
-
47
- let activeCache = cache;
48
- if (!activeCache) {
49
- const { CacheService } = await import('../cache-service.js');
50
- activeCache = CacheService.create();
51
- }
52
-
53
- const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.originalUrl || req.url}`;
54
- const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
55
-
56
- try {
57
- const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string }>(
58
- key,
59
- async () => {
60
- return new Promise((resolve) => {
61
- const origJson = res.json?.bind(res);
62
- const origSend = res.send?.bind(res);
63
-
64
- if (origJson) {
65
- res.json = (body: any) => {
66
- const bodyEtag = etag ? generateETag(body) : undefined;
67
- resolve({ body, contentType: 'application/json; charset=utf-8', etag: bodyEtag });
68
- if (ifNoneMatch && ifNoneMatch === bodyEtag) {
69
- return res.status(304).end();
70
- }
71
- if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
72
- return origJson(body);
73
- };
74
- }
75
-
76
- if (origSend) {
77
- res.send = (body: any) => {
78
- const bodyEtag = etag ? generateETag(body) : undefined;
79
- resolve({ body, contentType: res.getHeader ? res.getHeader('content-type') : undefined, etag: bodyEtag });
80
- if (ifNoneMatch && ifNoneMatch === bodyEtag) {
81
- return res.status(304).end();
82
- }
83
- if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
84
- return origSend(body);
85
- };
86
- }
87
-
88
- next();
89
- });
90
- },
91
- ttl,
92
- { swr, tags }
93
- );
94
-
95
- if (!res.headersSent) {
96
- if (cached.etag) {
97
- if (res.setHeader) res.setHeader('ETag', cached.etag);
98
- if (ifNoneMatch === cached.etag) {
99
- return res.status(304).end();
100
- }
101
- }
102
- if (cached.contentType && res.setHeader) {
103
- res.setHeader('Content-Type', cached.contentType);
104
- }
105
- if (typeof cached.body === 'object' && cached.body !== null && res.json) {
106
- return res.json(cached.body);
107
- } else if (res.send) {
108
- return res.send(cached.body);
109
- }
110
- }
111
- } catch (err) {
112
- next(err);
113
- }
114
- };
115
- }
116
-
117
- /** Hono / Web Standard middleware */
118
- export function honoCache(options: HttpCacheOptions = {}) {
119
- const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
120
-
121
- return async (c: any, next: any) => {
122
- if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
123
- return await next();
124
- }
125
-
126
- let activeCache = cache;
127
- if (!activeCache) {
128
- const { CacheService } = await import('../cache-service.js');
129
- activeCache = CacheService.create();
130
- }
131
-
132
- const key = keyGenerator ? keyGenerator(c.req) : `http:${c.req.method}:${c.req.url}`;
133
- const ifNoneMatch = c.req.header ? c.req.header('if-none-match') : undefined;
134
-
135
- const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string }>(
136
- key,
137
- async () => {
138
- await next();
139
- const res = c.res;
140
- const text = await res.clone().text();
141
- const bodyEtag = etag ? generateETag(text) : undefined;
142
- return {
143
- body: text,
144
- contentType: res.headers.get('content-type') ?? 'text/plain',
145
- etag: bodyEtag,
146
- };
147
- },
148
- ttl,
149
- { swr, tags }
150
- );
151
-
152
- if (cached.etag && ifNoneMatch === cached.etag) {
153
- return c.body(null, 304, { ETag: cached.etag });
154
- }
155
-
156
- const headers: Record<string, string> = {};
157
- if (cached.etag) headers['ETag'] = cached.etag;
158
- if (cached.contentType) headers['Content-Type'] = cached.contentType;
159
-
160
- return c.body(cached.body, 200, headers);
161
- };
162
- }
163
-
164
- /** Fastify preHandler hook */
165
- export function fastifyCache(options: HttpCacheOptions = {}) {
166
- const { cache, keyGenerator, etag = true, ttl = 300, tags } = options;
167
-
168
- return async (req: any, reply: any) => {
169
- if (req.method !== 'GET' && req.method !== 'HEAD') return;
170
-
171
- let activeCache = cache;
172
- if (!activeCache) {
173
- const { CacheService } = await import('../cache-service.js');
174
- activeCache = CacheService.create();
175
- }
176
-
177
- const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.url}`;
178
- const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
179
-
180
- // Fast-path: Check if already cached in L1 / Disk / Redis
181
- const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string } | null>(
182
- key,
183
- async () => null,
184
- 0
185
- );
186
-
187
- if (cached) {
188
- if (cached.etag) {
189
- if (reply.header) reply.header('ETag', cached.etag);
190
- if (ifNoneMatch === cached.etag) {
191
- if (reply.code) reply.code(304);
192
- else if (reply.status) reply.status(304);
193
- if (reply.send) return reply.send();
194
- return;
195
- }
196
- }
197
- if (cached.contentType && reply.header) {
198
- reply.header('Content-Type', cached.contentType);
199
- }
200
- if (reply.send) return reply.send(cached.body);
201
- return;
202
- }
203
-
204
- // Miss path: intercept reply.send on completion
205
- const origSend = reply.send?.bind(reply);
206
- if (origSend) {
207
- reply.send = function (payload: any) {
208
- if (payload !== undefined && payload !== null) {
209
- const payloadEtag = etag ? generateETag(payload) : undefined;
210
- const contentType = (reply.getHeader && reply.getHeader('content-type')) || (typeof payload === 'object' ? 'application/json' : 'text/plain');
211
- activeCache!.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, undefined, { tags }).catch(() => {});
212
- if (ifNoneMatch && ifNoneMatch === payloadEtag) {
213
- if (reply.code) reply.code(304);
214
- else if (reply.status) reply.status(304);
215
- return origSend();
216
- }
217
- if (payloadEtag && reply.header) reply.header('ETag', payloadEtag);
218
- }
219
- return origSend(payload);
220
- };
221
- }
222
- };
223
- }
1
+ /**
2
+ * tricache/http — Universal HTTP Caching, ETag generation, and 304 Not Modified middleware
3
+ * for Express, Fastify, and Hono.
4
+ *
5
+ * Usage with Express:
6
+ * import { expressCache } from 'tricache/http';
7
+ * app.get('/api/users', expressCache({ cache, ttl: 300, tags: ['users'] }), handler);
8
+ *
9
+ * Usage with Hono:
10
+ * import { honoCache } from 'tricache/http';
11
+ * app.get('/api/users', honoCache({ cache, ttl: 300, tags: ['users'] }), handler);
12
+ */
13
+
14
+ import type { CacheService } from '../cache-service.js';
15
+ import type { WrapOptions } from '../types.js';
16
+ import crypto from 'crypto';
17
+
18
+ export interface HttpCacheOptions extends WrapOptions {
19
+ /** TriCache instance. If omitted, uses singleton CacheService.create(). */
20
+ cache?: CacheService;
21
+ /** Custom key derivation function. Defaults to `${method}:${url}`. */
22
+ keyGenerator?: (req: any) => string;
23
+ /** Whether to emit weak ETags (default: true). */
24
+ etag?: boolean;
25
+ }
26
+
27
+ /** Compute a weak ETag from a string, Buffer, or object */
28
+ export function generateETag(data: unknown): string {
29
+ const str = typeof data === 'string'
30
+ ? data
31
+ : Buffer.isBuffer(data)
32
+ ? data.toString('utf8')
33
+ : JSON.stringify(data);
34
+ const hash = crypto.createHash('sha1').update(str).digest('hex').slice(0, 16);
35
+ return `W/"${str.length.toString(16)}-${hash}"`;
36
+ }
37
+
38
+ /** Express / Connect middleware */
39
+ export function expressCache(options: HttpCacheOptions = {}) {
40
+ const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
41
+
42
+ return async (req: any, res: any, next: any) => {
43
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
44
+ return next();
45
+ }
46
+
47
+ let activeCache = cache;
48
+ if (!activeCache) {
49
+ const { CacheService } = await import('../cache-service.js');
50
+ activeCache = CacheService.create();
51
+ }
52
+
53
+ const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.originalUrl || req.url}`;
54
+ const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
55
+
56
+ try {
57
+ const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string; status?: number }>(
58
+ key,
59
+ async () => {
60
+ return new Promise((resolve) => {
61
+ const origJson = res.json?.bind(res);
62
+ const origSend = res.send?.bind(res);
63
+ const origEnd = res.end?.bind(res);
64
+ const statusOf = () => (res as { statusCode?: number }).statusCode;
65
+
66
+ if (origJson) {
67
+ res.json = (body: any) => {
68
+ const bodyEtag = etag ? generateETag(body) : undefined;
69
+ resolve({ body, contentType: 'application/json; charset=utf-8', etag: bodyEtag, status: statusOf() });
70
+ if (ifNoneMatch && ifNoneMatch === bodyEtag) {
71
+ res.status?.(304);
72
+ origEnd?.();
73
+ return;
74
+ }
75
+ if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
76
+ return origJson(body);
77
+ };
78
+ }
79
+
80
+ if (origSend) {
81
+ res.send = (body: any) => {
82
+ const bodyEtag = etag ? generateETag(body) : undefined;
83
+ resolve({ body, contentType: res.getHeader ? (res.getHeader('content-type') as string | undefined) : undefined, etag: bodyEtag, status: statusOf() });
84
+ if (ifNoneMatch && ifNoneMatch === bodyEtag) {
85
+ res.status?.(304);
86
+ origEnd?.();
87
+ return;
88
+ }
89
+ if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
90
+ return origSend(body);
91
+ };
92
+ }
93
+
94
+ // Handlers that answer via res.end() (empty bodies, strings, buffers)
95
+ // previously never resolved the fetchFn promise — the middleware hung
96
+ // forever. end() is a third completion signal alongside json/send.
97
+ if (origEnd) {
98
+ res.end = (body?: unknown) => {
99
+ const bodyEtag = etag && body != null ? generateETag(body) : undefined;
100
+ resolve({ body, contentType: res.getHeader ? (res.getHeader('content-type') as string | undefined) : undefined, etag: bodyEtag, status: statusOf() });
101
+ return origEnd(body as never);
102
+ };
103
+ }
104
+
105
+ next();
106
+ });
107
+ },
108
+ ttl,
109
+ { swr, tags }
110
+ );
111
+
112
+ // Status gate: error responses must never be cached. get() has already
113
+ // stored whatever the handler produced — evict it immediately so the next
114
+ // request re-runs the handler instead of replaying a transient 4xx/5xx
115
+ // for the whole TTL window.
116
+ const respStatus = (cached as { status?: number }).status;
117
+ if (typeof respStatus === 'number' && (respStatus < 200 || respStatus >= 300)) {
118
+ await activeCache.delete(key).catch(() => {});
119
+ return;
120
+ }
121
+
122
+ if (!res.headersSent) {
123
+ if (cached.etag) {
124
+ if (res.setHeader) res.setHeader('ETag', cached.etag);
125
+ if (ifNoneMatch === cached.etag) {
126
+ return res.status(304).end();
127
+ }
128
+ }
129
+ if (cached.contentType && res.setHeader) {
130
+ res.setHeader('Content-Type', cached.contentType);
131
+ }
132
+ if (typeof cached.body === 'object' && cached.body !== null && res.json) {
133
+ return res.json(cached.body);
134
+ } else if (res.send) {
135
+ return res.send(cached.body);
136
+ }
137
+ }
138
+ } catch (err) {
139
+ next(err);
140
+ }
141
+ };
142
+ }
143
+
144
+ /** Hono / Web Standard middleware */
145
+ export function honoCache(options: HttpCacheOptions = {}) {
146
+ const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
147
+
148
+ return async (c: any, next: any) => {
149
+ if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
150
+ return await next();
151
+ }
152
+
153
+ let activeCache = cache;
154
+ if (!activeCache) {
155
+ const { CacheService } = await import('../cache-service.js');
156
+ activeCache = CacheService.create();
157
+ }
158
+
159
+ const key = keyGenerator ? keyGenerator(c.req) : `http:${c.req.method}:${c.req.url}`;
160
+ const ifNoneMatch = c.req.header ? c.req.header('if-none-match') : undefined;
161
+
162
+ const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string; status?: number }>(
163
+ key,
164
+ async () => {
165
+ await next();
166
+ const res = c.res;
167
+ const text = await res.clone().text();
168
+ const bodyEtag = etag ? generateETag(text) : undefined;
169
+ return {
170
+ body: text,
171
+ contentType: res.headers.get('content-type') ?? 'text/plain',
172
+ etag: bodyEtag,
173
+ status: typeof (res as { status?: unknown }).status === 'number'
174
+ ? (res as { status: number }).status
175
+ : undefined,
176
+ };
177
+ },
178
+ ttl,
179
+ { swr, tags }
180
+ );
181
+
182
+ // Status gate: never replay a transient 4xx/5xx from cache — evict and let
183
+ // the (already-dispatched) live response stand for this request.
184
+ if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
185
+ await activeCache.delete(key).catch(() => {});
186
+ return;
187
+ }
188
+
189
+ if (cached.etag && ifNoneMatch === cached.etag) {
190
+ return c.body(null, 304, { ETag: cached.etag });
191
+ }
192
+
193
+ const headers: Record<string, string> = {};
194
+ if (cached.etag) headers['ETag'] = cached.etag;
195
+ if (cached.contentType) headers['Content-Type'] = cached.contentType;
196
+
197
+ return c.body(cached.body, 200, headers);
198
+ };
199
+ }
200
+
201
+ /** Fastify preHandler hook */
202
+ export function fastifyCache(options: HttpCacheOptions = {}) {
203
+ const { cache, keyGenerator, etag = true, ttl = 300, tags } = options;
204
+
205
+ return async (req: any, reply: any) => {
206
+ if (req.method !== 'GET' && req.method !== 'HEAD') return;
207
+
208
+ let activeCache = cache;
209
+ if (!activeCache) {
210
+ const { CacheService } = await import('../cache-service.js');
211
+ activeCache = CacheService.create();
212
+ }
213
+
214
+ const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.url}`;
215
+ const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
216
+
217
+ // Fast-path: Check if already cached in L1 / Disk / Redis
218
+ const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string } | null>(
219
+ key,
220
+ async () => null,
221
+ 0
222
+ );
223
+
224
+ if (cached) {
225
+ if (cached.etag) {
226
+ if (reply.header) reply.header('ETag', cached.etag);
227
+ if (ifNoneMatch === cached.etag) {
228
+ if (reply.code) reply.code(304);
229
+ else if (reply.status) reply.status(304);
230
+ if (reply.send) return reply.send();
231
+ return;
232
+ }
233
+ }
234
+ if (cached.contentType && reply.header) {
235
+ reply.header('Content-Type', cached.contentType);
236
+ }
237
+ if (reply.send) return reply.send(cached.body);
238
+ return;
239
+ }
240
+
241
+ // Miss path: intercept reply.send on completion
242
+ const origSend = reply.send?.bind(reply);
243
+ if (origSend) {
244
+ reply.send = function (payload: any) {
245
+ if (payload !== undefined && payload !== null) {
246
+ const payloadEtag = etag ? generateETag(payload) : undefined;
247
+ const contentType = (reply.getHeader && reply.getHeader('content-type')) || (typeof payload === 'object' ? 'application/json' : 'text/plain');
248
+ // Status gate: only cache 2xx. A transient 4xx/5xx must not poison
249
+ // this key for the whole TTL window.
250
+ const respStatus = reply.statusCode ?? reply.raw?.statusCode;
251
+ if (respStatus === undefined || (respStatus >= 200 && respStatus < 300)) {
252
+ activeCache!.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, undefined, { tags }).catch(() => {});
253
+ }
254
+ if (ifNoneMatch && ifNoneMatch === payloadEtag) {
255
+ if (reply.code) reply.code(304);
256
+ else if (reply.status) reply.status(304);
257
+ return origSend();
258
+ }
259
+ if (payloadEtag && reply.header) reply.header('ETag', payloadEtag);
260
+ }
261
+ return origSend(payload);
262
+ };
263
+ }
264
+ };
265
+ }