"use strict";
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.blockedWriteOperations = void 0;
exports.initializeFSBlocker = initializeFSBlocker;
exports.getBlockedWarnings = getBlockedWarnings;
exports.clearBlockedWarnings = clearBlockedWarnings;
exports.patchFSModule = patchFSModule;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const allowedReadPaths = new Set();
let isBlocked = false;
let blockWarnings = [];
function initializeFSBlocker(isMemoryMode, projectRoot) {
    isBlocked = isMemoryMode;
    if (isMemoryMode) {
        if (projectRoot) {
            allowedReadPaths.add(projectRoot);
            allowedReadPaths.add(path.join(projectRoot, 'node_modules'));
            allowedReadPaths.add(path.join(projectRoot, 'infra'));
            allowedReadPaths.add(path.join(projectRoot, '.env'));
            allowedReadPaths.add(path.join(projectRoot, 'infra', '.env'));
        }
        allowedReadPaths.add(process.cwd());
        allowedReadPaths.add(path.join(process.cwd(), 'node_modules'));
        console.warn('[No-Persistence] Filesystem write blocker activated. All writes will be blocked.');
    }
}
function isAllowedRead(filePath) {
    if (!isBlocked)
        return true;
    const resolvedPath = path.resolve(filePath);
    for (const allowedPath of allowedReadPaths) {
        if (resolvedPath.startsWith(path.resolve(allowedPath))) {
            return true;
        }
    }
    if (resolvedPath.startsWith('/proc/') ||
        resolvedPath.startsWith('/sys/') ||
        resolvedPath.startsWith('/dev/')) {
        return true;
    }
    return false;
}
function isAllowedWrite(filePath) {
    return !isBlocked;
}
function logBlockedWrite(operation, filePath) {
    blockWarnings.push({
        path: filePath,
        operation,
        timestamp: Date.now()
    });
    console.warn(`[No-Persistence] fs ${operation} blocked: ${filePath}`);
}
function getBlockedWarnings() {
    return [...blockWarnings];
}
function clearBlockedWarnings() {
    blockWarnings = [];
}
exports.blockedWriteOperations = {
    writeFile: (filePath, data, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('writeFile', filePath);
            if (typeof args[args.length - 1] === 'function') {
                args[args.length - 1](null);
            }
            return;
        }
        return fs.writeFileSync(filePath, data, ...args);
    },
    writeFileSync: (filePath, data, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('writeFileSync', filePath);
            return;
        }
        throw new Error('[No-Persistence] Filesystem writes are disabled. Code should not attempt writes.');
    },
    appendFile: (filePath, data, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('appendFile', filePath);
            if (typeof args[args.length - 1] === 'function') {
                args[args.length - 1](null);
            }
            return;
        }
        return fs.appendFileSync(filePath, data, ...args);
    },
    appendFileSync: (filePath, data, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('appendFileSync', filePath);
            return;
        }
        return fs.appendFileSync(filePath, data, ...args);
    },
    mkdir: (dirPath, ...args) => {
        if (!isAllowedWrite(dirPath)) {
            logBlockedWrite('mkdir', dirPath);
            if (typeof args[args.length - 1] === 'function') {
                args[args.length - 1](null);
            }
            return;
        }
        return fs.mkdirSync(dirPath, ...args);
    },
    mkdirSync: (dirPath, ...args) => {
        if (!isAllowedWrite(dirPath)) {
            logBlockedWrite('mkdirSync', dirPath);
            return;
        }
        return fs.mkdirSync(dirPath, ...args);
    },
    createWriteStream: (filePath, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('createWriteStream', filePath);
            return {
                write: () => true,
                end: () => { },
                destroy: () => { },
            };
        }
        return fs.createWriteStream(filePath, ...args);
    },
    open: (filePath, flags, ...args) => {
        if (flags.includes('w') || flags.includes('a') || flags === 'w' || flags === 'a') {
            if (!isAllowedWrite(filePath)) {
                logBlockedWrite('open', filePath);
                if (typeof args[args.length - 1] === 'function') {
                    args[args.length - 1](null, null);
                }
                return;
            }
        }
        if (!flags.includes('r') && !isAllowedRead(filePath)) {
            if (typeof args[args.length - 1] === 'function') {
                args[args.length - 1](new Error('Read not allowed in memory mode'), null);
            }
            return;
        }
        return fs.openSync(filePath, flags, ...args);
    },
    copyFile: (src, dest, ...args) => {
        if (!isAllowedWrite(dest)) {
            logBlockedWrite('copyFile', dest);
            if (typeof args[args.length - 1] === 'function') {
                args[args.length - 1](null);
            }
            return;
        }
        return fs.copyFileSync(src, dest, ...args);
    },
    copyFileSync: (src, dest) => {
        if (!isAllowedWrite(dest)) {
            logBlockedWrite('copyFileSync', dest);
            return;
        }
        return fs.copyFileSync(src, dest);
    },
    rm: (filePath, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('rm', filePath);
            if (typeof args[args.length - 1] === 'function') {
                args[args.length - 1](null);
            }
            return;
        }
        return fs.rmSync(filePath, ...args);
    },
    rmSync: (filePath, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('rmSync', filePath);
            return;
        }
        return fs.rmSync(filePath, ...args);
    },
    unlink: (filePath, ...args) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('unlink', filePath);
            if (typeof args[args.length - 1] === 'function') {
                args[args.length - 1](null);
            }
            return;
        }
        return fs.unlinkSync(filePath);
    },
    unlinkSync: (filePath) => {
        if (!isAllowedWrite(filePath)) {
            logBlockedWrite('unlinkSync', filePath);
            return;
        }
        return fs.unlinkSync(filePath);
    },
};
function patchFSModule() {
    if (!isBlocked)
        return;
    console.warn('[No-Persistence] Filesystem writes are blocked. Application code should not attempt writes.');
}
//# sourceMappingURL=fs-blocker.js.map