"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("mz/fs");
const pLimit = require("p-limit");
const path = require("path");
const parseJson_1 = require("./parseJson");
const limit = pLimit(20);
const MAX_BULK_SIZE = 1 * 1024 * 1024; // 1MB
async function default_1(cafs, dirname, manifest) {
    const index = {};
    await _retrieveFileIntegrities(cafs, dirname, dirname, index, manifest);
    return index;
}
exports.default = default_1;
async function _retrieveFileIntegrities(cafs, rootDir, currDir, index, deferredManifest) {
    try {
        const files = await fs.readdir(currDir);
        await Promise.all(files.map(async (file) => {
            const fullPath = path.join(currDir, file);
            const stat = await fs.stat(fullPath);
            if (stat.isDirectory()) {
                await _retrieveFileIntegrities(cafs, rootDir, fullPath, index);
                return;
            }
            if (stat.isFile()) {
                const relativePath = path.relative(rootDir, fullPath);
                const generatingIntegrity = limit(async () => {
                    if (deferredManifest && rootDir === currDir && file === 'package.json') {
                        const buffer = await fs.readFile(fullPath);
                        parseJson_1.parseJsonBuffer(buffer, deferredManifest);
                        return cafs.addBuffer(buffer, stat.mode);
                    }
                    if (stat.size < MAX_BULK_SIZE) {
                        const buffer = await fs.readFile(fullPath);
                        return cafs.addBuffer(buffer, stat.mode);
                    }
                    return cafs.addStream(fs.createReadStream(fullPath), stat.mode);
                });
                index[relativePath] = {
                    generatingIntegrity,
                    mode: stat.mode,
                    size: stat.size,
                };
            }
        }));
    }
    catch (err) {
        if (err.code !== 'ENOENT') {
            throw err;
        }
    }
}
//# sourceMappingURL=addFilesFromDir.js.map