@unikvs/rate-limit 0.0.0 → 0.0.14

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026-present, tai-kun
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
13
+ all 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
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,3 @@
1
1
  # @unikvs/rate-limit
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
4
-
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
-
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
-
9
- ## Purpose
10
-
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@unikvs/rate-limit`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
3
+ [Document](https://tai-kun.github.io/unikvs/)
@@ -0,0 +1,134 @@
1
+ import { ErrorBase, ErrorOptions, IMiddleware, InvalidUsageErrorBase } from "@unikvs/core";
2
+ import { PassThrough } from "@unikvs/passthrough";
3
+ //#region ../src/errors.d.ts
4
+ /**
5
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
6
+ */
7
+ type RateLimitExceededErrorMeta = {
8
+ /**
9
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-exceeded-retry-after-ms)
10
+ */
11
+ readonly retryAfterMs: number;
12
+ };
13
+ /**
14
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
15
+ */
16
+ type RateLimitExceededErrorArgs = ErrorOptions & RateLimitExceededErrorMeta;
17
+ /**
18
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
19
+ */
20
+ export declare class RateLimitExceededError extends ErrorBase<RateLimitExceededErrorMeta> {
21
+ /**
22
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
23
+ */
24
+ constructor(args: RateLimitExceededErrorArgs);
25
+ }
26
+ /**
27
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
28
+ */
29
+ type RateLimitInvalidOptionErrorMeta = {
30
+ /**
31
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-name)
32
+ */
33
+ readonly name: string;
34
+ /**
35
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-actual)
36
+ */
37
+ readonly actual: unknown;
38
+ };
39
+ /**
40
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
41
+ */
42
+ type RateLimitInvalidOptionErrorArgs = ErrorOptions & RateLimitInvalidOptionErrorMeta;
43
+ /**
44
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
45
+ */
46
+ export declare class RateLimitInvalidOptionError extends InvalidUsageErrorBase<RateLimitInvalidOptionErrorMeta> {
47
+ /**
48
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
49
+ */
50
+ constructor(args: RateLimitInvalidOptionErrorArgs);
51
+ }
52
+ //#endregion
53
+ //#region ../src/rate-limit.d.ts
54
+ /**
55
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-strategy)
56
+ */
57
+ type RateLimitStrategy = "wait" | "throw";
58
+ /**
59
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#irate-limit-sleep)
60
+ */
61
+ interface IRateLimitSleep {
62
+ (ms: number, signal: AbortSignal): Promise<void>;
63
+ }
64
+ /**
65
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options)
66
+ */
67
+ type RateLimitOptions = {
68
+ /**
69
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-tokens-per-interval)
70
+ */
71
+ readonly tokensPerInterval?: number | undefined;
72
+ /**
73
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-interval-ms)
74
+ */
75
+ readonly intervalMs?: number | undefined;
76
+ /**
77
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-max-tokens)
78
+ */
79
+ readonly maxTokens?: number | undefined;
80
+ /**
81
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-burst)
82
+ */
83
+ readonly burst?: number | undefined;
84
+ /**
85
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-strategy)
86
+ */
87
+ readonly strategy?: RateLimitStrategy | undefined;
88
+ /**
89
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-now)
90
+ */
91
+ readonly now?: (() => number) | undefined;
92
+ /**
93
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-sleep)
94
+ */
95
+ readonly sleep?: IRateLimitSleep | undefined;
96
+ };
97
+ /**
98
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
99
+ */
100
+ declare class RateLimit extends PassThrough implements IMiddleware {
101
+ #private;
102
+ /**
103
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
104
+ */
105
+ override readonly name: string;
106
+ /**
107
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
108
+ */
109
+ readonly tokensPerInterval: number;
110
+ /**
111
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
112
+ */
113
+ readonly intervalMs: number;
114
+ /**
115
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
116
+ */
117
+ readonly maxTokens: number;
118
+ /**
119
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
120
+ */
121
+ readonly strategy: RateLimitStrategy;
122
+ /**
123
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
124
+ */
125
+ constructor(options?: RateLimitOptions);
126
+ /**
127
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
128
+ */
129
+ get availableTokens(): number;
130
+ use(c: IMiddleware.UseContext, next: IMiddleware.INext): Promise<void>;
131
+ }
132
+ //#endregion
133
+ export { type IRateLimitSleep, RateLimit, type RateLimitExceededErrorArgs, type RateLimitExceededErrorMeta, type RateLimitInvalidOptionErrorArgs, type RateLimitInvalidOptionErrorMeta, type RateLimitOptions, type RateLimitStrategy };
134
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/errors.ts","../src/rate-limit.ts"],"mappings":";;;;;;KAKY;;;;WAID;;;;;KAMC,6BAA6B,eAAe;;;;qBAK3C,+BAA+B,UAAU;;;;EAQpD,YAAmB,MAAM;;;;;KAsBf;;;;WAID;;;;WAKA;;;;;KAMC,kCAAkC,eAAe;;;;qBAKhD,oCAAoC,sBAAsB;;;;EAQrE,YAAmB,MAAM;;;;;;;KCrEf;;;;UAKK;GACd,YAAY,QAAQ,cAAc;;;;;KAMzB;;;;WAID;;;;WAKA;;;;WAKA;;;;WAKA;;;;WAKA,WAAW;;;;WAKX;;;;WAKA,QAAQ;;;;;cAmCE,kBAAkB,uBAAuB;;;;;oBAInC;;;;WAKT;;;;WAKA;;;;WAKA;;;;WAKA,UAAU;;;;EAe1B,YAAmB,UAAS;;;;MAqDjB;EAMX,IAAiB,GAAG,YAAY,YAAY,MAAM,YAAY,QAAQ"}
package/dist/index.js ADDED
@@ -0,0 +1,210 @@
1
+ import { ErrorBase, InvalidUsageErrorBase, setErrorMessage } from "@unikvs/core";
2
+ import { PassThrough } from "@unikvs/passthrough";
3
+ import { getAbortReason, throwIfAborted } from "abort-signal-utils";
4
+ //#region ../src/errors.ts
5
+ var _RateLimitExceededError;
6
+ var _RateLimitInvalidOptionError;
7
+ /**
8
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
9
+ */
10
+ var RateLimitExceededError = class extends ErrorBase {
11
+ /**
12
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
13
+ */
14
+ constructor(args) {
15
+ const { retryAfterMs, ...options } = args;
16
+ super({ retryAfterMs }, ({ retryAfterMs: messageRetryAfterMs }) => `Rate limit exceeded. Retry after ${String(messageRetryAfterMs)}ms.`, options);
17
+ }
18
+ };
19
+ _RateLimitExceededError = RateLimitExceededError;
20
+ _RateLimitExceededError.prototype.name = "RateLimitExceededError";
21
+ setErrorMessage(RateLimitExceededError, ({ retryAfterMs }) => `レート制限を超えました。${String(retryAfterMs)}ms 後に再試行してください。`, "ja");
22
+ /**
23
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
24
+ */
25
+ var RateLimitInvalidOptionError = class extends InvalidUsageErrorBase {
26
+ /**
27
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
28
+ */
29
+ constructor(args) {
30
+ const { name, actual, ...options } = args;
31
+ super({
32
+ name,
33
+ actual
34
+ }, ({ name: messageName, actual: messageActual }) => `Invalid RateLimit option ${JSON.stringify(messageName)}: ${formatActual(messageActual)}`, options);
35
+ }
36
+ };
37
+ _RateLimitInvalidOptionError = RateLimitInvalidOptionError;
38
+ _RateLimitInvalidOptionError.prototype.name = "RateLimitInvalidOptionError";
39
+ setErrorMessage(RateLimitInvalidOptionError, ({ name, actual }) => `無効な RateLimit オプション ${JSON.stringify(name)}: ${formatActual(actual)}`, "ja");
40
+ /**
41
+ * エラーメッセージに埋め込む実際の値を整形します。
42
+ *
43
+ * @param actual 整形する値です。
44
+ *
45
+ * @returns 整形した文字列を返します。
46
+ */
47
+ function formatActual(actual) {
48
+ if (typeof actual === "string") return JSON.stringify(actual);
49
+ if (typeof actual === "number" || typeof actual === "boolean" || actual === null || actual === void 0) return String(actual);
50
+ try {
51
+ return JSON.stringify(actual) ?? "[object Object]";
52
+ } catch {
53
+ return "[object Object]";
54
+ }
55
+ }
56
+ //#endregion
57
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/checkPrivateRedeclaration.js
58
+ function _checkPrivateRedeclaration(e, t) {
59
+ if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
60
+ }
61
+ //#endregion
62
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateMethodInitSpec.js
63
+ function _classPrivateMethodInitSpec(e, a) {
64
+ _checkPrivateRedeclaration(e, a), a.add(e);
65
+ }
66
+ //#endregion
67
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateFieldInitSpec.js
68
+ function _classPrivateFieldInitSpec(e, t, a) {
69
+ _checkPrivateRedeclaration(e, t), t.set(e, a);
70
+ }
71
+ //#endregion
72
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/assertClassBrand.js
73
+ function _assertClassBrand(e, t, n) {
74
+ if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
75
+ throw new TypeError("Private element is not present on this object");
76
+ }
77
+ //#endregion
78
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateFieldSet2.js
79
+ function _classPrivateFieldSet2(s, a, r) {
80
+ return s.set(_assertClassBrand(s, a), r), r;
81
+ }
82
+ //#endregion
83
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/classPrivateFieldGet2.js
84
+ function _classPrivateFieldGet2(s, a) {
85
+ return s.get(_assertClassBrand(s, a));
86
+ }
87
+ //#endregion
88
+ //#region ../src/rate-limit.ts
89
+ function defaultSleep(ms, signal) {
90
+ return new Promise((resolve, reject) => {
91
+ if (signal.aborted) {
92
+ reject(getAbortReason(signal));
93
+ return;
94
+ }
95
+ const timer = setTimeout(() => {
96
+ signal.removeEventListener("abort", onAbort);
97
+ resolve();
98
+ }, ms);
99
+ const onAbort = () => {
100
+ clearTimeout(timer);
101
+ reject(getAbortReason(signal));
102
+ };
103
+ signal.addEventListener("abort", onAbort, { once: true });
104
+ });
105
+ }
106
+ function assertPositiveNumber(name, value) {
107
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw new RateLimitInvalidOptionError({
108
+ name,
109
+ actual: value
110
+ });
111
+ }
112
+ var _now = /* @__PURE__ */ new WeakMap();
113
+ var _sleep = /* @__PURE__ */ new WeakMap();
114
+ var _tokens = /* @__PURE__ */ new WeakMap();
115
+ var _lastRefill = /* @__PURE__ */ new WeakMap();
116
+ var _tail = /* @__PURE__ */ new WeakMap();
117
+ var _RateLimit_brand = /* @__PURE__ */ new WeakSet();
118
+ /**
119
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
120
+ */
121
+ var RateLimit = class extends PassThrough {
122
+ /**
123
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
124
+ */
125
+ constructor(options = {}) {
126
+ super();
127
+ _classPrivateMethodInitSpec(this, _RateLimit_brand);
128
+ this.name = "RateLimit";
129
+ _classPrivateFieldInitSpec(this, _now, void 0);
130
+ _classPrivateFieldInitSpec(this, _sleep, void 0);
131
+ _classPrivateFieldInitSpec(this, _tokens, void 0);
132
+ _classPrivateFieldInitSpec(this, _lastRefill, void 0);
133
+ _classPrivateFieldInitSpec(this, _tail, void 0);
134
+ const { now = Date.now, burst, sleep = defaultSleep, strategy = "wait", maxTokens, intervalMs = 1e3, tokensPerInterval = 1 } = options;
135
+ assertPositiveNumber("tokensPerInterval", tokensPerInterval);
136
+ assertPositiveNumber("intervalMs", intervalMs);
137
+ const capacity = maxTokens ?? burst ?? tokensPerInterval;
138
+ assertPositiveNumber("maxTokens", capacity);
139
+ if (strategy !== "wait" && strategy !== "throw") throw new RateLimitInvalidOptionError({
140
+ name: "strategy",
141
+ actual: strategy
142
+ });
143
+ if (typeof now !== "function") throw new RateLimitInvalidOptionError({
144
+ name: "now",
145
+ actual: now
146
+ });
147
+ if (typeof sleep !== "function") throw new RateLimitInvalidOptionError({
148
+ name: "sleep",
149
+ actual: sleep
150
+ });
151
+ this.tokensPerInterval = tokensPerInterval;
152
+ this.intervalMs = intervalMs;
153
+ this.maxTokens = capacity;
154
+ this.strategy = strategy;
155
+ _classPrivateFieldSet2(_now, this, now);
156
+ _classPrivateFieldSet2(_sleep, this, sleep);
157
+ _classPrivateFieldSet2(_tokens, this, capacity);
158
+ _classPrivateFieldSet2(_lastRefill, this, now());
159
+ _classPrivateFieldSet2(_tail, this, Promise.resolve());
160
+ }
161
+ /**
162
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
163
+ */
164
+ get availableTokens() {
165
+ _assertClassBrand(_RateLimit_brand, this, _refill).call(this);
166
+ return _classPrivateFieldGet2(_tokens, this);
167
+ }
168
+ async use(c, next) {
169
+ await _assertClassBrand(_RateLimit_brand, this, _acquire).call(this, c.signal);
170
+ await next();
171
+ }
172
+ };
173
+ async function _acquire(signal) {
174
+ throwIfAborted(signal);
175
+ let release;
176
+ const previous = _classPrivateFieldGet2(_tail, this);
177
+ _classPrivateFieldSet2(_tail, this, new Promise((resolve) => {
178
+ release = resolve;
179
+ }));
180
+ await previous;
181
+ try {
182
+ for (;;) {
183
+ throwIfAborted(signal);
184
+ _assertClassBrand(_RateLimit_brand, this, _refill).call(this);
185
+ if (_classPrivateFieldGet2(_tokens, this) >= 1) {
186
+ _classPrivateFieldSet2(_tokens, this, _classPrivateFieldGet2(_tokens, this) - 1);
187
+ return;
188
+ }
189
+ if (this.strategy === "throw") throw new RateLimitExceededError({ retryAfterMs: _assertClassBrand(_RateLimit_brand, this, _retryAfterMs).call(this) });
190
+ await _classPrivateFieldGet2(_sleep, this).call(this, _assertClassBrand(_RateLimit_brand, this, _retryAfterMs).call(this), signal);
191
+ }
192
+ } finally {
193
+ release();
194
+ }
195
+ }
196
+ function _refill() {
197
+ const now = _classPrivateFieldGet2(_now, this).call(this);
198
+ const elapsed = now - _classPrivateFieldGet2(_lastRefill, this);
199
+ if (elapsed <= 0) return;
200
+ _classPrivateFieldSet2(_tokens, this, Math.min(this.maxTokens, _classPrivateFieldGet2(_tokens, this) + elapsed * this.tokensPerInterval / this.intervalMs));
201
+ _classPrivateFieldSet2(_lastRefill, this, now);
202
+ }
203
+ function _retryAfterMs() {
204
+ const deficit = 1 - _classPrivateFieldGet2(_tokens, this);
205
+ return Math.max(0, Math.ceil(deficit * this.intervalMs / this.tokensPerInterval));
206
+ }
207
+ //#endregion
208
+ export { RateLimit, RateLimitExceededError, RateLimitInvalidOptionError };
209
+
210
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts","../src/rate-limit.ts"],"sourcesContent":["import { type ErrorOptions, ErrorBase, setErrorMessage, InvalidUsageErrorBase } from \"@unikvs/core\";\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\nexport type RateLimitExceededErrorMeta = {\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-exceeded-retry-after-ms)\n */\n readonly retryAfterMs: number;\n};\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\nexport type RateLimitExceededErrorArgs = ErrorOptions & RateLimitExceededErrorMeta;\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\nexport class RateLimitExceededError extends ErrorBase<RateLimitExceededErrorMeta> {\n static {\n this.prototype.name = \"RateLimitExceededError\";\n }\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)\n */\n public constructor(args: RateLimitExceededErrorArgs) {\n const { retryAfterMs, ...options } = args;\n const meta: RateLimitExceededErrorMeta = { retryAfterMs };\n super(\n meta,\n ({ retryAfterMs: messageRetryAfterMs }) =>\n `Rate limit exceeded. Retry after ${String(messageRetryAfterMs)}ms.`,\n options,\n );\n }\n}\n\nsetErrorMessage(\n RateLimitExceededError,\n ({ retryAfterMs }) =>\n `レート制限を超えました。${String(retryAfterMs)}ms 後に再試行してください。`,\n \"ja\",\n);\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\nexport type RateLimitInvalidOptionErrorMeta = {\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-name)\n */\n readonly name: string;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-actual)\n */\n readonly actual: unknown;\n};\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\nexport type RateLimitInvalidOptionErrorArgs = ErrorOptions & RateLimitInvalidOptionErrorMeta;\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\nexport class RateLimitInvalidOptionError extends InvalidUsageErrorBase<RateLimitInvalidOptionErrorMeta> {\n static {\n this.prototype.name = \"RateLimitInvalidOptionError\";\n }\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)\n */\n public constructor(args: RateLimitInvalidOptionErrorArgs) {\n const { name, actual, ...options } = args;\n const meta: RateLimitInvalidOptionErrorMeta = {\n name,\n actual,\n };\n super(\n meta,\n ({ name: messageName, actual: messageActual }) =>\n `Invalid RateLimit option ${JSON.stringify(messageName)}: ${formatActual(messageActual)}`,\n options,\n );\n }\n}\n\nsetErrorMessage(\n RateLimitInvalidOptionError,\n ({ name, actual }) =>\n `無効な RateLimit オプション ${JSON.stringify(name)}: ${formatActual(actual)}`,\n \"ja\",\n);\n\n/**\n * エラーメッセージに埋め込む実際の値を整形します。\n *\n * @param actual 整形する値です。\n *\n * @returns 整形した文字列を返します。\n */\nfunction formatActual(actual: unknown): string {\n if (typeof actual === \"string\") {\n return JSON.stringify(actual);\n }\n\n if (\n typeof actual === \"number\" ||\n typeof actual === \"boolean\" ||\n actual === null ||\n actual === undefined\n ) {\n return String(actual);\n }\n\n try {\n return JSON.stringify(actual) ?? \"[object Object]\";\n } catch {\n return \"[object Object]\";\n }\n}\n","import type { IMiddleware } from \"@unikvs/core\";\nimport { PassThrough } from \"@unikvs/passthrough\";\nimport { getAbortReason, throwIfAborted } from \"abort-signal-utils\";\n\nimport { RateLimitExceededError, RateLimitInvalidOptionError } from \"./errors.js\";\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-strategy)\n */\nexport type RateLimitStrategy = \"wait\" | \"throw\";\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#irate-limit-sleep)\n */\nexport interface IRateLimitSleep {\n (ms: number, signal: AbortSignal): Promise<void>;\n}\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options)\n */\nexport type RateLimitOptions = {\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-tokens-per-interval)\n */\n readonly tokensPerInterval?: number | undefined;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-interval-ms)\n */\n readonly intervalMs?: number | undefined;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-max-tokens)\n */\n readonly maxTokens?: number | undefined;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-burst)\n */\n readonly burst?: number | undefined;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-strategy)\n */\n readonly strategy?: RateLimitStrategy | undefined;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-now)\n */\n readonly now?: (() => number) | undefined;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-sleep)\n */\n readonly sleep?: IRateLimitSleep | undefined;\n};\n\nfunction defaultSleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(getAbortReason(signal));\n\n return;\n }\n\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(getAbortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nfunction assertPositiveNumber(name: string, value: number): void {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n throw new RateLimitInvalidOptionError({\n name,\n actual: value,\n });\n }\n}\n\n/**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\nexport default class RateLimit extends PassThrough implements IMiddleware {\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public override readonly name: string = \"RateLimit\";\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly tokensPerInterval: number;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly intervalMs: number;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly maxTokens: number;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public readonly strategy: RateLimitStrategy;\n\n readonly #now: () => number;\n\n readonly #sleep: IRateLimitSleep;\n\n #tokens: number;\n\n #lastRefill: number;\n\n #tail: Promise<void>;\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public constructor(options: RateLimitOptions = {}) {\n super();\n\n const {\n now = Date.now,\n burst,\n sleep = defaultSleep,\n strategy = \"wait\",\n maxTokens,\n intervalMs = 1000,\n tokensPerInterval = 1,\n } = options;\n assertPositiveNumber(\"tokensPerInterval\", tokensPerInterval);\n assertPositiveNumber(\"intervalMs\", intervalMs);\n\n const capacity = maxTokens ?? burst ?? tokensPerInterval;\n assertPositiveNumber(\"maxTokens\", capacity);\n\n if (strategy !== \"wait\" && strategy !== \"throw\") {\n throw new RateLimitInvalidOptionError({\n name: \"strategy\",\n actual: strategy,\n });\n }\n\n if (typeof now !== \"function\") {\n throw new RateLimitInvalidOptionError({\n name: \"now\",\n actual: now,\n });\n }\n\n if (typeof sleep !== \"function\") {\n throw new RateLimitInvalidOptionError({\n name: \"sleep\",\n actual: sleep,\n });\n }\n\n this.tokensPerInterval = tokensPerInterval;\n this.intervalMs = intervalMs;\n this.maxTokens = capacity;\n this.strategy = strategy;\n this.#now = now;\n this.#sleep = sleep;\n this.#tokens = capacity;\n this.#lastRefill = now();\n this.#tail = Promise.resolve();\n }\n\n /**\n * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)\n */\n public get availableTokens(): number {\n this.#refill();\n\n return this.#tokens;\n }\n\n public async use(c: IMiddleware.UseContext, next: IMiddleware.INext): Promise<void> {\n await this.#acquire(c.signal);\n\n await next();\n }\n\n async #acquire(signal: AbortSignal): Promise<void> {\n throwIfAborted(signal);\n\n let release!: () => void;\n const previous = this.#tail;\n this.#tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n\n try {\n for (;;) {\n throwIfAborted(signal);\n this.#refill();\n\n if (this.#tokens >= 1) {\n this.#tokens -= 1;\n\n return;\n }\n\n if (this.strategy === \"throw\") {\n throw new RateLimitExceededError({ retryAfterMs: this.#retryAfterMs() });\n }\n\n await this.#sleep(this.#retryAfterMs(), signal);\n }\n } finally {\n release();\n }\n }\n\n #refill(): void {\n const now = this.#now();\n const elapsed = now - this.#lastRefill;\n\n if (elapsed <= 0) {\n return;\n }\n\n this.#tokens = Math.min(\n this.maxTokens,\n this.#tokens + (elapsed * this.tokensPerInterval) / this.intervalMs,\n );\n this.#lastRefill = now;\n }\n\n #retryAfterMs(): number {\n const deficit = 1 - this.#tokens;\n\n return Math.max(0, Math.ceil((deficit * this.intervalMs) / this.tokensPerInterval));\n }\n}\n"],"mappings":"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"}
package/package.json CHANGED
@@ -1,10 +1,47 @@
1
1
  {
2
2
  "name": "@unikvs/rate-limit",
3
- "version": "0.0.0",
4
- "description": "OIDC trusted publishing setup package for @unikvs/rate-limit",
5
- "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
3
+ "version": "0.0.14",
4
+ "description": "Transformer plugin that limits operations per time window with a token bucket.",
5
+ "homepage": "https://tai-kun.github.io/unikvs/",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "url": "https://github.com/tai-kun/unikvs",
9
+ "directory": "packages/rate-limit"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "src",
14
+ "package.json",
15
+ "LICENSE",
16
+ "README.md"
17
+ ],
18
+ "type": "module",
19
+ "sideEffects": false,
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "dependencies": {
27
+ "@unikvs/core": "0.0.14",
28
+ "@unikvs/passthrough": "0.0.14",
29
+ "abort-signal-utils": "^0.0.6"
30
+ },
31
+ "devDependencies": {
32
+ "@unikvs/testing": "0.0.0",
33
+ "@vitest/browser-playwright": "5.0.5",
34
+ "@vitest/coverage-istanbul": "5.0.5",
35
+ "@vitest/coverage-v8": "5.0.5",
36
+ "playwright": "1.64.1",
37
+ "valibot": "1.5.0",
38
+ "vite-plus": "1.3.0"
39
+ },
40
+ "peerDependencies": {
41
+ "@logtape/logtape": "^2.0.0"
42
+ },
43
+ "readme": "README.md",
44
+ "scripts": {
45
+ "build": "vp -C .config pack"
46
+ }
47
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,127 @@
1
+ import { type ErrorOptions, ErrorBase, setErrorMessage, InvalidUsageErrorBase } from "@unikvs/core";
2
+
3
+ /**
4
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
5
+ */
6
+ export type RateLimitExceededErrorMeta = {
7
+ /**
8
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-exceeded-retry-after-ms)
9
+ */
10
+ readonly retryAfterMs: number;
11
+ };
12
+
13
+ /**
14
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
15
+ */
16
+ export type RateLimitExceededErrorArgs = ErrorOptions & RateLimitExceededErrorMeta;
17
+
18
+ /**
19
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
20
+ */
21
+ export class RateLimitExceededError extends ErrorBase<RateLimitExceededErrorMeta> {
22
+ static {
23
+ this.prototype.name = "RateLimitExceededError";
24
+ }
25
+
26
+ /**
27
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-exceeded)
28
+ */
29
+ public constructor(args: RateLimitExceededErrorArgs) {
30
+ const { retryAfterMs, ...options } = args;
31
+ const meta: RateLimitExceededErrorMeta = { retryAfterMs };
32
+ super(
33
+ meta,
34
+ ({ retryAfterMs: messageRetryAfterMs }) =>
35
+ `Rate limit exceeded. Retry after ${String(messageRetryAfterMs)}ms.`,
36
+ options,
37
+ );
38
+ }
39
+ }
40
+
41
+ setErrorMessage(
42
+ RateLimitExceededError,
43
+ ({ retryAfterMs }) =>
44
+ `レート制限を超えました。${String(retryAfterMs)}ms 後に再試行してください。`,
45
+ "ja",
46
+ );
47
+
48
+ /**
49
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
50
+ */
51
+ export type RateLimitInvalidOptionErrorMeta = {
52
+ /**
53
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-name)
54
+ */
55
+ readonly name: string;
56
+
57
+ /**
58
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-invalid-option-actual)
59
+ */
60
+ readonly actual: unknown;
61
+ };
62
+
63
+ /**
64
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
65
+ */
66
+ export type RateLimitInvalidOptionErrorArgs = ErrorOptions & RateLimitInvalidOptionErrorMeta;
67
+
68
+ /**
69
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
70
+ */
71
+ export class RateLimitInvalidOptionError extends InvalidUsageErrorBase<RateLimitInvalidOptionErrorMeta> {
72
+ static {
73
+ this.prototype.name = "RateLimitInvalidOptionError";
74
+ }
75
+
76
+ /**
77
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#error-rate-limit-invalid-option)
78
+ */
79
+ public constructor(args: RateLimitInvalidOptionErrorArgs) {
80
+ const { name, actual, ...options } = args;
81
+ const meta: RateLimitInvalidOptionErrorMeta = {
82
+ name,
83
+ actual,
84
+ };
85
+ super(
86
+ meta,
87
+ ({ name: messageName, actual: messageActual }) =>
88
+ `Invalid RateLimit option ${JSON.stringify(messageName)}: ${formatActual(messageActual)}`,
89
+ options,
90
+ );
91
+ }
92
+ }
93
+
94
+ setErrorMessage(
95
+ RateLimitInvalidOptionError,
96
+ ({ name, actual }) =>
97
+ `無効な RateLimit オプション ${JSON.stringify(name)}: ${formatActual(actual)}`,
98
+ "ja",
99
+ );
100
+
101
+ /**
102
+ * エラーメッセージに埋め込む実際の値を整形します。
103
+ *
104
+ * @param actual 整形する値です。
105
+ *
106
+ * @returns 整形した文字列を返します。
107
+ */
108
+ function formatActual(actual: unknown): string {
109
+ if (typeof actual === "string") {
110
+ return JSON.stringify(actual);
111
+ }
112
+
113
+ if (
114
+ typeof actual === "number" ||
115
+ typeof actual === "boolean" ||
116
+ actual === null ||
117
+ actual === undefined
118
+ ) {
119
+ return String(actual);
120
+ }
121
+
122
+ try {
123
+ return JSON.stringify(actual) ?? "[object Object]";
124
+ } catch {
125
+ return "[object Object]";
126
+ }
127
+ }
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ export type {
2
+ RateLimitExceededErrorArgs,
3
+ RateLimitExceededErrorMeta,
4
+ RateLimitInvalidOptionErrorArgs,
5
+ RateLimitInvalidOptionErrorMeta,
6
+ } from "./errors.js";
7
+ export { RateLimitExceededError, RateLimitInvalidOptionError } from "./errors.js";
8
+
9
+ export type * from "./rate-limit.js";
10
+ export { default as RateLimit } from "./rate-limit.js";
@@ -0,0 +1,247 @@
1
+ import type { IMiddleware } from "@unikvs/core";
2
+ import { PassThrough } from "@unikvs/passthrough";
3
+ import { getAbortReason, throwIfAborted } from "abort-signal-utils";
4
+
5
+ import { RateLimitExceededError, RateLimitInvalidOptionError } from "./errors.js";
6
+
7
+ /**
8
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-strategy)
9
+ */
10
+ export type RateLimitStrategy = "wait" | "throw";
11
+
12
+ /**
13
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#irate-limit-sleep)
14
+ */
15
+ export interface IRateLimitSleep {
16
+ (ms: number, signal: AbortSignal): Promise<void>;
17
+ }
18
+
19
+ /**
20
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options)
21
+ */
22
+ export type RateLimitOptions = {
23
+ /**
24
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-tokens-per-interval)
25
+ */
26
+ readonly tokensPerInterval?: number | undefined;
27
+
28
+ /**
29
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-interval-ms)
30
+ */
31
+ readonly intervalMs?: number | undefined;
32
+
33
+ /**
34
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-max-tokens)
35
+ */
36
+ readonly maxTokens?: number | undefined;
37
+
38
+ /**
39
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-burst)
40
+ */
41
+ readonly burst?: number | undefined;
42
+
43
+ /**
44
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-strategy)
45
+ */
46
+ readonly strategy?: RateLimitStrategy | undefined;
47
+
48
+ /**
49
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-now)
50
+ */
51
+ readonly now?: (() => number) | undefined;
52
+
53
+ /**
54
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit-options-sleep)
55
+ */
56
+ readonly sleep?: IRateLimitSleep | undefined;
57
+ };
58
+
59
+ function defaultSleep(ms: number, signal: AbortSignal): Promise<void> {
60
+ return new Promise<void>((resolve, reject) => {
61
+ if (signal.aborted) {
62
+ reject(getAbortReason(signal));
63
+
64
+ return;
65
+ }
66
+
67
+ const timer = setTimeout(() => {
68
+ signal.removeEventListener("abort", onAbort);
69
+ resolve();
70
+ }, ms);
71
+ const onAbort = (): void => {
72
+ clearTimeout(timer);
73
+ reject(getAbortReason(signal));
74
+ };
75
+ signal.addEventListener("abort", onAbort, { once: true });
76
+ });
77
+ }
78
+
79
+ function assertPositiveNumber(name: string, value: number): void {
80
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
81
+ throw new RateLimitInvalidOptionError({
82
+ name,
83
+ actual: value,
84
+ });
85
+ }
86
+ }
87
+
88
+ /**
89
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
90
+ */
91
+ export default class RateLimit extends PassThrough implements IMiddleware {
92
+ /**
93
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
94
+ */
95
+ public override readonly name: string = "RateLimit";
96
+
97
+ /**
98
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
99
+ */
100
+ public readonly tokensPerInterval: number;
101
+
102
+ /**
103
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
104
+ */
105
+ public readonly intervalMs: number;
106
+
107
+ /**
108
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
109
+ */
110
+ public readonly maxTokens: number;
111
+
112
+ /**
113
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
114
+ */
115
+ public readonly strategy: RateLimitStrategy;
116
+
117
+ readonly #now: () => number;
118
+
119
+ readonly #sleep: IRateLimitSleep;
120
+
121
+ #tokens: number;
122
+
123
+ #lastRefill: number;
124
+
125
+ #tail: Promise<void>;
126
+
127
+ /**
128
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
129
+ */
130
+ public constructor(options: RateLimitOptions = {}) {
131
+ super();
132
+
133
+ const {
134
+ now = Date.now,
135
+ burst,
136
+ sleep = defaultSleep,
137
+ strategy = "wait",
138
+ maxTokens,
139
+ intervalMs = 1000,
140
+ tokensPerInterval = 1,
141
+ } = options;
142
+ assertPositiveNumber("tokensPerInterval", tokensPerInterval);
143
+ assertPositiveNumber("intervalMs", intervalMs);
144
+
145
+ const capacity = maxTokens ?? burst ?? tokensPerInterval;
146
+ assertPositiveNumber("maxTokens", capacity);
147
+
148
+ if (strategy !== "wait" && strategy !== "throw") {
149
+ throw new RateLimitInvalidOptionError({
150
+ name: "strategy",
151
+ actual: strategy,
152
+ });
153
+ }
154
+
155
+ if (typeof now !== "function") {
156
+ throw new RateLimitInvalidOptionError({
157
+ name: "now",
158
+ actual: now,
159
+ });
160
+ }
161
+
162
+ if (typeof sleep !== "function") {
163
+ throw new RateLimitInvalidOptionError({
164
+ name: "sleep",
165
+ actual: sleep,
166
+ });
167
+ }
168
+
169
+ this.tokensPerInterval = tokensPerInterval;
170
+ this.intervalMs = intervalMs;
171
+ this.maxTokens = capacity;
172
+ this.strategy = strategy;
173
+ this.#now = now;
174
+ this.#sleep = sleep;
175
+ this.#tokens = capacity;
176
+ this.#lastRefill = now();
177
+ this.#tail = Promise.resolve();
178
+ }
179
+
180
+ /**
181
+ * [API Reference](https://tai-kun.github.io/unikvs/packages/rate-limit#rate-limit)
182
+ */
183
+ public get availableTokens(): number {
184
+ this.#refill();
185
+
186
+ return this.#tokens;
187
+ }
188
+
189
+ public async use(c: IMiddleware.UseContext, next: IMiddleware.INext): Promise<void> {
190
+ await this.#acquire(c.signal);
191
+
192
+ await next();
193
+ }
194
+
195
+ async #acquire(signal: AbortSignal): Promise<void> {
196
+ throwIfAborted(signal);
197
+
198
+ let release!: () => void;
199
+ const previous = this.#tail;
200
+ this.#tail = new Promise<void>((resolve) => {
201
+ release = resolve;
202
+ });
203
+ await previous;
204
+
205
+ try {
206
+ for (;;) {
207
+ throwIfAborted(signal);
208
+ this.#refill();
209
+
210
+ if (this.#tokens >= 1) {
211
+ this.#tokens -= 1;
212
+
213
+ return;
214
+ }
215
+
216
+ if (this.strategy === "throw") {
217
+ throw new RateLimitExceededError({ retryAfterMs: this.#retryAfterMs() });
218
+ }
219
+
220
+ await this.#sleep(this.#retryAfterMs(), signal);
221
+ }
222
+ } finally {
223
+ release();
224
+ }
225
+ }
226
+
227
+ #refill(): void {
228
+ const now = this.#now();
229
+ const elapsed = now - this.#lastRefill;
230
+
231
+ if (elapsed <= 0) {
232
+ return;
233
+ }
234
+
235
+ this.#tokens = Math.min(
236
+ this.maxTokens,
237
+ this.#tokens + (elapsed * this.tokensPerInterval) / this.intervalMs,
238
+ );
239
+ this.#lastRefill = now;
240
+ }
241
+
242
+ #retryAfterMs(): number {
243
+ const deficit = 1 - this.#tokens;
244
+
245
+ return Math.max(0, Math.ceil((deficit * this.intervalMs) / this.tokensPerInterval));
246
+ }
247
+ }