"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateLockFiles = exports.getLernaConstraint = 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");
const utils_1 = require("./utils");
// Exported for testability
function getLernaConstraint(lernaPackageFile, lazyPkgJson) {
    const constraint = lazyPkgJson.dependencies?.lerna ?? lazyPkgJson.devDependencies?.lerna;
    if (!constraint || !semver_1.default.validRange(constraint)) {
        logger_1.logger.warn(
        // TODO: types (#7154)
        `Could not detect lerna version in ${lernaPackageFile.packageFile}, using 'latest'`);
        return null;
    }
    return constraint;
}
exports.getLernaConstraint = getLernaConstraint;
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 cmd = [];
    let cmdOptions = '';
    try {
        const lazyPgkJson = (0, utils_1.lazyLoadPackageJson)(lockFileDir);
        const toolConstraints = [
            await (0, node_version_1.getNodeToolConstraint)(config, [], lockFileDir, lazyPgkJson),
        ];
        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 ??
                (0, utils_1.getPackageManagerVersion)('yarn', await lazyPgkJson.getValue());
            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 ??
                (0, utils_1.getPackageManagerVersion)('npm', await lazyPgkJson.getValue());
            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 lernaConstraint = config.constraints?.lerna ??
            getLernaConstraint(lernaPackageFile, await lazyPgkJson.getValue());
        if (!is_1.default.string(lernaConstraint) ||
            (semver_1.default.valid(lernaConstraint) &&
                semver_1.default.gte(lernaConstraint, '7.0.0')) === true ||
            (semver_1.default.validRange(lernaConstraint) &&
                (semver_1.default.satisfies('7.0.0', lernaConstraint) ||
                    semver_1.default.satisfies('7.999.999', lernaConstraint)))) {
            logger_1.logger.debug('Skipping lerna bootstrap for lerna >= 7.0.0');
            cmd.push(`${lernaClient} install ${cmdOptions}`);
        }
        else {
            logger_1.logger.debug(`Using lerna version ${lernaConstraint}`);
            toolConstraints.push({ toolName: 'lerna', constraint: lernaConstraint });
            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