octokit-load-balancer 1.0.1

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
+ MIT License
2
+
3
+ Copyright (c) 2026 Mert Ciflikli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # octokit-load-balancer
2
+
3
+ > Load balance across multiple GitHub App instances, always picking the one with most available rate limit
4
+
5
+ [![npm version](https://img.shields.io/npm/v/octokit-load-balancer.svg)](https://www.npmjs.com/package/octokit-load-balancer)
6
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+
8
+ ## Features
9
+
10
+ - **Multiple App Support** - Pool multiple GitHub Apps for higher aggregate rate limits
11
+ - **Smart Selection** - Always picks the app with the most available rate limit
12
+ - **Auto Key Detection** - Automatically detects raw PEM vs base64 encoded private keys
13
+ - **TypeScript First** - Full type definitions using Octokit types
14
+ - **Single Function API** - Just one function: `getApp`
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install octokit-load-balancer octokit @octokit/auth-app
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```typescript
25
+ import { getApp } from 'octokit-load-balancer';
26
+
27
+ const octokit = await getApp({
28
+ apps: [
29
+ {
30
+ appId: process.env.GH_APP_1_ID,
31
+ installationId: process.env.GH_APP_1_INSTALLATION_ID,
32
+ privateKey: process.env.GH_APP_1_KEY,
33
+ },
34
+ {
35
+ appId: process.env.GH_APP_2_ID,
36
+ installationId: process.env.GH_APP_2_INSTALLATION_ID,
37
+ privateKey: process.env.GH_APP_2_KEY,
38
+ },
39
+ ],
40
+ baseUrl: 'https://api.github.com',
41
+ });
42
+
43
+ await octokit.rest.repos.get({ owner: 'your-org', repo: 'your-repo' });
44
+ ```
45
+
46
+ ## How It Works
47
+
48
+ Every time you call `getApp(config)`:
49
+
50
+ 1. Creates Octokit instances for all valid app configs
51
+ 2. Fetches rate limits for all apps in parallel
52
+ 3. Returns the Octokit with the highest remaining rate limit
53
+
54
+ ## Options
55
+
56
+ | Option | Type | Required | Description |
57
+ | --------- | ------------------- | -------- | --------------------------- |
58
+ | `apps` | `GitHubAppConfig[]` | Yes | Array of app configurations |
59
+ | `baseUrl` | `string` | Yes | GitHub API base URL |
60
+
61
+ App configs use `GitHubAppConfig` (re-exported from `@octokit/auth-app`'s `StrategyOptions`). All apps must have valid `appId` and `privateKey` — incomplete configs will throw an error.
62
+
63
+ ## Comparison with @octokit/plugin-throttling
64
+
65
+ [`@octokit/plugin-throttling`](https://github.com/octokit/plugin-throttling.js) handles rate limits by queuing and retrying requests. This library takes a different approach: distribute load across multiple GitHub Apps to maximize available quota.
66
+
67
+ | | octokit-load-balancer | plugin-throttling |
68
+ | ------------------ | ---------------------------------- | ------------------------- |
69
+ | Strategy | Pick app with most remaining quota | Queue and retry on limits |
70
+ | Multiple apps | Yes | No |
71
+ | Handles exhaustion | Throws | Waits and retries |
72
+
73
+ Choose based on your situation:
74
+
75
+ - **Need more than 5000 requests/hour?** → Create multiple GitHub Apps and use this library to distribute load across them (N apps = N × 5000 req/hr)
76
+ - **Single app, need graceful handling?** → Use plugin-throttling to wait and retry
77
+
78
+ ## Debugging
79
+
80
+ Enable debug logs with the `DEBUG` environment variable:
81
+
82
+ ```bash
83
+ DEBUG=octokit-load-balancer node your-script.js
84
+ ```
85
+
86
+ Output:
87
+
88
+ ```
89
+ [octokit-load-balancer] Using 2 valid app configs
90
+ [octokit-load-balancer] Rate limits: app[0]: 4500/5000, app[1]: 4900/5000
91
+ [octokit-load-balancer] Selected app[1] with 4900/5000 remaining
92
+ ```
93
+
94
+ ## License
95
+
96
+ MIT
@@ -0,0 +1,66 @@
1
+ import { Octokit } from 'octokit';
2
+ import { StrategyOptions } from '@octokit/auth-app';
3
+
4
+ /**
5
+ * Configuration for a single GitHub App.
6
+ * Uses Octokit's StrategyOptions directly.
7
+ */
8
+ type GitHubAppConfig = StrategyOptions;
9
+ /**
10
+ * Rate limit data from GitHub API
11
+ */
12
+ interface RateLimitData {
13
+ limit: number;
14
+ used: number;
15
+ remaining: number;
16
+ reset: number;
17
+ }
18
+ /**
19
+ * Configuration for getApp
20
+ */
21
+ interface GitHubAppPoolConfig {
22
+ /** Array of app configurations */
23
+ apps: GitHubAppConfig[];
24
+ /** Base URL for the GitHub API (e.g., 'https://api.github.com' or 'https://github.company.com/api/v3') */
25
+ baseUrl: string;
26
+ }
27
+ /**
28
+ * Rate limit information for a GitHub App
29
+ */
30
+ interface RateLimitInfo extends RateLimitData {
31
+ /** Index of the app in the config array */
32
+ appIndex: number;
33
+ }
34
+
35
+ /**
36
+ * Get the Octokit instance with the most available rate limit.
37
+ * Pass your app configurations directly - incomplete configs are filtered out.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * import { getApp } from 'octokit-load-balancer'
42
+ *
43
+ * const octokit = await getApp({
44
+ * apps: [
45
+ * {
46
+ * appId: process.env.APP_1_ID,
47
+ * installationId: process.env.APP_1_INSTALLATION_ID,
48
+ * privateKey: process.env.APP_1_KEY,
49
+ * },
50
+ * {
51
+ * appId: process.env.APP_2_ID,
52
+ * installationId: process.env.APP_2_INSTALLATION_ID,
53
+ * privateKey: process.env.APP_2_KEY,
54
+ * },
55
+ * ],
56
+ * baseUrl: 'https://github.example.com/api/v3',
57
+ * })
58
+ *
59
+ * await octokit.rest.repos.get({ owner: 'org', repo: 'repo' })
60
+ * ```
61
+ *
62
+ * @throws {Error} When no valid app configurations are provided
63
+ */
64
+ declare function getApp(config: GitHubAppPoolConfig): Promise<Octokit>;
65
+
66
+ export { type GitHubAppConfig, type GitHubAppPoolConfig, type RateLimitData, type RateLimitInfo, getApp };
@@ -0,0 +1,66 @@
1
+ import { Octokit } from 'octokit';
2
+ import { StrategyOptions } from '@octokit/auth-app';
3
+
4
+ /**
5
+ * Configuration for a single GitHub App.
6
+ * Uses Octokit's StrategyOptions directly.
7
+ */
8
+ type GitHubAppConfig = StrategyOptions;
9
+ /**
10
+ * Rate limit data from GitHub API
11
+ */
12
+ interface RateLimitData {
13
+ limit: number;
14
+ used: number;
15
+ remaining: number;
16
+ reset: number;
17
+ }
18
+ /**
19
+ * Configuration for getApp
20
+ */
21
+ interface GitHubAppPoolConfig {
22
+ /** Array of app configurations */
23
+ apps: GitHubAppConfig[];
24
+ /** Base URL for the GitHub API (e.g., 'https://api.github.com' or 'https://github.company.com/api/v3') */
25
+ baseUrl: string;
26
+ }
27
+ /**
28
+ * Rate limit information for a GitHub App
29
+ */
30
+ interface RateLimitInfo extends RateLimitData {
31
+ /** Index of the app in the config array */
32
+ appIndex: number;
33
+ }
34
+
35
+ /**
36
+ * Get the Octokit instance with the most available rate limit.
37
+ * Pass your app configurations directly - incomplete configs are filtered out.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * import { getApp } from 'octokit-load-balancer'
42
+ *
43
+ * const octokit = await getApp({
44
+ * apps: [
45
+ * {
46
+ * appId: process.env.APP_1_ID,
47
+ * installationId: process.env.APP_1_INSTALLATION_ID,
48
+ * privateKey: process.env.APP_1_KEY,
49
+ * },
50
+ * {
51
+ * appId: process.env.APP_2_ID,
52
+ * installationId: process.env.APP_2_INSTALLATION_ID,
53
+ * privateKey: process.env.APP_2_KEY,
54
+ * },
55
+ * ],
56
+ * baseUrl: 'https://github.example.com/api/v3',
57
+ * })
58
+ *
59
+ * await octokit.rest.repos.get({ owner: 'org', repo: 'repo' })
60
+ * ```
61
+ *
62
+ * @throws {Error} When no valid app configurations are provided
63
+ */
64
+ declare function getApp(config: GitHubAppPoolConfig): Promise<Octokit>;
65
+
66
+ export { type GitHubAppConfig, type GitHubAppPoolConfig, type RateLimitData, type RateLimitInfo, getApp };
package/dist/index.js ADDED
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ getApp: () => getApp
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/pool.ts
28
+ var import_auth_app = require("@octokit/auth-app");
29
+ var import_octokit = require("octokit");
30
+ var DEBUG_KEY = "octokit-load-balancer";
31
+ async function getApp(config) {
32
+ if (!Array.isArray(config?.apps)) {
33
+ throw new Error("Invalid config: apps must be an array");
34
+ }
35
+ if (typeof config?.baseUrl !== "string") {
36
+ throw new Error("Invalid config: baseUrl must be a string");
37
+ }
38
+ if (config.apps.length === 0) {
39
+ throw new Error("Invalid config: apps array is empty");
40
+ }
41
+ const invalidApps = config.apps.filter((app) => !isCompleteConfig(app));
42
+ if (invalidApps.length > 0) {
43
+ throw new Error(
44
+ `Invalid config: ${invalidApps.length} app(s) missing required appId or privateKey`
45
+ );
46
+ }
47
+ const validApps = config.apps;
48
+ log(`Using ${validApps.length} valid app configs`);
49
+ const octokits = validApps.map((app) => createOctokit(app, config.baseUrl));
50
+ const rateLimits = await Promise.all(
51
+ octokits.map((o, i) => getRateLimit(o, i))
52
+ );
53
+ log(
54
+ "Rate limits:",
55
+ rateLimits.map((r) => `app[${r.appIndex}]: ${r.remaining}/${r.limit}`).join(", ")
56
+ );
57
+ const { bestIndex, rateLimit } = rateLimits.reduce(
58
+ (acc, cur, i) => {
59
+ if (cur.remaining > acc.rateLimit.remaining) {
60
+ return { bestIndex: i, rateLimit: cur };
61
+ }
62
+ return acc;
63
+ },
64
+ { bestIndex: 0, rateLimit: rateLimits[0] }
65
+ );
66
+ if (rateLimit.remaining === 0) {
67
+ throw new Error("All GitHub Apps have exhausted their rate limits");
68
+ }
69
+ log(
70
+ `Selected app[${bestIndex}] with ${rateLimit.remaining}/${rateLimit.limit} remaining`
71
+ );
72
+ return octokits[bestIndex];
73
+ }
74
+ function isCompleteConfig(config) {
75
+ return typeof config === "object" && config !== null && "appId" in config && "privateKey" in config && !!(config.appId && config.privateKey);
76
+ }
77
+ function decodePrivateKey(key) {
78
+ if (key.startsWith("-----BEGIN ") && key.includes("-----END ")) {
79
+ return key;
80
+ }
81
+ return Buffer.from(key, "base64").toString("utf-8");
82
+ }
83
+ function createOctokit(appConfig, baseUrl) {
84
+ return new import_octokit.Octokit({
85
+ authStrategy: import_auth_app.createAppAuth,
86
+ baseUrl: baseUrl || "https://api.github.com",
87
+ auth: {
88
+ appId: appConfig.appId,
89
+ installationId: appConfig.installationId,
90
+ privateKey: decodePrivateKey(appConfig.privateKey)
91
+ }
92
+ });
93
+ }
94
+ async function getRateLimit(octokit, index) {
95
+ const response = await octokit.rest.rateLimit.get();
96
+ return {
97
+ ...response.data.rate,
98
+ appIndex: index
99
+ };
100
+ }
101
+ function isDebugEnabled() {
102
+ const debug = process.env.DEBUG;
103
+ if (!debug) return false;
104
+ return debug === "*" || debug.includes(DEBUG_KEY);
105
+ }
106
+ function log(...args) {
107
+ if (isDebugEnabled()) {
108
+ console.log(`[${DEBUG_KEY}]`, ...args);
109
+ }
110
+ }
111
+ // Annotate the CommonJS export names for ESM import in node:
112
+ 0 && (module.exports = {
113
+ getApp
114
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,87 @@
1
+ // src/pool.ts
2
+ import { createAppAuth } from "@octokit/auth-app";
3
+ import { Octokit } from "octokit";
4
+ var DEBUG_KEY = "octokit-load-balancer";
5
+ async function getApp(config) {
6
+ if (!Array.isArray(config?.apps)) {
7
+ throw new Error("Invalid config: apps must be an array");
8
+ }
9
+ if (typeof config?.baseUrl !== "string") {
10
+ throw new Error("Invalid config: baseUrl must be a string");
11
+ }
12
+ if (config.apps.length === 0) {
13
+ throw new Error("Invalid config: apps array is empty");
14
+ }
15
+ const invalidApps = config.apps.filter((app) => !isCompleteConfig(app));
16
+ if (invalidApps.length > 0) {
17
+ throw new Error(
18
+ `Invalid config: ${invalidApps.length} app(s) missing required appId or privateKey`
19
+ );
20
+ }
21
+ const validApps = config.apps;
22
+ log(`Using ${validApps.length} valid app configs`);
23
+ const octokits = validApps.map((app) => createOctokit(app, config.baseUrl));
24
+ const rateLimits = await Promise.all(
25
+ octokits.map((o, i) => getRateLimit(o, i))
26
+ );
27
+ log(
28
+ "Rate limits:",
29
+ rateLimits.map((r) => `app[${r.appIndex}]: ${r.remaining}/${r.limit}`).join(", ")
30
+ );
31
+ const { bestIndex, rateLimit } = rateLimits.reduce(
32
+ (acc, cur, i) => {
33
+ if (cur.remaining > acc.rateLimit.remaining) {
34
+ return { bestIndex: i, rateLimit: cur };
35
+ }
36
+ return acc;
37
+ },
38
+ { bestIndex: 0, rateLimit: rateLimits[0] }
39
+ );
40
+ if (rateLimit.remaining === 0) {
41
+ throw new Error("All GitHub Apps have exhausted their rate limits");
42
+ }
43
+ log(
44
+ `Selected app[${bestIndex}] with ${rateLimit.remaining}/${rateLimit.limit} remaining`
45
+ );
46
+ return octokits[bestIndex];
47
+ }
48
+ function isCompleteConfig(config) {
49
+ return typeof config === "object" && config !== null && "appId" in config && "privateKey" in config && !!(config.appId && config.privateKey);
50
+ }
51
+ function decodePrivateKey(key) {
52
+ if (key.startsWith("-----BEGIN ") && key.includes("-----END ")) {
53
+ return key;
54
+ }
55
+ return Buffer.from(key, "base64").toString("utf-8");
56
+ }
57
+ function createOctokit(appConfig, baseUrl) {
58
+ return new Octokit({
59
+ authStrategy: createAppAuth,
60
+ baseUrl: baseUrl || "https://api.github.com",
61
+ auth: {
62
+ appId: appConfig.appId,
63
+ installationId: appConfig.installationId,
64
+ privateKey: decodePrivateKey(appConfig.privateKey)
65
+ }
66
+ });
67
+ }
68
+ async function getRateLimit(octokit, index) {
69
+ const response = await octokit.rest.rateLimit.get();
70
+ return {
71
+ ...response.data.rate,
72
+ appIndex: index
73
+ };
74
+ }
75
+ function isDebugEnabled() {
76
+ const debug = process.env.DEBUG;
77
+ if (!debug) return false;
78
+ return debug === "*" || debug.includes(DEBUG_KEY);
79
+ }
80
+ function log(...args) {
81
+ if (isDebugEnabled()) {
82
+ console.log(`[${DEBUG_KEY}]`, ...args);
83
+ }
84
+ }
85
+ export {
86
+ getApp
87
+ };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "octokit-load-balancer",
3
+ "version": "1.0.1",
4
+ "description": "Load balance across multiple GitHub App instances, always picking the one with most available rate limit",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup src/index.ts --format cjs,esm --dts",
20
+ "test": "vitest",
21
+ "test:coverage": "vitest --coverage",
22
+ "format": "prettier --write .",
23
+ "format:check": "prettier --check .",
24
+ "typecheck": "tsc --noEmit",
25
+ "prepublishOnly": "npm run build",
26
+ "publish:jsr": "npx jsr publish"
27
+ },
28
+ "keywords": [
29
+ "github",
30
+ "github-app",
31
+ "octokit",
32
+ "rate-limit",
33
+ "load-balancing",
34
+ "load-balancer",
35
+ "api"
36
+ ],
37
+ "author": "Mert Ciflikli",
38
+ "license": "MIT",
39
+ "bugs": {
40
+ "url": "https://github.com/frankie303/octokit-load-balancer/issues"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/frankie303/octokit-load-balancer"
45
+ },
46
+ "peerDependencies": {
47
+ "@octokit/auth-app": "^7.0.0",
48
+ "octokit": "^5.0.0"
49
+ },
50
+ "devDependencies": {
51
+ "@octokit/auth-app": "^7.2.2",
52
+ "@types/node": "^20.19.28",
53
+ "@vitest/coverage-v8": "^4.0.17",
54
+ "octokit": "^5.0.5",
55
+ "prettier": "^3.7.4",
56
+ "tsup": "^8.5.1",
57
+ "typescript": "^5.9.3",
58
+ "vitest": "^4.0.17"
59
+ },
60
+ "engines": {
61
+ "node": ">=20.0.0"
62
+ }
63
+ }