wishforge-ide/scripts/env-file.mjs
eust-w 90a76f2d59 🐛 Make the local POC setup safe to rerun
- It allowed every IPv4 address of the en* interfaces as a web origin,
  public ones included; it now takes only private LAN addresses, as
  npm run local:network does.
- It rewrote .env.local in place, where a crash lost the generated
  secrets, and missed `export` assignments; the file is now replaced
  atomically through scripts/env-file.mjs.
- A binding file it could not read made it create a second project
  and environment; only a missing one means a first setup now.
- A runner registered for a replaced environment is registered again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:33:30 +08:00

49 lines
1.9 KiB
JavaScript

import { randomUUID } from 'node:crypto';
import { lstat, open, readFile, rename, rm } from 'node:fs/promises';
import path from 'node:path';
/**
* Sets values in the text of a .env file: an existing assignment, with or without `export`, is
* replaced where it stands and its duplicates dropped; a new one is appended.
*/
export function setEnvValues(source, values) {
const lines = source.split('\n');
if (lines.at(-1) === '') lines.pop();
for (const [key, value] of Object.entries(values)) {
if (!/^[A-Z_][A-Z0-9_]*$/.test(key) || /[\r\n]/.test(String(value)))
throw new Error(`Cannot write ${key} as a single-line setting`);
const assigns = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`);
const first = lines.findIndex(line => assigns.test(line));
if (first < 0) lines.push(`${key}=${value}`);
else {
lines[first] = `${key}=${value}`;
for (let index = lines.length - 1; index > first; index--) if (assigns.test(lines[index])) lines.splice(index, 1);
}
}
return `${lines.join('\n')}\n`;
}
/**
* Replaces a private .env file whole or not at all: the new text goes to a temporary file beside
* it (named like `.env.*.local`, which Git ignores) that then takes its place, unless the file
* changed meanwhile. A crash leaves either the old file or the new one, never half of either.
*/
export async function replaceEnvFile(file, expected, next) {
const temporary = path.join(path.dirname(file), `.env.update-${randomUUID()}.local`);
const handle = await open(temporary, 'wx', 0o600);
try {
await handle.writeFile(next);
await handle.sync();
} finally {
await handle.close();
}
try {
const latest = await lstat(file);
if (!latest.isFile() || (await readFile(file, 'utf8')) !== expected)
throw new Error(`${file} changed while it was being updated; it was left as it was.`);
await rename(temporary, file);
} finally {
await rm(temporary, { force: true });
}
}