"use strict";
/**
 * AsyncIO -- Non-blocking file I/O wrappers for governance modules.
 *
 * Provides async versions of common file operations used across
 * the governance framework. Prevents blocking the event loop
 * during heavy audit/log writes.
 *
 * T-027: Async I/O for file-based operations.
 *
 * @connexum/ai-governance
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureDirAsync = ensureDirAsync;
exports.appendJsonlAsync = appendJsonlAsync;
exports.readJsonlAsync = readJsonlAsync;
exports.loadJsonAsync = loadJsonAsync;
exports.saveJsonAsync = saveJsonAsync;
exports.sha256FileAsync = sha256FileAsync;
exports.readFromOffsetAsync = readFromOffsetAsync;
exports.readLastLinesAsync = readLastLinesAsync;
exports.fileExistsAsync = fileExistsAsync;
exports.fileStatsAsync = fileStatsAsync;
const fs = __importStar(require("fs"));
const fsp = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
/**
 * Ensure a directory exists (async).
 */
async function ensureDirAsync(dir) {
    try {
        await fsp.mkdir(dir, { recursive: true });
    }
    catch (err) {
        if (err.code !== 'EEXIST')
            throw err;
    }
}
/**
 * Append a JSON line to a JSONL file (async).
 */
async function appendJsonlAsync(filePath, data) {
    await ensureDirAsync(path.dirname(filePath));
    await fsp.appendFile(filePath, JSON.stringify(data) + '\n');
}
/**
 * Read all lines from a JSONL file (async).
 */
async function readJsonlAsync(filePath) {
    try {
        const content = await fsp.readFile(filePath, 'utf-8');
        return content
            .trim()
            .split('\n')
            .filter(Boolean)
            .map(line => {
            try {
                return JSON.parse(line);
            }
            catch {
                return null;
            }
        })
            .filter((item) => item !== null);
    }
    catch (err) {
        if (err.code === 'ENOENT')
            return [];
        throw err;
    }
}
/**
 * Load a JSON file (async).
 */
async function loadJsonAsync(filePath) {
    try {
        const content = await fsp.readFile(filePath, 'utf-8');
        return JSON.parse(content);
    }
    catch {
        return null;
    }
}
/**
 * Save a JSON file (async, atomic via temp file + rename).
 */
async function saveJsonAsync(filePath, data) {
    await ensureDirAsync(path.dirname(filePath));
    const tmpFile = filePath + `.tmp.${process.pid}`;
    try {
        await fsp.writeFile(tmpFile, JSON.stringify(data, null, 2));
        await fsp.rename(tmpFile, filePath);
    }
    catch (err) {
        // Cleanup temp file on failure
        try {
            await fsp.unlink(tmpFile);
        }
        catch { /* ignore */ }
        throw err;
    }
}
/**
 * Compute SHA-256 hash of a file (async, streaming).
 */
async function sha256FileAsync(filePath) {
    return new Promise((resolve, reject) => {
        const hash = crypto.createHash('sha256');
        const stream = fs.createReadStream(filePath);
        stream.on('data', (chunk) => hash.update(chunk));
        stream.on('end', () => resolve(hash.digest('hex')));
        stream.on('error', reject);
    });
}
/**
 * Read new bytes from a file starting at offset (async).
 * Returns the new content and the new offset.
 */
async function readFromOffsetAsync(filePath, offset) {
    const handle = await fsp.open(filePath, 'r');
    try {
        const stat = await handle.stat();
        if (stat.size <= offset) {
            return { content: '', newOffset: offset };
        }
        const buf = Buffer.alloc(stat.size - offset);
        await handle.read(buf, 0, buf.length, offset);
        return {
            content: buf.toString('utf-8'),
            newOffset: stat.size,
        };
    }
    finally {
        await handle.close();
    }
}
/**
 * Read the last N lines from a file (async).
 */
async function readLastLinesAsync(filePath, n) {
    try {
        const content = await fsp.readFile(filePath, 'utf-8');
        const lines = content.trim().split('\n').filter(Boolean);
        return lines.slice(-n);
    }
    catch (err) {
        if (err.code === 'ENOENT')
            return [];
        throw err;
    }
}
/**
 * Check if a file exists (async).
 */
async function fileExistsAsync(filePath) {
    try {
        await fsp.access(filePath);
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Get file stats (async). Returns null if file doesn't exist.
 */
async function fileStatsAsync(filePath) {
    try {
        return await fsp.stat(filePath);
    }
    catch {
        return null;
    }
}
//# sourceMappingURL=async-io.js.map