"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.map = exports.all = void 0;
const tslib_1 = require("tslib");
const aggregate_error_1 = tslib_1.__importDefault(require("aggregate-error"));
const p_all_1 = tslib_1.__importDefault(require("p-all"));
const p_map_1 = tslib_1.__importDefault(require("p-map"));
const logger_1 = require("../logger");
const external_host_error_1 = require("../types/errors/external-host-error");
function isExternalHostError(err) {
    return err instanceof external_host_error_1.ExternalHostError;
}
function handleMultipleErrors(errors) {
    const hostError = errors.find(isExternalHostError);
    if (hostError) {
        throw hostError;
    }
    if (errors.length === 1 ||
        new Set(errors.map(({ message }) => message)).size === 1) {
        const [error] = errors;
        throw error;
    }
    throw new aggregate_error_1.default(errors);
}
function handleError(err) {
    if (!(err instanceof aggregate_error_1.default)) {
        throw err;
    }
    logger_1.logger.debug({ err }, 'Aggregate error is thrown');
    handleMultipleErrors([...err]);
}
async function all(tasks, options) {
    try {
        const res = await (0, p_all_1.default)(tasks, {
            concurrency: 5,
            stopOnError: false,
            ...options,
        });
        return res;
    }
    catch (err) {
        return handleError(err);
    }
}
exports.all = all;
async function map(input, mapper, options) {
    try {
        const res = await (0, p_map_1.default)(input, mapper, {
            concurrency: 5,
            stopOnError: false,
            ...options,
        });
        return res;
    }
    catch (err) {
        return handleError(err);
    }
}
exports.map = map;
//# sourceMappingURL=promises.js.map