@upstash/ratelimit 0.4.5-canary.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.d.mts +556 -0
- package/dist/index.d.ts +556 -0
- package/dist/index.js +832 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +803 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +1 -22
- package/.github/actions/redis/action.yaml +0 -58
- package/.github/img/dashboard.png +0 -0
- package/.github/workflows/release.yml +0 -46
- package/.github/workflows/stale.yaml +0 -31
- package/.github/workflows/tests.yaml +0 -79
- package/biome.json +0 -37
- package/bun.lockb +0 -0
- package/cmd/set-version.js +0 -14
- package/examples/cloudflare-workers/package.json +0 -18
- package/examples/cloudflare-workers/src/index.ts +0 -35
- package/examples/cloudflare-workers/tsconfig.json +0 -105
- package/examples/cloudflare-workers/wrangler.toml +0 -3
- package/examples/nextjs/LICENSE +0 -21
- package/examples/nextjs/README.md +0 -17
- package/examples/nextjs/components/Breadcrumb.tsx +0 -67
- package/examples/nextjs/components/Header.tsx +0 -18
- package/examples/nextjs/components/ReadBlogPost.tsx +0 -9
- package/examples/nextjs/components/StarButton.tsx +0 -27
- package/examples/nextjs/middleware.ts +0 -35
- package/examples/nextjs/next-env.d.ts +0 -5
- package/examples/nextjs/package.json +0 -27
- package/examples/nextjs/pages/_app.tsx +0 -47
- package/examples/nextjs/pages/api/blocked.ts +0 -6
- package/examples/nextjs/pages/api/hello.ts +0 -5
- package/examples/nextjs/pages/index.tsx +0 -62
- package/examples/nextjs/postcss.config.js +0 -6
- package/examples/nextjs/public/favicon.ico +0 -0
- package/examples/nextjs/public/github.svg +0 -11
- package/examples/nextjs/public/upstash.svg +0 -27
- package/examples/nextjs/styles/globals.css +0 -76
- package/examples/nextjs/tailwind.config.js +0 -19
- package/examples/nextjs/tsconfig.json +0 -21
- package/examples/nextjs13/README.md +0 -38
- package/examples/nextjs13/app/favicon.ico +0 -0
- package/examples/nextjs13/app/globals.css +0 -107
- package/examples/nextjs13/app/layout.tsx +0 -18
- package/examples/nextjs13/app/page.module.css +0 -271
- package/examples/nextjs13/app/route.tsx +0 -14
- package/examples/nextjs13/next.config.js +0 -8
- package/examples/nextjs13/package.json +0 -22
- package/examples/nextjs13/public/next.svg +0 -1
- package/examples/nextjs13/public/thirteen.svg +0 -1
- package/examples/nextjs13/public/vercel.svg +0 -1
- package/examples/nextjs13/tsconfig.json +0 -28
- package/examples/remix/.env.example +0 -2
- package/examples/remix/.eslintrc.js +0 -4
- package/examples/remix/README.md +0 -59
- package/examples/remix/app/root.tsx +0 -25
- package/examples/remix/app/routes/index.tsx +0 -47
- package/examples/remix/package.json +0 -32
- package/examples/remix/public/favicon.ico +0 -0
- package/examples/remix/remix.config.js +0 -12
- package/examples/remix/remix.env.d.ts +0 -2
- package/examples/remix/server.js +0 -4
- package/examples/remix/tsconfig.json +0 -22
- package/examples/with-vercel-kv/README.md +0 -51
- package/examples/with-vercel-kv/app/favicon.ico +0 -0
- package/examples/with-vercel-kv/app/globals.css +0 -27
- package/examples/with-vercel-kv/app/layout.tsx +0 -21
- package/examples/with-vercel-kv/app/page.tsx +0 -71
- package/examples/with-vercel-kv/next.config.js +0 -8
- package/examples/with-vercel-kv/package.json +0 -25
- package/examples/with-vercel-kv/postcss.config.js +0 -6
- package/examples/with-vercel-kv/public/next.svg +0 -1
- package/examples/with-vercel-kv/public/vercel.svg +0 -1
- package/examples/with-vercel-kv/tailwind.config.js +0 -17
- package/examples/with-vercel-kv/tsconfig.json +0 -28
- package/src/analytics.test.ts +0 -23
- package/src/analytics.ts +0 -92
- package/src/blockUntilReady.test.ts +0 -56
- package/src/cache.test.ts +0 -41
- package/src/cache.ts +0 -43
- package/src/duration.test.ts +0 -23
- package/src/duration.ts +0 -30
- package/src/index.ts +0 -17
- package/src/multi.ts +0 -365
- package/src/ratelimit.test.ts +0 -155
- package/src/ratelimit.ts +0 -238
- package/src/single.ts +0 -487
- package/src/test_utils.ts +0 -65
- package/src/tools/seed.ts +0 -37
- package/src/types.ts +0 -78
- package/src/version.ts +0 -1
- package/tsconfig.json +0 -103
- package/tsup.config.js +0 -11
- package/turbo.json +0 -16
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics.ts","../src/cache.ts","../src/duration.ts","../src/ratelimit.ts","../src/multi.ts","../src/single.ts"],"sourcesContent":["import { Analytics as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"./types\";\n\nexport type Geo = {\n country?: string;\n city?: string;\n region?: string;\n ip?: string;\n};\nexport type Event = Geo & {\n identifier: string;\n time: number;\n success: boolean;\n};\n\nexport type AnalyticsConfig = {\n redis: Redis;\n prefix?: string;\n};\n\n/**\n * The Analytics package is experimental and can change at any time.\n */\nexport class Analytics {\n private readonly analytics: CoreAnalytics;\n private readonly table = \"events\";\n\n constructor(config: AnalyticsConfig) {\n this.analytics = new CoreAnalytics({\n // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk\n redis: config.redis,\n window: \"1h\",\n prefix: config.prefix ?? \"@upstash/ratelimit\",\n retention: \"90d\",\n });\n }\n\n /**\n * Try to extract the geo information from the request\n *\n * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties\n * @param req\n * @returns\n */\n public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {\n if (typeof req.geo !== \"undefined\") {\n return req.geo;\n }\n if (typeof req.cf !== \"undefined\") {\n return req.cf;\n }\n\n return {};\n }\n\n public async record(event: Event): Promise<void> {\n await this.analytics.ingest(this.table, event);\n }\n\n async series<TFilter extends keyof Omit<Event, \"time\">>(\n filter: TFilter,\n cutoff: number,\n ): Promise<({ time: number } & Record<string, number>)[]> {\n const records = await this.analytics.query(this.table, {\n filter: [filter],\n range: [cutoff, Date.now()],\n });\n return records;\n }\n public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {\n const records = await this.analytics.aggregateBy(this.table, \"identifier\", {\n range: [cutoff, Date.now()],\n });\n const usage = {} as Record<string, { success: number; blocked: number }>;\n for (const bucket of records) {\n for (const [k, v] of Object.entries(bucket)) {\n if (k === \"time\") {\n continue;\n }\n\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n // @ts-ignore\n usage[k].success += v.true ?? 0;\n // @ts-ignore\n usage[k].blocked += v.false ?? 0;\n }\n }\n return usage;\n }\n}\n","import { EphemeralCache } from \"./types\";\n\nexport class Cache implements EphemeralCache {\n /**\n * Stores identifier -> reset (in milliseconds)\n */\n private readonly cache: Map<string, number>;\n\n constructor(cache: Map<string, number>) {\n this.cache = cache;\n }\n\n public isBlocked(identifier: string): { blocked: boolean; reset: number } {\n if (!this.cache.has(identifier)) {\n return { blocked: false, reset: 0 };\n }\n const reset = this.cache.get(identifier)!;\n if (reset < Date.now()) {\n this.cache.delete(identifier);\n return { blocked: false, reset: 0 };\n }\n\n return { blocked: true, reset: reset };\n }\n\n public blockUntil(identifier: string, reset: number): void {\n this.cache.set(identifier, reset);\n }\n\n public set(key: string, value: number): void {\n this.cache.set(key, value);\n }\n public get(key: string): number | null {\n return this.cache.get(key) || null;\n }\n\n public incr(key: string): number {\n let value = this.cache.get(key) ?? 0;\n value += 1;\n this.cache.set(key, value);\n return value;\n }\n}\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}` | `${number}${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const match = d.match(/^(\\d+)\\s?(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Unable to parse window size: ${d}`);\n }\n const time = parseInt(match[1]);\n const unit = match[2] as Unit;\n\n switch (unit) {\n case \"ms\":\n return time;\n case \"s\":\n return time * 1000;\n case \"m\":\n return time * 1000 * 60;\n case \"h\":\n return time * 1000 * 60 * 60;\n case \"d\":\n return time * 1000 * 60 * 60 * 24;\n\n default:\n throw new Error(`Unable to parse window size: ${d}`);\n }\n}\n","import { Analytics, Geo } from \"./analytics\";\nimport { Cache } from \"./cache\";\nimport type { Algorithm, Context, RatelimitResponse } from \"./types\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Timeout\");\n this.name = \"TimeoutError\";\n }\n}\nexport type RatelimitConfig<TContext> = {\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n\n limiter: Algorithm<TContext>;\n\n ctx: TContext;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * ),\n * })\n *\n * ```\n */\nexport abstract class Ratelimit<TContext extends Context> {\n protected readonly limiter: Algorithm<TContext>;\n\n protected readonly ctx: TContext;\n\n protected readonly prefix: string;\n\n protected readonly timeout: number;\n protected readonly analytics?: Analytics;\n constructor(config: RatelimitConfig<TContext>) {\n this.ctx = config.ctx;\n this.limiter = config.limiter;\n this.timeout = config.timeout ?? 5000;\n this.prefix = config.prefix ?? \"@upstash/ratelimit\";\n this.analytics = config.analytics\n ? new Analytics({\n redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,\n prefix: this.prefix,\n })\n : undefined;\n\n if (config.ephemeralCache instanceof Map) {\n this.ctx.cache = new Cache(config.ephemeralCache);\n } else if (typeof config.ephemeralCache === \"undefined\") {\n this.ctx.cache = new Cache(new Map());\n }\n }\n\n /**\n * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.\n *\n * Use this if you want to reject all requests that you can not handle right now.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public limit = async (identifier: string, req?: { geo?: Geo }): Promise<RatelimitResponse> => {\n const key = [this.prefix, identifier].join(\":\");\n let timeoutId: any = null;\n try {\n const arr: Promise<RatelimitResponse>[] = [this.limiter(this.ctx, key)];\n if (this.timeout > 0) {\n arr.push(\n new Promise((resolve) => {\n timeoutId = setTimeout(() => {\n resolve({\n success: true,\n limit: 0,\n remaining: 0,\n reset: 0,\n pending: Promise.resolve(),\n });\n }, this.timeout);\n }),\n );\n }\n\n const res = await Promise.race(arr);\n if (this.analytics) {\n try {\n const geo = req ? this.analytics.extractGeo(req) : undefined;\n const analyticsP = this.analytics\n .record({\n identifier,\n time: Date.now(),\n success: res.success,\n ...geo,\n })\n .catch((err) => {\n console.warn(\"Failed to record analytics\", err);\n });\n res.pending = Promise.all([res.pending, analyticsP]);\n } catch (err) {\n console.warn(\"Failed to record analytics\", err);\n }\n }\n return res;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n };\n\n /**\n * Block until the request may pass or timeout is reached.\n *\n * This method returns a promise that resolves as soon as the request may be processed\n * or after the timeout has been reached.\n *\n * Use this if you want to delay the request until it is ready to get processed.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.blockUntilReady(id, 60_000)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public blockUntilReady = async (\n /**\n * An identifier per user or api.\n * Choose a userID, or api token, or ip address.\n *\n * If you want to limit your api across all users, you can set a constant string.\n */\n identifier: string,\n /**\n * Maximum duration to wait in milliseconds.\n * After this time the request will be denied.\n */\n timeout: number,\n ): Promise<RatelimitResponse> => {\n if (timeout <= 0) {\n throw new Error(\"timeout must be positive\");\n }\n let res: RatelimitResponse;\n\n const deadline = Date.now() + timeout;\n while (true) {\n res = await this.limit(identifier);\n if (res.success) {\n break;\n }\n if (res.reset === 0) {\n throw new Error(\"This should not happen\");\n }\n\n const wait = Math.min(res.reset, deadline) - Date.now();\n await new Promise((r) => setTimeout(r, wait));\n\n if (Date.now() > deadline) {\n break;\n }\n }\n return res!;\n };\n}\n","import { Cache } from \"./cache\";\nimport type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nfunction randomId(): string {\n let result = \"\";\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n const charactersLength = characters.length;\n for (let i = 0; i < 16; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\nexport type MultiRegionRatelimitConfig = {\n /**\n * Instances of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis[];\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - MultiRegionRatelimit.fixedWindow\n */\n limiter: Algorithm<MultiRegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new MultiRegionRatelimit({\n * redis: Redis.fromEnv(),\n * limiter: MultiRegionRatelimit.fixedWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n constructor(config: MultiRegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : undefined,\n },\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowDuration = ms(window);\n const script = `\n local key = KEYS[1]\n local id = ARGV[1]\n local window = ARGV[2]\n \n redis.call(\"SADD\", key, id)\n local members = redis.call(\"SMEMBERS\", key)\n if #members == 1 then\n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return members\n`;\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestId = randomId();\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<string[]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [key], [requestId, windowDuration]) as Promise<string[]>,\n }));\n\n const firstResponse = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = firstResponse.length;\n\n const remaining = tokens - usedTokens - 1;\n\n /**\n * If the length between two databases does not match, we sync the two databases\n */\n async function sync() {\n const individualIDs = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const ids = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(key, ...allIDs);\n }\n }\n\n /**\n * Do not await sync. This should not run in the critical path.\n */\n\n const success = remaining > 0;\n const reset = (bucket + 1) * windowDuration;\n\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowSize = ms(window);\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n local requestId = ARGV[4] -- uuid for this request\n\n\n local currentMembers = redis.call(\"SMEMBERS\", currentKey)\n local requestsInCurrentWindow = #currentMembers\n local previousMembers = redis.call(\"SMEMBERS\", previousKey)\n local requestsInPreviousWindow = #previousMembers\n\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return {currentMembers, previousMembers, false}\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, true}\n `;\n const windowDuration = ms(window);\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n // if (ctx.cache) {\n // const { blocked, reset } = ctx.cache.isBlocked(identifier);\n // if (blocked) {\n // return {\n // success: false,\n // limit: tokens,\n // remaining: 0,\n // reset: reset,\n // pending: Promise.resolve(),\n // };\n // }\n // }\n\n const requestId = randomId();\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n const dbs = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(\n script,\n [currentKey, previousKey],\n [tokens, now, windowDuration, requestId],\n // lua seems to return `1` for true and `null` for false\n ) as Promise<[string[], string[], 1 | null]>,\n }));\n\n const percentageInCurrent = (now % windowDuration) / windowDuration;\n const [current, previous, success] = await Promise.any(dbs.map((s) => s.request));\n\n const previousPartialUsed = previous.length * (1 - percentageInCurrent);\n const usedTokens = previousPartialUsed + 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 res = await Promise.all(dbs.map((s) => s.request));\n const allCurrentIds = res.flatMap(([current]) => current);\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 = allCurrentIds.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, ...diff);\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: Boolean(success),\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n}\n","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nimport { Ratelimit } from \"./ratelimit\";\nexport type RegionRatelimitConfig = {\n /**\n * Instance of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis;\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n limiter: Algorithm<RegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * \"30 m\", // interval of 30 minutes\n * 10, // Allow 10 requests per window of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class RegionRatelimit extends Ratelimit<RegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.\n */\n\n constructor(config: RegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n },\n ephemeralCache: config.ephemeralCache,\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n const usedTokensAfterUpdate = (await ctx.redis.eval(\n script,\n [key],\n [windowDuration],\n )) as number;\n\n const success = usedTokensAfterUpdate <= tokens;\n const reset = (bucket + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, tokens - usedTokensAfterUpdate),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n\n local requestsInCurrentWindow = redis.call(\"GET\", currentKey)\n if requestsInCurrentWindow == false then\n requestsInCurrentWindow = 0\n end\n\n local requestsInPreviousWindow = redis.call(\"GET\", previousKey)\n if requestsInPreviousWindow == false then\n requestsInPreviousWindow = 0\n end\n local percentageInCurrent = ( now % window ) / window\n -- weighted requests to consider from the previous window\n requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)\n if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then\n return -1\n end\n\n local newValue = redis.call(\"INCR\", currentKey)\n if newValue == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return tokens - ( newValue + requestsInPreviousWindow )\n `;\n const windowSize = ms(window);\n return async function (ctx: RegionContext, identifier: string) {\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const remaining = (await ctx.redis.eval(\n script,\n [currentKey, previousKey],\n [tokens, now, windowSize],\n )) as number;\n\n const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowSize;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, remaining),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * You have a bucket filled with `{maxTokens}` tokens that refills constantly\n * at `{refillRate}` per `{interval}`.\n * Every request will remove one token from the bucket and if there is no\n * token to take, the request is rejected.\n *\n * **Pro:**\n *\n * - Bursts of requests are smoothed out and you can process them at a constant\n * rate.\n * - Allows to set a higher initial burst limit by setting `maxTokens` higher\n * than `refillRate`\n */\n static tokenBucket(\n /**\n * How many tokens are refilled per `interval`\n *\n * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.\n */\n refillRate: number,\n /**\n * The interval for the `refillRate`\n */\n interval: Duration,\n /**\n * Maximum number of tokens.\n * A newly created bucket starts with this many tokens.\n * Useful to allow higher burst limits.\n */\n maxTokens: number,\n ): Algorithm<RegionContext> {\n const script = `\n local key = KEYS[1] -- identifier including prefixes\n local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens\n local interval = tonumber(ARGV[2]) -- size of the window in milliseconds\n local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval\n local now = tonumber(ARGV[4]) -- current timestamp in milliseconds\n \n local bucket = redis.call(\"HMGET\", key, \"refilledAt\", \"tokens\")\n \n local refilledAt\n local tokens\n\n if bucket[1] == false then\n refilledAt = now\n tokens = maxTokens\n else\n refilledAt = tonumber(bucket[1])\n tokens = tonumber(bucket[2])\n end\n \n if now >= refilledAt + interval then\n local numRefills = math.floor((now - refilledAt) / interval)\n tokens = math.min(maxTokens, tokens + numRefills * refillRate)\n\n refilledAt = refilledAt + numRefills * interval\n end\n\n if tokens == 0 then\n return {-1, refilledAt + interval}\n end\n\n local remaining = tokens - 1\n local expireAt = math.ceil(((maxTokens - remaining) / refillRate)) * interval\n \n redis.call(\"HSET\", key, \"refilledAt\", refilledAt, \"tokens\", remaining)\n redis.call(\"PEXPIRE\", key, expireAt)\n return {remaining, refilledAt + 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\n const [remaining, reset] = (await ctx.redis.eval(\n script,\n [identifier],\n [maxTokens, intervalDuration, refillRate, now],\n )) as [number, number];\n\n const success = remaining > 0;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: maxTokens,\n remaining,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates\n * it asynchronously.\n * This is experimental and not yet recommended for production use.\n *\n * @experimental\n *\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static cachedFixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n if (!ctx.cache) {\n throw new Error(\"This algorithm requires a cache\");\n }\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const reset = (bucket + 1) * windowDuration;\n\n const hit = typeof ctx.cache.get(key) === \"number\";\n if (hit) {\n const cachedTokensAfterUpdate = ctx.cache.incr(key);\n const success = cachedTokensAfterUpdate < tokens;\n\n const pending = success\n ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {\n ctx.cache!.set(key, t as number);\n })\n : Promise.resolve();\n\n return {\n success,\n limit: tokens,\n remaining: tokens - cachedTokensAfterUpdate,\n reset: reset,\n pending,\n };\n }\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(\n script,\n [key],\n [windowDuration],\n )) as number;\n ctx.cache.set(key, usedTokensAfterUpdate);\n const remaining = tokens - usedTokensAfterUpdate;\n\n return {\n success: remaining >= 0,\n limit: tokens,\n remaining,\n reset: reset,\n pending: Promise.resolve(),\n };\n };\n }\n}\n"],"mappings":";AAAA,SAAS,aAAa,qBAAqB;AAuBpC,IAAM,YAAN,MAAgB;AAAA,EACJ;AAAA,EACA,QAAQ;AAAA,EAEzB,YAAY,QAAyB;AACnC,SAAK,YAAY,IAAI,cAAc;AAAA;AAAA,MAEjC,OAAO,OAAO;AAAA,MACd,QAAQ;AAAA,MACR,QAAQ,OAAO,UAAU;AAAA,MACzB,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,WAAW,KAAmC;AACnD,QAAI,OAAO,IAAI,QAAQ,aAAa;AAClC,aAAO,IAAI;AAAA,IACb;AACA,QAAI,OAAO,IAAI,OAAO,aAAa;AACjC,aAAO,IAAI;AAAA,IACb;AAEA,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAa,OAAO,OAA6B;AAC/C,UAAM,KAAK,UAAU,OAAO,KAAK,OAAO,KAAK;AAAA,EAC/C;AAAA,EAEA,MAAM,OACJ,QACA,QACwD;AACxD,UAAM,UAAU,MAAM,KAAK,UAAU,MAAM,KAAK,OAAO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;AAAA,QACJ,CAAC,cAAc;AAAA,MACjB;AACA,UAAI,MAAM,IAAI,KAAK,qBAAqB;AACxC,YAAM,YAAY,SAAS;AAE3B,aAAO;AAAA,QACL,SAAS,aAAa;AAAA,QACtB,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,QAAQ,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;","names":["reset","current","reset"]}
|
package/package.json
CHANGED
|
@@ -1,22 +1 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@upstash/ratelimit",
|
|
3
|
-
"version": "0.4.5-canary.0",
|
|
4
|
-
"main": "./dist/index.js",
|
|
5
|
-
"types": "./dist/index.d.ts",
|
|
6
|
-
"scripts": {
|
|
7
|
-
"build": "tsup",
|
|
8
|
-
"test": "bun test src --coverage",
|
|
9
|
-
"fmt": "bunx @biomejs/biome check --apply ./src"
|
|
10
|
-
},
|
|
11
|
-
"devDependencies": {
|
|
12
|
-
"@upstash/redis": "^1.23.4",
|
|
13
|
-
"bun-types": "latest",
|
|
14
|
-
"rome": "^11.0.0",
|
|
15
|
-
"turbo": "^1.10.15",
|
|
16
|
-
"typescript": "^5.0.0"
|
|
17
|
-
},
|
|
18
|
-
"dependencies": {
|
|
19
|
-
"@upstash/core-analytics": "^0.0.6",
|
|
20
|
-
"tsup": "^7.2.0"
|
|
21
|
-
}
|
|
22
|
-
}
|
|
1
|
+
{ "name": "@upstash/ratelimit", "version": "v1.0.0", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "scripts": { "build": "tsup", "test": "bun test src --coverage", "fmt": "bunx @biomejs/biome check --apply ./src" }, "devDependencies": { "@upstash/redis": "^1.23.4", "bun-types": "latest", "rome": "^11.0.0", "turbo": "^1.10.15", "tsup": "^7.2.0", "typescript": "^5.0.0" }, "dependencies": { "@upstash/core-analytics": "^0.0.6" } }
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
name: Create local redis server
|
|
2
|
-
|
|
3
|
-
inputs:
|
|
4
|
-
UPSTASH_REDIS_REST_URL:
|
|
5
|
-
required: true
|
|
6
|
-
UPSTASH_REDIS_REST_TOKEN:
|
|
7
|
-
required: true
|
|
8
|
-
UPSTASH_REPO_ACCESS_TOKEN:
|
|
9
|
-
required: true
|
|
10
|
-
REDIS_SERVER_CONFIG:
|
|
11
|
-
required: true
|
|
12
|
-
|
|
13
|
-
runs:
|
|
14
|
-
using: "composite"
|
|
15
|
-
|
|
16
|
-
steps:
|
|
17
|
-
- name: Check out Redis Server
|
|
18
|
-
uses: actions/checkout@v2
|
|
19
|
-
with:
|
|
20
|
-
repository: upstash/redis-server
|
|
21
|
-
token: ${{ inputs.UPSTASH_REPO_ACCESS_TOKEN }}
|
|
22
|
-
path: redis-server
|
|
23
|
-
|
|
24
|
-
- uses: actions/setup-go@v2
|
|
25
|
-
with:
|
|
26
|
-
stable: "true"
|
|
27
|
-
go-version: "^1.17"
|
|
28
|
-
|
|
29
|
-
- uses: actions/cache@v2
|
|
30
|
-
with:
|
|
31
|
-
path: |
|
|
32
|
-
~/go/pkg/mod
|
|
33
|
-
~/.cache/go-build
|
|
34
|
-
key: ${{ runner.os }}-redis-server-${{ hashFiles('**/go.mod') }}
|
|
35
|
-
restore-keys: |
|
|
36
|
-
${{ runner.os }}-redis-server
|
|
37
|
-
|
|
38
|
-
- run: |
|
|
39
|
-
echo "$REDIS_SERVER_CONFIG" >> config.json
|
|
40
|
-
shell: bash
|
|
41
|
-
env:
|
|
42
|
-
REDIS_SERVER_CONFIG: ${{ inputs.REDIS_SERVER_CONFIG }}
|
|
43
|
-
|
|
44
|
-
- run: |
|
|
45
|
-
make
|
|
46
|
-
./upstash-redis -log-level error -config $GITHUB_WORKSPACE/config.json &
|
|
47
|
-
working-directory: ./redis-server/cmd
|
|
48
|
-
shell: bash
|
|
49
|
-
env:
|
|
50
|
-
UPSTASH_REDIS_REST_URL: ${{ inputs.UPSTASH_REDIS_REST_URL }}
|
|
51
|
-
UPSTASH_REDIS_REST_TOKEN: ${{ inputs.UPSTASH_REDIS_REST_TOKEN }}
|
|
52
|
-
|
|
53
|
-
- run: |
|
|
54
|
-
curl $UPSTASH_REDIS_REST_URL/info -H "Authorization: Bearer $UPSTASH_REDIS_REST_TOKEN"
|
|
55
|
-
shell: bash
|
|
56
|
-
env:
|
|
57
|
-
UPSTASH_REDIS_REST_URL: ${{ inputs.UPSTASH_REDIS_REST_URL }}
|
|
58
|
-
UPSTASH_REDIS_REST_TOKEN: ${{ inputs.UPSTASH_REDIS_REST_TOKEN }}
|
|
Binary file
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
name: Release
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
release:
|
|
5
|
-
types:
|
|
6
|
-
- published
|
|
7
|
-
|
|
8
|
-
jobs:
|
|
9
|
-
release:
|
|
10
|
-
name: Release
|
|
11
|
-
runs-on: ubuntu-latest
|
|
12
|
-
steps:
|
|
13
|
-
- name: Checkout Repo
|
|
14
|
-
uses: actions/checkout@v2
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
- name: Setup Node
|
|
18
|
-
uses: actions/setup-node@v2
|
|
19
|
-
with:
|
|
20
|
-
node-version: 18
|
|
21
|
-
|
|
22
|
-
- name: Set version
|
|
23
|
-
run: node cmd/set-version.js . ${GITHUB_REF#refs/*/}
|
|
24
|
-
|
|
25
|
-
- name: Install bun
|
|
26
|
-
run: npm install -g bun
|
|
27
|
-
|
|
28
|
-
- name: Install dependencies
|
|
29
|
-
run: bun install
|
|
30
|
-
|
|
31
|
-
- name: Build
|
|
32
|
-
run: bun run build
|
|
33
|
-
|
|
34
|
-
- name: Add npm token
|
|
35
|
-
run: echo "//registry.npmjs.org/:_authToken=${{secrets.NPM_TOKEN}}" > .npmrc
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
- name: Publish release candidate
|
|
39
|
-
if: "github.event.release.prerelease"
|
|
40
|
-
run: npm publish --access public --tag=canary --no-git-checks
|
|
41
|
-
|
|
42
|
-
- name: Publish
|
|
43
|
-
if: "!github.event.release.prerelease"
|
|
44
|
-
run: npm publish --access public --no-git-checks
|
|
45
|
-
|
|
46
|
-
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
name: 'Close stale issues and PRs'
|
|
2
|
-
on:
|
|
3
|
-
schedule:
|
|
4
|
-
- cron: "30 1 * * *"
|
|
5
|
-
|
|
6
|
-
env:
|
|
7
|
-
DAYS_BEFORE_ISSUE_STALE: 30
|
|
8
|
-
DAYS_BEFORE_ISSUE_CLOSE: 7
|
|
9
|
-
DAYS_BEFORE_PR_STALE: 30
|
|
10
|
-
DAYS_BEFORE_PR_CLOSE: 7
|
|
11
|
-
|
|
12
|
-
jobs:
|
|
13
|
-
close-issues:
|
|
14
|
-
runs-on: ubuntu-latest
|
|
15
|
-
permissions:
|
|
16
|
-
issues: write
|
|
17
|
-
pull-requests: write
|
|
18
|
-
steps:
|
|
19
|
-
- uses: actions/stale@v8
|
|
20
|
-
with:
|
|
21
|
-
days-before-issue-stale: ${{ env.DAYS_BEFORE_ISSUE_STALE }}
|
|
22
|
-
days-before-issue-close: ${{ env.DAYS_BEFORE_ISSUE_CLOSE }}
|
|
23
|
-
days-before-pr-stale: ${{ env.DAYS_BEFORE_PR_STALE }}
|
|
24
|
-
days-before-pr-close: ${{ env.DAYS_BEFORE_PR_CLOSE }}
|
|
25
|
-
stale-issue-label: "Inactive Issue"
|
|
26
|
-
stale-issue-message: 'This issue is stale because it has been open ${{ env.DAYS_BEFORE_ISSUE_STALE }} days with no activity. Remove stale label or comment or this will be closed in ${{ env.DAYS_BEFORE_ISSUE_CLOSE }} days.'
|
|
27
|
-
stale-pr-message: 'This PR is stale because it has been open ${{ env.DAYS_BEFORE_PR_STALE }} days with no activity. Remove stale label or comment or this will be closed in ${{ env.DAYS_BEFORE_PR_CLOSE }} days.'
|
|
28
|
-
close-issue-message: 'This issue was closed because it has been stalled for ${{ env.DAYS_BEFORE_ISSUE_CLOSE }} days with no activity.'
|
|
29
|
-
close-pr-message: 'This PR was closed because it has been stalled for ${{ env.DAYS_BEFORE_PR_CLOSE }} days with no activity.'
|
|
30
|
-
exempt-issue-labels: "Active Issue"
|
|
31
|
-
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
name: Tests
|
|
2
|
-
on:
|
|
3
|
-
pull_request:
|
|
4
|
-
schedule:
|
|
5
|
-
- cron: "0 0 * * *" # daily
|
|
6
|
-
|
|
7
|
-
jobs:
|
|
8
|
-
build:
|
|
9
|
-
runs-on: ubuntu-latest
|
|
10
|
-
|
|
11
|
-
name: Build
|
|
12
|
-
steps:
|
|
13
|
-
- name: Setup repo
|
|
14
|
-
uses: actions/checkout@v2
|
|
15
|
-
|
|
16
|
-
- uses: actions/setup-node@v3
|
|
17
|
-
with:
|
|
18
|
-
node-version: 18
|
|
19
|
-
|
|
20
|
-
- name: Install bun
|
|
21
|
-
run: npm install -g bun
|
|
22
|
-
|
|
23
|
-
- name: Install dependencies
|
|
24
|
-
run: bun install
|
|
25
|
-
|
|
26
|
-
- name: Verify formatting
|
|
27
|
-
run: bun run fmt
|
|
28
|
-
|
|
29
|
-
- name: Start redis server
|
|
30
|
-
uses: ./.github/actions/redis
|
|
31
|
-
with:
|
|
32
|
-
UPSTASH_REDIS_REST_URL: http://127.0.0.1:6379
|
|
33
|
-
UPSTASH_REDIS_REST_TOKEN: ${{ secrets.UPSTASH_REDIS_REST_TOKEN }}
|
|
34
|
-
UPSTASH_REPO_ACCESS_TOKEN: ${{ secrets.UPSTASH_REPO_ACCESS_TOKEN }}
|
|
35
|
-
REDIS_SERVER_CONFIG: ${{ secrets.REDIS_SERVER_CONFIG }}
|
|
36
|
-
|
|
37
|
-
- name: Build
|
|
38
|
-
run: bun run build
|
|
39
|
-
env:
|
|
40
|
-
UPSTASH_REDIS_REST_URL: http://127.0.0.1:6379
|
|
41
|
-
UPSTASH_REDIS_REST_TOKEN: ${{ secrets.UPSTASH_REDIS_REST_TOKEN }}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
test:
|
|
45
|
-
runs-on: ubuntu-latest
|
|
46
|
-
name: Tests
|
|
47
|
-
steps:
|
|
48
|
-
- name: Setup repo
|
|
49
|
-
uses: actions/checkout@v2
|
|
50
|
-
|
|
51
|
-
- uses: actions/setup-node@v3
|
|
52
|
-
with:
|
|
53
|
-
node-version: 18
|
|
54
|
-
|
|
55
|
-
- name: Install bun
|
|
56
|
-
run: npm install -g bun
|
|
57
|
-
|
|
58
|
-
- name: Install dependencies
|
|
59
|
-
run: bun install
|
|
60
|
-
|
|
61
|
-
- name: Start redis server
|
|
62
|
-
uses: ./.github/actions/redis
|
|
63
|
-
with:
|
|
64
|
-
UPSTASH_REDIS_REST_URL: http://127.0.0.1:6379
|
|
65
|
-
UPSTASH_REDIS_REST_TOKEN: ${{ secrets.UPSTASH_REDIS_REST_TOKEN }}
|
|
66
|
-
UPSTASH_REPO_ACCESS_TOKEN: ${{ secrets.UPSTASH_REPO_ACCESS_TOKEN }}
|
|
67
|
-
REDIS_SERVER_CONFIG: ${{ secrets.REDIS_SERVER_CONFIG }}
|
|
68
|
-
|
|
69
|
-
- name: Run tests
|
|
70
|
-
run: bun run test
|
|
71
|
-
env:
|
|
72
|
-
UPSTASH_REDIS_REST_URL: http://127.0.0.1:6379
|
|
73
|
-
UPSTASH_REDIS_REST_TOKEN: ${{ secrets.UPSTASH_REDIS_REST_TOKEN }}
|
|
74
|
-
EU2_UPSTASH_REDIS_REST_URL: ${{ secrets.EU2_UPSTASH_REDIS_REST_URL }}
|
|
75
|
-
EU2_UPSTASH_REDIS_REST_TOKEN: ${{ secrets.EU2_UPSTASH_REDIS_REST_TOKEN }}
|
|
76
|
-
APN_UPSTASH_REDIS_REST_URL: ${{ secrets.APN_UPSTASH_REDIS_REST_URL }}
|
|
77
|
-
APN_UPSTASH_REDIS_REST_TOKEN: ${{ secrets.APN_UPSTASH_REDIS_REST_TOKEN }}
|
|
78
|
-
US1_UPSTASH_REDIS_REST_URL: ${{ secrets.US1_UPSTASH_REDIS_REST_URL }}
|
|
79
|
-
US1_UPSTASH_REDIS_REST_TOKEN: ${{ secrets.US1_UPSTASH_REDIS_REST_TOKEN }}
|
package/biome.json
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"$schema": "https://biomejs.dev/schemas/1.0.0/schema.json",
|
|
3
|
-
|
|
4
|
-
"linter": {
|
|
5
|
-
"enabled": true,
|
|
6
|
-
"rules": {
|
|
7
|
-
"recommended": true,
|
|
8
|
-
"a11y": {
|
|
9
|
-
"noSvgWithoutTitle": "off"
|
|
10
|
-
},
|
|
11
|
-
"correctness": {
|
|
12
|
-
"noUnusedVariables": "warn"
|
|
13
|
-
},
|
|
14
|
-
"security": {
|
|
15
|
-
"noDangerouslySetInnerHtml": "off"
|
|
16
|
-
},
|
|
17
|
-
"style": {
|
|
18
|
-
"useBlockStatements": "error",
|
|
19
|
-
"noNonNullAssertion": "off"
|
|
20
|
-
},
|
|
21
|
-
"performance": {
|
|
22
|
-
"noDelete": "off"
|
|
23
|
-
},
|
|
24
|
-
"suspicious": {
|
|
25
|
-
"noExplicitAny": "off"
|
|
26
|
-
}
|
|
27
|
-
},
|
|
28
|
-
"ignore": ["node_modules", ".next", "dist", ".nuxt", ".contentlayer"]
|
|
29
|
-
},
|
|
30
|
-
"formatter": {
|
|
31
|
-
"indentStyle": "space",
|
|
32
|
-
"indentWidth": 2,
|
|
33
|
-
"enabled": true,
|
|
34
|
-
"lineWidth": 100,
|
|
35
|
-
"ignore": ["node_modules", ".next", "dist", ".nuxt", ".contentlayer"]
|
|
36
|
-
}
|
|
37
|
-
}
|
package/bun.lockb
DELETED
|
Binary file
|
package/cmd/set-version.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
const fs = require("fs");
|
|
2
|
-
const path = require("path");
|
|
3
|
-
|
|
4
|
-
const root = process.argv[2]; // path to project root
|
|
5
|
-
const version = process.argv[3].replace(/^v/, ""); // new version
|
|
6
|
-
|
|
7
|
-
console.log(`Updating version=${version} in ${root}`);
|
|
8
|
-
|
|
9
|
-
const content = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8"));
|
|
10
|
-
|
|
11
|
-
content.version = version;
|
|
12
|
-
|
|
13
|
-
fs.writeFileSync(path.join(root, "package.json"), JSON.stringify(content, null, 2));
|
|
14
|
-
fs.writeFileSync(path.join(root, "src", "version.ts"), `export const VERSION = "${version}";`);
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "cloudflare-workers",
|
|
3
|
-
"version": "0.0.0",
|
|
4
|
-
"devDependencies": {
|
|
5
|
-
"@cloudflare/workers-types": "^4.20230419.0",
|
|
6
|
-
"typescript": "^5.0.4",
|
|
7
|
-
"wrangler": "2.20.0"
|
|
8
|
-
},
|
|
9
|
-
"private": true,
|
|
10
|
-
"scripts": {
|
|
11
|
-
"dev": "wrangler dev",
|
|
12
|
-
"deploy": "wrangler publish"
|
|
13
|
-
},
|
|
14
|
-
"dependencies": {
|
|
15
|
-
"@upstash/ratelimit": "link:../../dist",
|
|
16
|
-
"@upstash/redis": "^1.20.6"
|
|
17
|
-
}
|
|
18
|
-
}
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { Ratelimit } from "@upstash/ratelimit";
|
|
2
|
-
import { Redis } from "@upstash/redis/cloudflare";
|
|
3
|
-
export interface Env {
|
|
4
|
-
UPSTASH_REDIS_REST_URL: string;
|
|
5
|
-
UPSTASH_REDIS_REST_TOKEN: string;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
const cache = new Map();
|
|
9
|
-
|
|
10
|
-
export default {
|
|
11
|
-
async fetch(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
|
|
12
|
-
try {
|
|
13
|
-
console.log("URL:", env.UPSTASH_REDIS_REST_URL);
|
|
14
|
-
|
|
15
|
-
if (new URL(request.url).pathname !== "/limit") {
|
|
16
|
-
return new Response("go to /limit", { status: 400 });
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
const ratelimit = new Ratelimit({
|
|
20
|
-
redis: Redis.fromEnv(env),
|
|
21
|
-
limiter: Ratelimit.cachedFixedWindow(5, "5 s"),
|
|
22
|
-
ephemeralCache: cache,
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
const res = await ratelimit.limit("identifier");
|
|
26
|
-
if (res.success) {
|
|
27
|
-
return new Response(JSON.stringify(res, null, 2), { status: 200 });
|
|
28
|
-
} else {
|
|
29
|
-
return new Response(JSON.stringify({ res }, null, 2), { status: 429 });
|
|
30
|
-
}
|
|
31
|
-
} catch (err) {
|
|
32
|
-
return new Response((err as Error).message, { status: 500 });
|
|
33
|
-
}
|
|
34
|
-
},
|
|
35
|
-
};
|
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
|
4
|
-
|
|
5
|
-
/* Projects */
|
|
6
|
-
// "incremental": true, /* Enable incremental compilation */
|
|
7
|
-
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
8
|
-
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
|
|
9
|
-
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
|
|
10
|
-
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
11
|
-
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
12
|
-
|
|
13
|
-
/* Language and Environment */
|
|
14
|
-
"target": "es2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
|
15
|
-
"lib": [
|
|
16
|
-
"es2021"
|
|
17
|
-
], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
18
|
-
"jsx": "react", /* Specify what JSX code is generated. */
|
|
19
|
-
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
|
20
|
-
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
|
21
|
-
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
|
|
22
|
-
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
23
|
-
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
|
|
24
|
-
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
|
|
25
|
-
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
26
|
-
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
27
|
-
|
|
28
|
-
/* Modules */
|
|
29
|
-
"module": "es2022", /* Specify what module code is generated. */
|
|
30
|
-
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
31
|
-
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
|
32
|
-
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
33
|
-
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
34
|
-
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
35
|
-
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
|
|
36
|
-
"types": [
|
|
37
|
-
"@cloudflare/workers-types"
|
|
38
|
-
], /* Specify type package names to be included without being referenced in a source file. */
|
|
39
|
-
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
40
|
-
"resolveJsonModule": true, /* Enable importing .json files */
|
|
41
|
-
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
|
|
42
|
-
|
|
43
|
-
/* JavaScript Support */
|
|
44
|
-
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
|
|
45
|
-
"checkJs": false, /* Enable error reporting in type-checked JavaScript files. */
|
|
46
|
-
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
|
|
47
|
-
|
|
48
|
-
/* Emit */
|
|
49
|
-
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
|
50
|
-
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
51
|
-
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
52
|
-
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
53
|
-
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
|
|
54
|
-
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
|
55
|
-
// "removeComments": true, /* Disable emitting comments. */
|
|
56
|
-
"noEmit": true, /* Disable emitting files from a compilation. */
|
|
57
|
-
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
58
|
-
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
|
|
59
|
-
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
60
|
-
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
61
|
-
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
62
|
-
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
63
|
-
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
64
|
-
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
65
|
-
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
66
|
-
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
|
|
67
|
-
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
|
|
68
|
-
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
69
|
-
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
|
|
70
|
-
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
71
|
-
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
|
72
|
-
|
|
73
|
-
/* Interop Constraints */
|
|
74
|
-
"isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
75
|
-
"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
76
|
-
// "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
|
|
77
|
-
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
78
|
-
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
|
79
|
-
|
|
80
|
-
/* Type Checking */
|
|
81
|
-
"strict": true, /* Enable all strict type-checking options. */
|
|
82
|
-
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
|
|
83
|
-
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
|
|
84
|
-
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
85
|
-
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
|
|
86
|
-
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
87
|
-
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
|
|
88
|
-
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
|
|
89
|
-
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
90
|
-
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
|
|
91
|
-
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
|
|
92
|
-
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
93
|
-
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
94
|
-
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
95
|
-
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
|
96
|
-
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
97
|
-
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
|
|
98
|
-
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
99
|
-
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
100
|
-
|
|
101
|
-
/* Completeness */
|
|
102
|
-
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
103
|
-
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
104
|
-
}
|
|
105
|
-
}
|
package/examples/nextjs/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2022 Upstash
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
# Next.js + Tailwind CSS Example
|
|
2
|
-
|
|
3
|
-
This example shows how to use [Tailwind CSS](https://tailwindcss.com/)
|
|
4
|
-
[(v3.0)](https://tailwindcss.com/blog/tailwindcss-v3) with Next.js. It follows
|
|
5
|
-
the steps outlined in the official
|
|
6
|
-
[Tailwind docs](https://tailwindcss.com/docs/guides/nextjs).
|
|
7
|
-
|
|
8
|
-
## How to use
|
|
9
|
-
|
|
10
|
-
Execute
|
|
11
|
-
[`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app)
|
|
12
|
-
with [npm](https://docs.npmjs.com/cli/init) or
|
|
13
|
-
[Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
|
|
14
|
-
|
|
15
|
-
```bash
|
|
16
|
-
yarn create next-app -e https://github.com/upstash/next-template your-app-name
|
|
17
|
-
```
|