histoire
Version:
A fast story book powered by Vite
59 lines (58 loc) • 2.89 kB
JavaScript
import { randomUUID } from 'node:crypto';
import { rm, writeFile } from 'node:fs/promises';
import path from 'pathe';
import { configFileHash, restoreConfigBackup, writeConfig } from './codemod/write.js';
import { loadConfigFile } from './load.js';
/** Verification failure with explicit config rollback evidence. */
export class SafeConfigWriteError extends Error {
/** Whether original config remains byte-for-byte current. */ restored;
/** Records rollback outcome without exposing arbitrary loader output. */
constructor(restored) {
super(restored ? 'Plugin config could not be loaded. Original config restored.' : 'Plugin config could not be verified. Check the config; changes may remain.');
this.restored = restored;
}
}
/** Checks identity order after both temporary evaluation and committed reload. */
function pluginNames(config, allowMissing) {
const plugins = config.plugins ?? (allowMissing ? [] : undefined);
if (!Array.isArray(plugins) || plugins.some(plugin => typeof plugin?.name !== 'string'))
throw new Error('Plugin config did not preserve identities');
return plugins.map(plugin => plugin.name);
}
/** Validates relative imports, writes atomically and restores guarded backups on failure. */
export async function safeConfigWrite(input) {
const { root, file, code, expectedHash } = input;
if (await configFileHash(file, { root }) !== expectedHash)
throw new Error('Config changed on disk. Reload settings.');
const temporary = path.join(path.dirname(file), `.histoire-config-check-${randomUUID()}${path.extname(file)}`);
let expected;
try {
await writeFile(temporary, code, { flag: 'wx', mode: 0o600 });
expected = pluginNames(await loadConfigFile(temporary), input.expectedNames === undefined);
if (input.expectedNames && JSON.stringify(expected) !== JSON.stringify(input.expectedNames))
throw new Error('Plugin config did not preserve identities');
}
finally {
await rm(temporary, { force: true });
}
if (!input.isActive())
throw new Error('Plugin changes cancelled. Reload settings.');
await input.beforeWrite?.();
const written = await writeConfig(file, code, { root, expectedHash });
try {
if (JSON.stringify(pluginNames(await loadConfigFile(file), input.expectedNames === undefined)) !== JSON.stringify(expected))
throw new Error('Plugin config did not preserve identities');
}
catch {
let restored = false;
try {
if (written.backup) {
await restoreConfigBackup(file, written.backup, { root, expectedHash: written.hash });
restored = true;
}
}
catch { /* Never overwrite a newer concurrent config revision. */ }
throw new SafeConfigWriteError(restored);
}
return written;
}