import path from "pathe";
import { Bytes } from "./Bytes.js";
import { getErrorMessage } from "./errors.js";
export async function enumFilesRecursive(fs, rootDir, predicate) {
    const ret = [];
    try {
        const filesAndDirs = await fs.readDir(rootDir);
        for (const f of filesAndDirs) {
            const fullPath = path.join(rootDir, f);
            if ((await fs.stat(fullPath)).isDirectory()) {
                ret.push(...(await enumFilesRecursive(fs, fullPath, predicate)));
            }
            else if (predicate == undefined || predicate(fullPath)) {
                ret.push(fullPath);
            }
        }
    }
    catch (e) {
        console.error(`Cannot read directory: "${rootDir}": ${getErrorMessage(e, true)}`);
    }
    return ret;
}
export async function copyFilesRecursive(fs, sourceDir, targetDir, predicate) {
    const files = await enumFilesRecursive(fs, sourceDir, predicate);
    for (const file of files) {
        const relative = path.relative(sourceDir, file);
        const target = path.join(targetDir, relative);
        await fs.ensureDir(path.dirname(target));
        await fs.copyFile(file, target);
    }
}
export async function readTextFile(fs, filename, encoding = "utf8") {
    const buffer = await fs.readFile(filename);
    return Bytes.view(buffer).toString(encoding);
}
export async function writeTextFile(fs, filename, content, encoding = "utf8") {
    const buffer = Bytes.from(content, encoding);
    await fs.writeFile(filename, buffer);
}
export async function readJSON(fs, filename) {
    const content = await readTextFile(fs, filename);
    return JSON.parse(content);
}
export async function pathExists(fs, filename) {
    try {
        await fs.stat(filename);
        return true;
    }
    catch {
        return false;
    }
}
export function fileHandleToWritableStream(handle) {
    return new WritableStream({
        async write(chunk) {
            while (chunk.length > 0) {
                const { bytesWritten } = await handle.write(chunk);
                chunk = chunk.subarray(bytesWritten);
            }
        },
    });
}
export function fileHandleToReadableStream(handle) {
    return new ReadableStream({
        async pull(controller) {
            const { data } = await handle.read(null, 16 * 1024);
            controller.enqueue(data);
        },
    });
}
export function fileHandleToStreams(handle) {
    return {
        readable: fileHandleToReadableStream(handle),
        writable: fileHandleToWritableStream(handle),
    };
}
//# sourceMappingURL=fs.js.map