@upstash/ratelimit 0.4.3-canary.0 → 0.4.4

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/README.md CHANGED
@@ -239,7 +239,7 @@ Here's how you could do that:
239
239
 
240
240
  ```ts
241
241
  import { Redis } from "@upstash/redis"
242
- import { Ratelimit from "@upstash/ratelimit"
242
+ import { Ratelimit } from "@upstash/ratelimit"
243
243
 
244
244
  const redis = Redis.fromEnv()
245
245
 
@@ -464,6 +464,8 @@ const ratelimit = new Ratelimit({
464
464
 
465
465
  Go to the [Ratelimit Dashboard](https://console.upstash.com/ratelimit) and select the database you are using.
466
466
 
467
+ If you are using a custom prefix, you need to use the same in the dashboard's top right corner.
468
+
467
469
  ![Ratelimit Dashboard](/.github/img/dashboard.png)
468
470
 
469
471
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * EphemeralCache is used to block certain identifiers right away in case they have already exceedd the ratelimit.
2
+ * EphemeralCache is used to block certain identifiers right away in case they have already exceeded the ratelimit.
3
3
  */
4
4
  interface EphemeralCache {
5
5
  isBlocked: (identifier: string) => {
@@ -41,7 +41,7 @@ type RatelimitResponse = {
41
41
  * For the MultiRegion setup we do some synchronizing in the background, after returning the current limit.
42
42
  * In most case you can simply ignore this.
43
43
  *
44
- * On Vercel Edge or Cloudflare workers, you need to explicitely handle the pending Promise like this:
44
+ * On Vercel Edge or Cloudflare workers, you need to explicitly handle the pending Promise like this:
45
45
  *
46
46
  * **Vercel Edge:**
47
47
  * https://nextjs.org/docs/api-reference/next/server#nextfetchevent
@@ -125,7 +125,6 @@ type RatelimitConfig<TContext> = {
125
125
  * Choose one of the predefined ones or implement your own.
126
126
  * Available algorithms are exposed via static methods:
127
127
  * - Ratelimiter.fixedWindow
128
- * - Ratelimiter.slidingLogs
129
128
  * - Ratelimiter.slidingWindow
130
129
  * - Ratelimiter.tokenBucket
131
130
  */
@@ -164,7 +163,7 @@ type RatelimitConfig<TContext> = {
164
163
  timeout?: number;
165
164
  /**
166
165
  * If enabled, the ratelimiter will store analytics data in redis, which you can check out at
167
- * https://upstash.com/ratelimit
166
+ * https://console.upstash.com/ratelimit
168
167
  *
169
168
  * @default false
170
169
  */
@@ -218,7 +217,7 @@ declare abstract class Ratelimit<TContext extends Context> {
218
217
  * Block until the request may pass or timeout is reached.
219
218
  *
220
219
  * This method returns a promise that resolves as soon as the request may be processed
221
- * or after the timeoue has been reached.
220
+ * or after the timeout has been reached.
222
221
  *
223
222
  * Use this if you want to delay the request until it is ready to get processed.
224
223
  *
@@ -273,7 +272,7 @@ type MultiRegionRatelimitConfig = {
273
272
  * Set to `false` to disable.
274
273
  *
275
274
  * If left undefined, a map is created automatically, but it can only work
276
- * if the map or th ratelimit instance is created outside your serverless function handler.
275
+ * if the map or the ratelimit instance is created outside your serverless function handler.
277
276
  */
278
277
  ephemeralCache?: Map<string, number> | false;
279
278
  /**
@@ -284,7 +283,7 @@ type MultiRegionRatelimitConfig = {
284
283
  timeout?: number;
285
284
  /**
286
285
  * If enabled, the ratelimiter will store analytics data in redis, which you can check out at
287
- * https://upstash.com/ratelimit
286
+ * https://console.upstash.com/ratelimit
288
287
  *
289
288
  * @default true
290
289
  */
@@ -311,8 +310,8 @@ declare class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {
311
310
  */
312
311
  constructor(config: MultiRegionRatelimitConfig);
313
312
  /**
314
- * Each requests inside a fixed time increases a counter.
315
- * Once the counter reaches a maxmimum allowed number, all further requests are
313
+ * Each request inside a fixed time increases a counter.
314
+ * Once the counter reaches the maximum allowed number, all further requests are
316
315
  * rejected.
317
316
  *
318
317
  * **Pro:**
@@ -339,7 +338,7 @@ declare class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {
339
338
  window: Duration): Algorithm<MultiRegionContext>;
340
339
  /**
341
340
  * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
342
- * costs than `slidingLogs` and improved boundary behavior by calcualting a
341
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
343
342
  * weighted score between two windows.
344
343
  *
345
344
  * **Pro:**
@@ -376,7 +375,6 @@ type RegionRatelimitConfig = {
376
375
  * Choose one of the predefined ones or implement your own.
377
376
  * Available algorithms are exposed via static methods:
378
377
  * - Ratelimiter.fixedWindow
379
- * - Ratelimiter.slidingLogs
380
378
  * - Ratelimiter.slidingWindow
381
379
  * - Ratelimiter.tokenBucket
382
380
  */
@@ -412,7 +410,7 @@ type RegionRatelimitConfig = {
412
410
  timeout?: number;
413
411
  /**
414
412
  * If enabled, the ratelimiter will store analytics data in redis, which you can check out at
415
- * https://upstash.com/ratelimit
413
+ * https://console.upstash.com/ratelimit
416
414
  *
417
415
  * @default true
418
416
  */
@@ -435,12 +433,12 @@ type RegionRatelimitConfig = {
435
433
  */
436
434
  declare class RegionRatelimit extends Ratelimit<RegionContext> {
437
435
  /**
438
- * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
436
+ * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
439
437
  */
440
438
  constructor(config: RegionRatelimitConfig);
441
439
  /**
442
- * Each requests inside a fixed time increases a counter.
443
- * Once the counter reaches a maxmimum allowed number, all further requests are
440
+ * Each request inside a fixed time increases a counter.
441
+ * Once the counter reaches the maximum allowed number, all further requests are
444
442
  * rejected.
445
443
  *
446
444
  * **Pro:**
@@ -467,7 +465,7 @@ declare class RegionRatelimit extends Ratelimit<RegionContext> {
467
465
  window: Duration): Algorithm<RegionContext>;
468
466
  /**
469
467
  * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
470
- * costs than `slidingLogs` and improved boundary behavior by calcualting a
468
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
471
469
  * weighted score between two windows.
472
470
  *
473
471
  * **Pro:**
@@ -527,8 +525,8 @@ declare class RegionRatelimit extends Ratelimit<RegionContext> {
527
525
  *
528
526
  * @experimental
529
527
  *
530
- * Each requests inside a fixed time increases a counter.
531
- * Once the counter reaches a maxmimum allowed number, all further requests are
528
+ * Each request inside a fixed time increases a counter.
529
+ * Once the counter reaches the maximum allowed number, all further requests are
532
530
  * rejected.
533
531
  *
534
532
  * **Pro:**
package/dist/index.js CHANGED
@@ -237,7 +237,7 @@ var Ratelimit = class {
237
237
  * Block until the request may pass or timeout is reached.
238
238
  *
239
239
  * This method returns a promise that resolves as soon as the request may be processed
240
- * or after the timeoue has been reached.
240
+ * or after the timeout has been reached.
241
241
  *
242
242
  * Use this if you want to delay the request until it is ready to get processed.
243
243
  *
@@ -306,8 +306,8 @@ var MultiRegionRatelimit = class extends Ratelimit {
306
306
  });
307
307
  }
308
308
  /**
309
- * Each requests inside a fixed time increases a counter.
310
- * Once the counter reaches a maxmimum allowed number, all further requests are
309
+ * Each request inside a fixed time increases a counter.
310
+ * Once the counter reaches the maximum allowed number, all further requests are
311
311
  * rejected.
312
312
  *
313
313
  * **Pro:**
@@ -394,7 +394,7 @@ var MultiRegionRatelimit = class extends Ratelimit {
394
394
  }
395
395
  /**
396
396
  * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
397
- * costs than `slidingLogs` and improved boundary behavior by calcualting a
397
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
398
398
  * weighted score between two windows.
399
399
  *
400
400
  * **Pro:**
@@ -456,7 +456,7 @@ var MultiRegionRatelimit = class extends Ratelimit {
456
456
  const now = Date.now();
457
457
  const currentWindow = Math.floor(now / windowSize);
458
458
  const currentKey = [identifier, currentWindow].join(":");
459
- const previousWindow = currentWindow - windowSize;
459
+ const previousWindow = currentWindow - 1;
460
460
  const previousKey = [identifier, previousWindow].join(":");
461
461
  const dbs = ctx.redis.map((redis) => ({
462
462
  redis,
@@ -500,7 +500,7 @@ var MultiRegionRatelimit = class extends Ratelimit {
500
500
  // src/single.ts
501
501
  var RegionRatelimit = class extends Ratelimit {
502
502
  /**
503
- * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
503
+ * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
504
504
  */
505
505
  constructor(config) {
506
506
  super({
@@ -515,8 +515,8 @@ var RegionRatelimit = class extends Ratelimit {
515
515
  });
516
516
  }
517
517
  /**
518
- * Each requests inside a fixed time increases a counter.
519
- * Once the counter reaches a maxmimum allowed number, all further requests are
518
+ * Each request inside a fixed time increases a counter.
519
+ * Once the counter reaches the maximum allowed number, all further requests are
520
520
  * rejected.
521
521
  *
522
522
  * **Pro:**
@@ -571,7 +571,7 @@ var RegionRatelimit = class extends Ratelimit {
571
571
  return {
572
572
  success,
573
573
  limit: tokens,
574
- remaining: tokens - usedTokensAfterUpdate,
574
+ remaining: Math.max(0, tokens - usedTokensAfterUpdate),
575
575
  reset,
576
576
  pending: Promise.resolve()
577
577
  };
@@ -579,7 +579,7 @@ var RegionRatelimit = class extends Ratelimit {
579
579
  }
580
580
  /**
581
581
  * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
582
- * costs than `slidingLogs` and improved boundary behavior by calcualting a
582
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
583
583
  * weighted score between two windows.
584
584
  *
585
585
  * **Pro:**
@@ -603,16 +603,17 @@ var RegionRatelimit = class extends Ratelimit {
603
603
 
604
604
  local requestsInCurrentWindow = redis.call("GET", currentKey)
605
605
  if requestsInCurrentWindow == false then
606
- requestsInCurrentWindow = -1
606
+ requestsInCurrentWindow = 0
607
607
  end
608
608
 
609
-
610
609
  local requestsInPreviousWindow = redis.call("GET", previousKey)
611
610
  if requestsInPreviousWindow == false then
612
611
  requestsInPreviousWindow = 0
613
612
  end
614
- local percentageInCurrent = ( now % window) / window
615
- if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then
613
+ local percentageInCurrent = ( now % window ) / window
614
+ -- weighted requests to consider from the previous window
615
+ requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
616
+ if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then
616
617
  return -1
617
618
  end
618
619
 
@@ -622,14 +623,14 @@ var RegionRatelimit = class extends Ratelimit {
622
623
  -- So we only need the expire command once
623
624
  redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
624
625
  end
625
- return tokens - newValue
626
+ return tokens - ( newValue + requestsInPreviousWindow )
626
627
  `;
627
628
  const windowSize = ms(window);
628
629
  return async function(ctx, identifier) {
629
630
  const now = Date.now();
630
631
  const currentWindow = Math.floor(now / windowSize);
631
632
  const currentKey = [identifier, currentWindow].join(":");
632
- const previousWindow = currentWindow - windowSize;
633
+ const previousWindow = currentWindow - 1;
633
634
  const previousKey = [identifier, previousWindow].join(":");
634
635
  if (ctx.cache) {
635
636
  const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
@@ -688,28 +689,31 @@ var RegionRatelimit = class extends Ratelimit {
688
689
 
689
690
  redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
690
691
  redis.call("PEXPIRE", key, interval)
691
-
692
+
692
693
  return {remaining, now + interval}
693
694
  end
694
695
 
695
696
  -- The bucket does exist
696
-
697
+
697
698
  local updatedAt = tonumber(bucket[1])
698
699
  local tokens = tonumber(bucket[2])
699
-
700
+
700
701
  if now >= updatedAt + interval then
701
- remaining = math.min(maxTokens, tokens + refillRate) - 1
702
-
703
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
704
- return {remaining, now + interval}
705
- end
706
-
707
- if tokens > 0 then
708
- remaining = tokens - 1
709
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
710
- end
711
-
712
- return {remaining, updatedAt + interval}
702
+ if tokens <= 0 then
703
+ -- No more tokens were left before the refill.
704
+ remaining = math.min(maxTokens, refillRate) - 1
705
+ else
706
+ remaining = math.min(maxTokens, tokens + refillRate) - 1
707
+ end
708
+ redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
709
+ return {remaining, now + interval}
710
+ end
711
+
712
+ remaining = tokens - 1
713
+ redis.call("HSET", key, "tokens", remaining)
714
+ return {remaining, updatedAt + interval}
715
+
716
+
713
717
  `;
714
718
  const intervalDuration = ms(interval);
715
719
  return async function(ctx, identifier) {
@@ -752,8 +756,8 @@ var RegionRatelimit = class extends Ratelimit {
752
756
  *
753
757
  * @experimental
754
758
  *
755
- * Each requests inside a fixed time increases a counter.
756
- * Once the counter reaches a maxmimum allowed number, all further requests are
759
+ * Each request inside a fixed time increases a counter.
760
+ * Once the counter reaches the maximum allowed number, all further requests are
757
761
  * rejected.
758
762
  *
759
763
  * **Pro:**
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/analytics.ts","../src/cache.ts","../src/duration.ts","../src/ratelimit.ts","../src/multi.ts","../src/single.ts"],"sourcesContent":["import { Analytics } from \"./analytics\";\nimport type { AnalyticsConfig } from \"./analytics\";\nimport { MultiRegionRatelimit } from \"./multi\";\nimport type { MultiRegionRatelimitConfig } from \"./multi\";\nimport { RegionRatelimit as Ratelimit } from \"./single\";\nimport type { RegionRatelimitConfig as RatelimitConfig } from \"./single\";\nimport type { Algorithm } from \"./types\";\n\nexport {\n Ratelimit,\n RatelimitConfig,\n MultiRegionRatelimit,\n MultiRegionRatelimitConfig,\n Algorithm,\n Analytics,\n AnalyticsConfig,\n};\n","import { Analytics as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"./types\";\n\nexport type Geo = {\n country?: string;\n city?: string;\n region?: string;\n ip?: string;\n};\nexport type Event = Geo & {\n identifier: string;\n time: number;\n success: boolean;\n};\n\nexport type AnalyticsConfig = {\n redis: Redis;\n prefix?: string;\n};\n\n/**\n * The Analytics package is experimental and can change at any time.\n */\nexport class Analytics {\n private readonly analytics: CoreAnalytics;\n private readonly table = \"events\";\n\n constructor(config: AnalyticsConfig) {\n this.analytics = new CoreAnalytics({\n // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk\n redis: config.redis,\n window: \"1h\",\n prefix: config.prefix ?? \"@upstash/ratelimit\",\n retention: \"90d\",\n });\n }\n\n /**\n * Try to extract the geo information from the request\n *\n * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties\n * @param req\n * @returns\n */\n public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {\n if (typeof req.geo !== \"undefined\") {\n return req.geo;\n }\n if (typeof req.cf !== \"undefined\") {\n return req.cf;\n }\n\n return {};\n }\n\n public async record(event: Event): Promise<void> {\n await this.analytics.ingest(this.table, event);\n }\n\n async series<TFilter extends keyof Omit<Event, \"time\">>(\n filter: TFilter,\n cutoff: number,\n ): Promise<({ time: number } & Record<string, number>)[]> {\n const records = await this.analytics.query(this.table, {\n filter: [filter],\n range: [cutoff, Date.now()],\n });\n return records;\n }\n public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {\n const records = await this.analytics.aggregateBy(this.table, \"identifier\", {\n range: [cutoff, Date.now()],\n });\n const usage = {} as Record<string, { success: number; blocked: number }>;\n for (const bucket of records) {\n for (const [k, v] of Object.entries(bucket)) {\n if (k === \"time\") {\n continue;\n }\n\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n // @ts-ignore\n usage[k].success += v[\"true\"] ?? 0;\n // @ts-ignore\n usage[k].blocked += v[\"false\"] ?? 0;\n }\n }\n return usage;\n }\n}\n","import { EphemeralCache } from \"./types\";\n\nexport class Cache implements EphemeralCache {\n /**\n * Stores identifier -> reset (in milliseconds)\n */\n private readonly cache: Map<string, number>;\n\n constructor(cache: Map<string, number>) {\n this.cache = cache;\n }\n\n public isBlocked(identifier: string): { blocked: boolean; reset: number } {\n if (!this.cache.has(identifier)) {\n return { blocked: false, reset: 0 };\n }\n const reset = this.cache.get(identifier)!;\n if (reset < Date.now()) {\n this.cache.delete(identifier);\n return { blocked: false, reset: 0 };\n }\n\n return { blocked: true, reset: reset };\n }\n\n public blockUntil(identifier: string, reset: number): void {\n this.cache.set(identifier, reset);\n }\n\n public set(key: string, value: number): void {\n this.cache.set(key, value);\n }\n public get(key: string): number | null {\n return this.cache.get(key) || null;\n }\n\n public incr(key: string): number {\n let value = this.cache.get(key) ?? 0;\n value += 1;\n this.cache.set(key, value);\n return value;\n }\n}\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}` | `${number}${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const match = d.match(/^(\\d+)\\s?(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Unable to parse window size: ${d}`);\n }\n const time = parseInt(match[1]);\n const unit = match[2] as Unit;\n\n switch (unit) {\n case \"ms\":\n return time;\n case \"s\":\n return time * 1000;\n case \"m\":\n return time * 1000 * 60;\n case \"h\":\n return time * 1000 * 60 * 60;\n case \"d\":\n return time * 1000 * 60 * 60 * 24;\n\n default:\n throw new Error(`Unable to parse window size: ${d}`);\n }\n}\n","import { Analytics, Geo } from \"./analytics\";\nimport { Cache } from \"./cache\";\nimport type { Algorithm, Context, RatelimitResponse } from \"./types\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Timeout\");\n this.name = \"TimeoutError\";\n }\n}\nexport type RatelimitConfig<TContext> = {\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingLogs\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n\n limiter: Algorithm<TContext>;\n\n ctx: TContext;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * ),\n * })\n *\n * ```\n */\nexport abstract class Ratelimit<TContext extends Context> {\n protected readonly limiter: Algorithm<TContext>;\n\n protected readonly ctx: TContext;\n\n protected readonly prefix: string;\n\n protected readonly timeout: number;\n protected readonly analytics?: Analytics;\n constructor(config: RatelimitConfig<TContext>) {\n this.ctx = config.ctx;\n this.limiter = config.limiter;\n this.timeout = config.timeout ?? 5000;\n this.prefix = config.prefix ?? \"@upstash/ratelimit\";\n this.analytics = config.analytics\n ? new Analytics({\n redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,\n prefix: this.prefix,\n })\n : undefined;\n\n if (config.ephemeralCache instanceof Map) {\n this.ctx.cache = new Cache(config.ephemeralCache);\n } else if (typeof config.ephemeralCache === \"undefined\") {\n this.ctx.cache = new Cache(new Map());\n }\n }\n\n /**\n * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.\n *\n * Use this if you want to reject all requests that you can not handle right now.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public limit = async (identifier: string, req?: { geo?: Geo }): Promise<RatelimitResponse> => {\n const key = [this.prefix, identifier].join(\":\");\n let timeoutId: any = null;\n try {\n const arr: Promise<RatelimitResponse>[] = [this.limiter(this.ctx, key)];\n if (this.timeout > 0) {\n arr.push(\n new Promise((resolve) => {\n timeoutId = setTimeout(() => {\n resolve({\n success: true,\n limit: 0,\n remaining: 0,\n reset: 0,\n pending: Promise.resolve(),\n });\n }, this.timeout);\n }),\n );\n }\n\n const res = await Promise.race(arr);\n if (this.analytics) {\n try {\n const geo = req ? this.analytics.extractGeo(req) : undefined;\n const analyticsP = this.analytics\n .record({\n identifier,\n time: Date.now(),\n success: res.success,\n ...geo,\n })\n .catch((err) => {\n console.warn(\"Failed to record analytics\", err);\n });\n res.pending = Promise.all([res.pending, analyticsP]);\n } catch (err) {\n console.warn(\"Failed to record analytics\", err);\n }\n }\n return res;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n };\n\n /**\n * Block until the request may pass or timeout is reached.\n *\n * This method returns a promise that resolves as soon as the request may be processed\n * or after the timeoue has been reached.\n *\n * Use this if you want to delay the request until it is ready to get processed.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.blockUntilReady(id, 60_000)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public blockUntilReady = async (\n /**\n * An identifier per user or api.\n * Choose a userID, or api token, or ip address.\n *\n * If you want to limit your api across all users, you can set a constant string.\n */\n identifier: string,\n /**\n * Maximum duration to wait in milliseconds.\n * After this time the request will be denied.\n */\n timeout: number,\n ): Promise<RatelimitResponse> => {\n if (timeout <= 0) {\n throw new Error(\"timeout must be positive\");\n }\n let res: RatelimitResponse;\n\n const deadline = Date.now() + timeout;\n while (true) {\n res = await this.limit(identifier);\n if (res.success) {\n break;\n }\n if (res.reset === 0) {\n throw new Error(\"This should not happen\");\n }\n\n const wait = Math.min(res.reset, deadline) - Date.now();\n await new Promise((r) => setTimeout(r, wait));\n\n if (Date.now() > deadline) {\n break;\n }\n }\n return res!;\n };\n}\n","import { Cache } from \"./cache\";\nimport type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nfunction randomId(): string {\n let result = \"\";\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n const charactersLength = characters.length;\n for (let i = 0; i < 16; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\nexport type MultiRegionRatelimitConfig = {\n /**\n * Instances of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis[];\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - MultiRegionRatelimit.fixedWindow\n */\n limiter: Algorithm<MultiRegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or th ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new MultiRegionRatelimit({\n * redis: Redis.fromEnv(),\n * limiter: MultiRegionRatelimit.fixedWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n constructor(config: MultiRegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : undefined,\n },\n });\n }\n\n /**\n * Each requests inside a fixed time increases a counter.\n * Once the counter reaches a maxmimum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowDuration = ms(window);\n const script = `\n local key = KEYS[1]\n local id = ARGV[1]\n local window = ARGV[2]\n \n redis.call(\"SADD\", key, id)\n local members = redis.call(\"SMEMBERS\", key)\n if #members == 1 then\n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return members\n`;\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<string[]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [key], [requestID, windowDuration]) as Promise<string[]>,\n }));\n\n const firstResponse = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = firstResponse.length;\n\n const remaining = tokens - usedTokens - 1;\n\n /**\n * If the length between two databases does not match, we sync the two databases\n */\n async function sync() {\n const individualIDs = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const ids = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(key, ...allIDs);\n }\n }\n\n /**\n * Do not await sync. This should not run in the critical path.\n */\n\n const success = remaining > 0;\n const reset = (bucket + 1) * windowDuration;\n\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calcualting a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowSize = ms(window);\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n local requestID = ARGV[4] -- uuid for this request\n\n\n local currentMembers = redis.call(\"SMEMBERS\", currentKey)\n local requestsInCurrentWindow = #currentMembers\n local previousMembers = redis.call(\"SMEMBERS\", previousKey)\n local requestsInPreviousWindow = #previousMembers\n\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return {currentMembers, previousMembers}\n end\n\n redis.call(\"SADD\", currentKey, requestID)\n table.insert(currentMembers, requestID)\n if requestsInCurrentWindow == 0 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return {currentMembers, previousMembers}\n `;\n const windowDuration = ms(window);\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - windowSize;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<[string[], string[]]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [currentKey, previousKey], [tokens, now, windowDuration, requestID]) as Promise<\n [string[], string[]]\n >,\n }));\n\n const percentageInCurrent = (now % windowDuration) / windowDuration;\n const [current, previous] = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = previous.length * (1 - percentageInCurrent) + current.length;\n\n const remaining = tokens - usedTokens;\n\n /**\n * If a database differs from the consensus, we sync it\n */\n async function sync() {\n const [individualIDs] = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const [ids] = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(currentKey, ...allIDs);\n }\n }\n\n const success = remaining > 0;\n const reset = (currentWindow + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n}\n","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nimport { Ratelimit } from \"./ratelimit\";\nexport type RegionRatelimitConfig = {\n /**\n * Instance of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis;\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingLogs\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n limiter: Algorithm<RegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * \"30 m\", // interval of 30 minutes\n * 10, // Allow 10 requests per window of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class RegionRatelimit extends Ratelimit<RegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n\n constructor(config: RegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n },\n ephemeralCache: config.ephemeralCache,\n });\n }\n\n /**\n * Each requests inside a fixed time increases a counter.\n * Once the counter reaches a maxmimum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n\n const success = usedTokensAfterUpdate <= tokens;\n const reset = (bucket + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: tokens,\n remaining: tokens - usedTokensAfterUpdate,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calcualting a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n\n local requestsInCurrentWindow = redis.call(\"GET\", currentKey)\n if requestsInCurrentWindow == false then\n requestsInCurrentWindow = -1\n end\n\n\n local requestsInPreviousWindow = redis.call(\"GET\", previousKey)\n if requestsInPreviousWindow == false then\n requestsInPreviousWindow = 0\n end\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return -1\n end\n\n local newValue = redis.call(\"INCR\", currentKey)\n if newValue == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return tokens - newValue\n `;\n const windowSize = ms(window);\n return async function (ctx: RegionContext, identifier: string) {\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - windowSize;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const remaining = (await ctx.redis.eval(script, [currentKey, previousKey], [tokens, now, windowSize])) as number;\n\n const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowSize;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, remaining),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * You have a bucket filled with `{maxTokens}` tokens that refills constantly\n * at `{refillRate}` per `{interval}`.\n * Every request will remove one token from the bucket and if there is no\n * token to take, the request is rejected.\n *\n * **Pro:**\n *\n * - Bursts of requests are smoothed out and you can process them at a constant\n * rate.\n * - Allows to set a higher initial burst limit by setting `maxTokens` higher\n * than `refillRate`\n */\n static tokenBucket(\n /**\n * How many tokens are refilled per `interval`\n *\n * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.\n */\n refillRate: number,\n /**\n * The interval for the `refillRate`\n */\n interval: Duration,\n /**\n * Maximum number of tokens.\n * A newly created bucket starts with this many tokens.\n * Useful to allow higher burst limits.\n */\n maxTokens: number,\n ): Algorithm<RegionContext> {\n const script = `\n local key = KEYS[1] -- identifier including prefixes\n local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens\n local interval = tonumber(ARGV[2]) -- size of the window in milliseconds\n local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval\n local now = tonumber(ARGV[4]) -- current timestamp in milliseconds\n local remaining = 0\n \n local bucket = redis.call(\"HMGET\", key, \"updatedAt\", \"tokens\")\n \n if bucket[1] == false then\n -- The bucket does not exist yet, so we create it and add a ttl.\n remaining = maxTokens - 1\n \n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n redis.call(\"PEXPIRE\", key, interval)\n \n return {remaining, now + interval}\n end\n\n -- The bucket does exist\n \n local updatedAt = tonumber(bucket[1])\n local tokens = tonumber(bucket[2])\n \n if now >= updatedAt + interval then\n remaining = math.min(maxTokens, tokens + refillRate) - 1\n \n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n return {remaining, now + interval}\n end\n \n if tokens > 0 then\n remaining = tokens - 1\n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n end\n \n return {remaining, updatedAt + interval}\n `;\n\n const intervalDuration = ms(interval);\n return async function (ctx: RegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: maxTokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const now = Date.now();\n const key = [identifier, Math.floor(now / intervalDuration)].join(\":\");\n\n const [remaining, reset] = (await ctx.redis.eval(\n script,\n [key],\n [maxTokens, intervalDuration, refillRate, now],\n )) as [number, number];\n\n const success = remaining > 0;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: maxTokens,\n remaining,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates\n * it asynchronously.\n * This is experimental and not yet recommended for production use.\n *\n * @experimental\n *\n * Each requests inside a fixed time increases a counter.\n * Once the counter reaches a maxmimum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static cachedFixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n if (!ctx.cache) {\n throw new Error(\"This algorithm requires a cache\");\n }\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const reset = (bucket + 1) * windowDuration;\n\n const hit = typeof ctx.cache.get(key) === \"number\";\n if (hit) {\n const cachedTokensAfterUpdate = ctx.cache.incr(key);\n const success = cachedTokensAfterUpdate < tokens;\n\n const pending = success\n ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {\n ctx.cache!.set(key, t as number);\n })\n : Promise.resolve();\n\n return {\n success,\n limit: tokens,\n remaining: tokens - cachedTokensAfterUpdate,\n reset: reset,\n pending,\n };\n }\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n ctx.cache.set(key, usedTokensAfterUpdate);\n const remaining = tokens - usedTokensAfterUpdate;\n\n return {\n success: remaining >= 0,\n limit: tokens,\n remaining,\n reset: reset,\n pending: Promise.resolve(),\n };\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAA2C;AAuBpC,IAAM,YAAN,MAAgB;AAAA,EACJ;AAAA,EACA,QAAQ;AAAA,EAEzB,YAAY,QAAyB;AACnC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AS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcf,WAAO,eAAgB,KAAoB,YAAoB;AAC7D,UAAI,CAAC,IAAI,OAAO;AACd,cAAM,IAAI,MAAM,iCAAiC;AAAA,MACnD;AACA,YAAM,SAAS,KAAK,MAAM,KAAK,IAAI,IAAI,cAAc;AACrD,YAAM,MAAM,CAAC,YAAY,MAAM,EAAE,KAAK,GAAG;AACzC,YAAM,SAAS,SAAS,KAAK;AAE7B,YAAM,MAAM,OAAO,IAAI,MAAM,IAAI,GAAG,MAAM;AAC1C,UAAI,KAAK;AACP,cAAM,0BAA0B,IAAI,MAAM,KAAK,GAAG;AAClD,cAAM,UAAU,0BAA0B;AAE1C,cAAM,UAAU,UACZ,IAAI,MAAM,KAAK,QAAQ,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC,EAAE,KAAK,CAAC,MAAM;AAC1D,cAAI,MAAO,IAAI,KAAK,CAAW;AAAA,QACjC,CAAC,IACD,QAAQ,QAAQ;AAEpB,eAAO;AAAA,UACL;AAAA,UACA,OAAO;AAAA,UACP,WAAW,SAAS;AAAA,UACpB;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,YAAM,wBAAyB,MAAM,IAAI,MAAM,KAAK,QAAQ,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC;AACnF,UAAI,MAAM,IAAI,KAAK,qBAAqB;AACxC,YAAM,YAAY,SAAS;AAE3B,aAAO;AAAA,QACL,SAAS,aAAa;AAAA,QACtB,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,QAAQ,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;","names":["CoreAnalytics","reset","reset"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/analytics.ts","../src/cache.ts","../src/duration.ts","../src/ratelimit.ts","../src/multi.ts","../src/single.ts"],"sourcesContent":["import { Analytics } from \"./analytics\";\nimport type { AnalyticsConfig } from \"./analytics\";\nimport { MultiRegionRatelimit } from \"./multi\";\nimport type { MultiRegionRatelimitConfig } from \"./multi\";\nimport { RegionRatelimit as Ratelimit } from \"./single\";\nimport type { RegionRatelimitConfig as RatelimitConfig } from \"./single\";\nimport type { Algorithm } from \"./types\";\n\nexport {\n Ratelimit,\n RatelimitConfig,\n MultiRegionRatelimit,\n MultiRegionRatelimitConfig,\n Algorithm,\n Analytics,\n AnalyticsConfig,\n};\n","import { Analytics as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"./types\";\n\nexport type Geo = {\n country?: string;\n city?: string;\n region?: string;\n ip?: string;\n};\nexport type Event = Geo & {\n identifier: string;\n time: number;\n success: boolean;\n};\n\nexport type AnalyticsConfig = {\n redis: Redis;\n prefix?: string;\n};\n\n/**\n * The Analytics package is experimental and can change at any time.\n */\nexport class Analytics {\n private readonly analytics: CoreAnalytics;\n private readonly table = \"events\";\n\n constructor(config: AnalyticsConfig) {\n this.analytics = new CoreAnalytics({\n // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk\n redis: config.redis,\n window: \"1h\",\n prefix: config.prefix ?? \"@upstash/ratelimit\",\n retention: \"90d\",\n });\n }\n\n /**\n * Try to extract the geo information from the request\n *\n * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties\n * @param req\n * @returns\n */\n public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {\n if (typeof req.geo !== \"undefined\") {\n return req.geo;\n }\n if (typeof req.cf !== \"undefined\") {\n return req.cf;\n }\n\n return {};\n }\n\n public async record(event: Event): Promise<void> {\n await this.analytics.ingest(this.table, event);\n }\n\n async series<TFilter extends keyof Omit<Event, \"time\">>(\n filter: TFilter,\n cutoff: number,\n ): Promise<({ time: number } & Record<string, number>)[]> {\n const records = await this.analytics.query(this.table, {\n filter: [filter],\n range: [cutoff, Date.now()],\n });\n return records;\n }\n public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {\n const records = await this.analytics.aggregateBy(this.table, \"identifier\", {\n range: [cutoff, Date.now()],\n });\n const usage = {} as Record<string, { success: number; blocked: number }>;\n for (const bucket of records) {\n for (const [k, v] of Object.entries(bucket)) {\n if (k === \"time\") {\n continue;\n }\n\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n // @ts-ignore\n usage[k].success += v[\"true\"] ?? 0;\n // @ts-ignore\n usage[k].blocked += v[\"false\"] ?? 0;\n }\n }\n return usage;\n }\n}\n","import { EphemeralCache } from \"./types\";\n\nexport class Cache implements EphemeralCache {\n /**\n * Stores identifier -> reset (in milliseconds)\n */\n private readonly cache: Map<string, number>;\n\n constructor(cache: Map<string, number>) {\n this.cache = cache;\n }\n\n public isBlocked(identifier: string): { blocked: boolean; reset: number } {\n if (!this.cache.has(identifier)) {\n return { blocked: false, reset: 0 };\n }\n const reset = this.cache.get(identifier)!;\n if (reset < Date.now()) {\n this.cache.delete(identifier);\n return { blocked: false, reset: 0 };\n }\n\n return { blocked: true, reset: reset };\n }\n\n public blockUntil(identifier: string, reset: number): void {\n this.cache.set(identifier, reset);\n }\n\n public set(key: string, value: number): void {\n this.cache.set(key, value);\n }\n public get(key: string): number | null {\n return this.cache.get(key) || null;\n }\n\n public incr(key: string): number {\n let value = this.cache.get(key) ?? 0;\n value += 1;\n this.cache.set(key, value);\n return value;\n }\n}\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}` | `${number}${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const match = d.match(/^(\\d+)\\s?(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Unable to parse window size: ${d}`);\n }\n const time = parseInt(match[1]);\n const unit = match[2] as Unit;\n\n switch (unit) {\n case \"ms\":\n return time;\n case \"s\":\n return time * 1000;\n case \"m\":\n return time * 1000 * 60;\n case \"h\":\n return time * 1000 * 60 * 60;\n case \"d\":\n return time * 1000 * 60 * 60 * 24;\n\n default:\n throw new Error(`Unable to parse window size: ${d}`);\n }\n}\n","import { Analytics, Geo } from \"./analytics\";\nimport { Cache } from \"./cache\";\nimport type { Algorithm, Context, RatelimitResponse } from \"./types\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Timeout\");\n this.name = \"TimeoutError\";\n }\n}\nexport type RatelimitConfig<TContext> = {\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n\n limiter: Algorithm<TContext>;\n\n ctx: TContext;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * ),\n * })\n *\n * ```\n */\nexport abstract class Ratelimit<TContext extends Context> {\n protected readonly limiter: Algorithm<TContext>;\n\n protected readonly ctx: TContext;\n\n protected readonly prefix: string;\n\n protected readonly timeout: number;\n protected readonly analytics?: Analytics;\n constructor(config: RatelimitConfig<TContext>) {\n this.ctx = config.ctx;\n this.limiter = config.limiter;\n this.timeout = config.timeout ?? 5000;\n this.prefix = config.prefix ?? \"@upstash/ratelimit\";\n this.analytics = config.analytics\n ? new Analytics({\n redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,\n prefix: this.prefix,\n })\n : undefined;\n\n if (config.ephemeralCache instanceof Map) {\n this.ctx.cache = new Cache(config.ephemeralCache);\n } else if (typeof config.ephemeralCache === \"undefined\") {\n this.ctx.cache = new Cache(new Map());\n }\n }\n\n /**\n * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.\n *\n * Use this if you want to reject all requests that you can not handle right now.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public limit = async (identifier: string, req?: { geo?: Geo }): Promise<RatelimitResponse> => {\n const key = [this.prefix, identifier].join(\":\");\n let timeoutId: any = null;\n try {\n const arr: Promise<RatelimitResponse>[] = [this.limiter(this.ctx, key)];\n if (this.timeout > 0) {\n arr.push(\n new Promise((resolve) => {\n timeoutId = setTimeout(() => {\n resolve({\n success: true,\n limit: 0,\n remaining: 0,\n reset: 0,\n pending: Promise.resolve(),\n });\n }, this.timeout);\n }),\n );\n }\n\n const res = await Promise.race(arr);\n if (this.analytics) {\n try {\n const geo = req ? this.analytics.extractGeo(req) : undefined;\n const analyticsP = this.analytics\n .record({\n identifier,\n time: Date.now(),\n success: res.success,\n ...geo,\n })\n .catch((err) => {\n console.warn(\"Failed to record analytics\", err);\n });\n res.pending = Promise.all([res.pending, analyticsP]);\n } catch (err) {\n console.warn(\"Failed to record analytics\", err);\n }\n }\n return res;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n };\n\n /**\n * Block until the request may pass or timeout is reached.\n *\n * This method returns a promise that resolves as soon as the request may be processed\n * or after the timeout has been reached.\n *\n * Use this if you want to delay the request until it is ready to get processed.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.blockUntilReady(id, 60_000)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public blockUntilReady = async (\n /**\n * An identifier per user or api.\n * Choose a userID, or api token, or ip address.\n *\n * If you want to limit your api across all users, you can set a constant string.\n */\n identifier: string,\n /**\n * Maximum duration to wait in milliseconds.\n * After this time the request will be denied.\n */\n timeout: number,\n ): Promise<RatelimitResponse> => {\n if (timeout <= 0) {\n throw new Error(\"timeout must be positive\");\n }\n let res: RatelimitResponse;\n\n const deadline = Date.now() + timeout;\n while (true) {\n res = await this.limit(identifier);\n if (res.success) {\n break;\n }\n if (res.reset === 0) {\n throw new Error(\"This should not happen\");\n }\n\n const wait = Math.min(res.reset, deadline) - Date.now();\n await new Promise((r) => setTimeout(r, wait));\n\n if (Date.now() > deadline) {\n break;\n }\n }\n return res!;\n };\n}\n","import { Cache } from \"./cache\";\nimport type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nfunction randomId(): string {\n let result = \"\";\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n const charactersLength = characters.length;\n for (let i = 0; i < 16; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\nexport type MultiRegionRatelimitConfig = {\n /**\n * Instances of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis[];\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - MultiRegionRatelimit.fixedWindow\n */\n limiter: Algorithm<MultiRegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new MultiRegionRatelimit({\n * redis: Redis.fromEnv(),\n * limiter: MultiRegionRatelimit.fixedWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n constructor(config: MultiRegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : undefined,\n },\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowDuration = ms(window);\n const script = `\n local key = KEYS[1]\n local id = ARGV[1]\n local window = ARGV[2]\n \n redis.call(\"SADD\", key, id)\n local members = redis.call(\"SMEMBERS\", key)\n if #members == 1 then\n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return members\n`;\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<string[]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [key], [requestID, windowDuration]) as Promise<string[]>,\n }));\n\n const firstResponse = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = firstResponse.length;\n\n const remaining = tokens - usedTokens - 1;\n\n /**\n * If the length between two databases does not match, we sync the two databases\n */\n async function sync() {\n const individualIDs = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const ids = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(key, ...allIDs);\n }\n }\n\n /**\n * Do not await sync. This should not run in the critical path.\n */\n\n const success = remaining > 0;\n const reset = (bucket + 1) * windowDuration;\n\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowSize = ms(window);\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n local requestID = ARGV[4] -- uuid for this request\n\n\n local currentMembers = redis.call(\"SMEMBERS\", currentKey)\n local requestsInCurrentWindow = #currentMembers\n local previousMembers = redis.call(\"SMEMBERS\", previousKey)\n local requestsInPreviousWindow = #previousMembers\n\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return {currentMembers, previousMembers}\n end\n\n redis.call(\"SADD\", currentKey, requestID)\n table.insert(currentMembers, requestID)\n if requestsInCurrentWindow == 0 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return {currentMembers, previousMembers}\n `;\n const windowDuration = ms(window);\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<[string[], string[]]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [currentKey, previousKey], [tokens, now, windowDuration, requestID]) as Promise<\n [string[], string[]]\n >,\n }));\n\n const percentageInCurrent = (now % windowDuration) / windowDuration;\n const [current, previous] = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = previous.length * (1 - percentageInCurrent) + current.length;\n\n const remaining = tokens - usedTokens;\n\n /**\n * If a database differs from the consensus, we sync it\n */\n async function sync() {\n const [individualIDs] = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const [ids] = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(currentKey, ...allIDs);\n }\n }\n\n const success = remaining > 0;\n const reset = (currentWindow + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n}\n","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nimport { Ratelimit } from \"./ratelimit\";\nexport type RegionRatelimitConfig = {\n /**\n * Instance of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis;\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n limiter: Algorithm<RegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * \"30 m\", // interval of 30 minutes\n * 10, // Allow 10 requests per window of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class RegionRatelimit extends Ratelimit<RegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.\n */\n\n constructor(config: RegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n },\n ephemeralCache: config.ephemeralCache,\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n\n const success = usedTokensAfterUpdate <= tokens;\n const reset = (bucket + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, tokens - usedTokensAfterUpdate),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n\n local requestsInCurrentWindow = redis.call(\"GET\", currentKey)\n if requestsInCurrentWindow == false then\n requestsInCurrentWindow = 0\n end\n\n local requestsInPreviousWindow = redis.call(\"GET\", previousKey)\n if requestsInPreviousWindow == false then\n requestsInPreviousWindow = 0\n end\n local percentageInCurrent = ( now % window ) / window\n -- weighted requests to consider from the previous window\n requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)\n if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then\n return -1\n end\n\n local newValue = redis.call(\"INCR\", currentKey)\n if newValue == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return tokens - ( newValue + requestsInPreviousWindow )\n `;\n const windowSize = ms(window);\n return async function (ctx: RegionContext, identifier: string) {\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const remaining = (await ctx.redis.eval(script, [currentKey, previousKey], [tokens, now, windowSize])) as number;\n\n const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowSize;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, remaining),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * You have a bucket filled with `{maxTokens}` tokens that refills constantly\n * at `{refillRate}` per `{interval}`.\n * Every request will remove one token from the bucket and if there is no\n * token to take, the request is rejected.\n *\n * **Pro:**\n *\n * - Bursts of requests are smoothed out and you can process them at a constant\n * rate.\n * - Allows to set a higher initial burst limit by setting `maxTokens` higher\n * than `refillRate`\n */\n static tokenBucket(\n /**\n * How many tokens are refilled per `interval`\n *\n * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.\n */\n refillRate: number,\n /**\n * The interval for the `refillRate`\n */\n interval: Duration,\n /**\n * Maximum number of tokens.\n * A newly created bucket starts with this many tokens.\n * Useful to allow higher burst limits.\n */\n maxTokens: number,\n ): Algorithm<RegionContext> {\n const script = `\n local key = KEYS[1] -- identifier including prefixes\n local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens\n local interval = tonumber(ARGV[2]) -- size of the window in milliseconds\n local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval\n local now = tonumber(ARGV[4]) -- current timestamp in milliseconds\n local remaining = 0\n \n local bucket = redis.call(\"HMGET\", key, \"updatedAt\", \"tokens\")\n \n if bucket[1] == false then\n -- The bucket does not exist yet, so we create it and add a ttl.\n remaining = maxTokens - 1\n \n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n redis.call(\"PEXPIRE\", key, interval)\n\n return {remaining, now + interval}\n end\n\n -- The bucket does exist\n \n local updatedAt = tonumber(bucket[1])\n local tokens = tonumber(bucket[2])\n\n if now >= updatedAt + interval then\n if tokens <= 0 then \n -- No more tokens were left before the refill.\n remaining = math.min(maxTokens, refillRate) - 1\n else\n remaining = math.min(maxTokens, tokens + refillRate) - 1\n end\n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n return {remaining, now + interval}\n end\n \n remaining = tokens - 1\n redis.call(\"HSET\", key, \"tokens\", remaining)\n return {remaining, updatedAt + interval}\n\n \n `;\n\n const intervalDuration = ms(interval);\n return async function (ctx: RegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: maxTokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const now = Date.now();\n const key = [identifier, Math.floor(now / intervalDuration)].join(\":\");\n\n const [remaining, reset] = (await ctx.redis.eval(\n script,\n [key],\n [maxTokens, intervalDuration, refillRate, now],\n )) as [number, number];\n\n const success = remaining > 0;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: maxTokens,\n remaining,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates\n * it asynchronously.\n * This is experimental and not yet recommended for production use.\n *\n * @experimental\n *\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static cachedFixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n if (!ctx.cache) {\n throw new Error(\"This algorithm requires a cache\");\n }\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const reset = (bucket + 1) * windowDuration;\n\n const hit = typeof ctx.cache.get(key) === \"number\";\n if (hit) {\n const cachedTokensAfterUpdate = ctx.cache.incr(key);\n const success = cachedTokensAfterUpdate < tokens;\n\n const pending = success\n ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {\n ctx.cache!.set(key, t as number);\n })\n : Promise.resolve();\n\n return {\n success,\n limit: tokens,\n remaining: tokens - cachedTokensAfterUpdate,\n reset: reset,\n pending,\n };\n }\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n ctx.cache.set(key, usedTokensAfterUpdate);\n const remaining = tokens - usedTokensAfterUpdate;\n\n return {\n success: remaining >= 0,\n limit: tokens,\n remaining,\n reset: reset,\n pending: Promise.resolve(),\n };\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAA2C;AAuBpC,IAAM,YAAN,MAAgB;AAAA,EACJ;AAAA,EACA,QAAQ;AAAA,EAEzB,YAAY,QAAyB;AACnC,SAAK,YAAY,IAAI,sBAAAA,UAAc;AAAA;AAAA,MAEjC,OAAO,OAAO;AAAA,MACd,QAAQ;AAAA,MACR,QAAQ,OAAO,UAAU;AAAA,MACzB,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,WAAW,KAAmC;AACnD,QAAI,OAAO,IAAI,QAAQ,aAAa;AAClC,aAAO,IAAI;AAAA,IACb;AACA,QAAI,OAAO,IAAI,OAAO,aAAa;AACjC,aAAO,IAAI;AAAA,IACb;AAEA,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAa,OAAO,OAA6B;AAC/C,UAAM,KAAK,UAAU,O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KAAK;AACP,cAAM,0BAA0B,IAAI,MAAM,KAAK,GAAG;AAClD,cAAM,UAAU,0BAA0B;AAE1C,cAAM,UAAU,UACZ,IAAI,MAAM,KAAK,QAAQ,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC,EAAE,KAAK,CAAC,MAAM;AAC1D,cAAI,MAAO,IAAI,KAAK,CAAW;AAAA,QACjC,CAAC,IACD,QAAQ,QAAQ;AAEpB,eAAO;AAAA,UACL;AAAA,UACA,OAAO;AAAA,UACP,WAAW,SAAS;AAAA,UACpB;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,YAAM,wBAAyB,MAAM,IAAI,MAAM,KAAK,QAAQ,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC;AACnF,UAAI,MAAM,IAAI,KAAK,qBAAqB;AACxC,YAAM,YAAY,SAAS;AAE3B,aAAO;AAAA,QACL,SAAS,aAAa;AAAA,QACtB,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,QAAQ,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;","names":["CoreAnalytics","reset","reset"]}
package/dist/index.mjs CHANGED
@@ -209,7 +209,7 @@ var Ratelimit = class {
209
209
  * Block until the request may pass or timeout is reached.
210
210
  *
211
211
  * This method returns a promise that resolves as soon as the request may be processed
212
- * or after the timeoue has been reached.
212
+ * or after the timeout has been reached.
213
213
  *
214
214
  * Use this if you want to delay the request until it is ready to get processed.
215
215
  *
@@ -278,8 +278,8 @@ var MultiRegionRatelimit = class extends Ratelimit {
278
278
  });
279
279
  }
280
280
  /**
281
- * Each requests inside a fixed time increases a counter.
282
- * Once the counter reaches a maxmimum allowed number, all further requests are
281
+ * Each request inside a fixed time increases a counter.
282
+ * Once the counter reaches the maximum allowed number, all further requests are
283
283
  * rejected.
284
284
  *
285
285
  * **Pro:**
@@ -366,7 +366,7 @@ var MultiRegionRatelimit = class extends Ratelimit {
366
366
  }
367
367
  /**
368
368
  * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
369
- * costs than `slidingLogs` and improved boundary behavior by calcualting a
369
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
370
370
  * weighted score between two windows.
371
371
  *
372
372
  * **Pro:**
@@ -428,7 +428,7 @@ var MultiRegionRatelimit = class extends Ratelimit {
428
428
  const now = Date.now();
429
429
  const currentWindow = Math.floor(now / windowSize);
430
430
  const currentKey = [identifier, currentWindow].join(":");
431
- const previousWindow = currentWindow - windowSize;
431
+ const previousWindow = currentWindow - 1;
432
432
  const previousKey = [identifier, previousWindow].join(":");
433
433
  const dbs = ctx.redis.map((redis) => ({
434
434
  redis,
@@ -472,7 +472,7 @@ var MultiRegionRatelimit = class extends Ratelimit {
472
472
  // src/single.ts
473
473
  var RegionRatelimit = class extends Ratelimit {
474
474
  /**
475
- * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
475
+ * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
476
476
  */
477
477
  constructor(config) {
478
478
  super({
@@ -487,8 +487,8 @@ var RegionRatelimit = class extends Ratelimit {
487
487
  });
488
488
  }
489
489
  /**
490
- * Each requests inside a fixed time increases a counter.
491
- * Once the counter reaches a maxmimum allowed number, all further requests are
490
+ * Each request inside a fixed time increases a counter.
491
+ * Once the counter reaches the maximum allowed number, all further requests are
492
492
  * rejected.
493
493
  *
494
494
  * **Pro:**
@@ -543,7 +543,7 @@ var RegionRatelimit = class extends Ratelimit {
543
543
  return {
544
544
  success,
545
545
  limit: tokens,
546
- remaining: tokens - usedTokensAfterUpdate,
546
+ remaining: Math.max(0, tokens - usedTokensAfterUpdate),
547
547
  reset,
548
548
  pending: Promise.resolve()
549
549
  };
@@ -551,7 +551,7 @@ var RegionRatelimit = class extends Ratelimit {
551
551
  }
552
552
  /**
553
553
  * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
554
- * costs than `slidingLogs` and improved boundary behavior by calcualting a
554
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
555
555
  * weighted score between two windows.
556
556
  *
557
557
  * **Pro:**
@@ -575,16 +575,17 @@ var RegionRatelimit = class extends Ratelimit {
575
575
 
576
576
  local requestsInCurrentWindow = redis.call("GET", currentKey)
577
577
  if requestsInCurrentWindow == false then
578
- requestsInCurrentWindow = -1
578
+ requestsInCurrentWindow = 0
579
579
  end
580
580
 
581
-
582
581
  local requestsInPreviousWindow = redis.call("GET", previousKey)
583
582
  if requestsInPreviousWindow == false then
584
583
  requestsInPreviousWindow = 0
585
584
  end
586
- local percentageInCurrent = ( now % window) / window
587
- if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then
585
+ local percentageInCurrent = ( now % window ) / window
586
+ -- weighted requests to consider from the previous window
587
+ requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
588
+ if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then
588
589
  return -1
589
590
  end
590
591
 
@@ -594,14 +595,14 @@ var RegionRatelimit = class extends Ratelimit {
594
595
  -- So we only need the expire command once
595
596
  redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
596
597
  end
597
- return tokens - newValue
598
+ return tokens - ( newValue + requestsInPreviousWindow )
598
599
  `;
599
600
  const windowSize = ms(window);
600
601
  return async function(ctx, identifier) {
601
602
  const now = Date.now();
602
603
  const currentWindow = Math.floor(now / windowSize);
603
604
  const currentKey = [identifier, currentWindow].join(":");
604
- const previousWindow = currentWindow - windowSize;
605
+ const previousWindow = currentWindow - 1;
605
606
  const previousKey = [identifier, previousWindow].join(":");
606
607
  if (ctx.cache) {
607
608
  const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
@@ -660,28 +661,31 @@ var RegionRatelimit = class extends Ratelimit {
660
661
 
661
662
  redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
662
663
  redis.call("PEXPIRE", key, interval)
663
-
664
+
664
665
  return {remaining, now + interval}
665
666
  end
666
667
 
667
668
  -- The bucket does exist
668
-
669
+
669
670
  local updatedAt = tonumber(bucket[1])
670
671
  local tokens = tonumber(bucket[2])
671
-
672
+
672
673
  if now >= updatedAt + interval then
673
- remaining = math.min(maxTokens, tokens + refillRate) - 1
674
-
675
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
676
- return {remaining, now + interval}
677
- end
678
-
679
- if tokens > 0 then
680
- remaining = tokens - 1
681
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
682
- end
683
-
684
- return {remaining, updatedAt + interval}
674
+ if tokens <= 0 then
675
+ -- No more tokens were left before the refill.
676
+ remaining = math.min(maxTokens, refillRate) - 1
677
+ else
678
+ remaining = math.min(maxTokens, tokens + refillRate) - 1
679
+ end
680
+ redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
681
+ return {remaining, now + interval}
682
+ end
683
+
684
+ remaining = tokens - 1
685
+ redis.call("HSET", key, "tokens", remaining)
686
+ return {remaining, updatedAt + interval}
687
+
688
+
685
689
  `;
686
690
  const intervalDuration = ms(interval);
687
691
  return async function(ctx, identifier) {
@@ -724,8 +728,8 @@ var RegionRatelimit = class extends Ratelimit {
724
728
  *
725
729
  * @experimental
726
730
  *
727
- * Each requests inside a fixed time increases a counter.
728
- * Once the counter reaches a maxmimum allowed number, all further requests are
731
+ * Each request inside a fixed time increases a counter.
732
+ * Once the counter reaches the maximum allowed number, all further requests are
729
733
  * rejected.
730
734
  *
731
735
  * **Pro:**
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/analytics.ts","../src/cache.ts","../src/duration.ts","../src/ratelimit.ts","../src/multi.ts","../src/single.ts"],"sourcesContent":["import { Analytics as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"./types\";\n\nexport type Geo = {\n country?: string;\n city?: string;\n region?: string;\n ip?: string;\n};\nexport type Event = Geo & {\n identifier: string;\n time: number;\n success: boolean;\n};\n\nexport type AnalyticsConfig = {\n redis: Redis;\n prefix?: string;\n};\n\n/**\n * The Analytics package is experimental and can change at any time.\n */\nexport class Analytics {\n private readonly analytics: CoreAnalytics;\n private readonly table = \"events\";\n\n constructor(config: AnalyticsConfig) {\n this.analytics = new CoreAnalytics({\n // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk\n redis: config.redis,\n window: \"1h\",\n prefix: config.prefix ?? \"@upstash/ratelimit\",\n retention: \"90d\",\n });\n }\n\n /**\n * Try to extract the geo information from the request\n *\n * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties\n * @param req\n * @returns\n */\n public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {\n if (typeof req.geo !== \"undefined\") {\n return req.geo;\n }\n if (typeof req.cf !== \"undefined\") {\n return req.cf;\n }\n\n return {};\n }\n\n public async record(event: Event): Promise<void> {\n await this.analytics.ingest(this.table, event);\n }\n\n async series<TFilter extends keyof Omit<Event, \"time\">>(\n filter: TFilter,\n cutoff: number,\n ): Promise<({ time: number } & Record<string, number>)[]> {\n const records = await this.analytics.query(this.table, {\n filter: [filter],\n range: [cutoff, Date.now()],\n });\n return records;\n }\n public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {\n const records = await this.analytics.aggregateBy(this.table, \"identifier\", {\n range: [cutoff, Date.now()],\n });\n const usage = {} as Record<string, { success: number; blocked: number }>;\n for (const bucket of records) {\n for (const [k, v] of Object.entries(bucket)) {\n if (k === \"time\") {\n continue;\n }\n\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n // @ts-ignore\n usage[k].success += v[\"true\"] ?? 0;\n // @ts-ignore\n usage[k].blocked += v[\"false\"] ?? 0;\n }\n }\n return usage;\n }\n}\n","import { EphemeralCache } from \"./types\";\n\nexport class Cache implements EphemeralCache {\n /**\n * Stores identifier -> reset (in milliseconds)\n */\n private readonly cache: Map<string, number>;\n\n constructor(cache: Map<string, number>) {\n this.cache = cache;\n }\n\n public isBlocked(identifier: string): { blocked: boolean; reset: number } {\n if (!this.cache.has(identifier)) {\n return { blocked: false, reset: 0 };\n }\n const reset = this.cache.get(identifier)!;\n if (reset < Date.now()) {\n this.cache.delete(identifier);\n return { blocked: false, reset: 0 };\n }\n\n return { blocked: true, reset: reset };\n }\n\n public blockUntil(identifier: string, reset: number): void {\n this.cache.set(identifier, reset);\n }\n\n public set(key: string, value: number): void {\n this.cache.set(key, value);\n }\n public get(key: string): number | null {\n return this.cache.get(key) || null;\n }\n\n public incr(key: string): number {\n let value = this.cache.get(key) ?? 0;\n value += 1;\n this.cache.set(key, value);\n return value;\n }\n}\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}` | `${number}${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const match = d.match(/^(\\d+)\\s?(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Unable to parse window size: ${d}`);\n }\n const time = parseInt(match[1]);\n const unit = match[2] as Unit;\n\n switch (unit) {\n case \"ms\":\n return time;\n case \"s\":\n return time * 1000;\n case \"m\":\n return time * 1000 * 60;\n case \"h\":\n return time * 1000 * 60 * 60;\n case \"d\":\n return time * 1000 * 60 * 60 * 24;\n\n default:\n throw new Error(`Unable to parse window size: ${d}`);\n }\n}\n","import { Analytics, Geo } from \"./analytics\";\nimport { Cache } from \"./cache\";\nimport type { Algorithm, Context, RatelimitResponse } from \"./types\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Timeout\");\n this.name = \"TimeoutError\";\n }\n}\nexport type RatelimitConfig<TContext> = {\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingLogs\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n\n limiter: Algorithm<TContext>;\n\n ctx: TContext;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * ),\n * })\n *\n * ```\n */\nexport abstract class Ratelimit<TContext extends Context> {\n protected readonly limiter: Algorithm<TContext>;\n\n protected readonly ctx: TContext;\n\n protected readonly prefix: string;\n\n protected readonly timeout: number;\n protected readonly analytics?: Analytics;\n constructor(config: RatelimitConfig<TContext>) {\n this.ctx = config.ctx;\n this.limiter = config.limiter;\n this.timeout = config.timeout ?? 5000;\n this.prefix = config.prefix ?? \"@upstash/ratelimit\";\n this.analytics = config.analytics\n ? new Analytics({\n redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,\n prefix: this.prefix,\n })\n : undefined;\n\n if (config.ephemeralCache instanceof Map) {\n this.ctx.cache = new Cache(config.ephemeralCache);\n } else if (typeof config.ephemeralCache === \"undefined\") {\n this.ctx.cache = new Cache(new Map());\n }\n }\n\n /**\n * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.\n *\n * Use this if you want to reject all requests that you can not handle right now.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public limit = async (identifier: string, req?: { geo?: Geo }): Promise<RatelimitResponse> => {\n const key = [this.prefix, identifier].join(\":\");\n let timeoutId: any = null;\n try {\n const arr: Promise<RatelimitResponse>[] = [this.limiter(this.ctx, key)];\n if (this.timeout > 0) {\n arr.push(\n new Promise((resolve) => {\n timeoutId = setTimeout(() => {\n resolve({\n success: true,\n limit: 0,\n remaining: 0,\n reset: 0,\n pending: Promise.resolve(),\n });\n }, this.timeout);\n }),\n );\n }\n\n const res = await Promise.race(arr);\n if (this.analytics) {\n try {\n const geo = req ? this.analytics.extractGeo(req) : undefined;\n const analyticsP = this.analytics\n .record({\n identifier,\n time: Date.now(),\n success: res.success,\n ...geo,\n })\n .catch((err) => {\n console.warn(\"Failed to record analytics\", err);\n });\n res.pending = Promise.all([res.pending, analyticsP]);\n } catch (err) {\n console.warn(\"Failed to record analytics\", err);\n }\n }\n return res;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n };\n\n /**\n * Block until the request may pass or timeout is reached.\n *\n * This method returns a promise that resolves as soon as the request may be processed\n * or after the timeoue has been reached.\n *\n * Use this if you want to delay the request until it is ready to get processed.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.blockUntilReady(id, 60_000)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public blockUntilReady = async (\n /**\n * An identifier per user or api.\n * Choose a userID, or api token, or ip address.\n *\n * If you want to limit your api across all users, you can set a constant string.\n */\n identifier: string,\n /**\n * Maximum duration to wait in milliseconds.\n * After this time the request will be denied.\n */\n timeout: number,\n ): Promise<RatelimitResponse> => {\n if (timeout <= 0) {\n throw new Error(\"timeout must be positive\");\n }\n let res: RatelimitResponse;\n\n const deadline = Date.now() + timeout;\n while (true) {\n res = await this.limit(identifier);\n if (res.success) {\n break;\n }\n if (res.reset === 0) {\n throw new Error(\"This should not happen\");\n }\n\n const wait = Math.min(res.reset, deadline) - Date.now();\n await new Promise((r) => setTimeout(r, wait));\n\n if (Date.now() > deadline) {\n break;\n }\n }\n return res!;\n };\n}\n","import { Cache } from \"./cache\";\nimport type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nfunction randomId(): string {\n let result = \"\";\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n const charactersLength = characters.length;\n for (let i = 0; i < 16; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\nexport type MultiRegionRatelimitConfig = {\n /**\n * Instances of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis[];\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - MultiRegionRatelimit.fixedWindow\n */\n limiter: Algorithm<MultiRegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or th ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new MultiRegionRatelimit({\n * redis: Redis.fromEnv(),\n * limiter: MultiRegionRatelimit.fixedWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n constructor(config: MultiRegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : undefined,\n },\n });\n }\n\n /**\n * Each requests inside a fixed time increases a counter.\n * Once the counter reaches a maxmimum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowDuration = ms(window);\n const script = `\n local key = KEYS[1]\n local id = ARGV[1]\n local window = ARGV[2]\n \n redis.call(\"SADD\", key, id)\n local members = redis.call(\"SMEMBERS\", key)\n if #members == 1 then\n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return members\n`;\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<string[]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [key], [requestID, windowDuration]) as Promise<string[]>,\n }));\n\n const firstResponse = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = firstResponse.length;\n\n const remaining = tokens - usedTokens - 1;\n\n /**\n * If the length between two databases does not match, we sync the two databases\n */\n async function sync() {\n const individualIDs = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const ids = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(key, ...allIDs);\n }\n }\n\n /**\n * Do not await sync. This should not run in the critical path.\n */\n\n const success = remaining > 0;\n const reset = (bucket + 1) * windowDuration;\n\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calcualting a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowSize = ms(window);\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n local requestID = ARGV[4] -- uuid for this request\n\n\n local currentMembers = redis.call(\"SMEMBERS\", currentKey)\n local requestsInCurrentWindow = #currentMembers\n local previousMembers = redis.call(\"SMEMBERS\", previousKey)\n local requestsInPreviousWindow = #previousMembers\n\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return {currentMembers, previousMembers}\n end\n\n redis.call(\"SADD\", currentKey, requestID)\n table.insert(currentMembers, requestID)\n if requestsInCurrentWindow == 0 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return {currentMembers, previousMembers}\n `;\n const windowDuration = ms(window);\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - windowSize;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<[string[], string[]]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [currentKey, previousKey], [tokens, now, windowDuration, requestID]) as Promise<\n [string[], string[]]\n >,\n }));\n\n const percentageInCurrent = (now % windowDuration) / windowDuration;\n const [current, previous] = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = previous.length * (1 - percentageInCurrent) + current.length;\n\n const remaining = tokens - usedTokens;\n\n /**\n * If a database differs from the consensus, we sync it\n */\n async function sync() {\n const [individualIDs] = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const [ids] = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(currentKey, ...allIDs);\n }\n }\n\n const success = remaining > 0;\n const reset = (currentWindow + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n}\n","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nimport { Ratelimit } from \"./ratelimit\";\nexport type RegionRatelimitConfig = {\n /**\n * Instance of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis;\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingLogs\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n limiter: Algorithm<RegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * \"30 m\", // interval of 30 minutes\n * 10, // Allow 10 requests per window of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class RegionRatelimit extends Ratelimit<RegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n\n constructor(config: RegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n },\n ephemeralCache: config.ephemeralCache,\n });\n }\n\n /**\n * Each requests inside a fixed time increases a counter.\n * Once the counter reaches a maxmimum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n\n const success = usedTokensAfterUpdate <= tokens;\n const reset = (bucket + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: tokens,\n remaining: tokens - usedTokensAfterUpdate,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calcualting a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n\n local requestsInCurrentWindow = redis.call(\"GET\", currentKey)\n if requestsInCurrentWindow == false then\n requestsInCurrentWindow = -1\n end\n\n\n local requestsInPreviousWindow = redis.call(\"GET\", previousKey)\n if requestsInPreviousWindow == false then\n requestsInPreviousWindow = 0\n end\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return -1\n end\n\n local newValue = redis.call(\"INCR\", currentKey)\n if newValue == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return tokens - newValue\n `;\n const windowSize = ms(window);\n return async function (ctx: RegionContext, identifier: string) {\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - windowSize;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const remaining = (await ctx.redis.eval(script, [currentKey, previousKey], [tokens, now, windowSize])) as number;\n\n const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowSize;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, remaining),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * You have a bucket filled with `{maxTokens}` tokens that refills constantly\n * at `{refillRate}` per `{interval}`.\n * Every request will remove one token from the bucket and if there is no\n * token to take, the request is rejected.\n *\n * **Pro:**\n *\n * - Bursts of requests are smoothed out and you can process them at a constant\n * rate.\n * - Allows to set a higher initial burst limit by setting `maxTokens` higher\n * than `refillRate`\n */\n static tokenBucket(\n /**\n * How many tokens are refilled per `interval`\n *\n * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.\n */\n refillRate: number,\n /**\n * The interval for the `refillRate`\n */\n interval: Duration,\n /**\n * Maximum number of tokens.\n * A newly created bucket starts with this many tokens.\n * Useful to allow higher burst limits.\n */\n maxTokens: number,\n ): Algorithm<RegionContext> {\n const script = `\n local key = KEYS[1] -- identifier including prefixes\n local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens\n local interval = tonumber(ARGV[2]) -- size of the window in milliseconds\n local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval\n local now = tonumber(ARGV[4]) -- current timestamp in milliseconds\n local remaining = 0\n \n local bucket = redis.call(\"HMGET\", key, \"updatedAt\", \"tokens\")\n \n if bucket[1] == false then\n -- The bucket does not exist yet, so we create it and add a ttl.\n remaining = maxTokens - 1\n \n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n redis.call(\"PEXPIRE\", key, interval)\n \n return {remaining, now + interval}\n end\n\n -- The bucket does exist\n \n local updatedAt = tonumber(bucket[1])\n local tokens = tonumber(bucket[2])\n \n if now >= updatedAt + interval then\n remaining = math.min(maxTokens, tokens + refillRate) - 1\n \n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n return {remaining, now + interval}\n end\n \n if tokens > 0 then\n remaining = tokens - 1\n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n end\n \n return {remaining, updatedAt + interval}\n `;\n\n const intervalDuration = ms(interval);\n return async function (ctx: RegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: maxTokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const now = Date.now();\n const key = [identifier, Math.floor(now / intervalDuration)].join(\":\");\n\n const [remaining, reset] = (await ctx.redis.eval(\n script,\n [key],\n [maxTokens, intervalDuration, refillRate, now],\n )) as [number, number];\n\n const success = remaining > 0;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: maxTokens,\n remaining,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates\n * it asynchronously.\n * This is experimental and not yet recommended for production use.\n *\n * @experimental\n *\n * Each requests inside a fixed time increases a counter.\n * Once the counter reaches a maxmimum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static cachedFixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n if (!ctx.cache) {\n throw new Error(\"This algorithm requires a cache\");\n }\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const reset = (bucket + 1) * windowDuration;\n\n const hit = typeof ctx.cache.get(key) === \"number\";\n if (hit) {\n const cachedTokensAfterUpdate = ctx.cache.incr(key);\n const success = cachedTokensAfterUpdate < tokens;\n\n const pending = success\n ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {\n ctx.cache!.set(key, t as number);\n })\n : Promise.resolve();\n\n return {\n success,\n limit: tokens,\n remaining: tokens - cachedTokensAfterUpdate,\n reset: reset,\n pending,\n };\n }\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n ctx.cache.set(key, usedTokensAfterUpdate);\n const remaining = tokens - usedTokensAfterUpdate;\n\n return {\n success: remaining >= 0,\n limit: tokens,\n remaining,\n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+ {"version":3,"sources":["../src/analytics.ts","../src/cache.ts","../src/duration.ts","../src/ratelimit.ts","../src/multi.ts","../src/single.ts"],"sourcesContent":["import { Analytics as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"./types\";\n\nexport type Geo = {\n country?: string;\n city?: string;\n region?: string;\n ip?: string;\n};\nexport type Event = Geo & {\n identifier: string;\n time: number;\n success: boolean;\n};\n\nexport type AnalyticsConfig = {\n redis: Redis;\n prefix?: string;\n};\n\n/**\n * The Analytics package is experimental and can change at any time.\n */\nexport class Analytics {\n private readonly analytics: CoreAnalytics;\n private readonly table = \"events\";\n\n constructor(config: AnalyticsConfig) {\n this.analytics = new CoreAnalytics({\n // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk\n redis: config.redis,\n window: \"1h\",\n prefix: config.prefix ?? \"@upstash/ratelimit\",\n retention: \"90d\",\n });\n }\n\n /**\n * Try to extract the geo information from the request\n *\n * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties\n * @param req\n * @returns\n */\n public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {\n if (typeof req.geo !== \"undefined\") {\n return req.geo;\n }\n if (typeof req.cf !== \"undefined\") {\n return req.cf;\n }\n\n return {};\n }\n\n public async record(event: Event): Promise<void> {\n await this.analytics.ingest(this.table, event);\n }\n\n async series<TFilter extends keyof Omit<Event, \"time\">>(\n filter: TFilter,\n cutoff: number,\n ): Promise<({ time: number } & Record<string, number>)[]> {\n const records = await this.analytics.query(this.table, {\n filter: [filter],\n range: [cutoff, Date.now()],\n });\n return records;\n }\n public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {\n const records = await this.analytics.aggregateBy(this.table, \"identifier\", {\n range: [cutoff, Date.now()],\n });\n const usage = {} as Record<string, { success: number; blocked: number }>;\n for (const bucket of records) {\n for (const [k, v] of Object.entries(bucket)) {\n if (k === \"time\") {\n continue;\n }\n\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n // @ts-ignore\n usage[k].success += v[\"true\"] ?? 0;\n // @ts-ignore\n usage[k].blocked += v[\"false\"] ?? 0;\n }\n }\n return usage;\n }\n}\n","import { EphemeralCache } from \"./types\";\n\nexport class Cache implements EphemeralCache {\n /**\n * Stores identifier -> reset (in milliseconds)\n */\n private readonly cache: Map<string, number>;\n\n constructor(cache: Map<string, number>) {\n this.cache = cache;\n }\n\n public isBlocked(identifier: string): { blocked: boolean; reset: number } {\n if (!this.cache.has(identifier)) {\n return { blocked: false, reset: 0 };\n }\n const reset = this.cache.get(identifier)!;\n if (reset < Date.now()) {\n this.cache.delete(identifier);\n return { blocked: false, reset: 0 };\n }\n\n return { blocked: true, reset: reset };\n }\n\n public blockUntil(identifier: string, reset: number): void {\n this.cache.set(identifier, reset);\n }\n\n public set(key: string, value: number): void {\n this.cache.set(key, value);\n }\n public get(key: string): number | null {\n return this.cache.get(key) || null;\n }\n\n public incr(key: string): number {\n let value = this.cache.get(key) ?? 0;\n value += 1;\n this.cache.set(key, value);\n return value;\n }\n}\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}` | `${number}${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const match = d.match(/^(\\d+)\\s?(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Unable to parse window size: ${d}`);\n }\n const time = parseInt(match[1]);\n const unit = match[2] as Unit;\n\n switch (unit) {\n case \"ms\":\n return time;\n case \"s\":\n return time * 1000;\n case \"m\":\n return time * 1000 * 60;\n case \"h\":\n return time * 1000 * 60 * 60;\n case \"d\":\n return time * 1000 * 60 * 60 * 24;\n\n default:\n throw new Error(`Unable to parse window size: ${d}`);\n }\n}\n","import { Analytics, Geo } from \"./analytics\";\nimport { Cache } from \"./cache\";\nimport type { Algorithm, Context, RatelimitResponse } from \"./types\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Timeout\");\n this.name = \"TimeoutError\";\n }\n}\nexport type RatelimitConfig<TContext> = {\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n\n limiter: Algorithm<TContext>;\n\n ctx: TContext;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * ),\n * })\n *\n * ```\n */\nexport abstract class Ratelimit<TContext extends Context> {\n protected readonly limiter: Algorithm<TContext>;\n\n protected readonly ctx: TContext;\n\n protected readonly prefix: string;\n\n protected readonly timeout: number;\n protected readonly analytics?: Analytics;\n constructor(config: RatelimitConfig<TContext>) {\n this.ctx = config.ctx;\n this.limiter = config.limiter;\n this.timeout = config.timeout ?? 5000;\n this.prefix = config.prefix ?? \"@upstash/ratelimit\";\n this.analytics = config.analytics\n ? new Analytics({\n redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,\n prefix: this.prefix,\n })\n : undefined;\n\n if (config.ephemeralCache instanceof Map) {\n this.ctx.cache = new Cache(config.ephemeralCache);\n } else if (typeof config.ephemeralCache === \"undefined\") {\n this.ctx.cache = new Cache(new Map());\n }\n }\n\n /**\n * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.\n *\n * Use this if you want to reject all requests that you can not handle right now.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public limit = async (identifier: string, req?: { geo?: Geo }): Promise<RatelimitResponse> => {\n const key = [this.prefix, identifier].join(\":\");\n let timeoutId: any = null;\n try {\n const arr: Promise<RatelimitResponse>[] = [this.limiter(this.ctx, key)];\n if (this.timeout > 0) {\n arr.push(\n new Promise((resolve) => {\n timeoutId = setTimeout(() => {\n resolve({\n success: true,\n limit: 0,\n remaining: 0,\n reset: 0,\n pending: Promise.resolve(),\n });\n }, this.timeout);\n }),\n );\n }\n\n const res = await Promise.race(arr);\n if (this.analytics) {\n try {\n const geo = req ? this.analytics.extractGeo(req) : undefined;\n const analyticsP = this.analytics\n .record({\n identifier,\n time: Date.now(),\n success: res.success,\n ...geo,\n })\n .catch((err) => {\n console.warn(\"Failed to record analytics\", err);\n });\n res.pending = Promise.all([res.pending, analyticsP]);\n } catch (err) {\n console.warn(\"Failed to record analytics\", err);\n }\n }\n return res;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n };\n\n /**\n * Block until the request may pass or timeout is reached.\n *\n * This method returns a promise that resolves as soon as the request may be processed\n * or after the timeout has been reached.\n *\n * Use this if you want to delay the request until it is ready to get processed.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.blockUntilReady(id, 60_000)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public blockUntilReady = async (\n /**\n * An identifier per user or api.\n * Choose a userID, or api token, or ip address.\n *\n * If you want to limit your api across all users, you can set a constant string.\n */\n identifier: string,\n /**\n * Maximum duration to wait in milliseconds.\n * After this time the request will be denied.\n */\n timeout: number,\n ): Promise<RatelimitResponse> => {\n if (timeout <= 0) {\n throw new Error(\"timeout must be positive\");\n }\n let res: RatelimitResponse;\n\n const deadline = Date.now() + timeout;\n while (true) {\n res = await this.limit(identifier);\n if (res.success) {\n break;\n }\n if (res.reset === 0) {\n throw new Error(\"This should not happen\");\n }\n\n const wait = Math.min(res.reset, deadline) - Date.now();\n await new Promise((r) => setTimeout(r, wait));\n\n if (Date.now() > deadline) {\n break;\n }\n }\n return res!;\n };\n}\n","import { Cache } from \"./cache\";\nimport type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nfunction randomId(): string {\n let result = \"\";\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n const charactersLength = characters.length;\n for (let i = 0; i < 16; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\nexport type MultiRegionRatelimitConfig = {\n /**\n * Instances of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis[];\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - MultiRegionRatelimit.fixedWindow\n */\n limiter: Algorithm<MultiRegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new MultiRegionRatelimit({\n * redis: Redis.fromEnv(),\n * limiter: MultiRegionRatelimit.fixedWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n constructor(config: MultiRegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : undefined,\n },\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowDuration = ms(window);\n const script = `\n local key = KEYS[1]\n local id = ARGV[1]\n local window = ARGV[2]\n \n redis.call(\"SADD\", key, id)\n local members = redis.call(\"SMEMBERS\", key)\n if #members == 1 then\n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return members\n`;\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<string[]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [key], [requestID, windowDuration]) as Promise<string[]>,\n }));\n\n const firstResponse = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = firstResponse.length;\n\n const remaining = tokens - usedTokens - 1;\n\n /**\n * If the length between two databases does not match, we sync the two databases\n */\n async function sync() {\n const individualIDs = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const ids = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(key, ...allIDs);\n }\n }\n\n /**\n * Do not await sync. This should not run in the critical path.\n */\n\n const success = remaining > 0;\n const reset = (bucket + 1) * windowDuration;\n\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowSize = ms(window);\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n local requestID = ARGV[4] -- uuid for this request\n\n\n local currentMembers = redis.call(\"SMEMBERS\", currentKey)\n local requestsInCurrentWindow = #currentMembers\n local previousMembers = redis.call(\"SMEMBERS\", previousKey)\n local requestsInPreviousWindow = #previousMembers\n\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return {currentMembers, previousMembers}\n end\n\n redis.call(\"SADD\", currentKey, requestID)\n table.insert(currentMembers, requestID)\n if requestsInCurrentWindow == 0 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return {currentMembers, previousMembers}\n `;\n const windowDuration = ms(window);\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestID = randomId();\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<[string[], string[]]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [currentKey, previousKey], [tokens, now, windowDuration, requestID]) as Promise<\n [string[], string[]]\n >,\n }));\n\n const percentageInCurrent = (now % windowDuration) / windowDuration;\n const [current, previous] = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = previous.length * (1 - percentageInCurrent) + current.length;\n\n const remaining = tokens - usedTokens;\n\n /**\n * If a database differs from the consensus, we sync it\n */\n async function sync() {\n const [individualIDs] = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const [ids] = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(currentKey, ...allIDs);\n }\n }\n\n const success = remaining > 0;\n const reset = (currentWindow + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n}\n","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nimport { Ratelimit } from \"./ratelimit\";\nexport type RegionRatelimitConfig = {\n /**\n * Instance of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis;\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n limiter: Algorithm<RegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * \"30 m\", // interval of 30 minutes\n * 10, // Allow 10 requests per window of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class RegionRatelimit extends Ratelimit<RegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.\n */\n\n constructor(config: RegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n },\n ephemeralCache: config.ephemeralCache,\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n\n const success = usedTokensAfterUpdate <= tokens;\n const reset = (bucket + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, tokens - usedTokensAfterUpdate),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n\n local requestsInCurrentWindow = redis.call(\"GET\", currentKey)\n if requestsInCurrentWindow == false then\n requestsInCurrentWindow = 0\n end\n\n local requestsInPreviousWindow = redis.call(\"GET\", previousKey)\n if requestsInPreviousWindow == false then\n requestsInPreviousWindow = 0\n end\n local percentageInCurrent = ( now % window ) / window\n -- weighted requests to consider from the previous window\n requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)\n if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then\n return -1\n end\n\n local newValue = redis.call(\"INCR\", currentKey)\n if newValue == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return tokens - ( newValue + requestsInPreviousWindow )\n `;\n const windowSize = ms(window);\n return async function (ctx: RegionContext, identifier: string) {\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const remaining = (await ctx.redis.eval(script, [currentKey, previousKey], [tokens, now, windowSize])) as number;\n\n const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowSize;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, remaining),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * You have a bucket filled with `{maxTokens}` tokens that refills constantly\n * at `{refillRate}` per `{interval}`.\n * Every request will remove one token from the bucket and if there is no\n * token to take, the request is rejected.\n *\n * **Pro:**\n *\n * - Bursts of requests are smoothed out and you can process them at a constant\n * rate.\n * - Allows to set a higher initial burst limit by setting `maxTokens` higher\n * than `refillRate`\n */\n static tokenBucket(\n /**\n * How many tokens are refilled per `interval`\n *\n * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.\n */\n refillRate: number,\n /**\n * The interval for the `refillRate`\n */\n interval: Duration,\n /**\n * Maximum number of tokens.\n * A newly created bucket starts with this many tokens.\n * Useful to allow higher burst limits.\n */\n maxTokens: number,\n ): Algorithm<RegionContext> {\n const script = `\n local key = KEYS[1] -- identifier including prefixes\n local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens\n local interval = tonumber(ARGV[2]) -- size of the window in milliseconds\n local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval\n local now = tonumber(ARGV[4]) -- current timestamp in milliseconds\n local remaining = 0\n \n local bucket = redis.call(\"HMGET\", key, \"updatedAt\", \"tokens\")\n \n if bucket[1] == false then\n -- The bucket does not exist yet, so we create it and add a ttl.\n remaining = maxTokens - 1\n \n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n redis.call(\"PEXPIRE\", key, interval)\n\n return {remaining, now + interval}\n end\n\n -- The bucket does exist\n \n local updatedAt = tonumber(bucket[1])\n local tokens = tonumber(bucket[2])\n\n if now >= updatedAt + interval then\n if tokens <= 0 then \n -- No more tokens were left before the refill.\n remaining = math.min(maxTokens, refillRate) - 1\n else\n remaining = math.min(maxTokens, tokens + refillRate) - 1\n end\n redis.call(\"HMSET\", key, \"updatedAt\", now, \"tokens\", remaining)\n return {remaining, now + interval}\n end\n \n remaining = tokens - 1\n redis.call(\"HSET\", key, \"tokens\", remaining)\n return {remaining, updatedAt + interval}\n\n \n `;\n\n const intervalDuration = ms(interval);\n return async function (ctx: RegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: maxTokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const now = Date.now();\n const key = [identifier, Math.floor(now / intervalDuration)].join(\":\");\n\n const [remaining, reset] = (await ctx.redis.eval(\n script,\n [key],\n [maxTokens, intervalDuration, refillRate, now],\n )) as [number, number];\n\n const success = remaining > 0;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: maxTokens,\n remaining,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates\n * it asynchronously.\n * This is experimental and not yet recommended for production use.\n *\n * @experimental\n *\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static cachedFixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n if (!ctx.cache) {\n throw new Error(\"This algorithm requires a cache\");\n }\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const reset = (bucket + 1) * windowDuration;\n\n const hit = typeof ctx.cache.get(key) === \"number\";\n if (hit) {\n const cachedTokensAfterUpdate = ctx.cache.incr(key);\n const success = cachedTokensAfterUpdate < tokens;\n\n const pending = success\n ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {\n ctx.cache!.set(key, t as number);\n })\n : Promise.resolve();\n\n return {\n success,\n limit: tokens,\n remaining: tokens - cachedTokensAfterUpdate,\n reset: reset,\n pending,\n };\n }\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration])) as number;\n ctx.cache.set(key, usedTokensAfterUpdate);\n const remaining = tokens - usedTokensAfterUpdate;\n\n return {\n success: remaining >= 0,\n limit: tokens,\n remaining,\n reset: reset,\n pending: Promise.resolve(),\n };\n };\n }\n}\n"],"mappings":";AAAA,SAAS,aAAa,qBAAqB;AAuBpC,IAAM,YAAN,MAAgB;AAAA,EACJ;AAAA,EACA,QAAQ;AAAA,EAEzB,YAAY,QAAyB;AACnC,SAAK,YAAY,IAAI,cAAc;AAAA;AAAA,MAEjC,OAAO,OAAO;AAAA,MACd,QAAQ;AAAA,MACR,QAAQ,OAAO,UAAU;AAAA,MACzB,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,WAAW,KAAmC;AACnD,QAAI,OAAO,IAAI,QAAQ,aAAa;AAClC,aAAO,IAAI;AAAA,IACb;AACA,QAAI,OAAO,IAAI,OAAO,aAAa;AACjC,aAAO,IAAI;AAAA,IACb;AAEA,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAa,OAAO,OAA6B;AAC/C,UAAM,KAAK,UAAU,OAAO,KAAK,OAAO,KAAK;AAAA,EAC/C;AAAA,EAEA,MAAM,OACJ,QACA,QACwD;AACxD,UAAM,UAAU,MAAM,KAAK,UAAU,MAAM,KAAK,OAAO;AAAA,MACrD,QAAQ,CAAC,MAAM;AAAA,MACf,OAAO,CAAC,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC5B,CAAC;AACD,WAAO;AAAA,EACT;AA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AAQ,QAAQ;AAEpB,eAAO;AAAA,UACL;AAAA,UACA,OAAO;AAAA,UACP,WAAW,SAAS;AAAA,UACpB;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,YAAM,wBAAyB,MAAM,IAAI,MAAM,KAAK,QAAQ,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC;AACnF,UAAI,MAAM,IAAI,KAAK,qBAAqB;AACxC,YAAM,YAAY,SAAS;AAE3B,aAAO;AAAA,QACL,SAAS,aAAa;AAAA,QACtB,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,QAAQ,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;","names":["reset","reset"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@upstash/ratelimit",
3
- "version": "0.4.3-canary.0",
3
+ "version": "0.4.4",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "license": "MIT",