import fs from 'fs'; export type EnvUpdateValue = string | null; const LINE_REGEX = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/; export function listEnvKeysFromFile(filePath: string): string[] { try { if (!fs.existsSync(filePath)) return []; const content = fs.readFileSync(filePath, 'utf8'); const keys: string[] = []; for (const line of content.split(/\r?\n/)) { const safeLine = line ?? ''; const trimmed = safeLine.trim(); if (!trimmed) continue; if (trimmed.startsWith('#')) continue; const match = safeLine.match(LINE_REGEX); if (match?.[1]) keys.push(match[1]); } return Array.from(new Set(keys)); } catch { return []; } } function encodeEnvValue(value: string): string { // Use JSON string escaping for safety, but avoid quotes for simple values. const v = String(value ?? ''); const needsQuoting = v === '' || /\s/.test(v) || /[#"'`]/.test(v) || /\r|\n/.test(v) || /=/.test(v); return needsQuoting ? JSON.stringify(v) : v; } export function upsertEnvFile(params: { filePath: string; updates: Record; }): { updatedKeys: string[] } { const { filePath, updates } = params; const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : ''; const lines = existing ? existing.split(/\r?\n/) : []; // Track all line indices for each key (to dedupe/remove) const indicesByKey = new Map(); for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (line === undefined) continue; const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('#')) continue; const match = line.match(LINE_REGEX); if (!match?.[1]) continue; const key = match[1]; const arr = indicesByKey.get(key) || []; arr.push(i); indicesByKey.set(key, arr); } const updatedKeys: string[] = []; for (const [rawKey, rawValue] of Object.entries(updates || {})) { const key = String(rawKey || '').trim(); if (!key) continue; const existingIndices = indicesByKey.get(key) || []; const value = rawValue; if (value === null) { // Remove all active occurrences for (const idx of existingIndices) { lines[idx] = ''; } if (existingIndices.length > 0) { updatedKeys.push(key); } continue; } const newLine = `${key}=${encodeEnvValue(String(value))}`; if (existingIndices.length === 0) { lines.push(newLine); updatedKeys.push(key); continue; } // Replace first, remove any duplicates const firstIdx = existingIndices[0]; if (firstIdx === undefined) { lines.push(newLine); updatedKeys.push(key); continue; } lines[firstIdx] = newLine; for (let j = 1; j < existingIndices.length; j++) { const idx = existingIndices[j]; if (idx === undefined) continue; lines[idx] = ''; } updatedKeys.push(key); } // Compact: keep comments/blank lines, but remove lines we blanked out. const compacted = lines.filter((l) => l !== ''); const output = compacted.join('\n') + '\n'; fs.writeFileSync(filePath, output, 'utf8'); return { updatedKeys: Array.from(new Set(updatedKeys)) }; }