revenuecat-api 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  import createClient, { type ClientOptions } from "openapi-fetch";
2
2
  import type { paths, components } from "./__generated/revenuecat-api-v2";
3
3
  export type { paths, components };
4
- export type CreateRevenueCatClientOptions = ClientOptions & {
5
- automaticRateLimit?: boolean;
6
- };
4
+ export type CreateRevenueCatClientOptions = ClientOptions;
7
5
  export declare function createRevenueCatClient(accessToken: string, options?: CreateRevenueCatClientOptions): createClient.PathBasedClient<paths, `${string}/${string}`>;
8
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,EAAE,EACnB,KAAK,aAAa,EAEnB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAGzE,YAAY,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AAElC,MAAM,MAAM,6BAA6B,GAAG,aAAa,GAAG;IAC1D,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAOF,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,6BAA6B,8DA2BxC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,EAAE,EACnB,KAAK,aAAa,EAEnB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAEzE,YAAY,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AAElC,MAAM,MAAM,6BAA6B,GAAG,aAAa,CAAC;AAM1D,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,6BAA6B,8DAuBxC"}
package/dist/index.js CHANGED
@@ -35,17 +35,15 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createRevenueCatClient = createRevenueCatClient;
37
37
  const openapi_fetch_1 = __importStar(require("openapi-fetch"));
38
- const rateLimitMiddleware_1 = require("./rateLimitMiddleware");
39
38
  const defaultOptions = {
40
39
  baseUrl: "https://api.revenuecat.com/v2",
41
- automaticRateLimit: false,
42
40
  };
43
41
  function createRevenueCatClient(accessToken, options) {
44
42
  if (!accessToken) {
45
43
  // For non-TS users, we'll throw an error if the accessToken is not provided
46
44
  throw new Error("accessToken is required");
47
45
  }
48
- const { automaticRateLimit, headers, ...otherOptions } = {
46
+ const { headers, ...otherOptions } = {
49
47
  ...defaultOptions,
50
48
  ...options,
51
49
  };
@@ -57,8 +55,5 @@ function createRevenueCatClient(accessToken, options) {
57
55
  },
58
56
  });
59
57
  const pathBasedClient = (0, openapi_fetch_1.wrapAsPathBasedClient)(client);
60
- if (automaticRateLimit) {
61
- client.use((0, rateLimitMiddleware_1.createRateLimitMiddleware)());
62
- }
63
58
  return pathBasedClient;
64
59
  }
package/eslint.config.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  import js from "@eslint/js";
2
- import globals from "globals";
3
- import tseslint from "typescript-eslint";
4
2
  import { defineConfig } from "eslint/config";
3
+ import tseslint from "typescript-eslint";
5
4
 
6
-
7
- export default defineConfig([
8
- { files: ["**/*.{js,mjs,cjs,ts,mts,cts}"], plugins: { js }, extends: ["js/recommended"] },
9
- { files: ["**/*.{js,mjs,cjs,ts,mts,cts}"], languageOptions: { globals: globals.node } },
5
+ export default defineConfig(
6
+ {
7
+ ignores: ["**/node_modules/**", "**/dist/**", "src/__generated/**"],
8
+ },
9
+ js.configs.recommended,
10
10
  tseslint.configs.recommended,
11
- ]);
11
+ );
package/package.json CHANGED
@@ -1,9 +1,19 @@
1
1
  {
2
2
  "name": "revenuecat-api",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "Type-safe RevenueCat API client using fetch with automatic rate limiting",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "prepack": "pnpm generate:openapi && tsc && cp -R ./src/__generated ./dist/",
9
+ "test": "vitest --no-watch",
10
+ "test:watch": "vitest",
11
+ "types:check": "tsc --noEmit",
12
+ "lint": "eslint .",
13
+ "lint:fix": "eslint . --fix",
14
+ "update:openapi": "rm downloaded/openapi.yaml && pnpm generate:openapi",
15
+ "generate:openapi": "scripts/generate_openapi_client.sh"
16
+ },
7
17
  "keywords": [
8
18
  "revenuecat",
9
19
  "revenue-cat",
@@ -18,26 +28,17 @@
18
28
  "type": "git",
19
29
  "url": "git+https://github.com/idolize/revenuecat-api.git"
20
30
  },
31
+ "packageManager": "pnpm@11.2.2",
21
32
  "dependencies": {
22
- "openapi-fetch": "^0.14.1"
33
+ "openapi-fetch": "^0.17.0"
23
34
  },
24
35
  "devDependencies": {
25
- "@eslint/js": "^9.37.0",
26
- "@types/node": "^24.7.1",
27
- "eslint": "^9.37.0",
28
- "globals": "^16.4.0",
29
- "openapi-typescript": "^7.9.1",
30
- "typescript": "^5.9.3",
31
- "typescript-eslint": "^8.46.0",
32
- "vitest": "^3.2.4"
33
- },
34
- "scripts": {
35
- "test": "vitest --no-watch",
36
- "test:watch": "vitest",
37
- "types:check": "tsc --noEmit",
38
- "lint": "eslint ./src/**",
39
- "lint:fix": "eslint ./src/** --fix",
40
- "update:openapi": "rm downloaded/openapi.yaml && pnpm generate:openapi",
41
- "generate:openapi": "scripts/generate_openapi_client.sh"
36
+ "@eslint/js": "^10.0.1",
37
+ "@types/node": "^25.9.1",
38
+ "eslint": "^10.4.0",
39
+ "openapi-typescript": "^7.13.0",
40
+ "typescript": "^6.0.3",
41
+ "typescript-eslint": "^8.59.4",
42
+ "vitest": "^4.1.7"
42
43
  }
43
- }
44
+ }
@@ -1,2 +1,4 @@
1
+ allowBuilds:
2
+ esbuild: true
1
3
  onlyBuiltDependencies:
2
4
  - msw
File without changes
@@ -0,0 +1,100 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { createRevenueCatClient } from "../src/index.js";
3
+
4
+ const mockFetch = vi.fn<(input: Request) => Promise<Response>>();
5
+
6
+ const listProjectsResponse = {
7
+ object: "list" as const,
8
+ items: [
9
+ {
10
+ object: "project" as const,
11
+ id: "proj1ab2c3d4",
12
+ name: "Test Project",
13
+ created_at: 1658399423658,
14
+ },
15
+ ],
16
+ next_page: null,
17
+ url: "/v2/projects",
18
+ };
19
+
20
+ describe("createRevenueCatClient", () => {
21
+ afterEach(() => {
22
+ vi.resetAllMocks();
23
+ });
24
+
25
+ it("throws when accessToken is missing", () => {
26
+ expect(() => createRevenueCatClient("")).toThrow("accessToken is required");
27
+ });
28
+
29
+ it("exposes path-based endpoints from the generated OpenAPI spec", () => {
30
+ const client = createRevenueCatClient("secret-token", { fetch: mockFetch });
31
+
32
+ expect(client["/projects"]).toBeDefined();
33
+ expect(client["/projects"].GET).toBeTypeOf("function");
34
+ expect(client["/projects"].POST).toBeTypeOf("function");
35
+ });
36
+
37
+ it("sends requests to the default base URL with Bearer auth", async () => {
38
+ mockFetch.mockResolvedValue(
39
+ new Response(JSON.stringify(listProjectsResponse), {
40
+ status: 200,
41
+ headers: { "Content-Type": "application/json" },
42
+ }),
43
+ );
44
+
45
+ const client = createRevenueCatClient("secret-token", { fetch: mockFetch });
46
+ const { data, error } = await client["/projects"].GET();
47
+
48
+ expect(error).toBeUndefined();
49
+ expect(data).toEqual(listProjectsResponse);
50
+ expect(mockFetch).toHaveBeenCalledOnce();
51
+
52
+ const request = mockFetch.mock.calls[0]![0];
53
+ expect(request.url).toBe("https://api.revenuecat.com/v2/projects");
54
+ expect(request.method).toBe("GET");
55
+ expect(request.headers.get("Authorization")).toBe("Bearer secret-token");
56
+ });
57
+
58
+ it("merges custom baseUrl and headers", async () => {
59
+ mockFetch.mockResolvedValue(
60
+ new Response(JSON.stringify(listProjectsResponse), {
61
+ status: 200,
62
+ headers: { "Content-Type": "application/json" },
63
+ }),
64
+ );
65
+
66
+ const client = createRevenueCatClient("secret-token", {
67
+ fetch: mockFetch,
68
+ baseUrl: "https://custom.example.com/v2",
69
+ headers: { "X-Custom": "value" },
70
+ });
71
+
72
+ await client["/projects"].GET();
73
+
74
+ const request = mockFetch.mock.calls[0]![0];
75
+ expect(request.url).toBe("https://custom.example.com/v2/projects");
76
+ expect(request.headers.get("Authorization")).toBe("Bearer secret-token");
77
+ expect(request.headers.get("X-Custom")).toBe("value");
78
+ });
79
+
80
+ it("returns typed API errors from failed responses", async () => {
81
+ const errorBody = {
82
+ type: "authentication_error",
83
+ message: "Invalid API key",
84
+ doc_url: "https://errors.rev.cat/authentication-error",
85
+ };
86
+
87
+ mockFetch.mockResolvedValue(
88
+ new Response(JSON.stringify(errorBody), {
89
+ status: 401,
90
+ headers: { "Content-Type": "application/json" },
91
+ }),
92
+ );
93
+
94
+ const client = createRevenueCatClient("bad-token", { fetch: mockFetch });
95
+ const { data, error } = await client["/projects"].GET();
96
+
97
+ expect(data).toBeUndefined();
98
+ expect(error).toEqual(errorBody);
99
+ });
100
+ });
package/tsconfig.json CHANGED
@@ -1,114 +1,20 @@
1
1
  {
2
2
  "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- "lib": ["es2023"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "libReplacement": true, /* Enable lib replacement. */
18
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
-
28
- /* Modules */
29
- "module": "NodeNext", /* Specify what module code is generated. */
30
- // "rootDir": "./", /* Specify the root folder within your source files. */
31
- "moduleResolution": "NodeNext", /* Specify how TypeScript looks up a file from a given module specifier. */
32
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
37
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
40
- "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
41
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
42
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
43
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
44
- // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
45
- "resolveJsonModule": true, /* Enable importing .json files. */
46
- "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
47
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
48
-
49
- /* JavaScript Support */
50
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
51
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
52
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
53
-
54
- /* Emit */
55
- "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
56
- "declarationMap": true, /* Create sourcemaps for d.ts files. */
57
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
58
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
59
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60
- // "noEmit": true, /* Disable emitting files from a compilation. */
61
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
62
- "outDir": "./dist", /* Specify an output folder for all emitted files. */
63
- // "removeComments": true, /* Disable emitting comments. */
64
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
65
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
66
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
67
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
68
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
69
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
70
- // "newLine": "crlf", /* Set the newline character for emitting files. */
71
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
72
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
73
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
74
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
75
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
76
-
77
- /* Interop Constraints */
78
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
79
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
80
- // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
81
- // "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
82
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
83
- // "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
84
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
85
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
86
-
87
- /* Type Checking */
88
- "strict": true, /* Enable all strict type-checking options. */
89
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
90
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
91
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
92
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
93
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
94
- // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
95
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
96
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
97
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
98
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
99
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
100
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
101
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
102
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
103
- "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
104
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
105
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
106
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
107
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
108
-
109
- /* Completeness */
110
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
111
- // "skipLibCheck": true /* Skip type checking all .d.ts files. */
3
+ "target": "es2022",
4
+ "lib": ["es2023"],
5
+ "types": ["node"],
6
+ "module": "NodeNext",
7
+ "rootDir": "./src",
8
+ "moduleResolution": "NodeNext",
9
+ "rewriteRelativeImportExtensions": true,
10
+ "resolveJsonModule": true,
11
+ "allowArbitraryExtensions": true,
12
+ "declaration": true,
13
+ "declarationMap": true,
14
+ "outDir": "./dist",
15
+ "forceConsistentCasingInFileNames": true,
16
+ "strict": true,
17
+ "noUncheckedIndexedAccess": true
112
18
  },
113
19
  "include": ["./src"]
114
20
  }
@@ -1,3 +0,0 @@
1
- import { Middleware } from "openapi-fetch";
2
- export declare const createRateLimitMiddleware: () => Middleware;
3
- //# sourceMappingURL=rateLimitMiddleware.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rateLimitMiddleware.d.ts","sourceRoot":"","sources":["../src/rateLimitMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAoM3C,eAAO,MAAM,yBAAyB,QAAO,UAuB5C,CAAC"}
@@ -1,160 +0,0 @@
1
- "use strict";
2
- // https://www.revenuecat.com/docs/api-v2#tag/Rate-Limit
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.createRateLimitMiddleware = void 0;
5
- class RateLimitManager {
6
- async delay(ms) {
7
- return new Promise((resolve) => setTimeout(resolve, ms));
8
- }
9
- endpointStates = new Map();
10
- maxRetries = 3;
11
- maxQueueSize = 100;
12
- getEndpointKey(request) {
13
- const url = new URL(request.url);
14
- return `${request.method}:${url.pathname}`;
15
- }
16
- getRetryAfterTime(response) {
17
- const retryAfter = response.headers.get("Retry-After");
18
- if (retryAfter) {
19
- const seconds = parseInt(retryAfter, 10);
20
- if (!isNaN(seconds)) {
21
- return seconds;
22
- }
23
- }
24
- // Fallback to 1 second if no valid Retry-After header
25
- return 1;
26
- }
27
- async isRetryable(response) {
28
- try {
29
- // Clone the response to avoid consuming the body
30
- const clonedResponse = response.clone();
31
- const body = await clonedResponse.json();
32
- // Check if retryable field exists and is false
33
- if (typeof body === "object" && body !== null && "retryable" in body) {
34
- return body.retryable !== false;
35
- }
36
- // Default to retryable if no retryable field is present
37
- return true;
38
- }
39
- catch {
40
- // If we can't parse the JSON, default to retryable
41
- return true;
42
- }
43
- }
44
- async waitForThrottle(request) {
45
- const endpointKey = this.getEndpointKey(request);
46
- // Initialize endpoint state if it doesn't exist
47
- if (!this.endpointStates.has(endpointKey)) {
48
- this.endpointStates.set(endpointKey, {
49
- isThrottled: false,
50
- retryAfter: 0,
51
- queue: [],
52
- lastRetryTime: 0,
53
- processing: false,
54
- });
55
- }
56
- const state = this.endpointStates.get(endpointKey);
57
- // If throttled, wait for the retry-after time
58
- if (state.isThrottled) {
59
- const now = Date.now();
60
- const waitTime = state.lastRetryTime + state.retryAfter * 1000 - now;
61
- if (waitTime > 0) {
62
- await this.delay(waitTime);
63
- }
64
- state.isThrottled = false;
65
- }
66
- }
67
- async handleResponse(request, response) {
68
- if (response.status !== 429) {
69
- return response;
70
- }
71
- // Check if the response indicates it's not retryable
72
- const shouldRetry = await this.isRetryable(response);
73
- if (!shouldRetry) {
74
- // If not retryable, return the original response immediately
75
- return response;
76
- }
77
- const endpointKey = this.getEndpointKey(request);
78
- // Initialize endpoint state if it doesn't exist
79
- if (!this.endpointStates.has(endpointKey)) {
80
- this.endpointStates.set(endpointKey, {
81
- isThrottled: false,
82
- retryAfter: 0,
83
- queue: [],
84
- lastRetryTime: 0,
85
- processing: false,
86
- });
87
- }
88
- const state = this.endpointStates.get(endpointKey);
89
- let retryAfter = this.getRetryAfterTime(response);
90
- state.isThrottled = true;
91
- state.retryAfter = retryAfter;
92
- state.lastRetryTime = Date.now();
93
- let lastResponse = response;
94
- for (let attempt = 0; attempt < this.maxRetries; attempt++) {
95
- // Wait for the retry-after time
96
- await this.delay(retryAfter * 1000);
97
- try {
98
- const retryResponse = await fetch(request, {});
99
- if (retryResponse.status !== 429) {
100
- // Success, clear throttled state and return
101
- state.isThrottled = false;
102
- return retryResponse;
103
- }
104
- // Check if the retry response is also not retryable
105
- const shouldRetryAgain = await this.isRetryable(retryResponse);
106
- if (!shouldRetryAgain) {
107
- // If not retryable, return the response immediately
108
- state.isThrottled = false;
109
- return retryResponse;
110
- }
111
- // If still 429, update retryAfter for next attempt
112
- retryAfter = this.getRetryAfterTime(retryResponse);
113
- state.retryAfter = retryAfter;
114
- state.lastRetryTime = Date.now();
115
- lastResponse = retryResponse;
116
- }
117
- catch (error) {
118
- // If fetch fails, throw the error
119
- state.isThrottled = false;
120
- throw error;
121
- }
122
- }
123
- // All retries exhausted, return the last 429 response
124
- state.isThrottled = false;
125
- return lastResponse;
126
- }
127
- getQueueSize(request) {
128
- const endpointKey = this.getEndpointKey(request);
129
- const state = this.endpointStates.get(endpointKey);
130
- return state?.queue.length || 0;
131
- }
132
- warnIfQueueTooLarge(request) {
133
- const queueSize = this.getQueueSize(request);
134
- if (queueSize >= this.maxQueueSize) {
135
- const endpointKey = this.getEndpointKey(request);
136
- console.warn(`[RevenueCat API] Rate limit queue for ${endpointKey} has reached maximum size of ${this.maxQueueSize}. Consider implementing additional throttling.`);
137
- }
138
- }
139
- }
140
- const createRateLimitMiddleware = () => {
141
- const rateLimitManager = new RateLimitManager();
142
- return {
143
- async onRequest({ request }) {
144
- // Wait if the endpoint is currently throttled
145
- await rateLimitManager.waitForThrottle(request);
146
- // Warn if queue is getting too large
147
- rateLimitManager.warnIfQueueTooLarge(request);
148
- // Don't return anything - let the request proceed normally
149
- return undefined;
150
- },
151
- async onResponse({ request, response }) {
152
- // Handle 429 responses with retry logic
153
- if (response.status === 429) {
154
- return await rateLimitManager.handleResponse(request, response);
155
- }
156
- return undefined;
157
- },
158
- };
159
- };
160
- exports.createRateLimitMiddleware = createRateLimitMiddleware;