tricache 0.8.0 → 1.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 (56) hide show
  1. package/README.md +10 -4
  2. package/dashboards/prometheus-scrape.yml +18 -0
  3. package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
  4. package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
  5. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  6. package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
  7. package/dist/chunk-BQRURGGD.js +60 -0
  8. package/dist/chunk-IITRFWHY.js +196 -0
  9. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  10. package/dist/cli.cjs +767 -133
  11. package/dist/cli.js +24 -6
  12. package/dist/dashboard/index.d.ts +2 -2
  13. package/dist/drizzle/index.cjs +734 -132
  14. package/dist/drizzle/index.d.ts +2 -2
  15. package/dist/drizzle/index.js +1 -1
  16. package/dist/edge/index.cjs +163 -46
  17. package/dist/edge/index.d.ts +3 -3
  18. package/dist/edge/index.js +42 -14
  19. package/dist/hono/index.cjs +8093 -0
  20. package/dist/hono/index.d.ts +91 -0
  21. package/dist/hono/index.js +185 -0
  22. package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
  23. package/dist/http/index.cjs +833 -170
  24. package/dist/http/index.d.ts +6 -30
  25. package/dist/http/index.js +9 -59
  26. package/dist/index.cjs +755 -130
  27. package/dist/index.d.ts +35 -6
  28. package/dist/index.js +16 -6
  29. package/dist/nestjs/index.cjs +725 -130
  30. package/dist/nestjs/index.d.ts +2 -2
  31. package/dist/nestjs/index.js +4 -4
  32. package/dist/next/index.cjs +725 -130
  33. package/dist/next/index.d.ts +2 -2
  34. package/dist/next/index.js +3 -3
  35. package/dist/prisma/index.d.ts +2 -2
  36. package/dist/serialize-worker.cjs +127 -9
  37. package/dist/serialize-worker.js +8 -4
  38. package/dist/{types-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
  39. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  40. package/package.json +22 -9
  41. package/src/cache-service.ts +540 -68
  42. package/src/cli.ts +21 -4
  43. package/src/compression.ts +193 -15
  44. package/src/cross-region.ts +1 -1
  45. package/src/edge/cache.ts +38 -11
  46. package/src/edge/hono.ts +123 -42
  47. package/src/env.d.ts +13 -0
  48. package/src/hono/index.ts +316 -0
  49. package/src/http/index.ts +5 -0
  50. package/src/index.ts +9 -1
  51. package/src/ipc-telemetry.ts +29 -1
  52. package/src/serialize-worker.ts +6 -2
  53. package/src/types.ts +68 -5
  54. package/src/utils/tag-matcher.ts +90 -0
  55. package/dist/chunk-ZTSWCFYO.js +0 -135
  56. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
@@ -0,0 +1,91 @@
1
+ import { C as CacheService } from '../cache-service-pJ-nFcVj.js';
2
+ import { W as WrapOptions } from '../types-5HXqBfAf.js';
3
+ import { K as KeyDerivationOptions } from '../utils-CEsU_Z0s.js';
4
+ import 'crypto';
5
+
6
+ /**
7
+ * tricache/hono — first-class Node.js Hono middleware on CacheService.
8
+ *
9
+ * This is the Node three-tier path (L1 RAM → L1.5 disk → L2 Redis), not the
10
+ * Web-Crypto edge helper exported from `tricache/edge` / `tricache/http`.
11
+ *
12
+ * Usage:
13
+ * import { Hono } from 'hono';
14
+ * import { cacheMiddleware } from 'tricache/hono';
15
+ *
16
+ * const app = new Hono();
17
+ * app.get('/api/posts', cacheMiddleware({ ttl: 300, tags: ['posts'] }), (c) => {
18
+ * return c.json({ data: '...' });
19
+ * });
20
+ */
21
+
22
+ /**
23
+ * Minimal Hono context surface used by the middleware.
24
+ * Compatible with `import('hono').Context` without taking a runtime dependency.
25
+ */
26
+ interface HonoCacheContext {
27
+ req: {
28
+ method: string;
29
+ url: string;
30
+ header?: (name: string) => string | undefined;
31
+ headers?: Headers | Record<string, string | string[] | undefined>;
32
+ };
33
+ res?: {
34
+ status?: number;
35
+ headers?: {
36
+ get(name: string): string | null | undefined;
37
+ };
38
+ clone?: () => {
39
+ text: () => Promise<string>;
40
+ };
41
+ body?: unknown;
42
+ };
43
+ body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
44
+ executionCtx?: unknown;
45
+ }
46
+ type HonoNext = () => Promise<void>;
47
+ type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
48
+ interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
49
+ /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
50
+ cache?: CacheService;
51
+ /** Whether to generate and evaluate weak ETags. Default: true. */
52
+ etag?: boolean;
53
+ /** Custom cache key. Overrides default method + URL + sorted query derivation. */
54
+ keyGenerator?: (c: HonoCacheContext) => string;
55
+ /** Custom predicate to skip caching dynamically (e.g. authenticated sessions). */
56
+ skipCache?: (c: HonoCacheContext) => boolean;
57
+ /** Dynamic tags derivation from the Hono context. */
58
+ tags?: string[] | ((c: HonoCacheContext) => string[]);
59
+ }
60
+ interface CachedHonoResponse {
61
+ body: string;
62
+ contentType?: string;
63
+ headers?: Record<string, string>;
64
+ etag?: string;
65
+ status: number;
66
+ }
67
+ /**
68
+ * Creates a Hono middleware that caches GET/HEAD responses through Node
69
+ * `CacheService`, with Express-aligned ttl/tags/SWR options, weak ETags, and
70
+ * RFC 7232 `If-None-Match` → `304 Not Modified`. Non-2xx, 206 Partial Content,
71
+ * private/no-store, and streaming SSE responses are never kept.
72
+ *
73
+ * @example
74
+ * import { Hono } from 'hono';
75
+ * import { CacheService } from 'tricache';
76
+ * import { cacheMiddleware } from 'tricache/hono';
77
+ *
78
+ * const app = new Hono();
79
+ * const cache = CacheService.create();
80
+ *
81
+ * app.get(
82
+ * '/api/posts',
83
+ * cacheMiddleware({ cache, ttl: 300, tags: ['posts'] }),
84
+ * (c) => c.json({ data: '...' }),
85
+ * );
86
+ */
87
+ declare function cacheMiddleware(options?: HonoCacheOptions): HonoMiddleware;
88
+ /** Alias matching `createExpressMiddleware` / `createKoaMiddleware` naming. */
89
+ declare const createHonoMiddleware: typeof cacheMiddleware;
90
+
91
+ export { type CachedHonoResponse, type HonoCacheContext, type HonoCacheOptions, type HonoMiddleware, type HonoNext, cacheMiddleware, createHonoMiddleware };
@@ -0,0 +1,185 @@
1
+ import {
2
+ buildDeterministicKey,
3
+ generateETag,
4
+ shouldSkipCache
5
+ } from "../chunk-BQRURGGD.js";
6
+
7
+ // src/hono/index.ts
8
+ function readRequestHeader(c, name) {
9
+ const headerFn = c.req.header;
10
+ if (typeof headerFn === "function") {
11
+ const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
12
+ if (viaFn !== void 0 && viaFn !== null && viaFn !== "") {
13
+ return viaFn;
14
+ }
15
+ }
16
+ const raw = c.req.headers;
17
+ if (!raw) return void 0;
18
+ if (typeof raw.get === "function") {
19
+ const viaGet = raw.get(name);
20
+ if (viaGet) return viaGet;
21
+ }
22
+ const record = raw;
23
+ const val = record[name.toLowerCase()] ?? record[name];
24
+ if (val === void 0 || val === null || val === "") return void 0;
25
+ return Array.isArray(val) ? val.join(",") : String(val);
26
+ }
27
+ function toRequestLike(c, headerWhitelist) {
28
+ const headers = {};
29
+ const cacheControl = readRequestHeader(c, "cache-control");
30
+ const ifNoneMatch = readRequestHeader(c, "if-none-match");
31
+ if (cacheControl) {
32
+ headers["cache-control"] = cacheControl;
33
+ headers["Cache-Control"] = cacheControl;
34
+ }
35
+ if (ifNoneMatch) {
36
+ headers["if-none-match"] = ifNoneMatch;
37
+ headers["If-None-Match"] = ifNoneMatch;
38
+ }
39
+ if (headerWhitelist) {
40
+ for (const h of headerWhitelist) {
41
+ headers[h.toLowerCase()] = readRequestHeader(c, h);
42
+ }
43
+ }
44
+ return {
45
+ method: (c.req.method || "GET").toUpperCase(),
46
+ url: c.req.url || "/",
47
+ headers
48
+ };
49
+ }
50
+ function isCacheableStatus(status) {
51
+ return status >= 200 && status < 300 && status !== 206;
52
+ }
53
+ function hasNoStoreDirective(cacheControl) {
54
+ if (!cacheControl) return false;
55
+ const lower = cacheControl.toLowerCase();
56
+ return lower.includes("no-store") || lower.includes("no-cache") || lower.includes("private");
57
+ }
58
+ function applyHonoCachedResponse(c, cached, ifNoneMatch) {
59
+ if (cached.etag && ifNoneMatch === cached.etag) {
60
+ const notModifiedHeaders = { ETag: cached.etag };
61
+ if (cached.headers?.["cache-control"]) notModifiedHeaders["Cache-Control"] = cached.headers["cache-control"];
62
+ if (cached.headers?.["vary"]) notModifiedHeaders["Vary"] = cached.headers["vary"];
63
+ const result2 = c.body(null, 304, notModifiedHeaders);
64
+ if (result2 != null) {
65
+ c.res = result2;
66
+ }
67
+ return result2;
68
+ }
69
+ const headers = { ...cached.headers };
70
+ if (cached.etag) headers["ETag"] = cached.etag;
71
+ if (cached.contentType) headers["Content-Type"] = cached.contentType;
72
+ const result = c.body(cached.body, cached.status ?? 200, headers);
73
+ if (result != null) {
74
+ c.res = result;
75
+ }
76
+ return result;
77
+ }
78
+ async function snapshotHonoResponse(c, etag) {
79
+ const res = c.res;
80
+ if (!res) {
81
+ return { body: "", status: 0 };
82
+ }
83
+ const contentType = res.headers?.get?.("content-type") || "text/plain; charset=utf-8";
84
+ if (contentType.toLowerCase().includes("text/event-stream")) {
85
+ return { body: "", contentType, status: 0 };
86
+ }
87
+ const cacheControl = res.headers?.get?.("cache-control");
88
+ if (hasNoStoreDirective(cacheControl)) {
89
+ return { body: "", contentType, status: 0 };
90
+ }
91
+ const status = res.status ?? 200;
92
+ if (!isCacheableStatus(status)) {
93
+ return { body: "", contentType, status };
94
+ }
95
+ const clone = typeof res.clone === "function" ? res.clone() : void 0;
96
+ const text = clone && typeof clone.text === "function" ? await clone.text() : typeof res.body === "string" ? res.body : "";
97
+ const bodyEtag = etag ? generateETag(text) : void 0;
98
+ const capturedHeaders = {};
99
+ if (res.headers && typeof res.headers.forEach === "function") {
100
+ res.headers.forEach((value, name) => {
101
+ const lower = name.toLowerCase();
102
+ if (lower !== "content-length" && lower !== "transfer-encoding" && lower !== "connection" && lower !== "etag" && lower !== "content-type") {
103
+ capturedHeaders[name] = value;
104
+ }
105
+ });
106
+ }
107
+ return {
108
+ body: text,
109
+ contentType,
110
+ headers: capturedHeaders,
111
+ etag: bodyEtag,
112
+ status
113
+ };
114
+ }
115
+ var NonCacheableHonoResponseError = class extends Error {
116
+ constructor(response) {
117
+ super(`Non-cacheable response: status=${response.status}`);
118
+ this.response = response;
119
+ this.name = "NonCacheableHonoResponseError";
120
+ }
121
+ response;
122
+ isNonCacheable = true;
123
+ };
124
+ function cacheMiddleware(options = {}) {
125
+ const {
126
+ cache,
127
+ etag = true,
128
+ ttl = 300,
129
+ swr,
130
+ tags,
131
+ skipCache,
132
+ keyGenerator,
133
+ headerWhitelist
134
+ } = options;
135
+ let resolvedCache = cache;
136
+ return async (c, next) => {
137
+ const method = (c.req.method || "GET").toUpperCase();
138
+ if (method !== "GET" && method !== "HEAD") {
139
+ return await next();
140
+ }
141
+ const reqLike = toRequestLike(c, headerWhitelist);
142
+ if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : void 0)) {
143
+ return await next();
144
+ }
145
+ if (!resolvedCache) {
146
+ const { CacheService } = await import("../cache-service-26GCO3UU.js");
147
+ resolvedCache = CacheService.create();
148
+ }
149
+ const activeCache = resolvedCache;
150
+ const key = keyGenerator ? keyGenerator(c) : buildDeterministicKey(reqLike, { headerWhitelist });
151
+ const ifNoneMatch = readRequestHeader(c, "if-none-match");
152
+ const resolvedTags = typeof tags === "function" ? tags(c) : tags;
153
+ let ranNext = false;
154
+ try {
155
+ const cached = await activeCache.get(
156
+ key,
157
+ async () => {
158
+ ranNext = true;
159
+ await next();
160
+ const snapshot = await snapshotHonoResponse(c, etag);
161
+ if (!isCacheableStatus(snapshot.status)) {
162
+ throw new NonCacheableHonoResponseError(snapshot);
163
+ }
164
+ return snapshot;
165
+ },
166
+ ttl,
167
+ { swr, tags: resolvedTags }
168
+ );
169
+ return applyHonoCachedResponse(c, cached, ifNoneMatch);
170
+ } catch (err) {
171
+ if (err instanceof NonCacheableHonoResponseError) {
172
+ if (!ranNext) {
173
+ return await next();
174
+ }
175
+ return;
176
+ }
177
+ throw err;
178
+ }
179
+ };
180
+ }
181
+ var createHonoMiddleware = cacheMiddleware;
182
+ export {
183
+ cacheMiddleware,
184
+ createHonoMiddleware
185
+ };
@@ -1,4 +1,4 @@
1
- import { I as ICacheTracer } from './types-B6krw64X.js';
1
+ import { I as ICacheTracer, a as InvalidateTagOptions } from './types-5HXqBfAf.js';
2
2
 
3
3
  /**
4
4
  * Pluggable asynchronous key-value storage adapter for Edge runtimes (L2 tier).
@@ -263,7 +263,7 @@ declare class EdgeCacheService {
263
263
  set<T>(key: string, value: T, ttlSeconds?: number, options?: {
264
264
  tags?: string[];
265
265
  swr?: number;
266
- }): Promise<void>;
266
+ } | string[]): Promise<void>;
267
267
  /**
268
268
  * Deletes a key from all tiers.
269
269
  */
@@ -271,7 +271,7 @@ declare class EdgeCacheService {
271
271
  /**
272
272
  * Invalidates all cached entries associated with a tag.
273
273
  */
274
- invalidateTag(tag: string): Promise<void>;
274
+ invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void>;
275
275
  /**
276
276
  * Clears all entries from the edge cache.
277
277
  */
@@ -279,7 +279,7 @@ declare class EdgeCacheService {
279
279
  /**
280
280
  * Batch get with miss-fetching.
281
281
  */
282
- mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T>>, ttlSeconds?: number): Promise<(T | null)[]>;
282
+ mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>, ttlSeconds?: number): Promise<(T | null)[]>;
283
283
  /**
284
284
  * Serializes active, unexpired L1 entries into a snapshot string (encrypted if WebCrypto encryption is enabled).
285
285
  * Ideal for persisting Edge state to Cloudflare R2 before worker restart.
@@ -335,6 +335,7 @@ interface HonoEdgeCacheOptions {
335
335
  interface CachedEdgeHttpResponse {
336
336
  body: string;
337
337
  contentType: string;
338
+ headers?: Record<string, string>;
338
339
  etag?: string;
339
340
  status: number;
340
341
  }
@@ -365,6 +366,6 @@ declare function buildEdgeDeterministicKey(c: any, options?: {
365
366
  * return c.json({ status: 'ok', timestamp: Date.now() });
366
367
  * });
367
368
  */
368
- declare function honoEdgeCache(options?: HonoEdgeCacheOptions): (c: any, next: () => Promise<void>) => Promise<any>;
369
+ declare function honoEdgeCache(options?: HonoEdgeCacheOptions): (c: any, next: () => Promise<void>) => Promise<void | Response>;
369
370
 
370
371
  export { type CachedEdgeHttpResponse as C, type EdgeCacheOptions as E, type HonoEdgeCacheOptions as H, type IEdgeRemoteStorage as I, type UpstashRedisOptions as U, type CloudflareKVNamespace as a, buildEdgeDeterministicKey as b, computeEdgeETag as c, type CloudflareDOStorage as d, type CloudflareR2Bucket as e, type CloudflareR2Object as f, EdgeCacheService as g, honoEdgeCache as h, type EdgeExportSnapshotOptions as i, type EdgeGetOptions as j, type EdgeHydrateOptions as k, type EdgeSnapshotPayload as l, type EdgeSnapshotSource as m, type IEdgeBloomFilter as n };