// file-mutex.ts — In-memory per-file mutex for concurrent access safety
// Uses async promise chaining: each file path gets its own sequential queue.
const locks = new Map();
/**
 * Execute `fn` while holding an exclusive lock on `filePath`.
 * Concurrent calls for the same path are serialized; different paths run in parallel.
 */
export async function withFileLock(filePath, fn) {
    const prev = locks.get(filePath) ?? Promise.resolve();
    let release;
    const next = new Promise((resolve) => {
        release = resolve;
    });
    locks.set(filePath, next);
    try {
        await prev;
        return await fn();
    }
    finally {
        release();
        // Clean up only if no newer lock has been queued
        if (locks.get(filePath) === next) {
            locks.delete(filePath);
        }
    }
}
/**
 * Number of active file locks. Useful for testing / diagnostics.
 */
export function activeLockCount() {
    return locks.size;
}
/**
 * Clear all locks. Only for use in tests.
 */
export function clearAllLocks() {
    locks.clear();
}
//# sourceMappingURL=file-mutex.js.map