@splashcodex/api-key-manager 5.2.0 → 5.4.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/README.md CHANGED
@@ -1,206 +1,211 @@
1
- # @splashcodex/ApiKeyManager v5.0 — Ecosystem Edition
2
-
3
- > Universal API Key Management Gateway with Provider Presets, Built-in Persistence, and Multi-Provider Vault.
4
-
5
- [![npm version](https://img.shields.io/npm/v/@splashcodex/ApiKeyManager)](https://www.npmjs.com/package/@splashcodex/ApiKeyManager)
6
-
7
- ## New in v5.0 (Ecosystem Edition)
8
-
9
- - **Provider Presets** — One-line setup for `GeminiManager`, `OpenAIManager`, and `MultiManager`.
10
- - **Automatic Env Parsing** — Reads `GOOGLE_GEMINI_API_KEY`, `OPENAI_API_KEY`, etc. (supports JSON arrays and comma-separated strings).
11
- - **Built-in Persistence** — `FileStorage` (survives restarts) and `MemoryStorage` included.
12
- - **Singleton Pattern** Thread-safe singletons with `getInstance()` and `Result<T>` pattern.
13
- - **Multi-Provider Vault** — Manage multiple providers (`gemini`, `openai`, `anthropic`) from a single entry point.
14
- - **Centralized API Gateway** — Built-in Fastify proxy server to centralize AI requests for multiple apps securely.
15
-
16
- ## Features
17
-
18
- - **Circuit Breaker** — Keys transition through `CLOSED OPEN HALF_OPEN DEAD`
19
- - **Error Classification** — Automatic detection of 429 (Quota), 403 (Auth), 5xx (Transient), Timeout, Safety blocks
20
- - **Pluggable Strategies** — `StandardStrategy`, `WeightedStrategy`, `LatencyStrategy`
21
- - **`execute()` Wrapper** — Single method: get key → call → latency → retry → fallback
22
- - **Event Emitter** — Typed lifecycle hooks for monitoring & alerting
23
- - **Auto-Retry with Backoff** — Built-in retry loop with exponential backoff + jitter
24
- - **Semantic Cache** — Cosine-similarity cache with pluggable embeddings
25
- - **Streaming Support** — `executeStream()` with initial retry + cache replay
26
- - **100% Backward Compatible** — v1.x through v4.x code works without changes
27
-
28
- ## Installation
29
-
30
- ```bash
31
- npm install @splashcodex/api-key-manager
32
- ```
33
-
34
- ### 🚀 Auto-Scaffold (New!)
35
- The fastest way to get started is to run the `init` command in your project directory:
36
- ```bash
37
- npx @splashcodex/api-key-manager init
38
- ```
39
- This will automatically create a `.env` template and a `demo.ts` file showing the Gemini Preset in action.
40
-
41
- ## Quick Start (v5 Presets)
42
-
43
- The fastest way to get started in any CodeDex repository.
44
-
45
- ### Gemini Preset
46
- Reads `GOOGLE_GEMINI_API_KEY` or `GEMINI_API_KEY` from environment.
47
-
48
- ```typescript
49
- import { GeminiManager } from '@splashcodex/api-key-manager/presets/gemini';
50
-
51
- const result = GeminiManager.getInstance();
52
- if (!result.success) throw result.error;
53
-
54
- const gemini = result.data;
55
- const response = await gemini.execute(async (key) => {
56
- // result.data is the underlying ApiKeyManager
57
- return await callGemini(key, "Hello!");
58
- });
59
- ```
60
-
61
- ### Centralized API Gateway (New!)
62
-
63
- Run a standalone proxy server that acts as a single point of entry for all your microservices or repositories. It centralizes key management, circuit breaking, and rate limiting across applications.
64
-
65
- 1. Install global/local and export your keys:
66
- ```bash
67
- export GOOGLE_GEMINI_API_KEY="AIzaSy...1,AIzaSy...2"
68
- ```
69
-
70
- 2. Start the gateway:
71
- ```bash
72
- npm run gateway
73
- # Server runs on http://localhost:9000
74
- ```
75
-
76
- 3. Call the proxy from ANY language without managing keys in the client app:
77
- ```bash
78
- curl -X POST http://localhost:9000/v1/generate \
79
- -H "Content-Type: application/json" \
80
- -d '{"provider": "gemini", "prompt": "Hello!"}'
81
- ```
82
- Route supports both `/v1/generate` (Standard JSON) and `/v1/stream` (Server-Sent Events). Monitoring available at `/v1/health` and `/v1/providers`.
83
-
84
- ---
85
-
86
- ### Multi-Provider Vault
87
-
88
- Manage ALL your provider keys across your system from one pool.Perfect for gateways or complex bots handling multiple models.
89
-
90
- ```typescript
91
- import { MultiManager } from '@splashcodex/api-key-manager/presets/multi';
92
-
93
- const vault = MultiManager.getInstance({
94
- providers: {
95
- gemini: { envKeys: ['GOOGLE_GEMINI_API_KEY'] },
96
- openai: { envKeys: ['OPENAI_API_KEY'] }
97
- }
98
- }).data!;
99
-
100
- // Route by provider
101
- const res = await vault.execute(fn, { provider: 'gemini' });
102
- ```
103
-
104
- ---
105
-
106
- ## v5.0 Architecture & Persistence
107
-
108
- ### Built-in Persistence
109
- State (cooling down keys, dead keys) now survives application restarts by default.
110
-
111
- ```typescript
112
- import { FileStorage } from '@splashcodex/api-key-manager/persistence/file';
113
-
114
- const manager = new ApiKeyManager(keys, {
115
- storage: new FileStorage({
116
- filePath: './api_state.json'
117
- })
118
- });
119
- ```
120
-
121
- ### Subpath Imports
122
- To keep your bundles small, you can import only what you need:
123
-
124
- ```typescript
125
- import { GeminiManager } from '@splashcodex/api-key-manager/presets/gemini';
126
- import { FileStorage } from '@splashcodex/api-key-manager/persistence/file';
127
- ```
128
-
129
- ---
130
-
131
- ## v4.0 Semantic Cache
132
-
133
- Automatically cache API responses by semantic similarity.
134
-
135
- ```typescript
136
- const manager = new ApiKeyManager(['key1', 'key2'], {
137
- semanticCache: {
138
- threshold: 0.92,
139
- getEmbedding: async (text) => await myModel.embed(text)
140
- }
141
- });
142
-
143
- // Cache HIT if prompt is semantically similar
144
- const r1 = await manager.execute(apiFn, { prompt: 'What is the weather?' });
145
- const r2 = await manager.execute(apiFn, { prompt: 'How is the weather today?' });
146
- ```
147
-
148
- ### v4.1 Streaming Support
149
- Real-time response handling with the same resilience as `execute()`.
150
-
151
- ```typescript
152
- const stream = await manager.executeStream(async (key) => {
153
- return await gemini.generateContentStream({ prompt: "..." });
154
- }, { prompt: "..." });
155
-
156
- for await (const chunk of stream) {
157
- console.log(chunk.text());
158
- }
159
- ```
160
-
161
- ---
162
-
163
- ## execute() Wrapper
164
-
165
- Wraps the entire lifecycle into one method:
166
-
167
- ```typescript
168
- const result = await manager.execute(
169
- async (key, signal) => {
170
- const res = await fetch(url, { headers: { 'x-api-key': key }, signal });
171
- return res.json();
172
- },
173
- { maxRetries: 3, timeoutMs: 10000 }
174
- );
175
- ```
176
-
177
- ## API Reference
178
-
179
- ### Presets
180
-
181
- | Class | Env Vars | Description |
182
- |-------|----------|-------------|
183
- | `GeminiManager` | `GOOGLE_GEMINI_API_KEY`, `GEMINI_API_KEY` | Gemini-optimized singleton |
184
- | `OpenAIManager` | `OPENAI_API_KEY` | OpenAI-optimized singleton |
185
- | `MultiManager` | Custom | Vault for multiple provider pools |
186
-
187
- ### Persistence
188
-
189
- | Class | Description |
190
- |-------|-------------|
191
- | `FileStorage` | Persists to a JSON file (recommended for servers) |
192
- | `MemoryStorage` | In-memory only (best for serverless/short-lived) |
193
-
194
- ### Core Methods
195
-
196
- | Method | Description |
197
- |--------|-------------|
198
- | `execute(fn, opts)` | Standard wrapper |
199
- | `executeStream(fn, opts)` | Streaming wrapper |
200
- | `getStats()` | Get pool health |
201
- | `getKey()` | Manual key rotation |
202
- | `markFailed(key, err)` | Manual failure reporting |
203
-
204
- ## License
205
-
206
- ISC
1
+ # @splashcodex/ApiKeyManager v5.0 — Ecosystem Edition
2
+
3
+ > Universal API Key Management Gateway with Provider Presets, Built-in Persistence, and Multi-Provider Vault.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@splashcodex/ApiKeyManager)](https://www.npmjs.com/package/@splashcodex/ApiKeyManager)
6
+
7
+ ## New in v5.3.0 (Resilience Upgrade)
8
+ - **Bulkhead Queueing (`cockatiel`)** — Safely handle traffic spikes. Requests that exceed your `concurrency` limit are queued (up to `concurrencyQueueSize`) rather than immediately rejected!
9
+ - **Strict Configuration Validation (`zod`)** — Deep runtime validation on all initialization options.
10
+ - **Improved Gateway SSE Parser** — Uses `eventsource-parser` for 100% reliable Server-Sent Events proxying.
11
+
12
+ ## Features in v5.0 (Ecosystem Edition)
13
+
14
+ - **Provider Presets** — One-line setup for `GeminiManager`, `OpenAIManager`, and `MultiManager`.
15
+ - **Automatic Env Parsing** — Reads `GOOGLE_GEMINI_API_KEY`, `OPENAI_API_KEY`, etc. (supports JSON arrays and comma-separated strings) from any OS directory smoothly.
16
+ - **Built-in Persistence** — `FileStorage` (survives restarts) and `MemoryStorage` included.
17
+ - **Singleton Pattern** — Thread-safe singletons with `getInstance()` and `Result<T>` pattern.
18
+ - **Multi-Provider Vault** — Manage multiple providers (`gemini`, `openai`, `anthropic`) from a single entry point.
19
+ - **Centralized API Gateway** — Built-in Fastify proxy server to centralize AI requests for multiple apps securely.
20
+
21
+ ## Core Features
22
+
23
+ - **Circuit Breaker** — Keys transition through `CLOSED OPEN HALF_OPEN → DEAD`
24
+ - **Error Classification** — Automatic detection of 429 (Quota), 403 (Auth), 5xx (Transient), Timeout, Safety blocks
25
+ - **Pluggable Strategies** — `StandardStrategy`, `WeightedStrategy`, `LatencyStrategy`
26
+ - **`execute()` Wrapper** — Single method: get key call → latency → retry → fallback
27
+ - **Event Emitter** — Typed lifecycle hooks for monitoring & alerting
28
+ - **Auto-Retry with Backoff** — Built-in retry loop with exponential backoff + jitter
29
+ - **Semantic Cache** — Cosine-similarity cache with pluggable embeddings
30
+ - **Streaming Support** — `executeStream()` with initial retry + cache replay
31
+ - **100% Backward Compatible** — v1.x through v4.x code works without changes
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ npm install @splashcodex/api-key-manager
37
+ ```
38
+
39
+ ### 🚀 Auto-Scaffold (New!)
40
+ The fastest way to get started is to run the `init` command in your project directory:
41
+ ```bash
42
+ npx @splashcodex/api-key-manager init
43
+ ```
44
+ This will automatically create a `.env` template and a `demo.ts` file showing the Gemini Preset in action.
45
+
46
+ ## Quick Start (v5 Presets)
47
+
48
+ The fastest way to get started in any CodeDex repository.
49
+
50
+ ### Gemini Preset
51
+ Reads `GOOGLE_GEMINI_API_KEY` or `GEMINI_API_KEY` from environment.
52
+
53
+ ```typescript
54
+ import { GeminiManager } from '@splashcodex/api-key-manager/presets/gemini';
55
+
56
+ const result = GeminiManager.getInstance();
57
+ if (!result.success) throw result.error;
58
+
59
+ const gemini = result.data;
60
+ const response = await gemini.execute(async (key) => {
61
+ // result.data is the underlying ApiKeyManager
62
+ return await callGemini(key, "Hello!");
63
+ });
64
+ ```
65
+
66
+ ### Centralized API Gateway (New!)
67
+
68
+ Run a standalone proxy server that acts as a single point of entry for all your microservices or repositories. It centralizes key management, circuit breaking, and rate limiting across applications.
69
+
70
+ 1. Install global/local and export your keys:
71
+ ```bash
72
+ export GOOGLE_GEMINI_API_KEY="AIzaSy...1,AIzaSy...2"
73
+ ```
74
+
75
+ 2. Start the gateway:
76
+ ```bash
77
+ npm run gateway
78
+ # Server runs on http://localhost:9000
79
+ ```
80
+
81
+ 3. Call the proxy from ANY language without managing keys in the client app:
82
+ ```bash
83
+ curl -X POST http://localhost:9000/v1/generate \
84
+ -H "Content-Type: application/json" \
85
+ -d '{"provider": "gemini", "prompt": "Hello!"}'
86
+ ```
87
+ Route supports both `/v1/generate` (Standard JSON) and `/v1/stream` (Server-Sent Events). Monitoring available at `/v1/health` and `/v1/providers`.
88
+
89
+ ---
90
+
91
+ ### Multi-Provider Vault
92
+
93
+ Manage ALL your provider keys across your system from one pool.Perfect for gateways or complex bots handling multiple models.
94
+
95
+ ```typescript
96
+ import { MultiManager } from '@splashcodex/api-key-manager/presets/multi';
97
+
98
+ const vault = MultiManager.getInstance({
99
+ providers: {
100
+ gemini: { envKeys: ['GOOGLE_GEMINI_API_KEY'] },
101
+ openai: { envKeys: ['OPENAI_API_KEY'] }
102
+ }
103
+ }).data!;
104
+
105
+ // Route by provider
106
+ const res = await vault.execute(fn, { provider: 'gemini' });
107
+ ```
108
+
109
+ ---
110
+
111
+ ## v5.0 — Architecture & Persistence
112
+
113
+ ### Built-in Persistence
114
+ State (cooling down keys, dead keys) now survives application restarts by default.
115
+
116
+ ```typescript
117
+ import { FileStorage } from '@splashcodex/api-key-manager/persistence/file';
118
+
119
+ const manager = new ApiKeyManager(keys, {
120
+ storage: new FileStorage({
121
+ filePath: './api_state.json'
122
+ })
123
+ });
124
+ ```
125
+
126
+ ### Subpath Imports
127
+ To keep your bundles small, you can import only what you need:
128
+
129
+ ```typescript
130
+ import { GeminiManager } from '@splashcodex/api-key-manager/presets/gemini';
131
+ import { FileStorage } from '@splashcodex/api-key-manager/persistence/file';
132
+ ```
133
+
134
+ ---
135
+
136
+ ## v4.0 Semantic Cache
137
+
138
+ Automatically cache API responses by semantic similarity.
139
+
140
+ ```typescript
141
+ const manager = new ApiKeyManager(['key1', 'key2'], {
142
+ semanticCache: {
143
+ threshold: 0.92,
144
+ getEmbedding: async (text) => await myModel.embed(text)
145
+ }
146
+ });
147
+
148
+ // Cache HIT if prompt is semantically similar
149
+ const r1 = await manager.execute(apiFn, { prompt: 'What is the weather?' });
150
+ const r2 = await manager.execute(apiFn, { prompt: 'How is the weather today?' });
151
+ ```
152
+
153
+ ### v4.1 Streaming Support
154
+ Real-time response handling with the same resilience as `execute()`.
155
+
156
+ ```typescript
157
+ const stream = await manager.executeStream(async (key) => {
158
+ return await gemini.generateContentStream({ prompt: "..." });
159
+ }, { prompt: "..." });
160
+
161
+ for await (const chunk of stream) {
162
+ console.log(chunk.text());
163
+ }
164
+ ```
165
+
166
+ ---
167
+
168
+ ## execute() Wrapper
169
+
170
+ Wraps the entire lifecycle into one method:
171
+
172
+ ```typescript
173
+ const result = await manager.execute(
174
+ async (key, signal) => {
175
+ const res = await fetch(url, { headers: { 'x-api-key': key }, signal });
176
+ return res.json();
177
+ },
178
+ { maxRetries: 3, timeoutMs: 10000 }
179
+ );
180
+ ```
181
+
182
+ ## API Reference
183
+
184
+ ### Presets
185
+
186
+ | Class | Env Vars | Description |
187
+ |-------|----------|-------------|
188
+ | `GeminiManager` | `GOOGLE_GEMINI_API_KEY`, `GEMINI_API_KEY` | Gemini-optimized singleton |
189
+ | `OpenAIManager` | `OPENAI_API_KEY` | OpenAI-optimized singleton |
190
+ | `MultiManager` | Custom | Vault for multiple provider pools |
191
+
192
+ ### Persistence
193
+
194
+ | Class | Description |
195
+ |-------|-------------|
196
+ | `FileStorage` | Persists to a JSON file (recommended for servers) |
197
+ | `MemoryStorage` | In-memory only (best for serverless/short-lived) |
198
+
199
+ ### Core Methods
200
+
201
+ | Method | Description |
202
+ |--------|-------------|
203
+ | `execute(fn, opts)` | Standard wrapper |
204
+ | `executeStream(fn, opts)` | Streaming wrapper |
205
+ | `getStats()` | Get pool health |
206
+ | `getKey()` | Manual key rotation |
207
+ | `markFailed(key, err)` | Manual failure reporting |
208
+
209
+ ## License
210
+
211
+ ISC