import fs from 'node:fs' import {randomUUID} from 'node:crypto' // Windows scanners can briefly lock the rename target. Preserve the old file // and retry the atomic replacement; never truncate it as a fallback. export function writeAtomic(file,contents){ const temporary=file+'.'+randomUUID()+'.tmp' fs.writeFileSync(temporary,contents,'utf8') try{ for(let attempt=0;;attempt++){ try{fs.renameSync(temporary,file);return} catch(error){if(attempt>=4||!['EPERM','EBUSY','EACCES'].includes(error.code))throw error;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25*(attempt+1))} } }finally{if(fs.existsSync(temporary))fs.unlinkSync(temporary)} }