"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get createDir () {
        return createDir;
    },
    get exists () {
        return exists;
    },
    get readJson () {
        return readJson;
    },
    get tmpDir () {
        return tmpDir;
    },
    get watchPaths () {
        return watchPaths;
    },
    get writeJson () {
        return writeJson;
    }
});
function _promises() {
    const data = require("fs/promises");
    _promises = function() {
        return data;
    };
    return data;
}
function _promises1() {
    const data = require("node:fs/promises");
    _promises1 = function() {
        return data;
    };
    return data;
}
function _os() {
    const data = require("os");
    _os = function() {
        return data;
    };
    return data;
}
function _path() {
    const data = require("path");
    _path = function() {
        return data;
    };
    return data;
}
function _chokidar() {
    const data = require("chokidar");
    _chokidar = function() {
        return data;
    };
    return data;
}
const exists = async (path)=>{
    try {
        await (0, _promises().stat)(path);
    } catch (err) {
        return false;
    }
    return true;
};
const readJson = async (path)=>{
    try {
        return await (0, _promises().readFile)(path, "utf8").then((r)=>JSON.parse(r));
    } catch (e) {
        console.trace(`Error reading json file: ${path}`);
        throw e;
    }
};
const maybeFmtJson = (data, format)=>{
    if (format) return JSON.stringify(data, null, 2);
    return JSON.stringify(data);
};
const writeJson = async (path, data, formatted = false)=>{
    await (0, _promises().writeFile)(path, maybeFmtJson(data, formatted), "utf8");
};
const tmpDir = async (prefix)=>{
    prefix = (0, _path().resolve)((0, _os().tmpdir)(), prefix ?? Date.now().toString());
    return await (0, _promises().mkdtemp)(prefix);
};
const createDir = async (path)=>{
    if (!await exists(path)) {
        await (0, _promises1().mkdir)(path, {
            recursive: true
        });
    }
};
const watchPaths = async ({ included, excluded = [], delay = 500 }, onChange)=>{
    let watcher;
    let runTimeout;
    watcher?.close();
    watcher = (0, _chokidar().watch)(included, {
        ignored: excluded,
        followSymlinks: true,
        ignoreInitial: true
    });
    watcher.on("change", (filename, stats)=>{
        clearTimeout(runTimeout);
        runTimeout = setTimeout(()=>{
            onChange(filename);
        }, delay);
    });
    return {
        cancel: ()=>watcher?.close()
    };
};
