"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.atomicWriteSync = atomicWriteSync;
exports.safeReadSync = safeReadSync;
const fs_1 = require("fs");
const path_1 = require("path");
const types_js_1 = require("./types.js");
/**
 * Write file atomically using temp + rename.
 * rename() is atomic on POSIX and NTFS.
 */
function atomicWriteSync(targetPath, data, mode = 0o600) {
    const tmp = targetPath + '.tmp.' + process.pid;
    (0, fs_1.mkdirSync)((0, path_1.dirname)(targetPath), { recursive: true });
    try {
        (0, fs_1.writeFileSync)(tmp, data, { encoding: 'utf-8', mode });
        (0, fs_1.renameSync)(tmp, targetPath);
    }
    catch (err) {
        // Clean up tmp file on failure
        try {
            (0, fs_1.unlinkSync)(tmp);
        }
        catch { /* ignore */ }
        const e = err;
        if (e.code === 'ENOSPC') {
            throw new types_js_1.StorageError('Disk full', 'DISK_FULL', targetPath, e);
        }
        if (e.code === 'EACCES' || e.code === 'EPERM') {
            throw new types_js_1.StorageError('Permission denied', 'PERMISSION', targetPath, e);
        }
        throw e;
    }
}
/**
 * Safe read that returns StorageError instead of throwing.
 */
function safeReadSync(path) {
    try {
        return (0, fs_1.readFileSync)(path, 'utf-8');
    }
    catch (err) {
        const e = err;
        if (e.code === 'ENOENT')
            return new types_js_1.StorageError('File not found', 'NOT_FOUND', path, e);
        if (e.code === 'EACCES' || e.code === 'EPERM')
            return new types_js_1.StorageError('Permission denied', 'PERMISSION', path, e);
        return new types_js_1.StorageError(`Read failed: ${e.message}`, 'CORRUPT', path, e);
    }
}
//# sourceMappingURL=atomic.js.map