@ooneex/rate-limit 1.1.2 → 1.2.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 +48 -8
- package/dist/index.js +217 -2
- package/dist/index.js.map +7 -5
- package/package.json +8 -7
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
constructor(message: string, data?: Record<string, unknown>);
|
|
4
|
-
}
|
|
5
|
-
import { AppEnv } from "@ooneex/app-env";
|
|
1
|
+
import { EContainerScope } from "@ooneex/container";
|
|
2
|
+
import { Duration } from "@upstash/ratelimit";
|
|
6
3
|
type RateLimiterClassType = new (...args: any[]) => IRateLimiter;
|
|
7
4
|
type RedisRateLimiterOptionsType = {
|
|
8
5
|
connectionString?: string;
|
|
@@ -14,6 +11,27 @@ type RedisRateLimiterOptionsType = {
|
|
|
14
11
|
enableAutoPipelining?: boolean;
|
|
15
12
|
tls?: boolean | object;
|
|
16
13
|
};
|
|
14
|
+
type UpstashAlgorithmType = {
|
|
15
|
+
type: "fixedWindow";
|
|
16
|
+
limit: number;
|
|
17
|
+
window: Duration;
|
|
18
|
+
} | {
|
|
19
|
+
type: "slidingWindow";
|
|
20
|
+
limit: number;
|
|
21
|
+
window: Duration;
|
|
22
|
+
} | {
|
|
23
|
+
type: "tokenBucket";
|
|
24
|
+
refillRate: number;
|
|
25
|
+
interval: Duration;
|
|
26
|
+
maxTokens: number;
|
|
27
|
+
};
|
|
28
|
+
type UpstashRedisRateLimiterOptionsType = {
|
|
29
|
+
url?: string;
|
|
30
|
+
token?: string;
|
|
31
|
+
algorithm?: UpstashAlgorithmType;
|
|
32
|
+
prefix?: string;
|
|
33
|
+
analytics?: boolean;
|
|
34
|
+
};
|
|
17
35
|
type RateLimitResultType = {
|
|
18
36
|
limited: boolean;
|
|
19
37
|
remaining: number;
|
|
@@ -21,18 +39,40 @@ type RateLimitResultType = {
|
|
|
21
39
|
resetAt: Date;
|
|
22
40
|
};
|
|
23
41
|
interface IRateLimiter {
|
|
24
|
-
check: (key: string
|
|
42
|
+
check: (key: string) => Promise<RateLimitResultType>;
|
|
43
|
+
isLimited: (key: string) => Promise<boolean>;
|
|
25
44
|
reset: (key: string) => Promise<boolean>;
|
|
26
45
|
getCount: (key: string) => Promise<number>;
|
|
27
46
|
}
|
|
47
|
+
declare const decorator: {
|
|
48
|
+
rateLimit: (scope?: EContainerScope) => (target: RateLimiterClassType) => void;
|
|
49
|
+
};
|
|
50
|
+
import { Exception } from "@ooneex/exception";
|
|
51
|
+
declare class RateLimitException extends Exception {
|
|
52
|
+
constructor(message: string, key: string, data?: Record<string, unknown>);
|
|
53
|
+
}
|
|
54
|
+
import { AppEnv } from "@ooneex/app-env";
|
|
28
55
|
declare class RedisRateLimiter implements IRateLimiter {
|
|
29
56
|
private readonly env;
|
|
30
57
|
private client;
|
|
31
58
|
constructor(env: AppEnv, options?: RedisRateLimiterOptionsType);
|
|
32
59
|
private connect;
|
|
33
60
|
private getKey;
|
|
34
|
-
check(key: string
|
|
61
|
+
check(key: string): Promise<RateLimitResultType>;
|
|
62
|
+
isLimited(key: string): Promise<boolean>;
|
|
63
|
+
reset(key: string): Promise<boolean>;
|
|
64
|
+
getCount(key: string): Promise<number>;
|
|
65
|
+
}
|
|
66
|
+
import { AppEnv as AppEnv2 } from "@ooneex/app-env";
|
|
67
|
+
declare class UpstashRedisRateLimiter implements IRateLimiter {
|
|
68
|
+
private readonly env;
|
|
69
|
+
private ratelimit;
|
|
70
|
+
private static readonly DEFAULT_ALGORITHM;
|
|
71
|
+
constructor(env: AppEnv2, options?: UpstashRedisRateLimiterOptionsType);
|
|
72
|
+
private buildLimiter;
|
|
73
|
+
check(key: string): Promise<RateLimitResultType>;
|
|
74
|
+
isLimited(key: string): Promise<boolean>;
|
|
35
75
|
reset(key: string): Promise<boolean>;
|
|
36
76
|
getCount(key: string): Promise<number>;
|
|
37
77
|
}
|
|
38
|
-
export { RedisRateLimiterOptionsType, RedisRateLimiter, RateLimiterClassType, RateLimitResultType, RateLimitException, IRateLimiter };
|
|
78
|
+
export { decorator, UpstashRedisRateLimiterOptionsType, UpstashRedisRateLimiter, UpstashAlgorithmType, RedisRateLimiterOptionsType, RedisRateLimiter, RateLimiterClassType, RateLimitResultType, RateLimitException, IRateLimiter };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,219 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var __legacyDecorateClassTS = function(decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
|
|
5
|
+
r = Reflect.decorate(decorators, target, key, desc);
|
|
6
|
+
else
|
|
7
|
+
for (var i = decorators.length - 1;i >= 0; i--)
|
|
8
|
+
if (d = decorators[i])
|
|
9
|
+
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
10
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
11
|
+
};
|
|
12
|
+
var __legacyDecorateParamTS = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
13
|
+
var __legacyMetadataTS = (k, v) => {
|
|
14
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
|
|
15
|
+
return Reflect.metadata(k, v);
|
|
16
|
+
};
|
|
3
17
|
|
|
4
|
-
|
|
18
|
+
// src/decorators.ts
|
|
19
|
+
import { container, EContainerScope } from "@ooneex/container";
|
|
20
|
+
var decorator = {
|
|
21
|
+
rateLimit: (scope = EContainerScope.Singleton) => {
|
|
22
|
+
return (target) => {
|
|
23
|
+
container.add(target, scope);
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
// src/RateLimitException.ts
|
|
28
|
+
import { Exception } from "@ooneex/exception";
|
|
29
|
+
import { HttpStatus } from "@ooneex/http-status";
|
|
30
|
+
|
|
31
|
+
class RateLimitException extends Exception {
|
|
32
|
+
constructor(message, key, data = {}) {
|
|
33
|
+
super(message, {
|
|
34
|
+
key,
|
|
35
|
+
status: HttpStatus.Code.TooManyRequests,
|
|
36
|
+
data
|
|
37
|
+
});
|
|
38
|
+
this.name = "RateLimitException";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// src/RedisRateLimiter.ts
|
|
42
|
+
import { AppEnv } from "@ooneex/app-env";
|
|
43
|
+
import { inject } from "@ooneex/container";
|
|
44
|
+
class RedisRateLimiter {
|
|
45
|
+
env;
|
|
46
|
+
client;
|
|
47
|
+
constructor(env, options = {}) {
|
|
48
|
+
this.env = env;
|
|
49
|
+
const connectionString = options.connectionString || this.env.RATE_LIMIT_REDIS_URL;
|
|
50
|
+
if (!connectionString) {
|
|
51
|
+
throw new RateLimitException("Redis connection string is required. Please provide a connection string either through the constructor options or set the RATE_LIMIT_REDIS_URL environment variable.", "RATE_LIMIT_CONNECTION_FAILED");
|
|
52
|
+
}
|
|
53
|
+
const { connectionString: _, ...userOptions } = options;
|
|
54
|
+
const defaultOptions = {
|
|
55
|
+
connectionTimeout: 1e4,
|
|
56
|
+
idleTimeout: 30000,
|
|
57
|
+
autoReconnect: true,
|
|
58
|
+
maxRetries: 3,
|
|
59
|
+
enableOfflineQueue: true,
|
|
60
|
+
enableAutoPipelining: true
|
|
61
|
+
};
|
|
62
|
+
const clientOptions = { ...defaultOptions, ...userOptions };
|
|
63
|
+
this.client = new Bun.RedisClient(connectionString, clientOptions);
|
|
64
|
+
}
|
|
65
|
+
async connect() {
|
|
66
|
+
if (!this.client.connected) {
|
|
67
|
+
await this.client.connect();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
getKey(key) {
|
|
71
|
+
return `ratelimit:${key}`;
|
|
72
|
+
}
|
|
73
|
+
async check(key) {
|
|
74
|
+
const limit = 120;
|
|
75
|
+
const windowSeconds = 60;
|
|
76
|
+
try {
|
|
77
|
+
await this.connect();
|
|
78
|
+
const rateLimitKey = this.getKey(key);
|
|
79
|
+
const count = await this.client.incr(rateLimitKey);
|
|
80
|
+
if (count === 1) {
|
|
81
|
+
await this.client.expire(rateLimitKey, windowSeconds);
|
|
82
|
+
}
|
|
83
|
+
const ttl = await this.client.ttl(rateLimitKey);
|
|
84
|
+
const resetAt = new Date(Date.now() + ttl * 1000);
|
|
85
|
+
return {
|
|
86
|
+
limited: count > limit,
|
|
87
|
+
remaining: Math.max(0, limit - count),
|
|
88
|
+
total: limit,
|
|
89
|
+
resetAt
|
|
90
|
+
};
|
|
91
|
+
} catch (error) {
|
|
92
|
+
throw new RateLimitException(`Failed to check rate limit for key "${key}": ${error}`, "RATE_LIMIT_CHECK_FAILED");
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async isLimited(key) {
|
|
96
|
+
const result = await this.check(key);
|
|
97
|
+
return result.limited;
|
|
98
|
+
}
|
|
99
|
+
async reset(key) {
|
|
100
|
+
try {
|
|
101
|
+
await this.connect();
|
|
102
|
+
const rateLimitKey = this.getKey(key);
|
|
103
|
+
const result = await this.client.del(rateLimitKey);
|
|
104
|
+
return result > 0;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
throw new RateLimitException(`Failed to reset rate limit for key "${key}": ${error}`, "RATE_LIMIT_RESET_FAILED");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
async getCount(key) {
|
|
110
|
+
try {
|
|
111
|
+
await this.connect();
|
|
112
|
+
const rateLimitKey = this.getKey(key);
|
|
113
|
+
const value = await this.client.get(rateLimitKey);
|
|
114
|
+
if (value === null) {
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
return Number.parseInt(value, 10);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw new RateLimitException(`Failed to get count for key "${key}": ${error}`, "RATE_LIMIT_COUNT_FAILED");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
RedisRateLimiter = __legacyDecorateClassTS([
|
|
124
|
+
decorator.rateLimit(),
|
|
125
|
+
__legacyDecorateParamTS(0, inject(AppEnv)),
|
|
126
|
+
__legacyMetadataTS("design:paramtypes", [
|
|
127
|
+
typeof AppEnv === "undefined" ? Object : AppEnv,
|
|
128
|
+
typeof RedisRateLimiterOptionsType === "undefined" ? Object : RedisRateLimiterOptionsType
|
|
129
|
+
])
|
|
130
|
+
], RedisRateLimiter);
|
|
131
|
+
// src/UpstashRedisRateLimiter.ts
|
|
132
|
+
import { AppEnv as AppEnv2 } from "@ooneex/app-env";
|
|
133
|
+
import { inject as inject2 } from "@ooneex/container";
|
|
134
|
+
import { Ratelimit } from "@upstash/ratelimit";
|
|
135
|
+
import { Redis } from "@upstash/redis";
|
|
136
|
+
class UpstashRedisRateLimiter {
|
|
137
|
+
env;
|
|
138
|
+
ratelimit;
|
|
139
|
+
static DEFAULT_ALGORITHM = {
|
|
140
|
+
type: "slidingWindow",
|
|
141
|
+
limit: 120,
|
|
142
|
+
window: "60 s"
|
|
143
|
+
};
|
|
144
|
+
constructor(env, options = {}) {
|
|
145
|
+
this.env = env;
|
|
146
|
+
const url = options.url || this.env.RATE_LIMIT_UPSTASH_REDIS_URL;
|
|
147
|
+
const token = options.token || this.env.RATE_LIMIT_UPSTASH_REDIS_TOKEN;
|
|
148
|
+
if (!url || !token) {
|
|
149
|
+
throw new RateLimitException("Upstash Redis URL and token are required. Please provide them through the constructor options or set the RATE_LIMIT_UPSTASH_REDIS_URL and RATE_LIMIT_UPSTASH_REDIS_TOKEN environment variables.", "RATE_LIMIT_CONNECTION_FAILED");
|
|
150
|
+
}
|
|
151
|
+
const redis = new Redis({ url, token });
|
|
152
|
+
const limiter = this.buildLimiter(options.algorithm);
|
|
153
|
+
this.ratelimit = new Ratelimit({
|
|
154
|
+
redis,
|
|
155
|
+
limiter,
|
|
156
|
+
prefix: options.prefix ?? "@ooneex/ratelimit",
|
|
157
|
+
analytics: options.analytics ?? true
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
buildLimiter(algorithm = UpstashRedisRateLimiter.DEFAULT_ALGORITHM) {
|
|
161
|
+
switch (algorithm.type) {
|
|
162
|
+
case "fixedWindow":
|
|
163
|
+
return Ratelimit.fixedWindow(algorithm.limit, algorithm.window);
|
|
164
|
+
case "slidingWindow":
|
|
165
|
+
return Ratelimit.slidingWindow(algorithm.limit, algorithm.window);
|
|
166
|
+
case "tokenBucket":
|
|
167
|
+
return Ratelimit.tokenBucket(algorithm.refillRate, algorithm.interval, algorithm.maxTokens);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async check(key) {
|
|
171
|
+
try {
|
|
172
|
+
const result = await this.ratelimit.limit(key);
|
|
173
|
+
return {
|
|
174
|
+
limited: !result.success,
|
|
175
|
+
remaining: result.remaining,
|
|
176
|
+
total: result.limit,
|
|
177
|
+
resetAt: new Date(result.reset)
|
|
178
|
+
};
|
|
179
|
+
} catch (error) {
|
|
180
|
+
throw new RateLimitException(`Failed to check rate limit for key "${key}": ${error}`, "RATE_LIMIT_CHECK_FAILED");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async isLimited(key) {
|
|
184
|
+
const result = await this.check(key);
|
|
185
|
+
return result.limited;
|
|
186
|
+
}
|
|
187
|
+
async reset(key) {
|
|
188
|
+
try {
|
|
189
|
+
await this.ratelimit.resetUsedTokens(key);
|
|
190
|
+
return true;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
throw new RateLimitException(`Failed to reset rate limit for key "${key}": ${error}`, "RATE_LIMIT_RESET_FAILED");
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
async getCount(key) {
|
|
196
|
+
try {
|
|
197
|
+
const { remaining } = await this.ratelimit.getRemaining(key);
|
|
198
|
+
return remaining;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
throw new RateLimitException(`Failed to get count for key "${key}": ${error}`, "RATE_LIMIT_COUNT_FAILED");
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
UpstashRedisRateLimiter = __legacyDecorateClassTS([
|
|
205
|
+
decorator.rateLimit(),
|
|
206
|
+
__legacyDecorateParamTS(0, inject2(AppEnv2)),
|
|
207
|
+
__legacyMetadataTS("design:paramtypes", [
|
|
208
|
+
typeof AppEnv2 === "undefined" ? Object : AppEnv2,
|
|
209
|
+
typeof UpstashRedisRateLimiterOptionsType === "undefined" ? Object : UpstashRedisRateLimiterOptionsType
|
|
210
|
+
])
|
|
211
|
+
], UpstashRedisRateLimiter);
|
|
212
|
+
export {
|
|
213
|
+
decorator,
|
|
214
|
+
UpstashRedisRateLimiter,
|
|
215
|
+
RedisRateLimiter,
|
|
216
|
+
RateLimitException
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
//# debugId=8F06C17BF8E11C5C64756E2164756E21
|
package/dist/index.js.map
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["src/RateLimitException.ts", "src/RedisRateLimiter.ts"],
|
|
3
|
+
"sources": ["src/decorators.ts", "src/RateLimitException.ts", "src/RedisRateLimiter.ts", "src/UpstashRedisRateLimiter.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import {
|
|
6
|
-
"import {
|
|
5
|
+
"import { container, EContainerScope } from \"@ooneex/container\";\nimport type { RateLimiterClassType } from \"./types\";\n\nexport const decorator = {\n rateLimit: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: RateLimiterClassType): void => {\n container.add(target, scope);\n };\n },\n};\n",
|
|
6
|
+
"import { Exception } from \"@ooneex/exception\";\nimport { HttpStatus } from \"@ooneex/http-status\";\n\nexport class RateLimitException extends Exception {\n constructor(message: string, key: string, data: Record<string, unknown> = {}) {\n super(message, {\n key,\n status: HttpStatus.Code.TooManyRequests,\n data,\n });\n this.name = \"RateLimitException\";\n }\n}\n",
|
|
7
|
+
"import { AppEnv } from \"@ooneex/app-env\";\nimport { inject } from \"@ooneex/container\";\nimport { decorator } from \"./decorators\";\nimport { RateLimitException } from \"./RateLimitException\";\nimport type { IRateLimiter, RateLimitResultType, RedisRateLimiterOptionsType } from \"./types\";\n\n@decorator.rateLimit()\nexport class RedisRateLimiter implements IRateLimiter {\n private client: Bun.RedisClient;\n\n constructor(\n @inject(AppEnv) private readonly env: AppEnv,\n options: RedisRateLimiterOptionsType = {},\n ) {\n const connectionString = options.connectionString || this.env.RATE_LIMIT_REDIS_URL;\n\n if (!connectionString) {\n throw new RateLimitException(\n \"Redis connection string is required. Please provide a connection string either through the constructor options or set the RATE_LIMIT_REDIS_URL environment variable.\",\n \"RATE_LIMIT_CONNECTION_FAILED\",\n );\n }\n\n const { connectionString: _, ...userOptions } = options;\n\n const defaultOptions = {\n connectionTimeout: 10_000,\n idleTimeout: 30_000,\n autoReconnect: true,\n maxRetries: 3,\n enableOfflineQueue: true,\n enableAutoPipelining: true,\n };\n\n const clientOptions = { ...defaultOptions, ...userOptions };\n\n this.client = new Bun.RedisClient(connectionString, clientOptions);\n }\n\n private async connect(): Promise<void> {\n if (!this.client.connected) {\n await this.client.connect();\n }\n }\n\n private getKey(key: string): string {\n return `ratelimit:${key}`;\n }\n\n public async check(key: string): Promise<RateLimitResultType> {\n const limit = 120;\n const windowSeconds = 60;\n try {\n await this.connect();\n\n const rateLimitKey = this.getKey(key);\n\n // Increment counter\n const count = await this.client.incr(rateLimitKey);\n\n // Set expiry if this is the first request in window\n if (count === 1) {\n await this.client.expire(rateLimitKey, windowSeconds);\n }\n\n // Get TTL for reset time calculation\n const ttl = await this.client.ttl(rateLimitKey);\n const resetAt = new Date(Date.now() + ttl * 1000);\n\n return {\n limited: count > limit,\n remaining: Math.max(0, limit - count),\n total: limit,\n resetAt,\n };\n } catch (error: unknown) {\n throw new RateLimitException(`Failed to check rate limit for key \"${key}\": ${error}`, \"RATE_LIMIT_CHECK_FAILED\");\n }\n }\n\n public async isLimited(key: string): Promise<boolean> {\n const result = await this.check(key);\n\n return result.limited;\n }\n\n public async reset(key: string): Promise<boolean> {\n try {\n await this.connect();\n\n const rateLimitKey = this.getKey(key);\n const result = await this.client.del(rateLimitKey);\n\n return result > 0;\n } catch (error: unknown) {\n throw new RateLimitException(`Failed to reset rate limit for key \"${key}\": ${error}`, \"RATE_LIMIT_RESET_FAILED\");\n }\n }\n\n public async getCount(key: string): Promise<number> {\n try {\n await this.connect();\n\n const rateLimitKey = this.getKey(key);\n const value = await this.client.get(rateLimitKey);\n\n if (value === null) {\n return 0;\n }\n\n return Number.parseInt(value, 10);\n } catch (error: unknown) {\n throw new RateLimitException(`Failed to get count for key \"${key}\": ${error}`, \"RATE_LIMIT_COUNT_FAILED\");\n }\n }\n}\n",
|
|
8
|
+
"import { AppEnv } from \"@ooneex/app-env\";\nimport { inject } from \"@ooneex/container\";\nimport { Ratelimit } from \"@upstash/ratelimit\";\nimport { Redis } from \"@upstash/redis\";\nimport { decorator } from \"./decorators\";\nimport { RateLimitException } from \"./RateLimitException\";\nimport type {\n IRateLimiter,\n RateLimitResultType,\n UpstashAlgorithmType,\n UpstashRedisRateLimiterOptionsType,\n} from \"./types\";\n\n@decorator.rateLimit()\nexport class UpstashRedisRateLimiter implements IRateLimiter {\n private ratelimit: Ratelimit;\n // Default: 120 requests per 60-second sliding window (high traffic)\n private static readonly DEFAULT_ALGORITHM: UpstashAlgorithmType = {\n type: \"slidingWindow\",\n limit: 120,\n window: \"60 s\",\n };\n\n constructor(\n @inject(AppEnv) private readonly env: AppEnv,\n options: UpstashRedisRateLimiterOptionsType = {},\n ) {\n const url = options.url || this.env.RATE_LIMIT_UPSTASH_REDIS_URL;\n const token = options.token || this.env.RATE_LIMIT_UPSTASH_REDIS_TOKEN;\n\n if (!url || !token) {\n throw new RateLimitException(\n \"Upstash Redis URL and token are required. Please provide them through the constructor options or set the RATE_LIMIT_UPSTASH_REDIS_URL and RATE_LIMIT_UPSTASH_REDIS_TOKEN environment variables.\",\n \"RATE_LIMIT_CONNECTION_FAILED\",\n );\n }\n\n const redis = new Redis({ url, token });\n const limiter = this.buildLimiter(options.algorithm);\n\n this.ratelimit = new Ratelimit({\n redis,\n limiter,\n prefix: options.prefix ?? \"@ooneex/ratelimit\",\n analytics: options.analytics ?? true,\n });\n }\n\n private buildLimiter(algorithm: UpstashAlgorithmType = UpstashRedisRateLimiter.DEFAULT_ALGORITHM) {\n switch (algorithm.type) {\n case \"fixedWindow\":\n return Ratelimit.fixedWindow(algorithm.limit, algorithm.window);\n case \"slidingWindow\":\n return Ratelimit.slidingWindow(algorithm.limit, algorithm.window);\n case \"tokenBucket\":\n return Ratelimit.tokenBucket(algorithm.refillRate, algorithm.interval, algorithm.maxTokens);\n }\n }\n\n public async check(key: string): Promise<RateLimitResultType> {\n try {\n const result = await this.ratelimit.limit(key);\n\n return {\n limited: !result.success,\n remaining: result.remaining,\n total: result.limit,\n resetAt: new Date(result.reset),\n };\n } catch (error) {\n throw new RateLimitException(`Failed to check rate limit for key \"${key}\": ${error}`, \"RATE_LIMIT_CHECK_FAILED\");\n }\n }\n\n public async isLimited(key: string): Promise<boolean> {\n const result = await this.check(key);\n\n return result.limited;\n }\n\n public async reset(key: string): Promise<boolean> {\n try {\n await this.ratelimit.resetUsedTokens(key);\n\n return true;\n } catch (error) {\n throw new RateLimitException(`Failed to reset rate limit for key \"${key}\": ${error}`, \"RATE_LIMIT_RESET_FAILED\");\n }\n }\n\n public async getCount(key: string): Promise<number> {\n try {\n const { remaining } = await this.ratelimit.getRemaining(key);\n\n return remaining;\n } catch (error) {\n throw new RateLimitException(`Failed to get count for key \"${key}\": ${error}`, \"RATE_LIMIT_COUNT_FAILED\");\n }\n }\n}\n"
|
|
7
9
|
],
|
|
8
|
-
"mappings": ";
|
|
9
|
-
"debugId": "
|
|
10
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAGO,IAAM,YAAY;AAAA,EACvB,WAAW,CAAC,QAAyB,gBAAgB,cAAc;AAAA,IACjE,OAAO,CAAC,WAAuC;AAAA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M,GAAG;AAAA,MAE7C,OAAO;AAAA,QACL,SAAS,CAAC,OAAO;AAAA,QACjB,WAAW,OAAO;AAAA,QAClB,OAAO,OAAO;AAAA,QACd,SAAS,IAAI,KAAK,OAAO,KAAK;AAAA,MAChC;AAAA,MACA,OAAO,OAAO;AAAA,MACd,MAAM,IAAI,mBAAmB,uCAAuC,SAAS,SAAS,yBAAyB;AAAA;AAAA;AAAA,OAItG,UAAS,CAAC,KAA+B;AAAA,IACpD,MAAM,SAAS,MAAM,KAAK,MAAM,GAAG;AAAA,IAEnC,OAAO,OAAO;AAAA;AAAA,OAGH,MAAK,CAAC,KAA+B;AAAA,IAChD,IAAI;AAAA,MACF,MAAM,KAAK,UAAU,gBAAgB,GAAG;AAAA,MAExC,OAAO;AAAA,MACP,OAAO,OAAO;AAAA,MACd,MAAM,IAAI,mBAAmB,uCAAuC,SAAS,SAAS,yBAAyB;AAAA;AAAA;AAAA,OAItG,SAAQ,CAAC,KAA8B;AAAA,IAClD,IAAI;AAAA,MACF,QAAQ,cAAc,MAAM,KAAK,UAAU,aAAa,GAAG;AAAA,MAE3D,OAAO;AAAA,MACP,OAAO,OAAO;AAAA,MACd,MAAM,IAAI,mBAAmB,gCAAgC,SAAS,SAAS,yBAAyB;AAAA;AAAA;AAG9G;AArFa,0BAAN;AAAA,EADN,UAAU,UAAU;AAAA,EAWhB,mCAAO,OAAM;AAAA,EAVX;AAAA;AAAA;AAAA;AAAA,GAAM;",
|
|
11
|
+
"debugId": "8F06C17BF8E11C5C64756E2164756E21",
|
|
10
12
|
"names": []
|
|
11
13
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ooneex/rate-limit",
|
|
3
3
|
"description": "API rate limiting middleware with configurable throttling strategies, sliding window counters, and per-client request quota enforcement",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist",
|
|
@@ -28,14 +28,15 @@
|
|
|
28
28
|
"npm:publish": "bun publish --tolerate-republish --force --production --access public"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"@ooneex/exception": "1.1.
|
|
32
|
-
"@ooneex/http-status": "1.1.
|
|
31
|
+
"@ooneex/exception": "1.1.3",
|
|
32
|
+
"@ooneex/http-status": "1.1.3"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@ooneex/app-env": "1.2.
|
|
36
|
-
"@ooneex/
|
|
37
|
-
"@ooneex/
|
|
38
|
-
"@ooneex/http-status": "1.1.
|
|
35
|
+
"@ooneex/app-env": "1.2.1",
|
|
36
|
+
"@ooneex/container": "1.2.1",
|
|
37
|
+
"@ooneex/exception": "1.1.3",
|
|
38
|
+
"@ooneex/http-status": "1.1.3",
|
|
39
|
+
"@upstash/ratelimit": "^2.0.8"
|
|
39
40
|
},
|
|
40
41
|
"keywords": [
|
|
41
42
|
"api",
|