"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_promise_1 = require("child-process-promise");
const path_1 = require("path");
const semver_1 = require("semver");
const fs_extra_1 = require("fs-extra");
const ramda_1 = require("ramda");
const utils_1 = require("../../utils");
const env = (0, ramda_1.dissoc)('PUPPETEER_SKIP_CHROMIUM_DOWNLOAD', process.env);
const options = {
    env,
    cwd: (0, path_1.join)(__dirname, '../../../'),
};
function lazyRequire({ moduleName, version }, { unsafe } = { unsafe: false }) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const modulePath = require.resolve(moduleName);
            const currentVersion = require(`${moduleName}/package.json`).version;
            if (!(0, semver_1.valid)(version) || (0, semver_1.gt)(version, currentVersion)) {
                return installModule(moduleName, version, unsafe);
            }
            return require(modulePath).default;
        }
        catch (_a) {
            return installModule(moduleName, version);
        }
    });
}
function installModule(moduleName, version, unsafe) {
    var _a;
    return __awaiter(this, void 0, void 0, function* () {
        const npm = (_a = yield (0, utils_1.getGlobalNpm)()) !== null && _a !== void 0 ? _a : (0, utils_1.getNpm)();
        const commandParameters = [
            'install',
            '-g',
            `${moduleName}@${version}`,
            ...(unsafe ? [] : ['--unsafe-perm']),
        ];
        yield (0, child_process_promise_1.fork)(npm, commandParameters, options);
        yield (0, child_process_promise_1.fork)(npm, ['link', moduleName], options);
        return require(yield resolveModulePath(moduleName)).default;
    });
}
function resolveModulePath(moduleName) {
    return __awaiter(this, void 0, void 0, function* () {
        const moduleFolder = (0, path_1.join)(options.cwd, 'node_modules', moduleName);
        const modulePackage = yield (0, fs_extra_1.readJSON)((0, path_1.join)(moduleFolder, 'package.json'));
        return (0, path_1.join)(moduleFolder, modulePackage.main);
    });
}
exports.default = lazyRequire;
//# sourceMappingURL=lazyRequire.js.map