edge-throttle 0.0.0-stage → 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,338 @@
1
+ 'use strict';
2
+
3
+ // src/utils/headers.ts
4
+ function buildRateLimitHeaders(result, now) {
5
+ const headers = {
6
+ "X-RateLimit-Limit": String(result.limit),
7
+ "X-RateLimit-Remaining": String(Math.max(0, Math.floor(result.remaining))),
8
+ "X-RateLimit-Reset": String(Math.ceil(result.reset / 1e3))
9
+ };
10
+ if (!result.success) {
11
+ const retryAfterSec = Math.max(1, Math.ceil((result.reset - now) / 1e3));
12
+ headers["Retry-After"] = String(retryAfterSec);
13
+ }
14
+ return headers;
15
+ }
16
+
17
+ // src/limiter.ts
18
+ function createRateLimiter(config) {
19
+ if (!config || !config.adapter) {
20
+ throw new TypeError('createRateLimiter requires a "adapter" in config.');
21
+ }
22
+ if (!config.algorithm) {
23
+ throw new TypeError('createRateLimiter requires an "algorithm" in config.');
24
+ }
25
+ if (config.timeoutMs !== void 0 && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {
26
+ throw new RangeError(`createRateLimiter "timeoutMs" must be a positive finite number, got ${config.timeoutMs}.`);
27
+ }
28
+ const {
29
+ adapter,
30
+ algorithm,
31
+ prefix = "rl",
32
+ failOpen = false,
33
+ timeoutMs,
34
+ onError
35
+ } = config;
36
+ const pendingLocks = /* @__PURE__ */ new Map();
37
+ async function withKeyLock(key, fn) {
38
+ if (adapter.eval) {
39
+ return fn();
40
+ }
41
+ const previous = pendingLocks.get(key) ?? Promise.resolve();
42
+ let release;
43
+ const current = new Promise((resolve) => {
44
+ release = resolve;
45
+ });
46
+ pendingLocks.set(key, current);
47
+ try {
48
+ await previous;
49
+ return await fn();
50
+ } finally {
51
+ release();
52
+ if (pendingLocks.get(key) === current) {
53
+ pendingLocks.delete(key);
54
+ }
55
+ }
56
+ }
57
+ async function withTimeout(promise) {
58
+ if (timeoutMs === void 0) {
59
+ return promise;
60
+ }
61
+ let timerId;
62
+ const timeoutPromise = new Promise((_, reject) => {
63
+ timerId = setTimeout(() => {
64
+ reject(new Error(`edge-throttle: storage operation timed out after ${timeoutMs}ms`));
65
+ }, timeoutMs);
66
+ });
67
+ try {
68
+ return await Promise.race([promise, timeoutPromise]);
69
+ } finally {
70
+ if (timerId !== void 0) {
71
+ clearTimeout(timerId);
72
+ }
73
+ }
74
+ }
75
+ return {
76
+ async limit(identifier, options) {
77
+ if (typeof identifier !== "string" || identifier.length === 0) {
78
+ throw new TypeError("limiter.limit() requires a non-empty string identifier.");
79
+ }
80
+ const cost = options?.cost ?? 1;
81
+ if (!Number.isFinite(cost) || cost < 0) {
82
+ throw new RangeError(`limiter.limit() "cost" must be a non-negative finite number, got ${cost}.`);
83
+ }
84
+ const key = prefix ? `${prefix}:${identifier}` : identifier;
85
+ const now = Date.now();
86
+ try {
87
+ const outcome = await withTimeout(
88
+ withKeyLock(
89
+ key,
90
+ () => algorithm.consume({
91
+ adapter,
92
+ key,
93
+ cost,
94
+ now
95
+ })
96
+ )
97
+ );
98
+ return {
99
+ ...outcome,
100
+ headers: buildRateLimitHeaders(outcome, now)
101
+ };
102
+ } catch (error) {
103
+ onError?.(error, identifier);
104
+ if (failOpen) {
105
+ const fallback = {
106
+ success: true,
107
+ limit: algorithm.maxLimit,
108
+ remaining: algorithm.maxLimit,
109
+ reset: now
110
+ };
111
+ return {
112
+ ...fallback,
113
+ headers: buildRateLimitHeaders(fallback, now)
114
+ };
115
+ }
116
+ throw error;
117
+ }
118
+ }
119
+ };
120
+ }
121
+
122
+ // src/utils/duration.ts
123
+ var UNIT_MS = {
124
+ ms: 1,
125
+ s: 1e3,
126
+ m: 6e4,
127
+ h: 36e5,
128
+ d: 864e5
129
+ };
130
+ var DURATION_REGEX = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i;
131
+ function parseDuration(duration) {
132
+ if (typeof duration === "number") {
133
+ if (!Number.isFinite(duration) || duration <= 0) {
134
+ throw new RangeError(`Invalid duration: ${String(duration)}. Expected a positive finite number.`);
135
+ }
136
+ return duration;
137
+ }
138
+ if (typeof duration === "string") {
139
+ const match = DURATION_REGEX.exec(duration.trim());
140
+ if (!match) {
141
+ throw new RangeError(
142
+ `Invalid duration string: "${duration}". Expected format like "500ms", "10s", "1m", "1h", or "1d".`
143
+ );
144
+ }
145
+ const value = Number(match[1]);
146
+ const unit = match[2].toLowerCase();
147
+ const ms = value * UNIT_MS[unit];
148
+ if (!Number.isFinite(ms) || ms <= 0) {
149
+ throw new RangeError(`Invalid duration: "${duration}". Result must be > 0ms.`);
150
+ }
151
+ return ms;
152
+ }
153
+ throw new RangeError(`Invalid duration type: ${typeof duration}.`);
154
+ }
155
+
156
+ // src/algorithms/sliding-window.ts
157
+ var SLIDING_WINDOW_LUA = `
158
+ local curr = tonumber(redis.call('GET', KEYS[1]) or '0')
159
+ local prev = tonumber(redis.call('GET', KEYS[2]) or '0')
160
+ local limit = tonumber(ARGV[1])
161
+ local cost = tonumber(ARGV[2])
162
+ local weight = tonumber(ARGV[3])
163
+ local ttl = tonumber(ARGV[4])
164
+ local estimated = prev * weight + curr
165
+ if estimated + cost <= limit then
166
+ local newCurr = tonumber(redis.call('INCRBYFLOAT', KEYS[1], cost))
167
+ if curr == 0 then
168
+ redis.call('PEXPIRE', KEYS[1], ttl)
169
+ end
170
+ local rem = math.max(0, math.floor(limit - (estimated + cost)))
171
+ return {1, rem}
172
+ else
173
+ local rem = math.max(0, math.floor(limit - estimated))
174
+ return {0, rem}
175
+ end
176
+ `.trim();
177
+ function slidingWindow(config) {
178
+ if (!Number.isFinite(config.limit) || config.limit <= 0) {
179
+ throw new RangeError(`slidingWindow "limit" must be a positive finite number, got ${config.limit}.`);
180
+ }
181
+ const limit = config.limit;
182
+ const windowMs = parseDuration(config.window);
183
+ const ttlMs = windowMs * 2;
184
+ return {
185
+ name: "sliding-window",
186
+ maxLimit: limit,
187
+ async consume(ctx) {
188
+ const { adapter, key, cost, now } = ctx;
189
+ const currentWindow = Math.floor(now / windowMs);
190
+ const prevWindow = currentWindow - 1;
191
+ const elapsedMs = now - currentWindow * windowMs;
192
+ const weight = (windowMs - elapsedMs) / windowMs;
193
+ const reset = (currentWindow + 1) * windowMs;
194
+ const currentKey = `${key}:${currentWindow}`;
195
+ const prevKey = `${key}:${prevWindow}`;
196
+ if (adapter.eval) {
197
+ const raw = await adapter.eval(
198
+ SLIDING_WINDOW_LUA,
199
+ [currentKey, prevKey],
200
+ [limit, cost, weight, ttlMs]
201
+ );
202
+ return {
203
+ success: raw[0] === 1,
204
+ limit,
205
+ remaining: Math.max(0, Number(raw[1] ?? 0)),
206
+ reset
207
+ };
208
+ }
209
+ const [prevCount, currCount] = await Promise.all([
210
+ adapter.get(prevKey),
211
+ adapter.get(currentKey)
212
+ ]);
213
+ const prev = prevCount ?? 0;
214
+ const curr = currCount ?? 0;
215
+ const estimated = prev * weight + curr;
216
+ if (estimated + cost <= limit) {
217
+ await adapter.set(currentKey, curr + cost, ttlMs);
218
+ return {
219
+ success: true,
220
+ limit,
221
+ remaining: Math.max(0, Math.floor(limit - (estimated + cost))),
222
+ reset
223
+ };
224
+ }
225
+ return {
226
+ success: false,
227
+ limit,
228
+ remaining: Math.max(0, Math.floor(limit - estimated)),
229
+ reset
230
+ };
231
+ }
232
+ };
233
+ }
234
+
235
+ // src/algorithms/token-bucket.ts
236
+ var TOKEN_BUCKET_LUA = `
237
+ local raw = redis.call('GET', KEYS[1])
238
+ local capacity = tonumber(ARGV[1])
239
+ local refillRate = tonumber(ARGV[2])
240
+ local refillInterval = tonumber(ARGV[3])
241
+ local cost = tonumber(ARGV[4])
242
+ local now = tonumber(ARGV[5])
243
+ local ttl = tonumber(ARGV[6])
244
+
245
+ local tokens = capacity
246
+ local lastRefill = now
247
+
248
+ if raw then
249
+ local sep = string.find(raw, ':')
250
+ if sep then
251
+ tokens = tonumber(string.sub(raw, 1, sep - 1)) or capacity
252
+ lastRefill = tonumber(string.sub(raw, sep + 1)) or now
253
+ end
254
+ end
255
+
256
+ local elapsed = math.max(0, now - lastRefill)
257
+ local added = (elapsed / refillInterval) * refillRate
258
+ tokens = math.min(capacity, tokens + added)
259
+
260
+ if tokens >= cost then
261
+ local newTokens = tokens - cost
262
+ redis.call('SET', KEYS[1], tostring(newTokens) .. ':' .. tostring(now), 'PX', ttl)
263
+ local reset = now + math.ceil(((capacity - newTokens) / refillRate) * refillInterval)
264
+ return {1, math.floor(newTokens), reset}
265
+ else
266
+ local deficit = cost - tokens
267
+ local reset = now + math.ceil((deficit / refillRate) * refillInterval)
268
+ return {0, math.floor(tokens), reset}
269
+ end
270
+ `.trim();
271
+ function tokenBucket(config) {
272
+ if (!Number.isFinite(config.capacity) || config.capacity <= 0) {
273
+ throw new RangeError(`tokenBucket "capacity" must be a positive finite number, got ${config.capacity}.`);
274
+ }
275
+ if (!Number.isFinite(config.refillRate) || config.refillRate <= 0) {
276
+ throw new RangeError(
277
+ `tokenBucket "refillRate" must be a positive finite number, got ${config.refillRate}.`
278
+ );
279
+ }
280
+ const capacity = config.capacity;
281
+ const refillRate = config.refillRate;
282
+ const refillIntervalMs = parseDuration(config.refillInterval);
283
+ const ttlMs = Math.max(refillIntervalMs * 2, Math.ceil(capacity / refillRate * refillIntervalMs) * 2);
284
+ return {
285
+ name: "token-bucket",
286
+ maxLimit: capacity,
287
+ async consume(ctx) {
288
+ const { adapter, key, cost, now } = ctx;
289
+ const bucketKey = `${key}:tb`;
290
+ if (adapter.eval) {
291
+ const raw = await adapter.eval(
292
+ TOKEN_BUCKET_LUA,
293
+ [bucketKey],
294
+ [capacity, refillRate, refillIntervalMs, cost, now, ttlMs]
295
+ );
296
+ return {
297
+ success: raw[0] === 1,
298
+ limit: capacity,
299
+ remaining: Math.max(0, Number(raw[1] ?? 0)),
300
+ reset: Number(raw[2] ?? now)
301
+ };
302
+ }
303
+ const existing = await adapter.get(bucketKey);
304
+ let tokens = capacity;
305
+ if (existing) {
306
+ const elapsed = Math.max(0, now - existing.lastRefill);
307
+ const added = elapsed / refillIntervalMs * refillRate;
308
+ tokens = Math.min(capacity, existing.tokens + added);
309
+ }
310
+ if (tokens >= cost) {
311
+ const newTokens = tokens - cost;
312
+ await adapter.set(bucketKey, { tokens: newTokens, lastRefill: now }, ttlMs);
313
+ const reset2 = now + Math.ceil((capacity - newTokens) / refillRate * refillIntervalMs);
314
+ return {
315
+ success: true,
316
+ limit: capacity,
317
+ remaining: Math.max(0, Math.floor(newTokens)),
318
+ reset: reset2
319
+ };
320
+ }
321
+ const deficit = cost - tokens;
322
+ const reset = now + Math.ceil(deficit / refillRate * refillIntervalMs);
323
+ return {
324
+ success: false,
325
+ limit: capacity,
326
+ remaining: Math.max(0, Math.floor(tokens)),
327
+ reset
328
+ };
329
+ }
330
+ };
331
+ }
332
+
333
+ exports.createRateLimiter = createRateLimiter;
334
+ exports.parseDuration = parseDuration;
335
+ exports.slidingWindow = slidingWindow;
336
+ exports.tokenBucket = tokenBucket;
337
+ //# sourceMappingURL=index.cjs.map
338
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/headers.ts","../src/limiter.ts","../src/utils/duration.ts","../src/algorithms/sliding-window.ts","../src/algorithms/token-bucket.ts"],"names":["reset"],"mappings":";;;AAKO,SAAS,qBAAA,CACd,QACA,GAAA,EACwB;AACxB,EAAA,MAAM,OAAA,GAAkC;AAAA,IACtC,mBAAA,EAAqB,MAAA,CAAO,MAAA,CAAO,KAAK,CAAA;AAAA,IACxC,uBAAA,EAAyB,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAK,KAAA,CAAM,MAAA,CAAO,SAAS,CAAC,CAAC,CAAA;AAAA,IACzE,qBAAqB,MAAA,CAAO,IAAA,CAAK,KAAK,MAAA,CAAO,KAAA,GAAQ,GAAI,CAAC;AAAA,GAC5D;AAEA,EAAA,IAAI,CAAC,OAAO,OAAA,EAAS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A,MAAM,OAAA,CAAQ,IAAsB,SAAA,EAAW,EAAE,QAAQ,SAAA,EAAW,UAAA,EAAY,GAAA,EAAI,EAAG,KAAK,CAAA;AAC5F,QAAA,MAAMA,SAAQ,GAAA,GAAM,IAAA,CAAK,MAAO,QAAA,GAAW,SAAA,IAAa,aAAc,gBAAgB,CAAA;AACtF,QAAA,OAAO;AAAA,UACL,OAAA,EAAS,IAAA;AAAA,UACT,KAAA,EAAO,QAAA;AAAA,UACP,WAAW,IAAA,CAAK,GAAA,CAAI,GAAG,IAAA,CAAK,KAAA,CAAM,SAAS,CAAC,CAAA;AAAA,UAC5C,KAAA,EAAAA;AAAA,SACF;AAAA,MACF;AAEA,MAAA,MAAM,UAAU,IAAA,GAAO,MAAA;AACvB,MAAA,MAAM,QAAQ,GAAA,GAAM,IAAA,CAAK,IAAA,CAAM,OAAA,GAAU,aAAc,gBAAgB,CAAA;AACvE,MAAA,OAAO;AAAA,QACL,OAAA,EAAS,KAAA;AAAA,QACT,KAAA,EAAO,QAAA;AAAA,QACP,WAAW,IAAA,CAAK,GAAA,CAAI,GAAG,IAAA,CAAK,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,QACzC;AAAA,OACF;AAAA,IACF;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import type { RateLimitResult } from '../types.js';\n\n/**\n * Build standard HTTP rate-limit response headers from a rate-limit outcome.\n */\nexport function buildRateLimitHeaders(\n result: Omit<RateLimitResult, 'headers'>,\n now: number,\n): Record<string, string> {\n const headers: Record<string, string> = {\n 'X-RateLimit-Limit': String(result.limit),\n 'X-RateLimit-Remaining': String(Math.max(0, Math.floor(result.remaining))),\n 'X-RateLimit-Reset': String(Math.ceil(result.reset / 1000)),\n };\n\n if (!result.success) {\n const retryAfterSec = Math.max(1, Math.ceil((result.reset - now) / 1000));\n headers['Retry-After'] = String(retryAfterSec);\n }\n\n return headers;\n}\n","import type {\n LimitOptions,\n RateLimiter,\n RateLimiterConfig,\n RateLimitResult,\n} from './types.js';\nimport { buildRateLimitHeaders } from './utils/headers.js';\n\n/**\n * Create a rate limiter instance configured with a storage adapter and algorithm.\n *\n * @example\n * ```ts\n * import { createRateLimiter, slidingWindow } from 'edge-throttle';\n * import { MemoryAdapter } from 'edge-throttle/adapters/memory';\n *\n * const limiter = createRateLimiter({\n * adapter: new MemoryAdapter(),\n * algorithm: slidingWindow({ limit: 100, window: '1m' }),\n * prefix: 'rl:api',\n * failOpen: true,\n * timeoutMs: 2000,\n * });\n *\n * const result = await limiter.limit('user_123');\n * ```\n */\nexport function createRateLimiter(config: RateLimiterConfig): RateLimiter {\n if (!config || !config.adapter) {\n throw new TypeError('createRateLimiter requires a \"adapter\" in config.');\n }\n if (!config.algorithm) {\n throw new TypeError('createRateLimiter requires an \"algorithm\" in config.');\n }\n if (config.timeoutMs !== undefined && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {\n throw new RangeError(`createRateLimiter \"timeoutMs\" must be a positive finite number, got ${config.timeoutMs}.`);\n }\n\n const {\n adapter,\n algorithm,\n prefix = 'rl',\n failOpen = false,\n timeoutMs,\n onError,\n } = config;\n\n // Serialize in-process updates per key when the adapter does not support atomic Lua `eval`.\n const pendingLocks = new Map<string, Promise<void>>();\n\n async function withKeyLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n if (adapter.eval) {\n return fn();\n }\n\n const previous = pendingLocks.get(key) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n pendingLocks.set(key, current);\n\n try {\n await previous;\n return await fn();\n } finally {\n release();\n if (pendingLocks.get(key) === current) {\n pendingLocks.delete(key);\n }\n }\n }\n\n async function withTimeout<T>(promise: Promise<T>): Promise<T> {\n if (timeoutMs === undefined) {\n return promise;\n }\n\n let timerId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timerId = setTimeout(() => {\n reject(new Error(`edge-throttle: storage operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n }\n }\n\n return {\n async limit(identifier: string, options?: LimitOptions): Promise<RateLimitResult> {\n if (typeof identifier !== 'string' || identifier.length === 0) {\n throw new TypeError('limiter.limit() requires a non-empty string identifier.');\n }\n\n const cost = options?.cost ?? 1;\n if (!Number.isFinite(cost) || cost < 0) {\n throw new RangeError(`limiter.limit() \"cost\" must be a non-negative finite number, got ${cost}.`);\n }\n\n const key = prefix ? `${prefix}:${identifier}` : identifier;\n const now = Date.now();\n\n try {\n const outcome = await withTimeout(\n withKeyLock(key, () =>\n algorithm.consume({\n adapter,\n key,\n cost,\n now,\n }),\n ),\n );\n\n return {\n ...outcome,\n headers: buildRateLimitHeaders(outcome, now),\n };\n } catch (error) {\n onError?.(error, identifier);\n\n if (failOpen) {\n const fallback = {\n success: true,\n limit: algorithm.maxLimit,\n remaining: algorithm.maxLimit,\n reset: now,\n };\n return {\n ...fallback,\n headers: buildRateLimitHeaders(fallback, now),\n };\n }\n\n throw error;\n }\n },\n };\n}\n","import type { Duration, DurationUnit } from '../types.js';\n\nconst UNIT_MS: Record<DurationUnit, number> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\nconst DURATION_REGEX = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/i;\n\n/**\n * Parse a `Duration` (milliseconds number or string like `\"10s\"`, `\"1m\"`, `\"1h\"`)\n * into a positive number of milliseconds.\n *\n * @throws {RangeError} If the duration is invalid, non-finite, or `<= 0`.\n */\nexport function parseDuration(duration: Duration): number {\n if (typeof duration === 'number') {\n if (!Number.isFinite(duration) || duration <= 0) {\n throw new RangeError(`Invalid duration: ${String(duration)}. Expected a positive finite number.`);\n }\n return duration;\n }\n\n if (typeof duration === 'string') {\n const match = DURATION_REGEX.exec(duration.trim());\n if (!match) {\n throw new RangeError(\n `Invalid duration string: \"${duration}\". Expected format like \"500ms\", \"10s\", \"1m\", \"1h\", or \"1d\".`,\n );\n }\n\n const value = Number(match[1]);\n const unit = match[2]!.toLowerCase() as DurationUnit;\n const ms = value * UNIT_MS[unit];\n\n if (!Number.isFinite(ms) || ms <= 0) {\n throw new RangeError(`Invalid duration: \"${duration}\". Result must be > 0ms.`);\n }\n\n return ms;\n }\n\n throw new RangeError(`Invalid duration type: ${typeof duration}.`);\n}\n","import type { AlgorithmContext, Duration, RateLimitAlgorithm, RateLimitResult } from '../types.js';\nimport { parseDuration } from '../utils/duration.js';\n\n/**\n * Configuration options for the `slidingWindow` algorithm.\n */\nexport interface SlidingWindowConfig {\n /** Maximum number of requests (or weighted cost) allowed per rolling window. */\n limit: number;\n /** Window duration as milliseconds or a duration string (e.g., `\"10s\"`, `\"1m\"`, `\"1h\"`). */\n window: Duration;\n}\n\nconst SLIDING_WINDOW_LUA = `\nlocal curr = tonumber(redis.call('GET', KEYS[1]) or '0')\nlocal prev = tonumber(redis.call('GET', KEYS[2]) or '0')\nlocal limit = tonumber(ARGV[1])\nlocal cost = tonumber(ARGV[2])\nlocal weight = tonumber(ARGV[3])\nlocal ttl = tonumber(ARGV[4])\nlocal estimated = prev * weight + curr\nif estimated + cost <= limit then\n local newCurr = tonumber(redis.call('INCRBYFLOAT', KEYS[1], cost))\n if curr == 0 then\n redis.call('PEXPIRE', KEYS[1], ttl)\n end\n local rem = math.max(0, math.floor(limit - (estimated + cost)))\n return {1, rem}\nelse\n local rem = math.max(0, math.floor(limit - estimated))\n return {0, rem}\nend\n`.trim();\n\n/**\n * Create a weighted Sliding Window Counter rate-limiting algorithm.\n *\n * Uses two adjacent fixed windows (previous and current) weighted by the elapsed\n * fraction of the current window to prevent boundary bursts while keeping storage\n * overhead constant at 2 keys per identifier.\n */\nexport function slidingWindow(config: SlidingWindowConfig): RateLimitAlgorithm {\n if (!Number.isFinite(config.limit) || config.limit <= 0) {\n throw new RangeError(`slidingWindow \"limit\" must be a positive finite number, got ${config.limit}.`);\n }\n\n const limit = config.limit;\n const windowMs = parseDuration(config.window);\n const ttlMs = windowMs * 2;\n\n return {\n name: 'sliding-window',\n maxLimit: limit,\n\n async consume(ctx: AlgorithmContext): Promise<Omit<RateLimitResult, 'headers'>> {\n const { adapter, key, cost, now } = ctx;\n\n const currentWindow = Math.floor(now / windowMs);\n const prevWindow = currentWindow - 1;\n const elapsedMs = now - currentWindow * windowMs;\n const weight = (windowMs - elapsedMs) / windowMs;\n const reset = (currentWindow + 1) * windowMs;\n\n const currentKey = `${key}:${currentWindow}`;\n const prevKey = `${key}:${prevWindow}`;\n\n if (adapter.eval) {\n const raw = (await adapter.eval(\n SLIDING_WINDOW_LUA,\n [currentKey, prevKey],\n [limit, cost, weight, ttlMs],\n )) as [number, number];\n\n return {\n success: raw[0] === 1,\n limit,\n remaining: Math.max(0, Number(raw[1] ?? 0)),\n reset,\n };\n }\n\n const [prevCount, currCount] = await Promise.all([\n adapter.get<number>(prevKey),\n adapter.get<number>(currentKey),\n ]);\n\n const prev = prevCount ?? 0;\n const curr = currCount ?? 0;\n const estimated = prev * weight + curr;\n\n if (estimated + cost <= limit) {\n await adapter.set(currentKey, curr + cost, ttlMs);\n return {\n success: true,\n limit,\n remaining: Math.max(0, Math.floor(limit - (estimated + cost))),\n reset,\n };\n }\n\n return {\n success: false,\n limit,\n remaining: Math.max(0, Math.floor(limit - estimated)),\n reset,\n };\n },\n };\n}\n","import type { AlgorithmContext, Duration, RateLimitAlgorithm, RateLimitResult } from '../types.js';\nimport { parseDuration } from '../utils/duration.js';\n\n/**\n * Configuration options for the `tokenBucket` algorithm.\n */\nexport interface TokenBucketConfig {\n /** Maximum number of tokens the bucket can hold (burst size). */\n capacity: number;\n /** Number of tokens added per `refillInterval`. */\n refillRate: number;\n /** Refill interval as milliseconds or a duration string (e.g., `\"1s\"`, `\"1m\"`). */\n refillInterval: Duration;\n}\n\ninterface TokenBucketState {\n tokens: number;\n lastRefill: number;\n}\n\nconst TOKEN_BUCKET_LUA = `\nlocal raw = redis.call('GET', KEYS[1])\nlocal capacity = tonumber(ARGV[1])\nlocal refillRate = tonumber(ARGV[2])\nlocal refillInterval = tonumber(ARGV[3])\nlocal cost = tonumber(ARGV[4])\nlocal now = tonumber(ARGV[5])\nlocal ttl = tonumber(ARGV[6])\n\nlocal tokens = capacity\nlocal lastRefill = now\n\nif raw then\n local sep = string.find(raw, ':')\n if sep then\n tokens = tonumber(string.sub(raw, 1, sep - 1)) or capacity\n lastRefill = tonumber(string.sub(raw, sep + 1)) or now\n end\nend\n\nlocal elapsed = math.max(0, now - lastRefill)\nlocal added = (elapsed / refillInterval) * refillRate\ntokens = math.min(capacity, tokens + added)\n\nif tokens >= cost then\n local newTokens = tokens - cost\n redis.call('SET', KEYS[1], tostring(newTokens) .. ':' .. tostring(now), 'PX', ttl)\n local reset = now + math.ceil(((capacity - newTokens) / refillRate) * refillInterval)\n return {1, math.floor(newTokens), reset}\nelse\n local deficit = cost - tokens\n local reset = now + math.ceil((deficit / refillRate) * refillInterval)\n return {0, math.floor(tokens), reset}\nend\n`.trim();\n\n/**\n * Create a continuous-refill Token Bucket rate-limiting algorithm.\n *\n * Allows bursts up to `capacity` and refills smoothly at `refillRate` tokens\n * per `refillInterval`. Supports variable request costs via `limit(id, { cost })`.\n */\nexport function tokenBucket(config: TokenBucketConfig): RateLimitAlgorithm {\n if (!Number.isFinite(config.capacity) || config.capacity <= 0) {\n throw new RangeError(`tokenBucket \"capacity\" must be a positive finite number, got ${config.capacity}.`);\n }\n if (!Number.isFinite(config.refillRate) || config.refillRate <= 0) {\n throw new RangeError(\n `tokenBucket \"refillRate\" must be a positive finite number, got ${config.refillRate}.`,\n );\n }\n\n const capacity = config.capacity;\n const refillRate = config.refillRate;\n const refillIntervalMs = parseDuration(config.refillInterval);\n const ttlMs = Math.max(refillIntervalMs * 2, Math.ceil((capacity / refillRate) * refillIntervalMs) * 2);\n\n return {\n name: 'token-bucket',\n maxLimit: capacity,\n\n async consume(ctx: AlgorithmContext): Promise<Omit<RateLimitResult, 'headers'>> {\n const { adapter, key, cost, now } = ctx;\n const bucketKey = `${key}:tb`;\n\n if (adapter.eval) {\n const raw = (await adapter.eval(\n TOKEN_BUCKET_LUA,\n [bucketKey],\n [capacity, refillRate, refillIntervalMs, cost, now, ttlMs],\n )) as [number, number, number];\n\n return {\n success: raw[0] === 1,\n limit: capacity,\n remaining: Math.max(0, Number(raw[1] ?? 0)),\n reset: Number(raw[2] ?? now),\n };\n }\n\n const existing = await adapter.get<TokenBucketState>(bucketKey);\n let tokens = capacity;\n if (existing) {\n const elapsed = Math.max(0, now - existing.lastRefill);\n const added = (elapsed / refillIntervalMs) * refillRate;\n tokens = Math.min(capacity, existing.tokens + added);\n }\n\n if (tokens >= cost) {\n const newTokens = tokens - cost;\n await adapter.set<TokenBucketState>(bucketKey, { tokens: newTokens, lastRefill: now }, ttlMs);\n const reset = now + Math.ceil(((capacity - newTokens) / refillRate) * refillIntervalMs);\n return {\n success: true,\n limit: capacity,\n remaining: Math.max(0, Math.floor(newTokens)),\n reset,\n };\n }\n\n const deficit = cost - tokens;\n const reset = now + Math.ceil((deficit / refillRate) * refillIntervalMs);\n return {\n success: false,\n limit: capacity,\n remaining: Math.max(0, Math.floor(tokens)),\n reset,\n };\n },\n };\n}\n"]}
@@ -0,0 +1,70 @@
1
+ import { R as RateLimiterConfig, a as RateLimiter, D as Duration, b as RateLimitAlgorithm } from './types-Ca_Pa4mZ.cjs';
2
+ export { A as AlgorithmContext, c as DurationUnit, L as LimitOptions, d as RateLimitResult, S as StorageAdapter } from './types-Ca_Pa4mZ.cjs';
3
+
4
+ /**
5
+ * Create a rate limiter instance configured with a storage adapter and algorithm.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { createRateLimiter, slidingWindow } from 'edge-throttle';
10
+ * import { MemoryAdapter } from 'edge-throttle/adapters/memory';
11
+ *
12
+ * const limiter = createRateLimiter({
13
+ * adapter: new MemoryAdapter(),
14
+ * algorithm: slidingWindow({ limit: 100, window: '1m' }),
15
+ * prefix: 'rl:api',
16
+ * failOpen: true,
17
+ * timeoutMs: 2000,
18
+ * });
19
+ *
20
+ * const result = await limiter.limit('user_123');
21
+ * ```
22
+ */
23
+ declare function createRateLimiter(config: RateLimiterConfig): RateLimiter;
24
+
25
+ /**
26
+ * Configuration options for the `slidingWindow` algorithm.
27
+ */
28
+ interface SlidingWindowConfig {
29
+ /** Maximum number of requests (or weighted cost) allowed per rolling window. */
30
+ limit: number;
31
+ /** Window duration as milliseconds or a duration string (e.g., `"10s"`, `"1m"`, `"1h"`). */
32
+ window: Duration;
33
+ }
34
+ /**
35
+ * Create a weighted Sliding Window Counter rate-limiting algorithm.
36
+ *
37
+ * Uses two adjacent fixed windows (previous and current) weighted by the elapsed
38
+ * fraction of the current window to prevent boundary bursts while keeping storage
39
+ * overhead constant at 2 keys per identifier.
40
+ */
41
+ declare function slidingWindow(config: SlidingWindowConfig): RateLimitAlgorithm;
42
+
43
+ /**
44
+ * Configuration options for the `tokenBucket` algorithm.
45
+ */
46
+ interface TokenBucketConfig {
47
+ /** Maximum number of tokens the bucket can hold (burst size). */
48
+ capacity: number;
49
+ /** Number of tokens added per `refillInterval`. */
50
+ refillRate: number;
51
+ /** Refill interval as milliseconds or a duration string (e.g., `"1s"`, `"1m"`). */
52
+ refillInterval: Duration;
53
+ }
54
+ /**
55
+ * Create a continuous-refill Token Bucket rate-limiting algorithm.
56
+ *
57
+ * Allows bursts up to `capacity` and refills smoothly at `refillRate` tokens
58
+ * per `refillInterval`. Supports variable request costs via `limit(id, { cost })`.
59
+ */
60
+ declare function tokenBucket(config: TokenBucketConfig): RateLimitAlgorithm;
61
+
62
+ /**
63
+ * Parse a `Duration` (milliseconds number or string like `"10s"`, `"1m"`, `"1h"`)
64
+ * into a positive number of milliseconds.
65
+ *
66
+ * @throws {RangeError} If the duration is invalid, non-finite, or `<= 0`.
67
+ */
68
+ declare function parseDuration(duration: Duration): number;
69
+
70
+ export { Duration, RateLimitAlgorithm, RateLimiter, RateLimiterConfig, type SlidingWindowConfig, type TokenBucketConfig, createRateLimiter, parseDuration, slidingWindow, tokenBucket };
@@ -0,0 +1,70 @@
1
+ import { R as RateLimiterConfig, a as RateLimiter, D as Duration, b as RateLimitAlgorithm } from './types-Ca_Pa4mZ.js';
2
+ export { A as AlgorithmContext, c as DurationUnit, L as LimitOptions, d as RateLimitResult, S as StorageAdapter } from './types-Ca_Pa4mZ.js';
3
+
4
+ /**
5
+ * Create a rate limiter instance configured with a storage adapter and algorithm.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { createRateLimiter, slidingWindow } from 'edge-throttle';
10
+ * import { MemoryAdapter } from 'edge-throttle/adapters/memory';
11
+ *
12
+ * const limiter = createRateLimiter({
13
+ * adapter: new MemoryAdapter(),
14
+ * algorithm: slidingWindow({ limit: 100, window: '1m' }),
15
+ * prefix: 'rl:api',
16
+ * failOpen: true,
17
+ * timeoutMs: 2000,
18
+ * });
19
+ *
20
+ * const result = await limiter.limit('user_123');
21
+ * ```
22
+ */
23
+ declare function createRateLimiter(config: RateLimiterConfig): RateLimiter;
24
+
25
+ /**
26
+ * Configuration options for the `slidingWindow` algorithm.
27
+ */
28
+ interface SlidingWindowConfig {
29
+ /** Maximum number of requests (or weighted cost) allowed per rolling window. */
30
+ limit: number;
31
+ /** Window duration as milliseconds or a duration string (e.g., `"10s"`, `"1m"`, `"1h"`). */
32
+ window: Duration;
33
+ }
34
+ /**
35
+ * Create a weighted Sliding Window Counter rate-limiting algorithm.
36
+ *
37
+ * Uses two adjacent fixed windows (previous and current) weighted by the elapsed
38
+ * fraction of the current window to prevent boundary bursts while keeping storage
39
+ * overhead constant at 2 keys per identifier.
40
+ */
41
+ declare function slidingWindow(config: SlidingWindowConfig): RateLimitAlgorithm;
42
+
43
+ /**
44
+ * Configuration options for the `tokenBucket` algorithm.
45
+ */
46
+ interface TokenBucketConfig {
47
+ /** Maximum number of tokens the bucket can hold (burst size). */
48
+ capacity: number;
49
+ /** Number of tokens added per `refillInterval`. */
50
+ refillRate: number;
51
+ /** Refill interval as milliseconds or a duration string (e.g., `"1s"`, `"1m"`). */
52
+ refillInterval: Duration;
53
+ }
54
+ /**
55
+ * Create a continuous-refill Token Bucket rate-limiting algorithm.
56
+ *
57
+ * Allows bursts up to `capacity` and refills smoothly at `refillRate` tokens
58
+ * per `refillInterval`. Supports variable request costs via `limit(id, { cost })`.
59
+ */
60
+ declare function tokenBucket(config: TokenBucketConfig): RateLimitAlgorithm;
61
+
62
+ /**
63
+ * Parse a `Duration` (milliseconds number or string like `"10s"`, `"1m"`, `"1h"`)
64
+ * into a positive number of milliseconds.
65
+ *
66
+ * @throws {RangeError} If the duration is invalid, non-finite, or `<= 0`.
67
+ */
68
+ declare function parseDuration(duration: Duration): number;
69
+
70
+ export { Duration, RateLimitAlgorithm, RateLimiter, RateLimiterConfig, type SlidingWindowConfig, type TokenBucketConfig, createRateLimiter, parseDuration, slidingWindow, tokenBucket };