"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateLockFiles = exports.getLernaVersion = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const semver_1 = tslib_1.__importDefault(require("semver"));
const upath_1 = tslib_1.__importDefault(require("upath"));
const global_1 = require("../../../../config/global");
const error_messages_1 = require("../../../../constants/error-messages");
const logger_1 = require("../../../../logger");
const exec_1 = require("../../../../util/exec");
const node_version_1 = require("./node-version");
// Exported for testability
function getLernaVersion(lernaPackageFile) {
    const lernaDep = lernaPackageFile.deps?.find((d) => d.depName === 'lerna');
    if (!lernaDep?.currentValue || !semver_1.default.validRange(lernaDep.currentValue)) {
        logger_1.logger.warn(
        // TODO: types (#7154)
        // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
        `Could not detect lerna version in ${lernaPackageFile.packageFile}, using 'latest'`);
        return null;
    }
    return lernaDep.currentValue;
}
exports.getLernaVersion = getLernaVersion;
async function generateLockFiles(lernaPackageFile, lockFileDir, config, env, skipInstalls) {
    const lernaClient = lernaPackageFile.managerData?.lernaClient;
    if (!is_1.default.nonEmptyString(lernaClient)) {
        logger_1.logger.warn('No lernaClient specified - returning');
        return { error: false };
    }
    logger_1.logger.debug(`Spawning lerna with ${lernaClient} to create lock files`);
    const toolConstraints = [
        await (0, node_version_1.getNodeToolConstraint)(config, [], lockFileDir),
    ];
    const cmd = [];
    let cmdOptions = '';
    try {
        if (lernaClient === 'yarn') {
            const yarnTool = {
                toolName: 'yarn',
                constraint: '^1.22.18', // needs to be a v1 yarn, otherwise v2 will be installed
            };
            const yarnCompatibility = config.constraints?.yarn ?? config.extractedConstraints?.yarn;
            if (semver_1.default.validRange(yarnCompatibility)) {
                yarnTool.constraint = yarnCompatibility;
            }
            toolConstraints.push(yarnTool);
            if (skipInstalls !== false) {
                // The following change causes Yarn 1.x to exit gracefully after updating the lock file but without installing node_modules
                yarnTool.toolName = 'yarn-slim';
            }
            cmdOptions = '--ignore-scripts --ignore-engines --ignore-platform';
        }
        else if (lernaClient === 'npm') {
            const npmTool = { toolName: 'npm' };
            const npmCompatibility = config.constraints?.npm ?? config.extractedConstraints?.npm;
            if (semver_1.default.validRange(npmCompatibility)) {
                npmTool.constraint = npmCompatibility;
            }
            toolConstraints.push(npmTool);
            cmdOptions = '--ignore-scripts  --no-audit';
            if (skipInstalls !== false) {
                cmdOptions += ' --package-lock-only';
            }
        }
        else {
            logger_1.logger.warn({ lernaClient }, 'Unknown lernaClient');
            return { error: false };
        }
        let lernaCommand = `lerna bootstrap --no-ci --ignore-scripts -- `;
        if (global_1.GlobalConfig.get('allowScripts') && !config.ignoreScripts) {
            cmdOptions = cmdOptions.replace('--ignore-scripts ', '');
            lernaCommand = lernaCommand.replace('--ignore-scripts ', '');
        }
        lernaCommand += cmdOptions;
        const extraEnv = {
            NPM_CONFIG_CACHE: env.NPM_CONFIG_CACHE,
            npm_config_store: env.npm_config_store,
        };
        const execOptions = {
            cwdFile: upath_1.default.join(lockFileDir, 'package.json'),
            extraEnv,
            docker: {},
            toolConstraints,
        };
        // istanbul ignore if
        if (global_1.GlobalConfig.get('exposeAllEnv')) {
            extraEnv.NPM_AUTH = env.NPM_AUTH;
            extraEnv.NPM_EMAIL = env.NPM_EMAIL;
        }
        const lernaVersion = getLernaVersion(lernaPackageFile);
        logger_1.logger.debug(`Using lerna version ${lernaVersion ?? 'latest'}`);
        toolConstraints.push({ toolName: 'lerna', constraint: lernaVersion });
        cmd.push('lerna info || echo "Ignoring lerna info failure"');
        cmd.push(`${lernaClient} install ${cmdOptions}`);
        cmd.push(lernaCommand);
        await (0, exec_1.exec)(cmd, execOptions);
    }
    catch (err) /* istanbul ignore next */ {
        if (err.message === error_messages_1.TEMPORARY_ERROR) {
            throw err;
        }
        logger_1.logger.debug({
            cmd,
            err,
            type: 'lerna',
            lernaClient,
        }, 'lock file error');
        return { error: true, stderr: err.stderr };
    }
    return { error: false };
}
exports.generateLockFiles = generateLockFiles;
//# sourceMappingURL=lerna.js.map