@jellyfungus/hono-rate-limiter 0.1.0 → 0.3.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.
package/dist/index.d.cts CHANGED
@@ -26,9 +26,42 @@ type StoreResult = {
26
26
  reset: number;
27
27
  };
28
28
  /**
29
- * Header format versions
29
+ * Quota unit for IETF standard headers.
30
+ * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/
30
31
  */
31
- type HeadersFormat = "draft-6" | "draft-7" | false;
32
+ type QuotaUnit = "requests" | "content-bytes" | "concurrent-requests";
33
+ /**
34
+ * Header format options.
35
+ *
36
+ * ## "legacy" (default)
37
+ * Common X-RateLimit-* headers used by GitHub, Twitter, and most APIs:
38
+ * - `X-RateLimit-Limit`: max requests in window
39
+ * - `X-RateLimit-Remaining`: remaining requests
40
+ * - `X-RateLimit-Reset`: Unix timestamp (seconds) when window resets
41
+ *
42
+ * ## "draft-6"
43
+ * IETF draft-06 format with individual RateLimit-* headers:
44
+ * - `RateLimit-Policy`: policy description (e.g., `100;w=60`)
45
+ * - `RateLimit-Limit`: max requests
46
+ * - `RateLimit-Remaining`: remaining requests
47
+ * - `RateLimit-Reset`: seconds until reset
48
+ *
49
+ * ## "draft-7"
50
+ * IETF draft-07 format with combined RateLimit header:
51
+ * - `RateLimit-Policy`: policy description
52
+ * - `RateLimit`: combined (e.g., `limit=100, remaining=50, reset=30`)
53
+ *
54
+ * ## "standard"
55
+ * Current IETF draft-08+ format with structured field values (RFC 9651):
56
+ * - `RateLimit-Policy`: `"name";q=100;w=60`
57
+ * - `RateLimit`: `"name";r=50;t=30`
58
+ *
59
+ * ## false
60
+ * Disable all rate limit headers.
61
+ *
62
+ * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/
63
+ */
64
+ type HeadersFormat = "legacy" | "draft-6" | "draft-7" | "standard" | false;
32
65
  /**
33
66
  * Rate limit algorithm
34
67
  */
@@ -53,6 +86,10 @@ type RateLimitStore = {
53
86
  * Reset a specific key.
54
87
  */
55
88
  resetKey: (key: string) => void | Promise<void>;
89
+ /**
90
+ * Reset all keys.
91
+ */
92
+ resetAll?: () => void | Promise<void>;
56
93
  /**
57
94
  * Get current state for key.
58
95
  */
@@ -62,6 +99,15 @@ type RateLimitStore = {
62
99
  */
63
100
  shutdown?: () => void | Promise<void>;
64
101
  };
102
+ /**
103
+ * Store access interface exposed in context
104
+ */
105
+ type RateLimitStoreAccess = {
106
+ /** Get rate limit info for a key */
107
+ getKey: (key: string) => StoreResult | Promise<StoreResult | undefined> | undefined;
108
+ /** Reset rate limit for a key */
109
+ resetKey: (key: string) => void | Promise<void>;
110
+ };
65
111
  /**
66
112
  * Options for rate limit middleware
67
113
  */
@@ -97,9 +143,28 @@ type RateLimitOptions<E extends Env = Env> = {
97
143
  handler?: (c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>;
98
144
  /**
99
145
  * HTTP header format to use.
100
- * @default 'draft-6'
146
+ *
147
+ * - "legacy": X-RateLimit-* headers (GitHub/Twitter style, default)
148
+ * - "draft-6": IETF draft-06 individual headers
149
+ * - "draft-7": IETF draft-07 combined header
150
+ * - "standard": IETF draft-08+ structured fields (current spec)
151
+ * - false: Disable headers
152
+ *
153
+ * @default 'legacy'
101
154
  */
102
155
  headers?: HeadersFormat;
156
+ /**
157
+ * Policy identifier for IETF headers (draft-6+).
158
+ * Used in RateLimit and RateLimit-Policy headers.
159
+ * @default 'default'
160
+ */
161
+ identifier?: string;
162
+ /**
163
+ * Quota unit for IETF standard headers.
164
+ * Only included in "standard" format when not "requests".
165
+ * @default 'requests'
166
+ */
167
+ quotaUnit?: QuotaUnit;
103
168
  /**
104
169
  * Skip rate limiting for certain requests.
105
170
  */
@@ -119,9 +184,41 @@ type RateLimitOptions<E extends Env = Env> = {
119
184
  */
120
185
  onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;
121
186
  };
187
+ /**
188
+ * Cloudflare Rate Limiting binding interface
189
+ */
190
+ type RateLimitBinding = {
191
+ limit: (options: {
192
+ key: string;
193
+ }) => Promise<{
194
+ success: boolean;
195
+ }>;
196
+ };
197
+ /**
198
+ * Options for Cloudflare Rate Limiting binding
199
+ */
200
+ type CloudflareRateLimitOptions<E extends Env = Env> = {
201
+ /**
202
+ * Cloudflare Rate Limiting binding from env
203
+ */
204
+ binding: RateLimitBinding | ((c: Context<E>) => RateLimitBinding);
205
+ /**
206
+ * Generate unique key for each client.
207
+ */
208
+ keyGenerator: (c: Context<E>) => string | Promise<string>;
209
+ /**
210
+ * Handler called when rate limit is exceeded.
211
+ */
212
+ handler?: (c: Context<E>) => Response | Promise<Response>;
213
+ /**
214
+ * Skip rate limiting for certain requests.
215
+ */
216
+ skip?: (c: Context<E>) => boolean | Promise<boolean>;
217
+ };
122
218
  declare module "hono" {
123
219
  interface ContextVariableMap {
124
220
  rateLimit?: RateLimitInfo;
221
+ rateLimitStore?: RateLimitStoreAccess;
125
222
  }
126
223
  }
127
224
  /**
@@ -137,6 +234,7 @@ declare class MemoryStore implements RateLimitStore {
137
234
  get(key: string): StoreResult | undefined;
138
235
  decrement(key: string): void;
139
236
  resetKey(key: string): void;
237
+ resetAll(): void;
140
238
  shutdown(): void;
141
239
  }
142
240
  declare function getClientIP(c: Context): string;
@@ -149,7 +247,7 @@ declare function getClientIP(c: Context): string;
149
247
  * @example
150
248
  * ```ts
151
249
  * import { Hono } from 'hono'
152
- * import { rateLimiter } from 'hono-rate-limit'
250
+ * import { rateLimiter } from '@jellyfungus/hono-rate-limiter'
153
251
  *
154
252
  * const app = new Hono()
155
253
  *
@@ -164,5 +262,26 @@ declare function getClientIP(c: Context): string;
164
262
  * ```
165
263
  */
166
264
  declare const rateLimiter: <E extends Env = Env>(options?: RateLimitOptions<E>) => MiddlewareHandler<E>;
265
+ /**
266
+ * Rate limiter using Cloudflare's built-in Rate Limiting binding.
267
+ *
268
+ * This uses Cloudflare's globally distributed rate limiting infrastructure,
269
+ * which is ideal for high-traffic applications.
270
+ *
271
+ * @example
272
+ * ```ts
273
+ * import { cloudflareRateLimiter } from '@jellyfungus/hono-rate-limiter'
274
+ *
275
+ * type Bindings = { RATE_LIMITER: RateLimitBinding }
276
+ *
277
+ * const app = new Hono<{ Bindings: Bindings }>()
278
+ *
279
+ * app.use(cloudflareRateLimiter({
280
+ * binding: (c) => c.env.RATE_LIMITER,
281
+ * keyGenerator: (c) => c.req.header('cf-connecting-ip') ?? 'unknown',
282
+ * }))
283
+ * ```
284
+ */
285
+ declare const cloudflareRateLimiter: <E extends Env = Env>(options: CloudflareRateLimitOptions<E>) => MiddlewareHandler<E>;
167
286
 
168
- export { type Algorithm, type HeadersFormat, MemoryStore, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type StoreResult, getClientIP, rateLimiter };
287
+ export { type Algorithm, type CloudflareRateLimitOptions, type HeadersFormat, MemoryStore, type QuotaUnit, type RateLimitBinding, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type RateLimitStoreAccess, type StoreResult, cloudflareRateLimiter, getClientIP, rateLimiter };
package/dist/index.d.ts CHANGED
@@ -26,9 +26,42 @@ type StoreResult = {
26
26
  reset: number;
27
27
  };
28
28
  /**
29
- * Header format versions
29
+ * Quota unit for IETF standard headers.
30
+ * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/
30
31
  */
31
- type HeadersFormat = "draft-6" | "draft-7" | false;
32
+ type QuotaUnit = "requests" | "content-bytes" | "concurrent-requests";
33
+ /**
34
+ * Header format options.
35
+ *
36
+ * ## "legacy" (default)
37
+ * Common X-RateLimit-* headers used by GitHub, Twitter, and most APIs:
38
+ * - `X-RateLimit-Limit`: max requests in window
39
+ * - `X-RateLimit-Remaining`: remaining requests
40
+ * - `X-RateLimit-Reset`: Unix timestamp (seconds) when window resets
41
+ *
42
+ * ## "draft-6"
43
+ * IETF draft-06 format with individual RateLimit-* headers:
44
+ * - `RateLimit-Policy`: policy description (e.g., `100;w=60`)
45
+ * - `RateLimit-Limit`: max requests
46
+ * - `RateLimit-Remaining`: remaining requests
47
+ * - `RateLimit-Reset`: seconds until reset
48
+ *
49
+ * ## "draft-7"
50
+ * IETF draft-07 format with combined RateLimit header:
51
+ * - `RateLimit-Policy`: policy description
52
+ * - `RateLimit`: combined (e.g., `limit=100, remaining=50, reset=30`)
53
+ *
54
+ * ## "standard"
55
+ * Current IETF draft-08+ format with structured field values (RFC 9651):
56
+ * - `RateLimit-Policy`: `"name";q=100;w=60`
57
+ * - `RateLimit`: `"name";r=50;t=30`
58
+ *
59
+ * ## false
60
+ * Disable all rate limit headers.
61
+ *
62
+ * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/
63
+ */
64
+ type HeadersFormat = "legacy" | "draft-6" | "draft-7" | "standard" | false;
32
65
  /**
33
66
  * Rate limit algorithm
34
67
  */
@@ -53,6 +86,10 @@ type RateLimitStore = {
53
86
  * Reset a specific key.
54
87
  */
55
88
  resetKey: (key: string) => void | Promise<void>;
89
+ /**
90
+ * Reset all keys.
91
+ */
92
+ resetAll?: () => void | Promise<void>;
56
93
  /**
57
94
  * Get current state for key.
58
95
  */
@@ -62,6 +99,15 @@ type RateLimitStore = {
62
99
  */
63
100
  shutdown?: () => void | Promise<void>;
64
101
  };
102
+ /**
103
+ * Store access interface exposed in context
104
+ */
105
+ type RateLimitStoreAccess = {
106
+ /** Get rate limit info for a key */
107
+ getKey: (key: string) => StoreResult | Promise<StoreResult | undefined> | undefined;
108
+ /** Reset rate limit for a key */
109
+ resetKey: (key: string) => void | Promise<void>;
110
+ };
65
111
  /**
66
112
  * Options for rate limit middleware
67
113
  */
@@ -97,9 +143,28 @@ type RateLimitOptions<E extends Env = Env> = {
97
143
  handler?: (c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>;
98
144
  /**
99
145
  * HTTP header format to use.
100
- * @default 'draft-6'
146
+ *
147
+ * - "legacy": X-RateLimit-* headers (GitHub/Twitter style, default)
148
+ * - "draft-6": IETF draft-06 individual headers
149
+ * - "draft-7": IETF draft-07 combined header
150
+ * - "standard": IETF draft-08+ structured fields (current spec)
151
+ * - false: Disable headers
152
+ *
153
+ * @default 'legacy'
101
154
  */
102
155
  headers?: HeadersFormat;
156
+ /**
157
+ * Policy identifier for IETF headers (draft-6+).
158
+ * Used in RateLimit and RateLimit-Policy headers.
159
+ * @default 'default'
160
+ */
161
+ identifier?: string;
162
+ /**
163
+ * Quota unit for IETF standard headers.
164
+ * Only included in "standard" format when not "requests".
165
+ * @default 'requests'
166
+ */
167
+ quotaUnit?: QuotaUnit;
103
168
  /**
104
169
  * Skip rate limiting for certain requests.
105
170
  */
@@ -119,9 +184,41 @@ type RateLimitOptions<E extends Env = Env> = {
119
184
  */
120
185
  onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;
121
186
  };
187
+ /**
188
+ * Cloudflare Rate Limiting binding interface
189
+ */
190
+ type RateLimitBinding = {
191
+ limit: (options: {
192
+ key: string;
193
+ }) => Promise<{
194
+ success: boolean;
195
+ }>;
196
+ };
197
+ /**
198
+ * Options for Cloudflare Rate Limiting binding
199
+ */
200
+ type CloudflareRateLimitOptions<E extends Env = Env> = {
201
+ /**
202
+ * Cloudflare Rate Limiting binding from env
203
+ */
204
+ binding: RateLimitBinding | ((c: Context<E>) => RateLimitBinding);
205
+ /**
206
+ * Generate unique key for each client.
207
+ */
208
+ keyGenerator: (c: Context<E>) => string | Promise<string>;
209
+ /**
210
+ * Handler called when rate limit is exceeded.
211
+ */
212
+ handler?: (c: Context<E>) => Response | Promise<Response>;
213
+ /**
214
+ * Skip rate limiting for certain requests.
215
+ */
216
+ skip?: (c: Context<E>) => boolean | Promise<boolean>;
217
+ };
122
218
  declare module "hono" {
123
219
  interface ContextVariableMap {
124
220
  rateLimit?: RateLimitInfo;
221
+ rateLimitStore?: RateLimitStoreAccess;
125
222
  }
126
223
  }
127
224
  /**
@@ -137,6 +234,7 @@ declare class MemoryStore implements RateLimitStore {
137
234
  get(key: string): StoreResult | undefined;
138
235
  decrement(key: string): void;
139
236
  resetKey(key: string): void;
237
+ resetAll(): void;
140
238
  shutdown(): void;
141
239
  }
142
240
  declare function getClientIP(c: Context): string;
@@ -149,7 +247,7 @@ declare function getClientIP(c: Context): string;
149
247
  * @example
150
248
  * ```ts
151
249
  * import { Hono } from 'hono'
152
- * import { rateLimiter } from 'hono-rate-limit'
250
+ * import { rateLimiter } from '@jellyfungus/hono-rate-limiter'
153
251
  *
154
252
  * const app = new Hono()
155
253
  *
@@ -164,5 +262,26 @@ declare function getClientIP(c: Context): string;
164
262
  * ```
165
263
  */
166
264
  declare const rateLimiter: <E extends Env = Env>(options?: RateLimitOptions<E>) => MiddlewareHandler<E>;
265
+ /**
266
+ * Rate limiter using Cloudflare's built-in Rate Limiting binding.
267
+ *
268
+ * This uses Cloudflare's globally distributed rate limiting infrastructure,
269
+ * which is ideal for high-traffic applications.
270
+ *
271
+ * @example
272
+ * ```ts
273
+ * import { cloudflareRateLimiter } from '@jellyfungus/hono-rate-limiter'
274
+ *
275
+ * type Bindings = { RATE_LIMITER: RateLimitBinding }
276
+ *
277
+ * const app = new Hono<{ Bindings: Bindings }>()
278
+ *
279
+ * app.use(cloudflareRateLimiter({
280
+ * binding: (c) => c.env.RATE_LIMITER,
281
+ * keyGenerator: (c) => c.req.header('cf-connecting-ip') ?? 'unknown',
282
+ * }))
283
+ * ```
284
+ */
285
+ declare const cloudflareRateLimiter: <E extends Env = Env>(options: CloudflareRateLimitOptions<E>) => MiddlewareHandler<E>;
167
286
 
168
- export { type Algorithm, type HeadersFormat, MemoryStore, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type StoreResult, getClientIP, rateLimiter };
287
+ export { type Algorithm, type CloudflareRateLimitOptions, type HeadersFormat, MemoryStore, type QuotaUnit, type RateLimitBinding, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type RateLimitStoreAccess, type StoreResult, cloudflareRateLimiter, getClientIP, rateLimiter };
package/dist/index.js CHANGED
@@ -44,6 +44,9 @@ var MemoryStore = class {
44
44
  resetKey(key) {
45
45
  this.entries.delete(key);
46
46
  }
47
+ resetAll() {
48
+ this.entries.clear();
49
+ }
47
50
  shutdown() {
48
51
  if (this.cleanupTimer) {
49
52
  clearInterval(this.cleanupTimer);
@@ -52,18 +55,40 @@ var MemoryStore = class {
52
55
  }
53
56
  };
54
57
  var defaultStore;
55
- function setHeaders(c, info, format) {
58
+ function setHeaders(c, info, format, windowMs, identifier, quotaUnit) {
56
59
  if (format === false) {
57
60
  return;
58
61
  }
62
+ const windowSeconds = Math.ceil(windowMs / 1e3);
59
63
  const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1e3));
60
64
  switch (format) {
65
+ case "standard":
66
+ {
67
+ let policy = `"${identifier}";q=${info.limit};w=${windowSeconds}`;
68
+ if (quotaUnit !== "requests") {
69
+ policy += `;qu="${quotaUnit}"`;
70
+ }
71
+ c.header("RateLimit-Policy", policy);
72
+ c.header(
73
+ "RateLimit",
74
+ `"${identifier}";r=${info.remaining};t=${resetSeconds}`
75
+ );
76
+ }
77
+ break;
61
78
  case "draft-7":
79
+ c.header("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
80
+ c.header(
81
+ "RateLimit",
82
+ `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`
83
+ );
84
+ break;
85
+ case "draft-6":
86
+ c.header("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
62
87
  c.header("RateLimit-Limit", String(info.limit));
63
88
  c.header("RateLimit-Remaining", String(info.remaining));
64
89
  c.header("RateLimit-Reset", String(resetSeconds));
65
90
  break;
66
- case "draft-6":
91
+ case "legacy":
67
92
  default:
68
93
  c.header("X-RateLimit-Limit", String(info.limit));
69
94
  c.header("X-RateLimit-Remaining", String(info.remaining));
@@ -139,7 +164,9 @@ var rateLimiter = (options) => {
139
164
  store: void 0,
140
165
  keyGenerator: getClientIP,
141
166
  handler: void 0,
142
- headers: "draft-6",
167
+ headers: "legacy",
168
+ identifier: "default",
169
+ quotaUnit: "requests",
143
170
  skip: void 0,
144
171
  skipSuccessfulRequests: false,
145
172
  skipFailedRequests: false,
@@ -163,7 +190,18 @@ var rateLimiter = (options) => {
163
190
  const limit = typeof opts.limit === "function" ? await opts.limit(c) : opts.limit;
164
191
  const { allowed, info } = opts.algorithm === "sliding-window" ? await checkSlidingWindow(store, key, limit, opts.windowMs) : await checkFixedWindow(store, key, limit, opts.windowMs);
165
192
  c.set("rateLimit", info);
166
- setHeaders(c, info, opts.headers);
193
+ c.set("rateLimitStore", {
194
+ getKey: store.get?.bind(store) ?? (() => void 0),
195
+ resetKey: store.resetKey.bind(store)
196
+ });
197
+ setHeaders(
198
+ c,
199
+ info,
200
+ opts.headers,
201
+ opts.windowMs,
202
+ opts.identifier,
203
+ opts.quotaUnit
204
+ );
167
205
  if (!allowed) {
168
206
  if (opts.onRateLimited) {
169
207
  await opts.onRateLimited(c, info);
@@ -185,8 +223,33 @@ var rateLimiter = (options) => {
185
223
  }
186
224
  };
187
225
  };
226
+ var cloudflareRateLimiter = (options) => {
227
+ const { binding, keyGenerator, handler, skip } = options;
228
+ return async function cloudflareRateLimiter2(c, next) {
229
+ if (skip) {
230
+ const shouldSkip = await skip(c);
231
+ if (shouldSkip) {
232
+ return next();
233
+ }
234
+ }
235
+ const rateLimitBinding = typeof binding === "function" ? binding(c) : binding;
236
+ const key = await keyGenerator(c);
237
+ const { success } = await rateLimitBinding.limit({ key });
238
+ if (!success) {
239
+ if (handler) {
240
+ return handler(c);
241
+ }
242
+ return new Response("Rate limit exceeded", {
243
+ status: 429,
244
+ headers: { "Content-Type": "text/plain" }
245
+ });
246
+ }
247
+ return next();
248
+ };
249
+ };
188
250
  export {
189
251
  MemoryStore,
252
+ cloudflareRateLimiter,
190
253
  getClientIP,
191
254
  rateLimiter
192
255
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @module\n * Rate Limit Middleware for Hono.\n */\n\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Rate limit information for a single request\n */\nexport type RateLimitInfo = {\n /** Maximum requests allowed in window */\n limit: number;\n /** Remaining requests in current window */\n remaining: number;\n /** Unix timestamp (ms) when window resets */\n reset: number;\n};\n\n/**\n * Result from store increment operation\n */\nexport type StoreResult = {\n /** Current request count in window */\n count: number;\n /** When the window resets (Unix timestamp ms) */\n reset: number;\n};\n\n/**\n * Header format versions\n */\nexport type HeadersFormat =\n | \"draft-6\" // X-RateLimit-* headers\n | \"draft-7\" // RateLimit-* without structured fields\n | false; // Disable headers\n\n/**\n * Rate limit algorithm\n */\nexport type Algorithm = \"fixed-window\" | \"sliding-window\";\n\n/**\n * Store interface for rate limit state\n */\nexport type RateLimitStore = {\n /**\n * Initialize store. Called once before first use.\n */\n init?: (windowMs: number) => void | Promise<void>;\n\n /**\n * Increment counter for key and return current state.\n */\n increment: (key: string) => StoreResult | Promise<StoreResult>;\n\n /**\n * Decrement counter for key.\n */\n decrement?: (key: string) => void | Promise<void>;\n\n /**\n * Reset a specific key.\n */\n resetKey: (key: string) => void | Promise<void>;\n\n /**\n * Get current state for key.\n */\n get?: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n\n /**\n * Graceful shutdown.\n */\n shutdown?: () => void | Promise<void>;\n};\n\n/**\n * Options for rate limit middleware\n */\nexport type RateLimitOptions<E extends Env = Env> = {\n /**\n * Maximum requests allowed in the time window.\n * @default 60\n */\n limit?: number | ((c: Context<E>) => number | Promise<number>);\n\n /**\n * Time window in milliseconds.\n * @default 60000 (1 minute)\n */\n windowMs?: number;\n\n /**\n * Rate limiting algorithm.\n * @default 'sliding-window'\n */\n algorithm?: Algorithm;\n\n /**\n * Storage backend for rate limit state.\n * @default MemoryStore\n */\n store?: RateLimitStore;\n\n /**\n * Generate unique key for each client.\n * @default IP address from headers\n */\n keyGenerator?: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (\n c: Context<E>,\n info: RateLimitInfo,\n ) => Response | Promise<Response>;\n\n /**\n * HTTP header format to use.\n * @default 'draft-6'\n */\n headers?: HeadersFormat;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n\n /**\n * Don't count successful (2xx) requests against limit.\n * @default false\n */\n skipSuccessfulRequests?: boolean;\n\n /**\n * Don't count failed (4xx, 5xx) requests against limit.\n * @default false\n */\n skipFailedRequests?: boolean;\n\n /**\n * Callback when a request is rate limited.\n */\n onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;\n};\n\n// ============================================================================\n// Context Variable Type Extension\n// ============================================================================\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n rateLimit?: RateLimitInfo;\n }\n}\n\n// ============================================================================\n// Memory Store\n// ============================================================================\n\ntype MemoryEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * In-memory store for rate limiting.\n * Suitable for single-instance deployments.\n */\nexport class MemoryStore implements RateLimitStore {\n private entries = new Map<string, MemoryEntry>();\n private windowMs = 60_000;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n\n // Cleanup expired entries every minute\n this.cleanupTimer = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.entries) {\n if (entry.reset <= now) {\n this.entries.delete(key);\n }\n }\n }, 60_000);\n\n // Don't keep process alive for cleanup\n if (typeof this.cleanupTimer.unref === \"function\") {\n this.cleanupTimer.unref();\n }\n }\n\n increment(key: string): StoreResult {\n const now = Date.now();\n const existing = this.entries.get(key);\n\n if (!existing || existing.reset <= now) {\n // New window\n const reset = now + this.windowMs;\n this.entries.set(key, { count: 1, reset });\n return { count: 1, reset };\n }\n\n // Increment existing\n existing.count++;\n return { count: existing.count, reset: existing.reset };\n }\n\n get(key: string): StoreResult | undefined {\n const entry = this.entries.get(key);\n if (!entry || entry.reset <= Date.now()) {\n return undefined;\n }\n return { count: entry.count, reset: entry.reset };\n }\n\n decrement(key: string): void {\n const entry = this.entries.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n resetKey(key: string): void {\n this.entries.delete(key);\n }\n\n shutdown(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n this.entries.clear();\n }\n}\n\n// Singleton default store\nlet defaultStore: MemoryStore | undefined;\n\n// ============================================================================\n// Header Generation\n// ============================================================================\n\nfunction setHeaders(\n c: Context,\n info: RateLimitInfo,\n format: HeadersFormat,\n): void {\n if (format === false) {\n return;\n }\n\n const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n switch (format) {\n case \"draft-7\":\n c.header(\"RateLimit-Limit\", String(info.limit));\n c.header(\"RateLimit-Remaining\", String(info.remaining));\n c.header(\"RateLimit-Reset\", String(resetSeconds));\n break;\n\n case \"draft-6\":\n default:\n c.header(\"X-RateLimit-Limit\", String(info.limit));\n c.header(\"X-RateLimit-Remaining\", String(info.remaining));\n c.header(\"X-RateLimit-Reset\", String(Math.ceil(info.reset / 1000)));\n break;\n }\n}\n\n// ============================================================================\n// Default Key Generator\n// ============================================================================\n\nfunction getClientIP(c: Context): string {\n // Platform-specific headers (most reliable)\n const cfIP = c.req.header(\"cf-connecting-ip\");\n if (cfIP) {\n return cfIP;\n }\n\n const xRealIP = c.req.header(\"x-real-ip\");\n if (xRealIP) {\n return xRealIP;\n }\n\n // X-Forwarded-For - take first IP\n const xff = c.req.header(\"x-forwarded-for\");\n if (xff) {\n return xff.split(\",\")[0].trim();\n }\n\n return \"unknown\";\n}\n\n// ============================================================================\n// Default Handler\n// ============================================================================\n\nfunction createDefaultResponse(info: RateLimitInfo): Response {\n const retryAfter = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: {\n \"Content-Type\": \"text/plain\",\n \"Retry-After\": String(retryAfter),\n },\n });\n}\n\n// ============================================================================\n// Sliding Window Algorithm\n// ============================================================================\n\nasync function checkSlidingWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const currentWindowStart = Math.floor(now / windowMs) * windowMs;\n const previousWindowStart = currentWindowStart - windowMs;\n\n const previousKey = `${key}:${previousWindowStart}`;\n const currentKey = `${key}:${currentWindowStart}`;\n\n // Increment current window\n const current = await store.increment(currentKey);\n\n // Get previous window (may not exist)\n let previousCount = 0;\n if (store.get) {\n const prev = await store.get(previousKey);\n previousCount = prev?.count ?? 0;\n }\n\n // Cloudflare's weighted formula\n const elapsedMs = now - currentWindowStart;\n const weight = (windowMs - elapsedMs) / windowMs;\n const estimatedCount = Math.floor(previousCount * weight) + current.count;\n\n const remaining = Math.max(0, limit - estimatedCount);\n const allowed = estimatedCount <= limit;\n const reset = currentWindowStart + windowMs;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Fixed Window Algorithm\n// ============================================================================\n\nasync function checkFixedWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const windowStart = Math.floor(now / windowMs) * windowMs;\n const windowKey = `${key}:${windowStart}`;\n\n const { count, reset } = await store.increment(windowKey);\n\n const remaining = Math.max(0, limit - count);\n const allowed = count <= limit;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Main Middleware\n// ============================================================================\n\n/**\n * Rate Limit Middleware for Hono.\n *\n * @param {RateLimitOptions} [options] - Configuration options\n * @returns {MiddlewareHandler} Middleware handler\n *\n * @example\n * ```ts\n * import { Hono } from 'hono'\n * import { rateLimiter } from 'hono-rate-limit'\n *\n * const app = new Hono()\n *\n * // Basic usage - 60 requests per minute\n * app.use(rateLimiter())\n *\n * // Custom configuration\n * app.use('/api/*', rateLimiter({\n * limit: 100,\n * windowMs: 60 * 1000,\n * }))\n * ```\n */\nexport const rateLimiter = <E extends Env = Env>(\n options?: RateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n // Merge with defaults\n const opts = {\n limit: 60 as number | ((c: Context<E>) => number | Promise<number>),\n windowMs: 60_000,\n algorithm: \"sliding-window\" as Algorithm,\n store: undefined as RateLimitStore | undefined,\n keyGenerator: getClientIP as (c: Context<E>) => string | Promise<string>,\n handler: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>)\n | undefined,\n headers: \"draft-6\" as HeadersFormat,\n skip: undefined as\n | ((c: Context<E>) => boolean | Promise<boolean>)\n | undefined,\n skipSuccessfulRequests: false,\n skipFailedRequests: false,\n onRateLimited: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => void | Promise<void>)\n | undefined,\n ...options,\n };\n\n // Use default store if none provided\n const store = opts.store ?? (defaultStore ??= new MemoryStore());\n\n // Track initialization\n let initialized = false;\n\n return async function rateLimiter(c, next) {\n // Initialize store on first request\n if (!initialized && store.init) {\n await store.init(opts.windowMs);\n initialized = true;\n }\n\n // Check if should skip\n if (opts.skip) {\n const shouldSkip = await opts.skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Generate key\n const key = await opts.keyGenerator(c);\n\n // Get limit (may be dynamic)\n const limit =\n typeof opts.limit === \"function\" ? await opts.limit(c) : opts.limit;\n\n // Check rate limit\n const { allowed, info } =\n opts.algorithm === \"sliding-window\"\n ? await checkSlidingWindow(store, key, limit, opts.windowMs)\n : await checkFixedWindow(store, key, limit, opts.windowMs);\n\n // Set context variable for downstream middleware\n c.set(\"rateLimit\", info);\n\n // Set headers\n setHeaders(c, info, opts.headers);\n\n // Handle rate limited\n if (!allowed) {\n // Fire callback\n if (opts.onRateLimited) {\n await opts.onRateLimited(c, info);\n }\n\n // Custom handler or default\n if (opts.handler) {\n return opts.handler(c, info);\n }\n return createDefaultResponse(info);\n }\n\n // Continue\n await next();\n\n // Handle skip options after response\n if (opts.skipSuccessfulRequests || opts.skipFailedRequests) {\n const status = c.res.status;\n const shouldDecrement =\n (opts.skipSuccessfulRequests && status >= 200 && status < 300) ||\n (opts.skipFailedRequests && status >= 400);\n\n if (shouldDecrement && store.decrement) {\n const windowStart =\n Math.floor(Date.now() / opts.windowMs) * opts.windowMs;\n const windowKey = `${key}:${windowStart}`;\n await store.decrement(windowKey);\n }\n }\n };\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { getClientIP };\n"],"mappings":";AAiLO,IAAM,cAAN,MAA4C;AAAA,EACzC,UAAU,oBAAI,IAAyB;AAAA,EACvC,WAAW;AAAA,EACX;AAAA,EAER,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAGhB,SAAK,eAAe,YAAY,MAAM;AACpC,YAAM,MAAM,KAAK,IAAI;AACrB,iBAAW,CAAC,KAAK,KAAK,KAAK,KAAK,SAAS;AACvC,YAAI,MAAM,SAAS,KAAK;AACtB,eAAK,QAAQ,OAAO,GAAG;AAAA,QACzB;AAAA,MACF;AAAA,IACF,GAAG,GAAM;AAGT,QAAI,OAAO,KAAK,aAAa,UAAU,YAAY;AACjD,WAAK,aAAa,MAAM;AAAA,IAC1B;AAAA,EACF;AAAA,EAEA,UAAU,KAA0B;AAClC,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,WAAW,KAAK,QAAQ,IAAI,GAAG;AAErC,QAAI,CAAC,YAAY,SAAS,SAAS,KAAK;AAEtC,YAAM,QAAQ,MAAM,KAAK;AACzB,WAAK,QAAQ,IAAI,KAAK,EAAE,OAAO,GAAG,MAAM,CAAC;AACzC,aAAO,EAAE,OAAO,GAAG,MAAM;AAAA,IAC3B;AAGA,aAAS;AACT,WAAO,EAAE,OAAO,SAAS,OAAO,OAAO,SAAS,MAAM;AAAA,EACxD;AAAA,EAEA,IAAI,KAAsC;AACxC,UAAM,QAAQ,KAAK,QAAQ,IAAI,GAAG;AAClC,QAAI,CAAC,SAAS,MAAM,SAAS,KAAK,IAAI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AEZ,UAAI,KAAK,eAAe;AACtB,cAAM,KAAK,cAAc,GAAG,IAAI;AAAA,MAClC;AAGA,UAAI,KAAK,SAAS;AAChB,eAAO,KAAK,QAAQ,GAAG,IAAI;AAAA,MAC7B;AACA,aAAO,sBAAsB,IAAI;AAAA,IACnC;AAGA,UAAM,KAAK;AAGX,QAAI,KAAK,0BAA0B,KAAK,oBAAoB;AAC1D,YAAM,SAAS,EAAE,IAAI;AACrB,YAAM,kBACH,KAAK,0BAA0B,UAAU,OAAO,SAAS,OACzD,KAAK,sBAAsB,UAAU;AAExC,UAAI,mBAAmB,MAAM,WAAW;AACtC,cAAM,cACJ,KAAK,MAAM,KAAK,IAAI,IAAI,KAAK,QAAQ,IAAI,KAAK;AAChD,cAAM,YAAY,GAAG,GAAG,IAAI,WAAW;AACvC,cAAM,MAAM,UAAU,SAAS;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AACF;","names":["rateLimiter"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @module\n * Rate Limit Middleware for Hono.\n */\n\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Rate limit information for a single request\n */\nexport type RateLimitInfo = {\n /** Maximum requests allowed in window */\n limit: number;\n /** Remaining requests in current window */\n remaining: number;\n /** Unix timestamp (ms) when window resets */\n reset: number;\n};\n\n/**\n * Result from store increment operation\n */\nexport type StoreResult = {\n /** Current request count in window */\n count: number;\n /** When the window resets (Unix timestamp ms) */\n reset: number;\n};\n\n/**\n * Quota unit for IETF standard headers.\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type QuotaUnit = \"requests\" | \"content-bytes\" | \"concurrent-requests\";\n\n/**\n * Header format options.\n *\n * ## \"legacy\" (default)\n * Common X-RateLimit-* headers used by GitHub, Twitter, and most APIs:\n * - `X-RateLimit-Limit`: max requests in window\n * - `X-RateLimit-Remaining`: remaining requests\n * - `X-RateLimit-Reset`: Unix timestamp (seconds) when window resets\n *\n * ## \"draft-6\"\n * IETF draft-06 format with individual RateLimit-* headers:\n * - `RateLimit-Policy`: policy description (e.g., `100;w=60`)\n * - `RateLimit-Limit`: max requests\n * - `RateLimit-Remaining`: remaining requests\n * - `RateLimit-Reset`: seconds until reset\n *\n * ## \"draft-7\"\n * IETF draft-07 format with combined RateLimit header:\n * - `RateLimit-Policy`: policy description\n * - `RateLimit`: combined (e.g., `limit=100, remaining=50, reset=30`)\n *\n * ## \"standard\"\n * Current IETF draft-08+ format with structured field values (RFC 9651):\n * - `RateLimit-Policy`: `\"name\";q=100;w=60`\n * - `RateLimit`: `\"name\";r=50;t=30`\n *\n * ## false\n * Disable all rate limit headers.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type HeadersFormat =\n | \"legacy\" // X-RateLimit-* headers (GitHub/Twitter style)\n | \"draft-6\" // IETF draft-06: individual RateLimit-* headers\n | \"draft-7\" // IETF draft-07: combined RateLimit header\n | \"standard\" // IETF draft-08+: structured field format (current)\n | false; // Disable headers\n\n/**\n * Rate limit algorithm\n */\nexport type Algorithm = \"fixed-window\" | \"sliding-window\";\n\n/**\n * Store interface for rate limit state\n */\nexport type RateLimitStore = {\n /**\n * Initialize store. Called once before first use.\n */\n init?: (windowMs: number) => void | Promise<void>;\n\n /**\n * Increment counter for key and return current state.\n */\n increment: (key: string) => StoreResult | Promise<StoreResult>;\n\n /**\n * Decrement counter for key.\n */\n decrement?: (key: string) => void | Promise<void>;\n\n /**\n * Reset a specific key.\n */\n resetKey: (key: string) => void | Promise<void>;\n\n /**\n * Reset all keys.\n */\n resetAll?: () => void | Promise<void>;\n\n /**\n * Get current state for key.\n */\n get?: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n\n /**\n * Graceful shutdown.\n */\n shutdown?: () => void | Promise<void>;\n};\n\n/**\n * Store access interface exposed in context\n */\nexport type RateLimitStoreAccess = {\n /** Get rate limit info for a key */\n getKey: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n /** Reset rate limit for a key */\n resetKey: (key: string) => void | Promise<void>;\n};\n\n/**\n * Options for rate limit middleware\n */\nexport type RateLimitOptions<E extends Env = Env> = {\n /**\n * Maximum requests allowed in the time window.\n * @default 60\n */\n limit?: number | ((c: Context<E>) => number | Promise<number>);\n\n /**\n * Time window in milliseconds.\n * @default 60000 (1 minute)\n */\n windowMs?: number;\n\n /**\n * Rate limiting algorithm.\n * @default 'sliding-window'\n */\n algorithm?: Algorithm;\n\n /**\n * Storage backend for rate limit state.\n * @default MemoryStore\n */\n store?: RateLimitStore;\n\n /**\n * Generate unique key for each client.\n * @default IP address from headers\n */\n keyGenerator?: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (\n c: Context<E>,\n info: RateLimitInfo,\n ) => Response | Promise<Response>;\n\n /**\n * HTTP header format to use.\n *\n * - \"legacy\": X-RateLimit-* headers (GitHub/Twitter style, default)\n * - \"draft-6\": IETF draft-06 individual headers\n * - \"draft-7\": IETF draft-07 combined header\n * - \"standard\": IETF draft-08+ structured fields (current spec)\n * - false: Disable headers\n *\n * @default 'legacy'\n */\n headers?: HeadersFormat;\n\n /**\n * Policy identifier for IETF headers (draft-6+).\n * Used in RateLimit and RateLimit-Policy headers.\n * @default 'default'\n */\n identifier?: string;\n\n /**\n * Quota unit for IETF standard headers.\n * Only included in \"standard\" format when not \"requests\".\n * @default 'requests'\n */\n quotaUnit?: QuotaUnit;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n\n /**\n * Don't count successful (2xx) requests against limit.\n * @default false\n */\n skipSuccessfulRequests?: boolean;\n\n /**\n * Don't count failed (4xx, 5xx) requests against limit.\n * @default false\n */\n skipFailedRequests?: boolean;\n\n /**\n * Callback when a request is rate limited.\n */\n onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;\n};\n\n/**\n * Cloudflare Rate Limiting binding interface\n */\nexport type RateLimitBinding = {\n limit: (options: { key: string }) => Promise<{ success: boolean }>;\n};\n\n/**\n * Options for Cloudflare Rate Limiting binding\n */\nexport type CloudflareRateLimitOptions<E extends Env = Env> = {\n /**\n * Cloudflare Rate Limiting binding from env\n */\n binding: RateLimitBinding | ((c: Context<E>) => RateLimitBinding);\n\n /**\n * Generate unique key for each client.\n */\n keyGenerator: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (c: Context<E>) => Response | Promise<Response>;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n};\n\n// ============================================================================\n// Context Variable Type Extension\n// ============================================================================\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n rateLimit?: RateLimitInfo;\n rateLimitStore?: RateLimitStoreAccess;\n }\n}\n\n// ============================================================================\n// Memory Store\n// ============================================================================\n\ntype MemoryEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * In-memory store for rate limiting.\n * Suitable for single-instance deployments.\n */\nexport class MemoryStore implements RateLimitStore {\n private entries = new Map<string, MemoryEntry>();\n private windowMs = 60_000;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n\n // Cleanup expired entries every minute\n this.cleanupTimer = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.entries) {\n if (entry.reset <= now) {\n this.entries.delete(key);\n }\n }\n }, 60_000);\n\n // Don't keep process alive for cleanup\n if (typeof this.cleanupTimer.unref === \"function\") {\n this.cleanupTimer.unref();\n }\n }\n\n increment(key: string): StoreResult {\n const now = Date.now();\n const existing = this.entries.get(key);\n\n if (!existing || existing.reset <= now) {\n // New window\n const reset = now + this.windowMs;\n this.entries.set(key, { count: 1, reset });\n return { count: 1, reset };\n }\n\n // Increment existing\n existing.count++;\n return { count: existing.count, reset: existing.reset };\n }\n\n get(key: string): StoreResult | undefined {\n const entry = this.entries.get(key);\n if (!entry || entry.reset <= Date.now()) {\n return undefined;\n }\n return { count: entry.count, reset: entry.reset };\n }\n\n decrement(key: string): void {\n const entry = this.entries.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n resetKey(key: string): void {\n this.entries.delete(key);\n }\n\n resetAll(): void {\n this.entries.clear();\n }\n\n shutdown(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n this.entries.clear();\n }\n}\n\n// Singleton default store\nlet defaultStore: MemoryStore | undefined;\n\n// ============================================================================\n// Header Generation\n// ============================================================================\n\n/**\n * Set rate limit response headers based on the configured format.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nfunction setHeaders(\n c: Context,\n info: RateLimitInfo,\n format: HeadersFormat,\n windowMs: number,\n identifier: string,\n quotaUnit: QuotaUnit,\n): void {\n if (format === false) {\n return;\n }\n\n const windowSeconds = Math.ceil(windowMs / 1000);\n const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n switch (format) {\n case \"standard\":\n // IETF draft-08+ (current): Structured field values per RFC 9651\n // RateLimit-Policy: describes the quota policy\n // Format: \"name\";q=<quota>;w=<window>[;qu=\"<unit>\"]\n {\n let policy = `\"${identifier}\";q=${info.limit};w=${windowSeconds}`;\n if (quotaUnit !== \"requests\") {\n policy += `;qu=\"${quotaUnit}\"`;\n }\n c.header(\"RateLimit-Policy\", policy);\n // RateLimit: describes current service limits\n // Format: \"name\";r=<remaining>;t=<reset>\n c.header(\n \"RateLimit\",\n `\"${identifier}\";r=${info.remaining};t=${resetSeconds}`,\n );\n }\n break;\n\n case \"draft-7\":\n // IETF draft-07: Combined RateLimit header with comma-separated values\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\n c.header(\n \"RateLimit\",\n `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`,\n );\n break;\n\n case \"draft-6\":\n // IETF draft-06: Individual RateLimit-* headers\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\n c.header(\"RateLimit-Limit\", String(info.limit));\n c.header(\"RateLimit-Remaining\", String(info.remaining));\n c.header(\"RateLimit-Reset\", String(resetSeconds));\n break;\n\n case \"legacy\":\n default:\n // Common X-RateLimit-* headers (GitHub, Twitter, most APIs)\n // Uses Unix timestamp for reset (seconds since epoch)\n c.header(\"X-RateLimit-Limit\", String(info.limit));\n c.header(\"X-RateLimit-Remaining\", String(info.remaining));\n c.header(\"X-RateLimit-Reset\", String(Math.ceil(info.reset / 1000)));\n break;\n }\n}\n\n// ============================================================================\n// Default Key Generator\n// ============================================================================\n\nfunction getClientIP(c: Context): string {\n // Platform-specific headers (most reliable)\n const cfIP = c.req.header(\"cf-connecting-ip\");\n if (cfIP) {\n return cfIP;\n }\n\n const xRealIP = c.req.header(\"x-real-ip\");\n if (xRealIP) {\n return xRealIP;\n }\n\n // X-Forwarded-For - take first IP\n const xff = c.req.header(\"x-forwarded-for\");\n if (xff) {\n return xff.split(\",\")[0].trim();\n }\n\n return \"unknown\";\n}\n\n// ============================================================================\n// Default Handler\n// ============================================================================\n\nfunction createDefaultResponse(info: RateLimitInfo): Response {\n const retryAfter = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: {\n \"Content-Type\": \"text/plain\",\n \"Retry-After\": String(retryAfter),\n },\n });\n}\n\n// ============================================================================\n// Sliding Window Algorithm\n// ============================================================================\n\nasync function checkSlidingWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const currentWindowStart = Math.floor(now / windowMs) * windowMs;\n const previousWindowStart = currentWindowStart - windowMs;\n\n const previousKey = `${key}:${previousWindowStart}`;\n const currentKey = `${key}:${currentWindowStart}`;\n\n // Increment current window\n const current = await store.increment(currentKey);\n\n // Get previous window (may not exist)\n let previousCount = 0;\n if (store.get) {\n const prev = await store.get(previousKey);\n previousCount = prev?.count ?? 0;\n }\n\n // Cloudflare's weighted formula\n const elapsedMs = now - currentWindowStart;\n const weight = (windowMs - elapsedMs) / windowMs;\n const estimatedCount = Math.floor(previousCount * weight) + current.count;\n\n const remaining = Math.max(0, limit - estimatedCount);\n const allowed = estimatedCount <= limit;\n const reset = currentWindowStart + windowMs;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Fixed Window Algorithm\n// ============================================================================\n\nasync function checkFixedWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const windowStart = Math.floor(now / windowMs) * windowMs;\n const windowKey = `${key}:${windowStart}`;\n\n const { count, reset } = await store.increment(windowKey);\n\n const remaining = Math.max(0, limit - count);\n const allowed = count <= limit;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Main Middleware\n// ============================================================================\n\n/**\n * Rate Limit Middleware for Hono.\n *\n * @param {RateLimitOptions} [options] - Configuration options\n * @returns {MiddlewareHandler} Middleware handler\n *\n * @example\n * ```ts\n * import { Hono } from 'hono'\n * import { rateLimiter } from '@jellyfungus/hono-rate-limiter'\n *\n * const app = new Hono()\n *\n * // Basic usage - 60 requests per minute\n * app.use(rateLimiter())\n *\n * // Custom configuration\n * app.use('/api/*', rateLimiter({\n * limit: 100,\n * windowMs: 60 * 1000,\n * }))\n * ```\n */\nexport const rateLimiter = <E extends Env = Env>(\n options?: RateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n // Merge with defaults\n const opts = {\n limit: 60 as number | ((c: Context<E>) => number | Promise<number>),\n windowMs: 60_000,\n algorithm: \"sliding-window\" as Algorithm,\n store: undefined as RateLimitStore | undefined,\n keyGenerator: getClientIP as (c: Context<E>) => string | Promise<string>,\n handler: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>)\n | undefined,\n headers: \"legacy\" as HeadersFormat,\n identifier: \"default\",\n quotaUnit: \"requests\" as QuotaUnit,\n skip: undefined as\n | ((c: Context<E>) => boolean | Promise<boolean>)\n | undefined,\n skipSuccessfulRequests: false,\n skipFailedRequests: false,\n onRateLimited: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => void | Promise<void>)\n | undefined,\n ...options,\n };\n\n // Use default store if none provided\n const store = opts.store ?? (defaultStore ??= new MemoryStore());\n\n // Track initialization\n let initialized = false;\n\n return async function rateLimiter(c, next) {\n // Initialize store on first request\n if (!initialized && store.init) {\n await store.init(opts.windowMs);\n initialized = true;\n }\n\n // Check if should skip\n if (opts.skip) {\n const shouldSkip = await opts.skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Generate key\n const key = await opts.keyGenerator(c);\n\n // Get limit (may be dynamic)\n const limit =\n typeof opts.limit === \"function\" ? await opts.limit(c) : opts.limit;\n\n // Check rate limit\n const { allowed, info } =\n opts.algorithm === \"sliding-window\"\n ? await checkSlidingWindow(store, key, limit, opts.windowMs)\n : await checkFixedWindow(store, key, limit, opts.windowMs);\n\n // Set context variable for downstream middleware\n c.set(\"rateLimit\", info);\n\n // Expose store access in context\n c.set(\"rateLimitStore\", {\n getKey: store.get?.bind(store) ?? (() => undefined),\n resetKey: store.resetKey.bind(store),\n });\n\n // Set headers\n setHeaders(\n c,\n info,\n opts.headers,\n opts.windowMs,\n opts.identifier,\n opts.quotaUnit,\n );\n\n // Handle rate limited\n if (!allowed) {\n // Fire callback\n if (opts.onRateLimited) {\n await opts.onRateLimited(c, info);\n }\n\n // Custom handler or default\n if (opts.handler) {\n return opts.handler(c, info);\n }\n return createDefaultResponse(info);\n }\n\n // Continue\n await next();\n\n // Handle skip options after response\n if (opts.skipSuccessfulRequests || opts.skipFailedRequests) {\n const status = c.res.status;\n const shouldDecrement =\n (opts.skipSuccessfulRequests && status >= 200 && status < 300) ||\n (opts.skipFailedRequests && status >= 400);\n\n if (shouldDecrement && store.decrement) {\n const windowStart =\n Math.floor(Date.now() / opts.windowMs) * opts.windowMs;\n const windowKey = `${key}:${windowStart}`;\n await store.decrement(windowKey);\n }\n }\n };\n};\n\n// ============================================================================\n// Cloudflare Rate Limiting Binding Middleware\n// ============================================================================\n\n/**\n * Rate limiter using Cloudflare's built-in Rate Limiting binding.\n *\n * This uses Cloudflare's globally distributed rate limiting infrastructure,\n * which is ideal for high-traffic applications.\n *\n * @example\n * ```ts\n * import { cloudflareRateLimiter } from '@jellyfungus/hono-rate-limiter'\n *\n * type Bindings = { RATE_LIMITER: RateLimitBinding }\n *\n * const app = new Hono<{ Bindings: Bindings }>()\n *\n * app.use(cloudflareRateLimiter({\n * binding: (c) => c.env.RATE_LIMITER,\n * keyGenerator: (c) => c.req.header('cf-connecting-ip') ?? 'unknown',\n * }))\n * ```\n */\nexport const cloudflareRateLimiter = <E extends Env = Env>(\n options: CloudflareRateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n const { binding, keyGenerator, handler, skip } = options;\n\n return async function cloudflareRateLimiter(c, next) {\n // Check if should skip\n if (skip) {\n const shouldSkip = await skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Get binding (may be dynamic)\n const rateLimitBinding =\n typeof binding === \"function\" ? binding(c) : binding;\n\n // Generate key\n const key = await keyGenerator(c);\n\n // Check rate limit\n const { success } = await rateLimitBinding.limit({ key });\n\n if (!success) {\n if (handler) {\n return handler(c);\n }\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: { \"Content-Type\": \"text/plain\" },\n });\n }\n\n return next();\n };\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { getClientIP };\n"],"mappings":";AA4RO,IAAM,cAAN,MAA4C;AAAA,EACzC,UAAU,oBAAI,IAAyB;AAAA,EACvC,WAAW;AAAA,EACX;AAAA,EAER,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAGhB,SAAK,eAAe,YAAY,MAAM;AACpC,YAAM,MAAM,KA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a,QAAQ,CAAC,IAAI;AAG/C,UAAM,MAAM,MAAM,aAAa,CAAC;AAGhC,UAAM,EAAE,QAAQ,IAAI,MAAM,iBAAiB,MAAM,EAAE,IAAI,CAAC;AAExD,QAAI,CAAC,SAAS;AACZ,UAAI,SAAS;AACX,eAAO,QAAQ,CAAC;AAAA,MAClB;AACA,aAAO,IAAI,SAAS,uBAAuB;AAAA,QACzC,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,aAAa;AAAA,MAC1C,CAAC;AAAA,IACH;AAEA,WAAO,KAAK;AAAA,EACd;AACF;","names":["rateLimiter","cloudflareRateLimiter"]}
@@ -81,6 +81,13 @@ var CloudflareKVStore = class {
81
81
  async resetKey(key) {
82
82
  await this.namespace.delete(`${this.prefix}${key}`);
83
83
  }
84
+ /**
85
+ * Reset all keys. Note: This is a no-op for Cloudflare KV as listing
86
+ * all keys with a prefix requires pagination and is expensive.
87
+ * Use resetKey() for individual keys instead.
88
+ */
89
+ resetAll() {
90
+ }
84
91
  };
85
92
  // Annotate the CommonJS export names for ESM import in node:
86
93
  0 && (module.exports = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/store/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV store for rate limiting.\n *\n * Note: KV is eventually consistent (~60s propagation).\n * For strict rate limiting, consider Durable Objects.\n */\n\nimport type { RateLimitStore, StoreResult } from \"../index\";\n\n/**\n * Cloudflare KV Namespace interface\n */\nexport type KVNamespace = {\n get: <T = string>(\n key: string,\n options?: { type: \"json\" },\n ) => Promise<T | null>;\n put: (\n key: string,\n value: string,\n options?: { expirationTtl?: number },\n ) => Promise<void>;\n delete: (key: string) => Promise<void>;\n};\n\n/**\n * Options for Cloudflare KV store\n */\nexport type CloudflareKVStoreOptions = {\n /**\n * KV Namespace binding\n */\n namespace: KVNamespace;\n\n /**\n * Key prefix for rate limit entries\n * @default 'rl:'\n */\n prefix?: string;\n};\n\ntype KVEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * Cloudflare KV store for rate limiting in Workers.\n *\n * @example\n * ```ts\n * import { rateLimiter } from 'hono-rate-limit'\n * import { CloudflareKVStore } from 'hono-rate-limit/store/cloudflare-kv'\n *\n * type Bindings = { RATE_LIMIT_KV: KVNamespace }\n *\n * app.use('*', async (c, next) => {\n * const limiter = rateLimiter({\n * store: new CloudflareKVStore({ namespace: c.env.RATE_LIMIT_KV }),\n * })\n * return limiter(c, next)\n * })\n * ```\n */\nexport class CloudflareKVStore implements RateLimitStore {\n private namespace: KVNamespace;\n private prefix: string;\n private windowMs = 60_000;\n\n constructor(options: CloudflareKVStoreOptions) {\n this.namespace = options.namespace;\n this.prefix = options.prefix ?? \"rl:\";\n }\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n }\n\n async increment(key: string): Promise<StoreResult> {\n const fullKey = `${this.prefix}${key}`;\n const now = Date.now();\n\n // KV minimum TTL is 60 seconds\n const ttlSeconds = Math.max(60, Math.ceil(this.windowMs / 1000));\n\n const existing = await this.namespace.get<KVEntry>(fullKey, {\n type: \"json\",\n });\n\n let count: number;\n let reset: number;\n\n if (!existing || existing.reset <= now) {\n // New window\n count = 1;\n reset = now + this.windowMs;\n } else {\n // Increment\n count = existing.count + 1;\n reset = existing.reset;\n }\n\n await this.namespace.put(fullKey, JSON.stringify({ count, reset }), {\n expirationTtl: ttlSeconds,\n });\n\n return { count, reset };\n }\n\n async get(key: string): Promise<StoreResult | undefined> {\n const fullKey = `${this.prefix}${key}`;\n const data = await this.namespace.get<KVEntry>(fullKey, { type: \"json\" });\n\n if (!data || data.reset <= Date.now()) {\n return undefined;\n }\n\n return { count: data.count, reset: data.reset };\n }\n\n async decrement(key: string): Promise<void> {\n const fullKey = `${this.prefix}${key}`;\n const now = Date.now();\n\n const existing = await this.namespace.get<KVEntry>(fullKey, {\n type: \"json\",\n });\n\n if (existing && existing.count > 0 && existing.reset > now) {\n const ttlSeconds = Math.max(60, Math.ceil((existing.reset - now) / 1000));\n await this.namespace.put(\n fullKey,\n JSON.stringify({ count: existing.count - 1, reset: existing.reset }),\n { expirationTtl: ttlSeconds },\n );\n }\n }\n\n async resetKey(key: string): Promise<void> {\n await this.namespace.delete(`${this.prefix}${key}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgEO,IAAM,oBAAN,MAAkD;AAAA,EAC/C;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EAEnB,YAAY,SAAmC;AAC7C,SAAK,YAAY,QAAQ;AACzB,SAAK,SAAS,QAAQ,UAAU;AAAA,EAClC;AAAA,EAEA,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,MAAM,UAAU,KAAmC;AACjD,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,MAAM,KAAK,IAAI;AAGrB,UAAM,aAAa,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,WAAW,GAAI,CAAC;AAE/D,UAAM,WAAW,MAAM,KAAK,UAAU,IAAa,SAAS;AAAA,MAC1D,MAAM;AAAA,IACR,CAAC;AAED,QAAI;AACJ,QAAI;AAEJ,QAAI,CAAC,YAAY,SAAS,SAAS,KAAK;AAEtC,cAAQ;AACR,cAAQ,MAAM,KAAK;AAAA,IACrB,OAAO;AAEL,cAAQ,SAAS,QAAQ;AACzB,cAAQ,SAAS;AAAA,IACnB;AAEA,UAAM,KAAK,UAAU,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,MAAM,CAAC,GAAG;AAAA,MAClE,eAAe;AAAA,IACjB,CAAC;AAED,WAAO,EAAE,OAAO,MAAM;AAAA,EACxB;AAAA,EAEA,MAAM,IAAI,KAA+C;AACvD,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,OAAO,MAAM,KAAK,UAAU,IAAa,SAAS,EAAE,MAAM,OAAO,CAAC;AAExE,QAAI,CAAC,QAAQ,KAAK,SAAS,KAAK,IAAI,GAAG;AACrC,aAAO;AAAA,IACT;AAEA,WAAO,EAAE,OAAO,KAAK,OAAO,OAAO,KAAK,MAAM;AAAA,EAChD;AAAA,EAEA,MAAM,UAAU,KAA4B;AAC1C,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,MAAM,KAAK,IAAI;AAErB,UAAM,WAAW,MAAM,KAAK,UAAU,IAAa,SAAS;AAAA,MAC1D,MAAM;AAAA,IACR,CAAC;AAED,QAAI,YAAY,SAAS,QAAQ,KAAK,SAAS,QAAQ,KAAK;AAC1D,YAAM,aAAa,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS,QAAQ,OAAO,GAAI,CAAC;AACxE,YAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,KAAK,UAAU,EAAE,OAAO,SAAS,QAAQ,GAAG,OAAO,SAAS,MAAM,CAAC;AAAA,QACnE,EAAE,eAAe,WAAW;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,SAAS,KAA4B;AACzC,UAAM,KAAK,UAAU,OAAO,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE;AAAA,EACpD;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/store/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV store for rate limiting.\n *\n * Note: KV is eventually consistent (~60s propagation).\n * For strict rate limiting, consider Durable Objects.\n */\n\nimport type { RateLimitStore, StoreResult } from \"../index\";\n\n/**\n * Cloudflare KV Namespace interface\n */\nexport type KVNamespace = {\n get: <T = string>(\n key: string,\n options?: { type: \"json\" },\n ) => Promise<T | null>;\n put: (\n key: string,\n value: string,\n options?: { expirationTtl?: number },\n ) => Promise<void>;\n delete: (key: string) => Promise<void>;\n};\n\n/**\n * Options for Cloudflare KV store\n */\nexport type CloudflareKVStoreOptions = {\n /**\n * KV Namespace binding\n */\n namespace: KVNamespace;\n\n /**\n * Key prefix for rate limit entries\n * @default 'rl:'\n */\n prefix?: string;\n};\n\ntype KVEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * Cloudflare KV store for rate limiting in Workers.\n *\n * @example\n * ```ts\n * import { rateLimiter } from 'hono-rate-limit'\n * import { CloudflareKVStore } from 'hono-rate-limit/store/cloudflare-kv'\n *\n * type Bindings = { RATE_LIMIT_KV: KVNamespace }\n *\n * app.use('*', async (c, next) => {\n * const limiter = rateLimiter({\n * store: new CloudflareKVStore({ namespace: c.env.RATE_LIMIT_KV }),\n * })\n * return limiter(c, next)\n * })\n * ```\n */\nexport class CloudflareKVStore implements RateLimitStore {\n private namespace: KVNamespace;\n private prefix: string;\n private windowMs = 60_000;\n\n constructor(options: CloudflareKVStoreOptions) {\n this.namespace = options.namespace;\n this.prefix = options.prefix ?? \"rl:\";\n }\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n }\n\n async increment(key: string): Promise<StoreResult> {\n const fullKey = `${this.prefix}${key}`;\n const now = Date.now();\n\n // KV minimum TTL is 60 seconds\n const ttlSeconds = Math.max(60, Math.ceil(this.windowMs / 1000));\n\n const existing = await this.namespace.get<KVEntry>(fullKey, {\n type: \"json\",\n });\n\n let count: number;\n let reset: number;\n\n if (!existing || existing.reset <= now) {\n // New window\n count = 1;\n reset = now + this.windowMs;\n } else {\n // Increment\n count = existing.count + 1;\n reset = existing.reset;\n }\n\n await this.namespace.put(fullKey, JSON.stringify({ count, reset }), {\n expirationTtl: ttlSeconds,\n });\n\n return { count, reset };\n }\n\n async get(key: string): Promise<StoreResult | undefined> {\n const fullKey = `${this.prefix}${key}`;\n const data = await this.namespace.get<KVEntry>(fullKey, { type: \"json\" });\n\n if (!data || data.reset <= Date.now()) {\n return undefined;\n }\n\n return { count: data.count, reset: data.reset };\n }\n\n async decrement(key: string): Promise<void> {\n const fullKey = `${this.prefix}${key}`;\n const now = Date.now();\n\n const existing = await this.namespace.get<KVEntry>(fullKey, {\n type: \"json\",\n });\n\n if (existing && existing.count > 0 && existing.reset > now) {\n const ttlSeconds = Math.max(60, Math.ceil((existing.reset - now) / 1000));\n await this.namespace.put(\n fullKey,\n JSON.stringify({ count: existing.count - 1, reset: existing.reset }),\n { expirationTtl: ttlSeconds },\n );\n }\n }\n\n async resetKey(key: string): Promise<void> {\n await this.namespace.delete(`${this.prefix}${key}`);\n }\n\n /**\n * Reset all keys. Note: This is a no-op for Cloudflare KV as listing\n * all keys with a prefix requires pagination and is expensive.\n * Use resetKey() for individual keys instead.\n */\n resetAll(): void {\n // No-op: Listing all keys with prefix is expensive in KV\n // Keys will expire naturally based on TTL\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgEO,IAAM,oBAAN,MAAkD;AAAA,EAC/C;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EAEnB,YAAY,SAAmC;AAC7C,SAAK,YAAY,QAAQ;AACzB,SAAK,SAAS,QAAQ,UAAU;AAAA,EAClC;AAAA,EAEA,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,MAAM,UAAU,KAAmC;AACjD,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,MAAM,KAAK,IAAI;AAGrB,UAAM,aAAa,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,WAAW,GAAI,CAAC;AAE/D,UAAM,WAAW,MAAM,KAAK,UAAU,IAAa,SAAS;AAAA,MAC1D,MAAM;AAAA,IACR,CAAC;AAED,QAAI;AACJ,QAAI;AAEJ,QAAI,CAAC,YAAY,SAAS,SAAS,KAAK;AAEtC,cAAQ;AACR,cAAQ,MAAM,KAAK;AAAA,IACrB,OAAO;AAEL,cAAQ,SAAS,QAAQ;AACzB,cAAQ,SAAS;AAAA,IACnB;AAEA,UAAM,KAAK,UAAU,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,MAAM,CAAC,GAAG;AAAA,MAClE,eAAe;AAAA,IACjB,CAAC;AAED,WAAO,EAAE,OAAO,MAAM;AAAA,EACxB;AAAA,EAEA,MAAM,IAAI,KAA+C;AACvD,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,OAAO,MAAM,KAAK,UAAU,IAAa,SAAS,EAAE,MAAM,OAAO,CAAC;AAExE,QAAI,CAAC,QAAQ,KAAK,SAAS,KAAK,IAAI,GAAG;AACrC,aAAO;AAAA,IACT;AAEA,WAAO,EAAE,OAAO,KAAK,OAAO,OAAO,KAAK,MAAM;AAAA,EAChD;AAAA,EAEA,MAAM,UAAU,KAA4B;AAC1C,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,MAAM,KAAK,IAAI;AAErB,UAAM,WAAW,MAAM,KAAK,UAAU,IAAa,SAAS;AAAA,MAC1D,MAAM;AAAA,IACR,CAAC;AAED,QAAI,YAAY,SAAS,QAAQ,KAAK,SAAS,QAAQ,KAAK;AAC1D,YAAM,aAAa,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS,QAAQ,OAAO,GAAI,CAAC;AACxE,YAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,KAAK,UAAU,EAAE,OAAO,SAAS,QAAQ,GAAG,OAAO,SAAS,MAAM,CAAC;AAAA,QACnE,EAAE,eAAe,WAAW;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,SAAS,KAA4B;AACzC,UAAM,KAAK,UAAU,OAAO,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAAiB;AAAA,EAGjB;AACF;","names":[]}
@@ -62,6 +62,12 @@ declare class CloudflareKVStore implements RateLimitStore {
62
62
  get(key: string): Promise<StoreResult | undefined>;
63
63
  decrement(key: string): Promise<void>;
64
64
  resetKey(key: string): Promise<void>;
65
+ /**
66
+ * Reset all keys. Note: This is a no-op for Cloudflare KV as listing
67
+ * all keys with a prefix requires pagination and is expensive.
68
+ * Use resetKey() for individual keys instead.
69
+ */
70
+ resetAll(): void;
65
71
  }
66
72
 
67
73
  export { CloudflareKVStore, type CloudflareKVStoreOptions, type KVNamespace };