@upstash/ratelimit 0.3.7 → 0.3.9-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -550,4 +550,4 @@ declare class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {
550
550
  window: Duration): Algorithm<MultiRegionContext>;
551
551
  }
552
552
 
553
- export { Algorithm, Analytics, AnalyticsConfig, Event, Geo, MultiRegionRatelimit, MultiRegionRatelimitConfig, RegionRatelimit as Ratelimit, RegionRatelimitConfig as RatelimitConfig };
553
+ export { Algorithm, Analytics, AnalyticsConfig, MultiRegionRatelimit, MultiRegionRatelimitConfig, RegionRatelimit as Ratelimit, RegionRatelimitConfig as RatelimitConfig };
package/dist/index.js CHANGED
@@ -95,16 +95,11 @@ var Analytics = class {
95
95
  if (k === "time") {
96
96
  continue;
97
97
  }
98
- if (k === "success") {
99
- if (!usage[k]) {
100
- usage[k] = { success: 0, blocked: 0 };
101
- }
102
- if (bucket[k]) {
103
- usage[k].success += v;
104
- } else {
105
- usage[k].blocked += v;
106
- }
98
+ if (!usage[k]) {
99
+ usage[k] = { success: 0, blocked: 0 };
107
100
  }
101
+ usage[k].success += v["true"] ?? 0;
102
+ usage[k].blocked += v["false"] ?? 0;
108
103
  }
109
104
  }
110
105
  return usage;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/duration.ts","../src/analytics.ts","../src/cache.ts","../src/ratelimit.ts","../src/single.ts","../src/multi.ts"],"sourcesContent":["export { RegionRatelimit as Ratelimit } from \"./single\";\nexport type { RegionRatelimitConfig as RatelimitConfig } from \"./single\";\nexport { MultiRegionRatelimit } from \"./multi\";\nexport type { MultiRegionRatelimitConfig } from \"./multi\";\nexport type { Algorithm } from \"./types\";\nexport * from \"./analytics\";\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const [timeString, duration] = d.split(\" \") as [string, Duration];\n const time = parseFloat(timeString);\n switch (duration) {\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 as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"@upstash/redis\";\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 redis: config.redis,\n window: \"1d\",\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 if (k === \"success\") {\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n if (bucket[k]) {\n usage[k].success += v as number;\n } else {\n usage[k].blocked += v as number;\n }\n }\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","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 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 * 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 =\n config.analytics !== false\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 promsie 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 type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"@upstash/redis\";\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 = 0\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 0\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,\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","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport { Ratelimit } from \"./ratelimit\";\nimport { Cache } from \"./cache\";\nimport type { Redis } from \"@upstash/redis\";\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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1
+ {"version":3,"sources":["../src/index.ts","../src/duration.ts","../src/analytics.ts","../src/cache.ts","../src/ratelimit.ts","../src/single.ts","../src/multi.ts"],"sourcesContent":["import { RegionRatelimit as Ratelimit } from \"./single\";\nimport type { RegionRatelimitConfig as RatelimitConfig } from \"./single\";\nimport { MultiRegionRatelimit } from \"./multi\";\nimport type { MultiRegionRatelimitConfig } from \"./multi\";\nimport type { Algorithm } from \"./types\";\nimport { Analytics } from \"./analytics\";\nimport type { AnalyticsConfig } from \"./analytics\";\n\nexport {\n Ratelimit,\n RatelimitConfig,\n MultiRegionRatelimit,\n MultiRegionRatelimitConfig,\n Algorithm,\n Analytics,\n AnalyticsConfig,\n};\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const [timeString, duration] = d.split(\" \") as [string, Duration];\n const time = parseFloat(timeString);\n switch (duration) {\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 as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"@upstash/redis\";\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 redis: config.redis,\n window: \"1d\",\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","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 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 * 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 =\n config.analytics !== false\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 promsie 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 type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"@upstash/redis\";\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 = 0\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 0\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,\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","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport { Ratelimit } from \"./ratelimit\";\nimport { Cache } from \"./cache\";\nimport type { Redis } from \"@upstash/redis\";\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,SAAS,GAAG,GAAqB;AACtC,QAAM,CAAC,YAAY,QAAQ,IAAI,EAAE,MAAM,GAAG;AAC1C,QAAM,OAAO,WAAW,UAAU;AAClC,UAAQ,UAAU;AAAA,IAChB,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,OAAO;AAAA,IAChB,KAAK;AACH,aAAO,OAAO,MAAO;AAAA,IACvB,KAAK;AACH,aAAO,OAAO,MAAO,KAAK;AAAA,IAC5B,KAAK;AACH,aAAO,OAAO,MAAO,KAAK,KAAK;AAAA,IAEjC;AACE,YAAM,IAAI,MAAM,gCAAgC,GAAG;AAAA,EACvD;AACF;;;ACxBA,4BAA2C;AAuBpC,IAAM,YAAN,MAAgB;AAAA,EACJ;AAAA,EACA,QAAQ;AAAA,EAEzB,YAAY,QAAyB;AACnC,SAAK,YAAY,IAAI,sBAAAA,UAAc;AAAA,MACjC,OAAO,OAAO;AAAA,MACd,QAAQ;A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,OAAO,CAAC,OAAO,CAAC,IAAI,SAAS,EAAE,CAAC;AAIpD,cAAI,KAAK,WAAW,GAAG;AACrB;AAAA,UACF;AAEA,gBAAM,GAAG,MAAM,KAAK,YAAY,GAAG,MAAM;AAAA,QAC3C;AAAA,MACF;AAEA,YAAM,UAAU,YAAY;AAC5B,YAAM,SAAS,gBAAgB,KAAK;AACpC,UAAI,IAAI,SAAS,CAAC,SAAS;AACzB,YAAI,MAAM,WAAW,YAAY,KAAK;AAAA,MACxC;AACA,aAAO;AAAA,QACL;AAAA,QACA,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,KAAK;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":["CoreAnalytics","reset","reset"]}
package/dist/index.mjs CHANGED
@@ -67,16 +67,11 @@ var Analytics = class {
67
67
  if (k === "time") {
68
68
  continue;
69
69
  }
70
- if (k === "success") {
71
- if (!usage[k]) {
72
- usage[k] = { success: 0, blocked: 0 };
73
- }
74
- if (bucket[k]) {
75
- usage[k].success += v;
76
- } else {
77
- usage[k].blocked += v;
78
- }
70
+ if (!usage[k]) {
71
+ usage[k] = { success: 0, blocked: 0 };
79
72
  }
73
+ usage[k].success += v["true"] ?? 0;
74
+ usage[k].blocked += v["false"] ?? 0;
80
75
  }
81
76
  }
82
77
  return usage;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/duration.ts","../src/analytics.ts","../src/cache.ts","../src/ratelimit.ts","../src/single.ts","../src/multi.ts"],"sourcesContent":["type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const [timeString, duration] = d.split(\" \") as [string, Duration];\n const time = parseFloat(timeString);\n switch (duration) {\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 as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"@upstash/redis\";\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 redis: config.redis,\n window: \"1d\",\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 if (k === \"success\") {\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n if (bucket[k]) {\n usage[k].success += v as number;\n } else {\n usage[k].blocked += v as number;\n }\n }\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","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 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 * 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 =\n config.analytics !== false\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 promsie 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 type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"@upstash/redis\";\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 = 0\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 0\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,\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","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport { Ratelimit } from \"./ratelimit\";\nimport { Cache } from \"./cache\";\nimport type { Redis } from \"@upstash/redis\";\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"],"mappings":";AAMO,SAAS,GAAG,GAAqB;AACtC,QAAM,CAAC,YAAY,QAAQ,IAAI,EAAE,MAAM,GAAG;AAC1C,QAAM,OAAO,WAAW,UAAU;AAClC,UAAQ,UAAU;AAAA,IAChB,KAAK;AACH,aAAO;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QAAQ,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC;AAEvE,YAAM,aAAa,SAAS,UAAU,IAAI,uBAAuB,QAAQ;AAEzE,YAAM,YAAY,SAAS;AAK3B,qBAAe,OAAO;AACpB,cAAM,CAAC,aAAa,IAAI,MAAM,QAAQ,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC;AACnE,cAAM,SAAS,MAAM,KAAK,IAAI,IAAI,cAAc,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC;AAE3E,mBAAW,MAAM,KAAK;AACpB,gBAAM,CAAC,GAAG,IAAI,MAAM,GAAG;AAKvB,cAAI,IAAI,UAAU,QAAQ;AACxB;AAAA,UACF;AACA,gBAAM,OAAO,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,SAAS,EAAE,CAAC;AAIpD,cAAI,KAAK,WAAW,GAAG;AACrB;AAAA,UACF;AAEA,gBAAM,GAAG,MAAM,KAAK,YAAY,GAAG,MAAM;AAAA,QAC3C;AAAA,MACF;AAEA,YAAM,UAAU,YAAY;AAC5B,YAAM,SAAS,gBAAgB,KAAK;AACpC,UAAI,IAAI,SAAS,CAAC,SAAS;AACzB,YAAI,MAAM,WAAW,YAAY,KAAK;AAAA,MACxC;AACA,aAAO;AAAA,QACL;AAAA,QACA,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,KAAK;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":["reset","reset"]}
1
+ {"version":3,"sources":["../src/duration.ts","../src/analytics.ts","../src/cache.ts","../src/ratelimit.ts","../src/single.ts","../src/multi.ts"],"sourcesContent":["type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const [timeString, duration] = d.split(\" \") as [string, Duration];\n const time = parseFloat(timeString);\n switch (duration) {\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 as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"@upstash/redis\";\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 redis: config.redis,\n window: \"1d\",\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","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 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 * 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 =\n config.analytics !== false\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 promsie 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 type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"@upstash/redis\";\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 = 0\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 0\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,\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","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport { Ratelimit } from \"./ratelimit\";\nimport { Cache } from \"./cache\";\nimport type { Redis } from \"@upstash/redis\";\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"],"mappings":";AAMO,SAAS,GAAG,GAAqB;AACtC,QAAM,CAAC,YAAY,Q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AM,iBAAkB;AACrD,YAAM,CAAC,SAAS,QAAQ,IAAI,MAAM,QAAQ,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC;AAEvE,YAAM,aAAa,SAAS,UAAU,IAAI,uBAAuB,QAAQ;AAEzE,YAAM,YAAY,SAAS;AAK3B,qBAAe,OAAO;AACpB,cAAM,CAAC,aAAa,IAAI,MAAM,QAAQ,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC;AACnE,cAAM,SAAS,MAAM,KAAK,IAAI,IAAI,cAAc,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC;AAE3E,mBAAW,MAAM,KAAK;AACpB,gBAAM,CAAC,GAAG,IAAI,MAAM,GAAG;AAKvB,cAAI,IAAI,UAAU,QAAQ;AACxB;AAAA,UACF;AACA,gBAAM,OAAO,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,SAAS,EAAE,CAAC;AAIpD,cAAI,KAAK,WAAW,GAAG;AACrB;AAAA,UACF;AAEA,gBAAM,GAAG,MAAM,KAAK,YAAY,GAAG,MAAM;AAAA,QAC3C;AAAA,MACF;AAEA,YAAM,UAAU,YAAY;AAC5B,YAAM,SAAS,gBAAgB,KAAK;AACpC,UAAI,IAAI,SAAS,CAAC,SAAS;AACzB,YAAI,MAAM,WAAW,YAAY,KAAK;AAAA,MACxC;AACA,aAAO;AAAA,QACL;AAAA,QACA,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,KAAK;AAAA,MAChB;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.3.7",
3
+ "version": "0.3.9-canary.0",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "license": "MIT",
@@ -34,7 +34,7 @@
34
34
  "typescript": "^4.9.4"
35
35
  },
36
36
  "dependencies": {
37
- "@upstash/core-analytics": "0.0.3"
37
+ "@upstash/core-analytics": "0.0.5"
38
38
  },
39
39
  "scripts": {
40
40
  "build": "tsup",