@metamask-previews/rate-limit-controller 7.0.1-preview-3866c0ff1 → 7.0.1-preview-e3275932a

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/CHANGELOG.md CHANGED
@@ -9,7 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Changed
11
11
 
12
- - **BREAKING:** Bump minimum Node.js version to 22 ([#9168](https://github.com/MetaMask/core/pull/9168))
13
12
  - Bump `@metamask/utils` from `^11.9.0` to `^11.11.0` ([#9074](https://github.com/MetaMask/core/pull/9074))
14
13
  - Bump `@metamask/messenger` from `^1.0.0` to `^2.0.0` ([#8364](https://github.com/MetaMask/core/pull/8364), [#8373](https://github.com/MetaMask/core/pull/8373), [#8632](https://github.com/MetaMask/core/pull/8632), [#9392](https://github.com/MetaMask/core/pull/9392))
15
14
  - Bump `@metamask/base-controller` from `^9.0.1` to `^9.1.0` ([#8457](https://github.com/MetaMask/core/pull/8457))
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _RateLimitController_instances, _RateLimitController_implementations, _RateLimitController_rateLimitTimeout, _RateLimitController_rateLimitCount, _RateLimitController_isRateLimited, _RateLimitController_recordRequest, _RateLimitController_resetRequestCount;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.RateLimitController = void 0;
16
+ const base_controller_1 = require("@metamask/base-controller");
17
+ const rpc_errors_1 = require("@metamask/rpc-errors");
18
+ const utils_1 = require("@metamask/utils");
19
+ const controllerName = 'RateLimitController';
20
+ const metadata = {
21
+ requests: {
22
+ includeInStateLogs: false,
23
+ persist: false,
24
+ includeInDebugSnapshot: false,
25
+ usedInUi: false,
26
+ },
27
+ };
28
+ /**
29
+ * Controller with logic for rate-limiting API endpoints per requesting origin.
30
+ */
31
+ class RateLimitController extends base_controller_1.BaseController {
32
+ /**
33
+ * Creates a RateLimitController instance.
34
+ *
35
+ * @param options - Constructor options.
36
+ * @param options.messenger - A reference to the messaging system.
37
+ * @param options.state - Initial state to set on this controller.
38
+ * @param options.implementations - Mapping from API type to API implementation.
39
+ * @param options.rateLimitTimeout - The time window in which the rate limit is applied (in ms).
40
+ * @param options.rateLimitCount - The amount of calls an origin can make in the rate limit time window.
41
+ */
42
+ constructor({ rateLimitTimeout = 5000, rateLimitCount = 1, messenger, state, implementations, }) {
43
+ const defaultState = {
44
+ requests: (0, utils_1.getKnownPropertyNames)(implementations).reduce((acc, key) => ({ ...acc, [key]: {} }), {}),
45
+ };
46
+ super({
47
+ name: controllerName,
48
+ metadata,
49
+ messenger,
50
+ state: { ...defaultState, ...state },
51
+ });
52
+ _RateLimitController_instances.add(this);
53
+ _RateLimitController_implementations.set(this, void 0);
54
+ _RateLimitController_rateLimitTimeout.set(this, void 0);
55
+ _RateLimitController_rateLimitCount.set(this, void 0);
56
+ __classPrivateFieldSet(this, _RateLimitController_implementations, implementations, "f");
57
+ __classPrivateFieldSet(this, _RateLimitController_rateLimitTimeout, rateLimitTimeout, "f");
58
+ __classPrivateFieldSet(this, _RateLimitController_rateLimitCount, rateLimitCount, "f");
59
+ this.messenger.registerActionHandler(`${controllerName}:call`, (origin, type, ...args) => this.call(origin, type, ...args));
60
+ }
61
+ /**
62
+ * Calls an API if the requesting origin is not rate-limited.
63
+ *
64
+ * @param origin - The requesting origin.
65
+ * @param type - The type of API call to make.
66
+ * @param args - Arguments for the API call.
67
+ * @returns The result of the API call.
68
+ */
69
+ async call(origin, type, ...args) {
70
+ if (__classPrivateFieldGet(this, _RateLimitController_instances, "m", _RateLimitController_isRateLimited).call(this, type, origin)) {
71
+ throw rpc_errors_1.rpcErrors.limitExceeded({
72
+ message: `"${type.toString()}" is currently rate-limited. Please try again later.`,
73
+ });
74
+ }
75
+ __classPrivateFieldGet(this, _RateLimitController_instances, "m", _RateLimitController_recordRequest).call(this, type, origin);
76
+ const implementation = __classPrivateFieldGet(this, _RateLimitController_implementations, "f")[type].method;
77
+ if (!implementation) {
78
+ throw new Error('Invalid api type');
79
+ }
80
+ return implementation(...args);
81
+ }
82
+ }
83
+ exports.RateLimitController = RateLimitController;
84
+ _RateLimitController_implementations = new WeakMap(), _RateLimitController_rateLimitTimeout = new WeakMap(), _RateLimitController_rateLimitCount = new WeakMap(), _RateLimitController_instances = new WeakSet(), _RateLimitController_isRateLimited = function _RateLimitController_isRateLimited(api, origin) {
85
+ const rateLimitCount = __classPrivateFieldGet(this, _RateLimitController_implementations, "f")[api].rateLimitCount ?? __classPrivateFieldGet(this, _RateLimitController_rateLimitCount, "f");
86
+ return this.state.requests[api][origin] >= rateLimitCount;
87
+ }, _RateLimitController_recordRequest = function _RateLimitController_recordRequest(api, origin) {
88
+ const rateLimitTimeout = __classPrivateFieldGet(this, _RateLimitController_implementations, "f")[api].rateLimitTimeout ?? __classPrivateFieldGet(this, _RateLimitController_rateLimitTimeout, "f");
89
+ const previous = this.state.requests[api][origin] ?? 0;
90
+ this.update((state) => {
91
+ if (previous === 0) {
92
+ setTimeout(() => __classPrivateFieldGet(this, _RateLimitController_instances, "m", _RateLimitController_resetRequestCount).call(this, api, origin), rateLimitTimeout);
93
+ }
94
+ Object.assign(state, {
95
+ requests: {
96
+ ...state.requests,
97
+ [api]: { [origin]: previous + 1 },
98
+ },
99
+ });
100
+ });
101
+ }, _RateLimitController_resetRequestCount = function _RateLimitController_resetRequestCount(api, origin) {
102
+ this.update((state) => {
103
+ Object.assign(state, {
104
+ requests: {
105
+ ...state.requests,
106
+ [api]: { [origin]: 0 },
107
+ },
108
+ });
109
+ });
110
+ };
111
+ //# sourceMappingURL=RateLimitController.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RateLimitController.cjs","sourceRoot":"","sources":["../src/RateLimitController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAA2D;AAM3D,qDAAiD;AACjD,2CAAwD;AAsCxD,MAAM,cAAc,GAAG,qBAAqB,CAAC;AAwC7C,MAAM,QAAQ,GAAG;IACf,QAAQ,EAAE;QACR,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,KAAK;KAChB;CACF,CAAC;AAEF;;GAEG;AACH,MAAa,mBAEX,SAAQ,gCAIT;IAOC;;;;;;;;;OASG;IACH,YAAY,EACV,gBAAgB,GAAG,IAAI,EACvB,cAAc,GAAG,CAAC,EAClB,SAAS,EACT,KAAK,EACL,eAAe,GAOhB;QACC,MAAM,YAAY,GAAG;YACnB,QAAQ,EAAE,IAAA,6BAAqB,EAAC,eAAe,CAAC,CAAC,MAAM,CAErD,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAW,CAAC;SACtD,CAAC;QACF,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ;YACR,SAAS;YACT,KAAK,EAAE,EAAE,GAAG,YAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;;QAvCI,uDAAiB;QAEjB,wDA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,CAAC,IAAI,cAAc,CAAC;AAC5D,CAAC,mFAQc,GAA0B,EAAE,MAAc;IACvD,MAAM,gBAAgB,GACpB,uBAAA,IAAI,4CAAiB,CAAC,GAAG,CAAC,CAAC,gBAAgB,IAAI,uBAAA,IAAI,6CAAkB,CAAC;IACxE,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,IAAI,QAAQ,KAAK,CAAC,EAAE,CAAC;YACnB,UAAU,CACR,GAAG,EAAE,CAAC,uBAAA,IAAI,8EAAmB,MAAvB,IAAI,EAAoB,GAAG,EAAE,MAAM,CAAC,EAC1C,gBAAgB,CACjB,CAAC;QACJ,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;YACnB,QAAQ,EAAE;gBACR,GAAI,KAAK,CAAC,QAAiD;gBAC3D,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,QAAQ,GAAG,CAAC,EAAE;aAClC;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,2FAQkB,GAA0B,EAAE,MAAc;IAC3D,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;YACnB,QAAQ,EAAE;gBACR,GAAI,KAAK,CAAC,QAAiD;gBAC3D,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;aACvB;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport type { Messenger, ActionConstraint } from '@metamask/messenger';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { getKnownPropertyNames } from '@metamask/utils';\n\n/**\n * A rate-limited API endpoint.\n *\n * @property method - The method that is rate-limited.\n * @property rateLimitTimeout - The time window in which the rate limit is applied (in ms).\n * @property rateLimitCount - The amount of calls an origin can make in the rate limit time window.\n */\nexport type RateLimitedApi = {\n method: ActionConstraint['handler'];\n rateLimitTimeout?: number;\n rateLimitCount?: number;\n};\n\n/**\n * A map of rate-limited API types to APIs.\n */\nexport type RateLimitedApiMap = Record<string, RateLimitedApi>;\n\n/**\n * A map of rate-limited API types to the number of requests made in a given interval for each origin and api type combination.\n *\n * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.\n */\nexport type RateLimitedRequests<RateLimitedApis extends RateLimitedApiMap> =\n Record<keyof RateLimitedApis, Record<string, number>>;\n\n/**\n * The state of the {@link RateLimitController}.\n *\n * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.\n * @property requests - An object containing the number of requests made in a given interval for each origin and api type combination.\n */\nexport type RateLimitState<RateLimitedApis extends RateLimitedApiMap> = {\n requests: RateLimitedRequests<RateLimitedApis>;\n};\n\nconst controllerName = 'RateLimitController';\n\nexport type RateLimitControllerStateChangeEvent<\n RateLimitedApis extends RateLimitedApiMap,\n> = ControllerStateChangeEvent<\n typeof controllerName,\n RateLimitState<RateLimitedApis>\n>;\n\nexport type RateLimitControllerGetStateAction<\n RateLimitedApis extends RateLimitedApiMap,\n> = ControllerGetStateAction<\n typeof controllerName,\n RateLimitState<RateLimitedApis>\n>;\n\nexport type RateLimitControllerCallApiAction<\n RateLimitedApis extends RateLimitedApiMap,\n> = {\n type: `${typeof controllerName}:call`;\n handler: RateLimitController<RateLimitedApis>['call'];\n};\n\nexport type RateLimitControllerActions<\n RateLimitedApis extends RateLimitedApiMap,\n> =\n | RateLimitControllerGetStateAction<RateLimitedApis>\n | RateLimitControllerCallApiAction<RateLimitedApis>;\n\nexport type RateLimitControllerEvents<\n RateLimitedApis extends RateLimitedApiMap,\n> = RateLimitControllerStateChangeEvent<RateLimitedApis>;\n\nexport type RateLimitMessenger<RateLimitedApis extends RateLimitedApiMap> =\n Messenger<\n typeof controllerName,\n RateLimitControllerActions<RateLimitedApis>,\n RateLimitControllerEvents<RateLimitedApis>\n >;\n\nconst metadata = {\n requests: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n};\n\n/**\n * Controller with logic for rate-limiting API endpoints per requesting origin.\n */\nexport class RateLimitController<\n RateLimitedApis extends RateLimitedApiMap,\n> extends BaseController<\n typeof controllerName,\n RateLimitState<RateLimitedApis>,\n RateLimitMessenger<RateLimitedApis>\n> {\n readonly #implementations;\n\n readonly #rateLimitTimeout;\n\n readonly #rateLimitCount;\n\n /**\n * Creates a RateLimitController instance.\n *\n * @param options - Constructor options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.implementations - Mapping from API type to API implementation.\n * @param options.rateLimitTimeout - The time window in which the rate limit is applied (in ms).\n * @param options.rateLimitCount - The amount of calls an origin can make in the rate limit time window.\n */\n constructor({\n rateLimitTimeout = 5000,\n rateLimitCount = 1,\n messenger,\n state,\n implementations,\n }: {\n rateLimitTimeout?: number;\n rateLimitCount?: number;\n messenger: RateLimitMessenger<RateLimitedApis>;\n state?: Partial<RateLimitState<RateLimitedApis>>;\n implementations: RateLimitedApis;\n }) {\n const defaultState = {\n requests: getKnownPropertyNames(implementations).reduce<\n RateLimitedRequests<RateLimitedApis>\n >((acc, key) => ({ ...acc, [key]: {} }), {} as never),\n };\n super({\n name: controllerName,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#implementations = implementations;\n this.#rateLimitTimeout = rateLimitTimeout;\n this.#rateLimitCount = rateLimitCount;\n\n this.messenger.registerActionHandler(\n `${controllerName}:call`,\n (\n origin: string,\n type: keyof RateLimitedApis,\n ...args: Parameters<RateLimitedApis[typeof type]['method']>\n ) => this.call(origin, type, ...args),\n );\n }\n\n /**\n * Calls an API if the requesting origin is not rate-limited.\n *\n * @param origin - The requesting origin.\n * @param type - The type of API call to make.\n * @param args - Arguments for the API call.\n * @returns The result of the API call.\n */\n async call<ApiType extends keyof RateLimitedApis>(\n origin: string,\n type: ApiType,\n ...args: Parameters<RateLimitedApis[ApiType]['method']>\n ): Promise<ReturnType<RateLimitedApis[ApiType]['method']>> {\n if (this.#isRateLimited(type, origin)) {\n throw rpcErrors.limitExceeded({\n message: `\"${type.toString()}\" is currently rate-limited. Please try again later.`,\n });\n }\n this.#recordRequest(type, origin);\n\n const implementation = this.#implementations[type].method as (\n ...args: Parameters<RateLimitedApis[ApiType]['method']>\n ) => ReturnType<RateLimitedApis[ApiType]['method']>;\n\n if (!implementation) {\n throw new Error('Invalid api type');\n }\n\n return implementation(...args);\n }\n\n /**\n * Checks whether an origin is rate limited for a specific API.\n *\n * @param api - The API the origin is trying to access.\n * @param origin - The origin trying to access the API.\n * @returns `true` if rate-limited, and `false` otherwise.\n */\n #isRateLimited(api: keyof RateLimitedApis, origin: string): boolean {\n const rateLimitCount =\n this.#implementations[api].rateLimitCount ?? this.#rateLimitCount;\n return this.state.requests[api][origin] >= rateLimitCount;\n }\n\n /**\n * Records that an origin has made a request to call an API, for rate-limiting purposes.\n *\n * @param api - The API the origin is trying to access.\n * @param origin - The origin trying to access the API.\n */\n #recordRequest(api: keyof RateLimitedApis, origin: string): void {\n const rateLimitTimeout =\n this.#implementations[api].rateLimitTimeout ?? this.#rateLimitTimeout;\n const previous = this.state.requests[api][origin] ?? 0;\n this.update((state) => {\n if (previous === 0) {\n setTimeout(\n () => this.#resetRequestCount(api, origin),\n rateLimitTimeout,\n );\n }\n Object.assign(state, {\n requests: {\n ...(state.requests as RateLimitedRequests<RateLimitedApis>),\n [api]: { [origin]: previous + 1 },\n },\n });\n });\n }\n\n /**\n * Resets the request count for a given origin and API combination, for rate-limiting purposes.\n *\n * @param api - The API in question.\n * @param origin - The origin in question.\n */\n #resetRequestCount(api: keyof RateLimitedApis, origin: string): void {\n this.update((state) => {\n Object.assign(state, {\n requests: {\n ...(state.requests as RateLimitedRequests<RateLimitedApis>),\n [api]: { [origin]: 0 },\n },\n });\n });\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { BaseController } from '@metamask/base-controller';
2
- import type { ControllerGetStateAction, ControllerStateChangeEvent } from '@metamask/base-controller';
3
- import type { Messenger, ActionConstraint } from '@metamask/messenger';
1
+ import { BaseController } from "@metamask/base-controller";
2
+ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
3
+ import type { Messenger, ActionConstraint } from "@metamask/messenger";
4
4
  /**
5
5
  * A rate-limited API endpoint.
6
6
  *
@@ -75,4 +75,4 @@ export declare class RateLimitController<RateLimitedApis extends RateLimitedApiM
75
75
  call<ApiType extends keyof RateLimitedApis>(origin: string, type: ApiType, ...args: Parameters<RateLimitedApis[ApiType]['method']>): Promise<ReturnType<RateLimitedApis[ApiType]['method']>>;
76
76
  }
77
77
  export {};
78
- //# sourceMappingURL=RateLimitController.d.ts.map
78
+ //# sourceMappingURL=RateLimitController.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RateLimitController.d.cts","sourceRoot":"","sources":["../src/RateLimitController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,4BAA4B;AAIvE;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC;IACpC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,cA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B,CACzC,SAAQ,cAAc,CACtB,OAAO,cAAc,EACrB,cAAc,CAAC,eAAe,CAAC,EAC/B,kBAAkB,CAAC,eAAe,CAAC,CACpC;;IAOC;;;;;;;;;OASG;gBACS,EACV,gBAAuB,EACvB,cAAkB,EAClB,SAAS,EACT,KAAK,EACL,eAAe,GAChB,EAAE;QACD,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,SAAS,EAAE,kBAAkB,CAAC,eAAe,CAAC,CAAC;QAC/C,KAAK,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC,CAAC;QACjD,eAAe,EAAE,eAAe,CAAC;KAClC;IA0BD;;;;;;;OAOG;IACG,IAAI,CAAC,OAAO,SAAS,MAAM,eAAe,EAC9C,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EACb,GAAG,IAAI,EAAE,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,GACtD,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;CA0E3D"}
@@ -0,0 +1,78 @@
1
+ import { BaseController } from "@metamask/base-controller";
2
+ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
3
+ import type { Messenger, ActionConstraint } from "@metamask/messenger";
4
+ /**
5
+ * A rate-limited API endpoint.
6
+ *
7
+ * @property method - The method that is rate-limited.
8
+ * @property rateLimitTimeout - The time window in which the rate limit is applied (in ms).
9
+ * @property rateLimitCount - The amount of calls an origin can make in the rate limit time window.
10
+ */
11
+ export type RateLimitedApi = {
12
+ method: ActionConstraint['handler'];
13
+ rateLimitTimeout?: number;
14
+ rateLimitCount?: number;
15
+ };
16
+ /**
17
+ * A map of rate-limited API types to APIs.
18
+ */
19
+ export type RateLimitedApiMap = Record<string, RateLimitedApi>;
20
+ /**
21
+ * A map of rate-limited API types to the number of requests made in a given interval for each origin and api type combination.
22
+ *
23
+ * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.
24
+ */
25
+ export type RateLimitedRequests<RateLimitedApis extends RateLimitedApiMap> = Record<keyof RateLimitedApis, Record<string, number>>;
26
+ /**
27
+ * The state of the {@link RateLimitController}.
28
+ *
29
+ * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.
30
+ * @property requests - An object containing the number of requests made in a given interval for each origin and api type combination.
31
+ */
32
+ export type RateLimitState<RateLimitedApis extends RateLimitedApiMap> = {
33
+ requests: RateLimitedRequests<RateLimitedApis>;
34
+ };
35
+ declare const controllerName = "RateLimitController";
36
+ export type RateLimitControllerStateChangeEvent<RateLimitedApis extends RateLimitedApiMap> = ControllerStateChangeEvent<typeof controllerName, RateLimitState<RateLimitedApis>>;
37
+ export type RateLimitControllerGetStateAction<RateLimitedApis extends RateLimitedApiMap> = ControllerGetStateAction<typeof controllerName, RateLimitState<RateLimitedApis>>;
38
+ export type RateLimitControllerCallApiAction<RateLimitedApis extends RateLimitedApiMap> = {
39
+ type: `${typeof controllerName}:call`;
40
+ handler: RateLimitController<RateLimitedApis>['call'];
41
+ };
42
+ export type RateLimitControllerActions<RateLimitedApis extends RateLimitedApiMap> = RateLimitControllerGetStateAction<RateLimitedApis> | RateLimitControllerCallApiAction<RateLimitedApis>;
43
+ export type RateLimitControllerEvents<RateLimitedApis extends RateLimitedApiMap> = RateLimitControllerStateChangeEvent<RateLimitedApis>;
44
+ export type RateLimitMessenger<RateLimitedApis extends RateLimitedApiMap> = Messenger<typeof controllerName, RateLimitControllerActions<RateLimitedApis>, RateLimitControllerEvents<RateLimitedApis>>;
45
+ /**
46
+ * Controller with logic for rate-limiting API endpoints per requesting origin.
47
+ */
48
+ export declare class RateLimitController<RateLimitedApis extends RateLimitedApiMap> extends BaseController<typeof controllerName, RateLimitState<RateLimitedApis>, RateLimitMessenger<RateLimitedApis>> {
49
+ #private;
50
+ /**
51
+ * Creates a RateLimitController instance.
52
+ *
53
+ * @param options - Constructor options.
54
+ * @param options.messenger - A reference to the messaging system.
55
+ * @param options.state - Initial state to set on this controller.
56
+ * @param options.implementations - Mapping from API type to API implementation.
57
+ * @param options.rateLimitTimeout - The time window in which the rate limit is applied (in ms).
58
+ * @param options.rateLimitCount - The amount of calls an origin can make in the rate limit time window.
59
+ */
60
+ constructor({ rateLimitTimeout, rateLimitCount, messenger, state, implementations, }: {
61
+ rateLimitTimeout?: number;
62
+ rateLimitCount?: number;
63
+ messenger: RateLimitMessenger<RateLimitedApis>;
64
+ state?: Partial<RateLimitState<RateLimitedApis>>;
65
+ implementations: RateLimitedApis;
66
+ });
67
+ /**
68
+ * Calls an API if the requesting origin is not rate-limited.
69
+ *
70
+ * @param origin - The requesting origin.
71
+ * @param type - The type of API call to make.
72
+ * @param args - Arguments for the API call.
73
+ * @returns The result of the API call.
74
+ */
75
+ call<ApiType extends keyof RateLimitedApis>(origin: string, type: ApiType, ...args: Parameters<RateLimitedApis[ApiType]['method']>): Promise<ReturnType<RateLimitedApis[ApiType]['method']>>;
76
+ }
77
+ export {};
78
+ //# sourceMappingURL=RateLimitController.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RateLimitController.d.mts","sourceRoot":"","sources":["../src/RateLimitController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,4BAA4B;AAIvE;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC;IACpC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;GAEG;AACH,MAA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EG;AACH,qBAAa,mBAAmB,CAC9B,eAAe,SAAS,iBAAiB,CACzC,SAAQ,cAAc,CACtB,OAAO,cAAc,EACrB,cAAc,CAAC,eAAe,CAAC,EAC/B,kBAAkB,CAAC,eAAe,CAAC,CACpC;;IAOC;;;;;;;;;OASG;gBACS,EACV,gBAAuB,EACvB,cAAkB,EAClB,SAAS,EACT,KAAK,EACL,eAAe,GAChB,EAAE;QACD,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,SAAS,EAAE,kBAAkB,CAAC,eAAe,CAAC,CAAC;QAC/C,KAAK,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC,CAAC;QACjD,eAAe,EAAE,eAAe,CAAC;KAClC;IA0BD;;;;;;;OAOG;IACG,IAAI,CAAC,OAAO,SAAS,MAAM,eAAe,EAC9C,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EACb,GAAG,IAAI,EAAE,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,GACtD,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;CA0E3D"}
@@ -0,0 +1,107 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _RateLimitController_instances, _RateLimitController_implementations, _RateLimitController_rateLimitTimeout, _RateLimitController_rateLimitCount, _RateLimitController_isRateLimited, _RateLimitController_recordRequest, _RateLimitController_resetRequestCount;
13
+ import { BaseController } from "@metamask/base-controller";
14
+ import { rpcErrors } from "@metamask/rpc-errors";
15
+ import { getKnownPropertyNames } from "@metamask/utils";
16
+ const controllerName = 'RateLimitController';
17
+ const metadata = {
18
+ requests: {
19
+ includeInStateLogs: false,
20
+ persist: false,
21
+ includeInDebugSnapshot: false,
22
+ usedInUi: false,
23
+ },
24
+ };
25
+ /**
26
+ * Controller with logic for rate-limiting API endpoints per requesting origin.
27
+ */
28
+ export class RateLimitController extends BaseController {
29
+ /**
30
+ * Creates a RateLimitController instance.
31
+ *
32
+ * @param options - Constructor options.
33
+ * @param options.messenger - A reference to the messaging system.
34
+ * @param options.state - Initial state to set on this controller.
35
+ * @param options.implementations - Mapping from API type to API implementation.
36
+ * @param options.rateLimitTimeout - The time window in which the rate limit is applied (in ms).
37
+ * @param options.rateLimitCount - The amount of calls an origin can make in the rate limit time window.
38
+ */
39
+ constructor({ rateLimitTimeout = 5000, rateLimitCount = 1, messenger, state, implementations, }) {
40
+ const defaultState = {
41
+ requests: getKnownPropertyNames(implementations).reduce((acc, key) => ({ ...acc, [key]: {} }), {}),
42
+ };
43
+ super({
44
+ name: controllerName,
45
+ metadata,
46
+ messenger,
47
+ state: { ...defaultState, ...state },
48
+ });
49
+ _RateLimitController_instances.add(this);
50
+ _RateLimitController_implementations.set(this, void 0);
51
+ _RateLimitController_rateLimitTimeout.set(this, void 0);
52
+ _RateLimitController_rateLimitCount.set(this, void 0);
53
+ __classPrivateFieldSet(this, _RateLimitController_implementations, implementations, "f");
54
+ __classPrivateFieldSet(this, _RateLimitController_rateLimitTimeout, rateLimitTimeout, "f");
55
+ __classPrivateFieldSet(this, _RateLimitController_rateLimitCount, rateLimitCount, "f");
56
+ this.messenger.registerActionHandler(`${controllerName}:call`, (origin, type, ...args) => this.call(origin, type, ...args));
57
+ }
58
+ /**
59
+ * Calls an API if the requesting origin is not rate-limited.
60
+ *
61
+ * @param origin - The requesting origin.
62
+ * @param type - The type of API call to make.
63
+ * @param args - Arguments for the API call.
64
+ * @returns The result of the API call.
65
+ */
66
+ async call(origin, type, ...args) {
67
+ if (__classPrivateFieldGet(this, _RateLimitController_instances, "m", _RateLimitController_isRateLimited).call(this, type, origin)) {
68
+ throw rpcErrors.limitExceeded({
69
+ message: `"${type.toString()}" is currently rate-limited. Please try again later.`,
70
+ });
71
+ }
72
+ __classPrivateFieldGet(this, _RateLimitController_instances, "m", _RateLimitController_recordRequest).call(this, type, origin);
73
+ const implementation = __classPrivateFieldGet(this, _RateLimitController_implementations, "f")[type].method;
74
+ if (!implementation) {
75
+ throw new Error('Invalid api type');
76
+ }
77
+ return implementation(...args);
78
+ }
79
+ }
80
+ _RateLimitController_implementations = new WeakMap(), _RateLimitController_rateLimitTimeout = new WeakMap(), _RateLimitController_rateLimitCount = new WeakMap(), _RateLimitController_instances = new WeakSet(), _RateLimitController_isRateLimited = function _RateLimitController_isRateLimited(api, origin) {
81
+ const rateLimitCount = __classPrivateFieldGet(this, _RateLimitController_implementations, "f")[api].rateLimitCount ?? __classPrivateFieldGet(this, _RateLimitController_rateLimitCount, "f");
82
+ return this.state.requests[api][origin] >= rateLimitCount;
83
+ }, _RateLimitController_recordRequest = function _RateLimitController_recordRequest(api, origin) {
84
+ const rateLimitTimeout = __classPrivateFieldGet(this, _RateLimitController_implementations, "f")[api].rateLimitTimeout ?? __classPrivateFieldGet(this, _RateLimitController_rateLimitTimeout, "f");
85
+ const previous = this.state.requests[api][origin] ?? 0;
86
+ this.update((state) => {
87
+ if (previous === 0) {
88
+ setTimeout(() => __classPrivateFieldGet(this, _RateLimitController_instances, "m", _RateLimitController_resetRequestCount).call(this, api, origin), rateLimitTimeout);
89
+ }
90
+ Object.assign(state, {
91
+ requests: {
92
+ ...state.requests,
93
+ [api]: { [origin]: previous + 1 },
94
+ },
95
+ });
96
+ });
97
+ }, _RateLimitController_resetRequestCount = function _RateLimitController_resetRequestCount(api, origin) {
98
+ this.update((state) => {
99
+ Object.assign(state, {
100
+ requests: {
101
+ ...state.requests,
102
+ [api]: { [origin]: 0 },
103
+ },
104
+ });
105
+ });
106
+ };
107
+ //# sourceMappingURL=RateLimitController.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RateLimitController.mjs","sourceRoot":"","sources":["../src/RateLimitController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAM3D,OAAO,EAAE,SAAS,EAAE,6BAA6B;AACjD,OAAO,EAAE,qBAAqB,EAAE,wBAAwB;AAsCxD,MAAM,cAAc,GAAG,qBAAqB,CAAC;AAwC7C,MAAM,QAAQ,GAAG;IACf,QAAQ,EAAE;QACR,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,KAAK;KAChB;CACF,CAAC;AAEF;;GAEG;AACH,MAAM,OAAO,mBAEX,SAAQ,cAIT;IAOC;;;;;;;;;OASG;IACH,YAAY,EACV,gBAAgB,GAAG,IAAI,EACvB,cAAc,GAAG,CAAC,EAClB,SAAS,EACT,KAAK,EACL,eAAe,GAOhB;QACC,MAAM,YAAY,GAAG;YACnB,QAAQ,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC,MAAM,CAErD,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAW,CAAC;SACtD,CAAC;QACF,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ;YACR,SAAS;YACT,KAAK,E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AC;IACpE,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC;AAC5D,CAAC,mFAQc,GAA0B,EAAE,MAAc;IACvD,MAAM,gBAAgB,GACpB,uBAAA,IAAI,4CAAiB,CAAC,GAAG,CAAC,CAAC,gBAAgB,IAAI,uBAAA,IAAI,6CAAkB,CAAC;IACxE,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,IAAI,QAAQ,KAAK,CAAC,EAAE,CAAC;YACnB,UAAU,CACR,GAAG,EAAE,CAAC,uBAAA,IAAI,8EAAmB,MAAvB,IAAI,EAAoB,GAAG,EAAE,MAAM,CAAC,EAC1C,gBAAgB,CACjB,CAAC;QACJ,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;YACnB,QAAQ,EAAE;gBACR,GAAI,KAAK,CAAC,QAAiD;gBAC3D,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,QAAQ,GAAG,CAAC,EAAE;aAClC;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,2FAQkB,GAA0B,EAAE,MAAc;IAC3D,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;YACnB,QAAQ,EAAE;gBACR,GAAI,KAAK,CAAC,QAAiD;gBAC3D,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;aACvB;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport type { Messenger, ActionConstraint } from '@metamask/messenger';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { getKnownPropertyNames } from '@metamask/utils';\n\n/**\n * A rate-limited API endpoint.\n *\n * @property method - The method that is rate-limited.\n * @property rateLimitTimeout - The time window in which the rate limit is applied (in ms).\n * @property rateLimitCount - The amount of calls an origin can make in the rate limit time window.\n */\nexport type RateLimitedApi = {\n method: ActionConstraint['handler'];\n rateLimitTimeout?: number;\n rateLimitCount?: number;\n};\n\n/**\n * A map of rate-limited API types to APIs.\n */\nexport type RateLimitedApiMap = Record<string, RateLimitedApi>;\n\n/**\n * A map of rate-limited API types to the number of requests made in a given interval for each origin and api type combination.\n *\n * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.\n */\nexport type RateLimitedRequests<RateLimitedApis extends RateLimitedApiMap> =\n Record<keyof RateLimitedApis, Record<string, number>>;\n\n/**\n * The state of the {@link RateLimitController}.\n *\n * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.\n * @property requests - An object containing the number of requests made in a given interval for each origin and api type combination.\n */\nexport type RateLimitState<RateLimitedApis extends RateLimitedApiMap> = {\n requests: RateLimitedRequests<RateLimitedApis>;\n};\n\nconst controllerName = 'RateLimitController';\n\nexport type RateLimitControllerStateChangeEvent<\n RateLimitedApis extends RateLimitedApiMap,\n> = ControllerStateChangeEvent<\n typeof controllerName,\n RateLimitState<RateLimitedApis>\n>;\n\nexport type RateLimitControllerGetStateAction<\n RateLimitedApis extends RateLimitedApiMap,\n> = ControllerGetStateAction<\n typeof controllerName,\n RateLimitState<RateLimitedApis>\n>;\n\nexport type RateLimitControllerCallApiAction<\n RateLimitedApis extends RateLimitedApiMap,\n> = {\n type: `${typeof controllerName}:call`;\n handler: RateLimitController<RateLimitedApis>['call'];\n};\n\nexport type RateLimitControllerActions<\n RateLimitedApis extends RateLimitedApiMap,\n> =\n | RateLimitControllerGetStateAction<RateLimitedApis>\n | RateLimitControllerCallApiAction<RateLimitedApis>;\n\nexport type RateLimitControllerEvents<\n RateLimitedApis extends RateLimitedApiMap,\n> = RateLimitControllerStateChangeEvent<RateLimitedApis>;\n\nexport type RateLimitMessenger<RateLimitedApis extends RateLimitedApiMap> =\n Messenger<\n typeof controllerName,\n RateLimitControllerActions<RateLimitedApis>,\n RateLimitControllerEvents<RateLimitedApis>\n >;\n\nconst metadata = {\n requests: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n};\n\n/**\n * Controller with logic for rate-limiting API endpoints per requesting origin.\n */\nexport class RateLimitController<\n RateLimitedApis extends RateLimitedApiMap,\n> extends BaseController<\n typeof controllerName,\n RateLimitState<RateLimitedApis>,\n RateLimitMessenger<RateLimitedApis>\n> {\n readonly #implementations;\n\n readonly #rateLimitTimeout;\n\n readonly #rateLimitCount;\n\n /**\n * Creates a RateLimitController instance.\n *\n * @param options - Constructor options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.implementations - Mapping from API type to API implementation.\n * @param options.rateLimitTimeout - The time window in which the rate limit is applied (in ms).\n * @param options.rateLimitCount - The amount of calls an origin can make in the rate limit time window.\n */\n constructor({\n rateLimitTimeout = 5000,\n rateLimitCount = 1,\n messenger,\n state,\n implementations,\n }: {\n rateLimitTimeout?: number;\n rateLimitCount?: number;\n messenger: RateLimitMessenger<RateLimitedApis>;\n state?: Partial<RateLimitState<RateLimitedApis>>;\n implementations: RateLimitedApis;\n }) {\n const defaultState = {\n requests: getKnownPropertyNames(implementations).reduce<\n RateLimitedRequests<RateLimitedApis>\n >((acc, key) => ({ ...acc, [key]: {} }), {} as never),\n };\n super({\n name: controllerName,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#implementations = implementations;\n this.#rateLimitTimeout = rateLimitTimeout;\n this.#rateLimitCount = rateLimitCount;\n\n this.messenger.registerActionHandler(\n `${controllerName}:call`,\n (\n origin: string,\n type: keyof RateLimitedApis,\n ...args: Parameters<RateLimitedApis[typeof type]['method']>\n ) => this.call(origin, type, ...args),\n );\n }\n\n /**\n * Calls an API if the requesting origin is not rate-limited.\n *\n * @param origin - The requesting origin.\n * @param type - The type of API call to make.\n * @param args - Arguments for the API call.\n * @returns The result of the API call.\n */\n async call<ApiType extends keyof RateLimitedApis>(\n origin: string,\n type: ApiType,\n ...args: Parameters<RateLimitedApis[ApiType]['method']>\n ): Promise<ReturnType<RateLimitedApis[ApiType]['method']>> {\n if (this.#isRateLimited(type, origin)) {\n throw rpcErrors.limitExceeded({\n message: `\"${type.toString()}\" is currently rate-limited. Please try again later.`,\n });\n }\n this.#recordRequest(type, origin);\n\n const implementation = this.#implementations[type].method as (\n ...args: Parameters<RateLimitedApis[ApiType]['method']>\n ) => ReturnType<RateLimitedApis[ApiType]['method']>;\n\n if (!implementation) {\n throw new Error('Invalid api type');\n }\n\n return implementation(...args);\n }\n\n /**\n * Checks whether an origin is rate limited for a specific API.\n *\n * @param api - The API the origin is trying to access.\n * @param origin - The origin trying to access the API.\n * @returns `true` if rate-limited, and `false` otherwise.\n */\n #isRateLimited(api: keyof RateLimitedApis, origin: string): boolean {\n const rateLimitCount =\n this.#implementations[api].rateLimitCount ?? this.#rateLimitCount;\n return this.state.requests[api][origin] >= rateLimitCount;\n }\n\n /**\n * Records that an origin has made a request to call an API, for rate-limiting purposes.\n *\n * @param api - The API the origin is trying to access.\n * @param origin - The origin trying to access the API.\n */\n #recordRequest(api: keyof RateLimitedApis, origin: string): void {\n const rateLimitTimeout =\n this.#implementations[api].rateLimitTimeout ?? this.#rateLimitTimeout;\n const previous = this.state.requests[api][origin] ?? 0;\n this.update((state) => {\n if (previous === 0) {\n setTimeout(\n () => this.#resetRequestCount(api, origin),\n rateLimitTimeout,\n );\n }\n Object.assign(state, {\n requests: {\n ...(state.requests as RateLimitedRequests<RateLimitedApis>),\n [api]: { [origin]: previous + 1 },\n },\n });\n });\n }\n\n /**\n * Resets the request count for a given origin and API combination, for rate-limiting purposes.\n *\n * @param api - The API in question.\n * @param origin - The origin in question.\n */\n #resetRequestCount(api: keyof RateLimitedApis, origin: string): void {\n this.update((state) => {\n Object.assign(state, {\n requests: {\n ...(state.requests as RateLimitedRequests<RateLimitedApis>),\n [api]: { [origin]: 0 },\n },\n });\n });\n }\n}\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RateLimitController = void 0;
4
+ var RateLimitController_js_1 = require("./RateLimitController.cjs");
5
+ Object.defineProperty(exports, "RateLimitController", { enumerable: true, get: function () { return RateLimitController_js_1.RateLimitController; } });
6
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAYA,oEAA+D;AAAtD,6HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n RateLimitedApi,\n RateLimitedApiMap,\n RateLimitedRequests,\n RateLimitControllerActions,\n RateLimitControllerCallApiAction,\n RateLimitControllerGetStateAction,\n RateLimitControllerEvents,\n RateLimitControllerStateChangeEvent,\n RateLimitMessenger,\n RateLimitState,\n} from './RateLimitController.js';\nexport { RateLimitController } from './RateLimitController.js';\n"]}
@@ -1,3 +1,3 @@
1
- export type { RateLimitedApi, RateLimitedApiMap, RateLimitedRequests, RateLimitControllerActions, RateLimitControllerCallApiAction, RateLimitControllerGetStateAction, RateLimitControllerEvents, RateLimitControllerStateChangeEvent, RateLimitMessenger, RateLimitState, } from './RateLimitController.js';
2
- export { RateLimitController } from './RateLimitController.js';
3
- //# sourceMappingURL=index.d.ts.map
1
+ export type { RateLimitedApi, RateLimitedApiMap, RateLimitedRequests, RateLimitControllerActions, RateLimitControllerCallApiAction, RateLimitControllerGetStateAction, RateLimitControllerEvents, RateLimitControllerStateChangeEvent, RateLimitMessenger, RateLimitState, } from "./RateLimitController.cjs";
2
+ export { RateLimitController } from "./RateLimitController.cjs";
3
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,cAAc,EACd,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,EAC1B,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,mCAAmC,EACnC,kBAAkB,EAClB,cAAc,GACf,kCAAiC;AAClC,OAAO,EAAE,mBAAmB,EAAE,kCAAiC"}
@@ -0,0 +1,3 @@
1
+ export type { RateLimitedApi, RateLimitedApiMap, RateLimitedRequests, RateLimitControllerActions, RateLimitControllerCallApiAction, RateLimitControllerGetStateAction, RateLimitControllerEvents, RateLimitControllerStateChangeEvent, RateLimitMessenger, RateLimitState, } from "./RateLimitController.mjs";
2
+ export { RateLimitController } from "./RateLimitController.mjs";
3
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,cAAc,EACd,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,EAC1B,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,mCAAmC,EACnC,kBAAkB,EAClB,cAAc,GACf,kCAAiC;AAClC,OAAO,EAAE,mBAAmB,EAAE,kCAAiC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export { RateLimitController } from "./RateLimitController.mjs";
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,mBAAmB,EAAE,kCAAiC","sourcesContent":["export type {\n RateLimitedApi,\n RateLimitedApiMap,\n RateLimitedRequests,\n RateLimitControllerActions,\n RateLimitControllerCallApiAction,\n RateLimitControllerGetStateAction,\n RateLimitControllerEvents,\n RateLimitControllerStateChangeEvent,\n RateLimitMessenger,\n RateLimitState,\n} from './RateLimitController.js';\nexport { RateLimitController } from './RateLimitController.js';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/rate-limit-controller",
3
- "version": "7.0.1-preview-3866c0ff1",
3
+ "version": "7.0.1-preview-e3275932a",
4
4
  "description": "Contains logic for rate-limiting API endpoints by requesting origin",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -18,12 +18,19 @@
18
18
  "files": [
19
19
  "dist/"
20
20
  ],
21
- "type": "module",
22
21
  "sideEffects": false,
22
+ "main": "./dist/index.cjs",
23
+ "types": "./dist/index.d.cts",
23
24
  "exports": {
24
25
  ".": {
25
- "types": "./dist/index.d.ts",
26
- "default": "./dist/index.js"
26
+ "import": {
27
+ "types": "./dist/index.d.mts",
28
+ "default": "./dist/index.mjs"
29
+ },
30
+ "require": {
31
+ "types": "./dist/index.d.cts",
32
+ "default": "./dist/index.cjs"
33
+ }
27
34
  },
28
35
  "./package.json": "./package.json"
29
36
  },
@@ -32,11 +39,9 @@
32
39
  "registry": "https://registry.npmjs.org/"
33
40
  },
34
41
  "scripts": {
35
- "build": "tsc --project tsconfig.build.json",
36
- "build:all": "tsc --build tsconfig.build.json --verbose",
37
- "build:clean": "yarn build:only-clean && yarn build",
42
+ "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
43
+ "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
38
44
  "build:docs": "typedoc",
39
- "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
40
45
  "changelog:update": "../../scripts/update-changelog.sh @metamask/rate-limit-controller",
41
46
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/rate-limit-controller",
42
47
  "lint:tsconfigs": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts",
@@ -55,18 +60,17 @@
55
60
  },
56
61
  "devDependencies": {
57
62
  "@metamask/auto-changelog": "^6.1.0",
63
+ "@ts-bridge/cli": "^0.6.4",
58
64
  "@types/jest": "^30.0.0",
59
- "@typescript/native": "npm:typescript@^7.0.2",
60
65
  "deepmerge": "^4.2.2",
61
66
  "jest": "^30.4.2",
62
- "rimraf": "^5.0.5",
63
67
  "ts-jest": "^29.4.11",
64
68
  "tsx": "^4.20.5",
65
69
  "typedoc": "^0.25.13",
66
70
  "typedoc-plugin-missing-exports": "^2.0.0",
67
- "typescript": "npm:@typescript/typescript6@^6.0.2"
71
+ "typescript": "~5.3.3"
68
72
  },
69
73
  "engines": {
70
- "node": "^22.14.0 || ^24"
74
+ "node": "^18.18 || >=20"
71
75
  }
72
76
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"RateLimitController.d.ts","sourceRoot":"","sources":["../src/RateLimitController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAIvE;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC;IACpC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;AAE/D;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,CAAC,eAAe,SAAS,iBAAiB,IACvE,MAAM,CAAC,MAAM,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAExD;;;;;GAKG;AACH,MAAM,MAAM,cAAc,CAAC,eAAe,SAAS,iBAAiB,IAAI;IACtE,QAAQ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AC1B,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,SAAS,EAAE,kBAAkB,CAAC,eAAe,CAAC,CAAC;QAC/C,KAAK,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC,CAAC;QACjD,eAAe,EAAE,eAAe,CAAC;KAClC,EAwBA;IAED;;;;;;;OAOG;IACG,IAAI,CAAC,OAAO,SAAS,MAAM,eAAe,EAC9C,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EACb,GAAG,IAAI,EAAE,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,GACtD,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAiBzD;CAyDF"}
@@ -1,115 +0,0 @@
1
- import { BaseController } from '@metamask/base-controller';
2
- import { rpcErrors } from '@metamask/rpc-errors';
3
- import { getKnownPropertyNames } from '@metamask/utils';
4
- const controllerName = 'RateLimitController';
5
- const metadata = {
6
- requests: {
7
- includeInStateLogs: false,
8
- persist: false,
9
- includeInDebugSnapshot: false,
10
- usedInUi: false,
11
- },
12
- };
13
- /**
14
- * Controller with logic for rate-limiting API endpoints per requesting origin.
15
- */
16
- export class RateLimitController extends BaseController {
17
- #implementations;
18
- #rateLimitTimeout;
19
- #rateLimitCount;
20
- /**
21
- * Creates a RateLimitController instance.
22
- *
23
- * @param options - Constructor options.
24
- * @param options.messenger - A reference to the messaging system.
25
- * @param options.state - Initial state to set on this controller.
26
- * @param options.implementations - Mapping from API type to API implementation.
27
- * @param options.rateLimitTimeout - The time window in which the rate limit is applied (in ms).
28
- * @param options.rateLimitCount - The amount of calls an origin can make in the rate limit time window.
29
- */
30
- constructor({ rateLimitTimeout = 5000, rateLimitCount = 1, messenger, state, implementations, }) {
31
- const defaultState = {
32
- requests: getKnownPropertyNames(implementations).reduce((acc, key) => ({ ...acc, [key]: {} }), {}),
33
- };
34
- super({
35
- name: controllerName,
36
- metadata,
37
- messenger,
38
- state: { ...defaultState, ...state },
39
- });
40
- this.#implementations = implementations;
41
- this.#rateLimitTimeout = rateLimitTimeout;
42
- this.#rateLimitCount = rateLimitCount;
43
- this.messenger.registerActionHandler(`${controllerName}:call`, (origin, type, ...args) => this.call(origin, type, ...args));
44
- }
45
- /**
46
- * Calls an API if the requesting origin is not rate-limited.
47
- *
48
- * @param origin - The requesting origin.
49
- * @param type - The type of API call to make.
50
- * @param args - Arguments for the API call.
51
- * @returns The result of the API call.
52
- */
53
- async call(origin, type, ...args) {
54
- if (this.#isRateLimited(type, origin)) {
55
- throw rpcErrors.limitExceeded({
56
- message: `"${type.toString()}" is currently rate-limited. Please try again later.`,
57
- });
58
- }
59
- this.#recordRequest(type, origin);
60
- const implementation = this.#implementations[type].method;
61
- if (!implementation) {
62
- throw new Error('Invalid api type');
63
- }
64
- return implementation(...args);
65
- }
66
- /**
67
- * Checks whether an origin is rate limited for a specific API.
68
- *
69
- * @param api - The API the origin is trying to access.
70
- * @param origin - The origin trying to access the API.
71
- * @returns `true` if rate-limited, and `false` otherwise.
72
- */
73
- #isRateLimited(api, origin) {
74
- const rateLimitCount = this.#implementations[api].rateLimitCount ?? this.#rateLimitCount;
75
- return this.state.requests[api][origin] >= rateLimitCount;
76
- }
77
- /**
78
- * Records that an origin has made a request to call an API, for rate-limiting purposes.
79
- *
80
- * @param api - The API the origin is trying to access.
81
- * @param origin - The origin trying to access the API.
82
- */
83
- #recordRequest(api, origin) {
84
- const rateLimitTimeout = this.#implementations[api].rateLimitTimeout ?? this.#rateLimitTimeout;
85
- const previous = this.state.requests[api][origin] ?? 0;
86
- this.update((state) => {
87
- if (previous === 0) {
88
- setTimeout(() => this.#resetRequestCount(api, origin), rateLimitTimeout);
89
- }
90
- Object.assign(state, {
91
- requests: {
92
- ...state.requests,
93
- [api]: { [origin]: previous + 1 },
94
- },
95
- });
96
- });
97
- }
98
- /**
99
- * Resets the request count for a given origin and API combination, for rate-limiting purposes.
100
- *
101
- * @param api - The API in question.
102
- * @param origin - The origin in question.
103
- */
104
- #resetRequestCount(api, origin) {
105
- this.update((state) => {
106
- Object.assign(state, {
107
- requests: {
108
- ...state.requests,
109
- [api]: { [origin]: 0 },
110
- },
111
- });
112
- });
113
- }
114
- }
115
- //# sourceMappingURL=RateLimitController.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RateLimitController.js","sourceRoot":"","sources":["../src/RateLimitController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAM3D,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAsCxD,MAAM,cAAc,GAAG,qBAAqB,CAAC;AAwC7C,MAAM,QAAQ,GAAG;IACf,QAAQ,EAAE;QACR,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,KAAK;KAChB;CACF,CAAC;AAEF;;GAEG;AACH,MAAM,OAAO,mBAEX,SAAQ,cAIT;IACU,gBAAgB,CAAC;IAEjB,iBAAiB,CAAC;IAElB,eAAe,CAAC;IAEzB;;;;;;;;;OASG;IACH,YAAY,EACV,gBAAgB,GAAG,IAAI,EACvB,cAAc,GAAG,CAAC,EAClB,SAAS,EACT,KAAK,EACL,eAAe,GAOhB;QACC,MAAM,YAAY,GAAG;YACnB,QAAQ,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC,MAAM,CAErD,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAW,CAAC;SACtD,CAAC;QACF,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ;YACR,SAAS;YACT,KAAK,EAAE,EAAE,GAAG,YAAY,EAAE,GAAG,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IAED;;;;;OAKG;IACH,cAAc,CAAC,GAA0B,EAAE,MAAc;QACvD,MAAM,gBAAgB,GACpB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,gBAAgB,IAAI,IAAI,CAAC,iBAAiB,CAAC;QACxE,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACvD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,IAAI,QAAQ,KAAK,CAAC,EAAE,CAAC;gBACnB,UAAU,CACR,GAAG,EAAE,CAAC,IAAI,CAAC,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,EAC1C,gBAAgB,CACjB,CAAC;YACJ,CAAC;YACD,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;gBACnB,QAAQ,EAAE;oBACR,GAAI,KAAK,CAAC,QAAiD;oBAC3D,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,QAAQ,GAAG,CAAC,EAAE;iBAClC;aACF,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACH,kBAAkB,CAAC,GAA0B,EAAE,MAAc;QAC3D,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;gBACnB,QAAQ,EAAE;oBACR,GAAI,KAAK,CAAC,QAAiD;oBAC3D,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;iBACvB;aACF,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport type { Messenger, ActionConstraint } from '@metamask/messenger';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { getKnownPropertyNames } from '@metamask/utils';\n\n/**\n * A rate-limited API endpoint.\n *\n * @property method - The method that is rate-limited.\n * @property rateLimitTimeout - The time window in which the rate limit is applied (in ms).\n * @property rateLimitCount - The amount of calls an origin can make in the rate limit time window.\n */\nexport type RateLimitedApi = {\n method: ActionConstraint['handler'];\n rateLimitTimeout?: number;\n rateLimitCount?: number;\n};\n\n/**\n * A map of rate-limited API types to APIs.\n */\nexport type RateLimitedApiMap = Record<string, RateLimitedApi>;\n\n/**\n * A map of rate-limited API types to the number of requests made in a given interval for each origin and api type combination.\n *\n * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.\n */\nexport type RateLimitedRequests<RateLimitedApis extends RateLimitedApiMap> =\n Record<keyof RateLimitedApis, Record<string, number>>;\n\n/**\n * The state of the {@link RateLimitController}.\n *\n * @template RateLimitedApis - A {@link RateLimitedApiMap} containing the rate-limited API endpoints that is used by the {@link RateLimitController}.\n * @property requests - An object containing the number of requests made in a given interval for each origin and api type combination.\n */\nexport type RateLimitState<RateLimitedApis extends RateLimitedApiMap> = {\n requests: RateLimitedRequests<RateLimitedApis>;\n};\n\nconst controllerName = 'RateLimitController';\n\nexport type RateLimitControllerStateChangeEvent<\n RateLimitedApis extends RateLimitedApiMap,\n> = ControllerStateChangeEvent<\n typeof controllerName,\n RateLimitState<RateLimitedApis>\n>;\n\nexport type RateLimitControllerGetStateAction<\n RateLimitedApis extends RateLimitedApiMap,\n> = ControllerGetStateAction<\n typeof controllerName,\n RateLimitState<RateLimitedApis>\n>;\n\nexport type RateLimitControllerCallApiAction<\n RateLimitedApis extends RateLimitedApiMap,\n> = {\n type: `${typeof controllerName}:call`;\n handler: RateLimitController<RateLimitedApis>['call'];\n};\n\nexport type RateLimitControllerActions<\n RateLimitedApis extends RateLimitedApiMap,\n> =\n | RateLimitControllerGetStateAction<RateLimitedApis>\n | RateLimitControllerCallApiAction<RateLimitedApis>;\n\nexport type RateLimitControllerEvents<\n RateLimitedApis extends RateLimitedApiMap,\n> = RateLimitControllerStateChangeEvent<RateLimitedApis>;\n\nexport type RateLimitMessenger<RateLimitedApis extends RateLimitedApiMap> =\n Messenger<\n typeof controllerName,\n RateLimitControllerActions<RateLimitedApis>,\n RateLimitControllerEvents<RateLimitedApis>\n >;\n\nconst metadata = {\n requests: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n};\n\n/**\n * Controller with logic for rate-limiting API endpoints per requesting origin.\n */\nexport class RateLimitController<\n RateLimitedApis extends RateLimitedApiMap,\n> extends BaseController<\n typeof controllerName,\n RateLimitState<RateLimitedApis>,\n RateLimitMessenger<RateLimitedApis>\n> {\n readonly #implementations;\n\n readonly #rateLimitTimeout;\n\n readonly #rateLimitCount;\n\n /**\n * Creates a RateLimitController instance.\n *\n * @param options - Constructor options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.implementations - Mapping from API type to API implementation.\n * @param options.rateLimitTimeout - The time window in which the rate limit is applied (in ms).\n * @param options.rateLimitCount - The amount of calls an origin can make in the rate limit time window.\n */\n constructor({\n rateLimitTimeout = 5000,\n rateLimitCount = 1,\n messenger,\n state,\n implementations,\n }: {\n rateLimitTimeout?: number;\n rateLimitCount?: number;\n messenger: RateLimitMessenger<RateLimitedApis>;\n state?: Partial<RateLimitState<RateLimitedApis>>;\n implementations: RateLimitedApis;\n }) {\n const defaultState = {\n requests: getKnownPropertyNames(implementations).reduce<\n RateLimitedRequests<RateLimitedApis>\n >((acc, key) => ({ ...acc, [key]: {} }), {} as never),\n };\n super({\n name: controllerName,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#implementations = implementations;\n this.#rateLimitTimeout = rateLimitTimeout;\n this.#rateLimitCount = rateLimitCount;\n\n this.messenger.registerActionHandler(\n `${controllerName}:call`,\n (\n origin: string,\n type: keyof RateLimitedApis,\n ...args: Parameters<RateLimitedApis[typeof type]['method']>\n ) => this.call(origin, type, ...args),\n );\n }\n\n /**\n * Calls an API if the requesting origin is not rate-limited.\n *\n * @param origin - The requesting origin.\n * @param type - The type of API call to make.\n * @param args - Arguments for the API call.\n * @returns The result of the API call.\n */\n async call<ApiType extends keyof RateLimitedApis>(\n origin: string,\n type: ApiType,\n ...args: Parameters<RateLimitedApis[ApiType]['method']>\n ): Promise<ReturnType<RateLimitedApis[ApiType]['method']>> {\n if (this.#isRateLimited(type, origin)) {\n throw rpcErrors.limitExceeded({\n message: `\"${type.toString()}\" is currently rate-limited. Please try again later.`,\n });\n }\n this.#recordRequest(type, origin);\n\n const implementation = this.#implementations[type].method as (\n ...args: Parameters<RateLimitedApis[ApiType]['method']>\n ) => ReturnType<RateLimitedApis[ApiType]['method']>;\n\n if (!implementation) {\n throw new Error('Invalid api type');\n }\n\n return implementation(...args);\n }\n\n /**\n * Checks whether an origin is rate limited for a specific API.\n *\n * @param api - The API the origin is trying to access.\n * @param origin - The origin trying to access the API.\n * @returns `true` if rate-limited, and `false` otherwise.\n */\n #isRateLimited(api: keyof RateLimitedApis, origin: string): boolean {\n const rateLimitCount =\n this.#implementations[api].rateLimitCount ?? this.#rateLimitCount;\n return this.state.requests[api][origin] >= rateLimitCount;\n }\n\n /**\n * Records that an origin has made a request to call an API, for rate-limiting purposes.\n *\n * @param api - The API the origin is trying to access.\n * @param origin - The origin trying to access the API.\n */\n #recordRequest(api: keyof RateLimitedApis, origin: string): void {\n const rateLimitTimeout =\n this.#implementations[api].rateLimitTimeout ?? this.#rateLimitTimeout;\n const previous = this.state.requests[api][origin] ?? 0;\n this.update((state) => {\n if (previous === 0) {\n setTimeout(\n () => this.#resetRequestCount(api, origin),\n rateLimitTimeout,\n );\n }\n Object.assign(state, {\n requests: {\n ...(state.requests as RateLimitedRequests<RateLimitedApis>),\n [api]: { [origin]: previous + 1 },\n },\n });\n });\n }\n\n /**\n * Resets the request count for a given origin and API combination, for rate-limiting purposes.\n *\n * @param api - The API in question.\n * @param origin - The origin in question.\n */\n #resetRequestCount(api: keyof RateLimitedApis, origin: string): void {\n this.update((state) => {\n Object.assign(state, {\n requests: {\n ...(state.requests as RateLimitedRequests<RateLimitedApis>),\n [api]: { [origin]: 0 },\n },\n });\n });\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,cAAc,EACd,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,EAC1B,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,mCAAmC,EACnC,kBAAkB,EAClB,cAAc,GACf,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC"}
package/dist/index.js DELETED
@@ -1,2 +0,0 @@
1
- export { RateLimitController } from './RateLimitController.js';
2
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["export type {\n RateLimitedApi,\n RateLimitedApiMap,\n RateLimitedRequests,\n RateLimitControllerActions,\n RateLimitControllerCallApiAction,\n RateLimitControllerGetStateAction,\n RateLimitControllerEvents,\n RateLimitControllerStateChangeEvent,\n RateLimitMessenger,\n RateLimitState,\n} from './RateLimitController.js';\nexport { RateLimitController } from './RateLimitController.js';\n"]}