| 23 | |
| 24 | /** Parse a simple KEY=value env file. Tolerates `export KEY=value`, quotes, blank lines, #comments. */ |
| 25 | export function parseEnvFile(text: string): Record<string, string> { |
| 26 | const out: Record<string, string> = {}; |
| 27 | for (const rawLine of text.split('\n')) { |
| 28 | const line = rawLine.trim(); |
| 29 | if (!line || line.startsWith('#')) continue; |
| 30 | const body = line.startsWith('export ') ? line.slice(7).trim() : line; |
| 31 | const eq = body.indexOf('='); |
| 32 | if (eq <= 0) continue; |
| 33 | const key = body.slice(0, eq).trim(); |
| 34 | let val = body.slice(eq + 1).trim(); |
| 35 | if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { |
| 36 | val = val.slice(1, -1); |
| 37 | } |
| 38 | if (key) out[key] = val; |
| 39 | } |
| 40 | return out; |
| 41 | } |
| 42 | |
| 43 | /** Serialize a key→value map back to env-file text (sorted for stable diffs). */ |
| 44 | export function serializeEnvFile(vars: Record<string, string>): string { |