"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lifecycle_1 = require("@pnpm/lifecycle");
const logger_1 = require("@pnpm/logger");
const utils_1 = require("@pnpm/utils");
const pLimit = require("p-limit");
exports.default = async (packageChunks, graph, args, cmd, opts) => {
    const scriptName = args[0];
    let hasCommand = 0;
    const result = {
        fails: [],
        passes: 0,
    };
    const limitRun = pLimit(opts.workspaceConcurrency);
    const stdio = (opts.workspaceConcurrency === 1 ||
        packageChunks.length === 1 && packageChunks[0].length === 1) ? 'inherit' : 'pipe';
    for (const chunk of packageChunks) {
        await Promise.all(chunk.map((prefix) => limitRun(async () => {
            const pkg = graph[prefix];
            if (!pkg.manifest.scripts || !pkg.manifest.scripts[scriptName]) {
                return;
            }
            hasCommand++;
            try {
                const lifecycleOpts = {
                    depPath: prefix,
                    pkgRoot: prefix,
                    rawNpmConfig: opts.rawNpmConfig,
                    rootNodeModulesDir: await utils_1.realNodeModulesDir(prefix),
                    stdio,
                    unsafePerm: opts.unsafePerm || false,
                };
                if (pkg.manifest.scripts[`pre${scriptName}`]) {
                    await lifecycle_1.default(`pre${scriptName}`, pkg.manifest, lifecycleOpts);
                }
                await lifecycle_1.default(scriptName, pkg.manifest, lifecycleOpts);
                if (pkg.manifest.scripts[`post${scriptName}`]) {
                    await lifecycle_1.default(`post${scriptName}`, pkg.manifest, lifecycleOpts);
                }
                result.passes++;
            }
            catch (err) {
                logger_1.default.info(err);
                if (!opts.bail) {
                    result.fails.push({
                        error: err,
                        message: err.message,
                        prefix,
                    });
                    return;
                }
                // tslint:disable:no-string-literal
                err['code'] = 'ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL';
                err['prefix'] = prefix;
                // tslint:enable:no-string-literal
                throw err;
            }
        })));
    }
    if (scriptName !== 'test' && !hasCommand) {
        const err = new Error(`None of the packages has a "${scriptName}" script`);
        err['code'] = 'RECURSIVE_RUN_NO_SCRIPT'; // tslint:disable-line:no-string-literal
        throw err;
    }
    return result;
};
//# sourceMappingURL=run.js.map