@splashcodex/api-key-manager 5.0.2 → 5.2.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.
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Centralized Environment Loader
3
+ *
4
+ * Loads environment variables from ~/codedex/env/ so that all 35+ projects
5
+ * share a single source of truth for secrets. Portable via Google Drive.
6
+ *
7
+ * Directory structure:
8
+ * ~/codedex/env/
9
+ * common.env — REDIS_URL, DATABASE_URL, shared across all projects
10
+ * llm.env — GEMINI_API_KEY, OPENAI_API_KEY (comma-separated or JSON arrays)
11
+ * stripe.env — STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET
12
+ * <custom>.env — Any additional groupings
13
+ *
14
+ * @module env/loader
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * // Load all env files from ~/codedex/env/
19
+ * import { loadCentralEnv } from '@splashcodex/api-key-manager/env';
20
+ * loadCentralEnv();
21
+ *
22
+ * // Now process.env has all the values
23
+ * console.log(process.env.GEMINI_API_KEY);
24
+ * ```
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * // Load specific files only
29
+ * import { loadCentralEnv } from '@splashcodex/api-key-manager/env';
30
+ * loadCentralEnv({ files: ['llm.env', 'common.env'] });
31
+ * ```
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * // Custom env directory (e.g., team-shared location)
36
+ * import { loadCentralEnv } from '@splashcodex/api-key-manager/env';
37
+ * loadCentralEnv({ envDir: '/shared/team/env' });
38
+ * ```
39
+ */
40
+
41
+ import { readFileSync, readdirSync, existsSync } from 'fs';
42
+ import { join } from 'path';
43
+ import { homedir } from 'os';
44
+
45
+ // ─── Types ───────────────────────────────────────────────────────────────────
46
+
47
+ export interface LoadCentralEnvOptions {
48
+ /**
49
+ * Path to the centralized env directory.
50
+ * Defaults to ~/codedex/env/
51
+ *
52
+ * Can also be set via CODEDEX_ENV_DIR environment variable.
53
+ */
54
+ envDir?: string;
55
+
56
+ /**
57
+ * Specific .env files to load (e.g., ['llm.env', 'common.env']).
58
+ * If omitted, loads ALL .env files in the directory.
59
+ */
60
+ files?: string[];
61
+
62
+ /**
63
+ * If true, central env values will NOT overwrite existing process.env values.
64
+ * Useful when a project needs to override a shared value locally.
65
+ * Default: false (central values take precedence over local .env)
66
+ */
67
+ preserveExisting?: boolean;
68
+
69
+ /**
70
+ * If true, silently continue when the env directory doesn't exist.
71
+ * If false, throw an error.
72
+ * Default: true (silent — for portability across dev environments)
73
+ */
74
+ silent?: boolean;
75
+ }
76
+
77
+ export interface LoadResult {
78
+ /** Whether the env directory was found and loaded */
79
+ loaded: boolean;
80
+ /** Path to the env directory that was used */
81
+ envDir: string;
82
+ /** List of .env files that were loaded */
83
+ filesLoaded: string[];
84
+ /** Number of environment variables set */
85
+ varsSet: number;
86
+ /** Variables that were skipped because they already existed (when preserveExisting=true) */
87
+ varsSkipped: string[];
88
+ }
89
+
90
+ // ─── Parser ──────────────────────────────────────────────────────────────────
91
+
92
+ /**
93
+ * Parse a .env file into key-value pairs.
94
+ * Supports:
95
+ * KEY=value
96
+ * KEY="quoted value"
97
+ * KEY='single quoted'
98
+ * # comments
99
+ * empty lines
100
+ * export KEY=value (bash-style)
101
+ */
102
+ function parseEnvFile(content: string): Map<string, string> {
103
+ const vars = new Map<string, string>();
104
+
105
+ for (const rawLine of content.split('\n')) {
106
+ const line = rawLine.trim();
107
+
108
+ // Skip empty lines and comments
109
+ if (!line || line.startsWith('#')) continue;
110
+
111
+ // Strip optional 'export ' prefix
112
+ const stripped = line.startsWith('export ') ? line.slice(7) : line;
113
+
114
+ // Find the first '=' that separates key from value
115
+ const eqIndex = stripped.indexOf('=');
116
+ if (eqIndex === -1) continue;
117
+
118
+ const key = stripped.slice(0, eqIndex).trim();
119
+ let value = stripped.slice(eqIndex + 1).trim();
120
+
121
+ // Strip surrounding quotes
122
+ if (
123
+ (value.startsWith('"') && value.endsWith('"')) ||
124
+ (value.startsWith("'") && value.endsWith("'"))
125
+ ) {
126
+ value = value.slice(1, -1);
127
+ }
128
+
129
+ // Skip empty keys
130
+ if (!key) continue;
131
+
132
+ vars.set(key, value);
133
+ }
134
+
135
+ return vars;
136
+ }
137
+
138
+ // ─── Loader ──────────────────────────────────────────────────────────────────
139
+
140
+ /**
141
+ * Default env directory path: ~/codedex/env/
142
+ */
143
+ export function getDefaultEnvDir(): string {
144
+ return process.env.CODEDEX_ENV_DIR || join(homedir(), 'codedex', 'env');
145
+ }
146
+
147
+ /**
148
+ * Load environment variables from the centralized env directory into process.env.
149
+ *
150
+ * Call this once at the top of your app's entry point, before any code
151
+ * that reads process.env.
152
+ */
153
+ export function loadCentralEnv(options: LoadCentralEnvOptions = {}): LoadResult {
154
+ const envDir = options.envDir || getDefaultEnvDir();
155
+ const silent = options.silent !== false;
156
+ const preserveExisting = options.preserveExisting === true;
157
+
158
+ const result: LoadResult = {
159
+ loaded: false,
160
+ envDir,
161
+ filesLoaded: [],
162
+ varsSet: 0,
163
+ varsSkipped: [],
164
+ };
165
+
166
+ // Check if directory exists
167
+ if (!existsSync(envDir)) {
168
+ if (!silent) {
169
+ throw new Error(
170
+ `Centralized env directory not found: ${envDir}\n` +
171
+ `Create it with: mkdir -p ${envDir}\n` +
172
+ `Or set CODEDEX_ENV_DIR to point to your env directory.`
173
+ );
174
+ }
175
+ return result;
176
+ }
177
+
178
+ // Determine which files to load
179
+ let filesToLoad: string[];
180
+ if (options.files) {
181
+ filesToLoad = options.files;
182
+ } else {
183
+ try {
184
+ filesToLoad = readdirSync(envDir)
185
+ .filter(f => f.endsWith('.env'))
186
+ .sort(); // Alphabetical order for deterministic loading
187
+ } catch {
188
+ if (!silent) throw new Error(`Cannot read env directory: ${envDir}`);
189
+ return result;
190
+ }
191
+ }
192
+
193
+ // Load each file
194
+ for (const fileName of filesToLoad) {
195
+ const filePath = join(envDir, fileName);
196
+
197
+ if (!existsSync(filePath)) {
198
+ if (!silent) {
199
+ throw new Error(`Env file not found: ${filePath}`);
200
+ }
201
+ continue;
202
+ }
203
+
204
+ try {
205
+ const content = readFileSync(filePath, 'utf-8');
206
+ const vars = parseEnvFile(content);
207
+
208
+ for (const [key, value] of vars) {
209
+ if (preserveExisting && process.env[key] !== undefined) {
210
+ result.varsSkipped.push(key);
211
+ continue;
212
+ }
213
+ process.env[key] = value;
214
+ result.varsSet++;
215
+ }
216
+
217
+ result.filesLoaded.push(fileName);
218
+ } catch (err) {
219
+ if (!silent) throw err;
220
+ }
221
+ }
222
+
223
+ result.loaded = result.filesLoaded.length > 0;
224
+ return result;
225
+ }
226
+
227
+ /**
228
+ * Read a single value from the centralized env without loading everything.
229
+ * Useful for one-off lookups.
230
+ */
231
+ export function getCentralEnvVar(key: string, options?: { envDir?: string }): string | undefined {
232
+ const envDir = options?.envDir || getDefaultEnvDir();
233
+
234
+ if (!existsSync(envDir)) return undefined;
235
+
236
+ try {
237
+ const files = readdirSync(envDir).filter(f => f.endsWith('.env')).sort();
238
+
239
+ for (const fileName of files) {
240
+ const content = readFileSync(join(envDir, fileName), 'utf-8');
241
+ const vars = parseEnvFile(content);
242
+ if (vars.has(key)) return vars.get(key);
243
+ }
244
+ } catch {
245
+ // Silent fail
246
+ }
247
+
248
+ return undefined;
249
+ }