export default async (key, newValue) => { const envFile = Bun.file(`.env`); let content = ""; // 1. Read existing file if it exists if (await envFile.exists()) { content = await envFile.text(); } const lines = content.split("\n"); let keyFound = false; // Format the value: wrap in quotes if it contains spaces const safeValue = newValue.includes(" ") ? `"${newValue}"` : newValue; // 2. Scan lines to find and replace the key for (let i = 0; i < lines.length; i++) { const line = lines[i]; // Regex matches the key at the start of the line (ignoring leading spaces) const keyRegex = new RegExp(`^\\s*${key}\\s*=`); if (keyRegex.test(line)) { lines[i] = `${key}=${safeValue}`; keyFound = true; break; } } // 3. If the key wasn't found, append it to the end if (!keyFound) { // Prevent appending to the same line if the file didn't end with a newline if (lines.length > 0 && lines[lines.length - 1] !== "") { lines.push(""); } lines.push(`${key}=${safeValue}`); } // 4. Write the updated content back to the file await Bun.write(`.env`, lines.join("\n")); // 5. Update the live process environment so your app can use it immediately process.env[key] = newValue; // console.log(`✅ Set ${key} to newly updated value in ${ENV_PATH}`); }