"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.packager = exports.list = void 0;
var gluegun_1 = require("gluegun");
var spawn_1 = require("./spawn");
var packageInstallOptions = {
    dev: false,
    onProgress: function (out) { return console.log(out); },
};
var packageListOptions = {
    global: false,
};
var isYarn;
function yarnAvailable() {
    if (isYarn !== undefined)
        return isYarn;
    isYarn = Boolean(gluegun_1.system.which("yarn"));
    return isYarn;
}
var isPnpm;
function pnpmAvailable() {
    if (isPnpm !== undefined)
        return isPnpm;
    isPnpm = Boolean(gluegun_1.system.which("pnpm"));
    return isPnpm;
}
function detectPackager() {
    if (yarnAvailable()) {
        return "yarn";
    }
    else if (pnpmAvailable()) {
        return "pnpm";
    }
    else {
        return "npm";
    }
}
function availablePackagers() {
    var packagers = ["npm"];
    if (yarnAvailable()) {
        packagers.push("yarn");
    }
    if (pnpmAvailable()) {
        packagers.push("pnpm");
    }
    return packagers;
}
/**
 *
 * Returns a string command to run a generic install with a packager of your choice (or auto-detects).
 *
 * For example, `yarn add ramda` or `npm install ramda`.
 *
 */
function addCmd(pkg, options) {
    if (options === void 0) { options = packageInstallOptions; }
    var silent = options.silent ? " --silent" : "";
    var cmd;
    if (options.packagerName === "pnpm") {
        cmd = "pnpm install";
    }
    else if (options.packagerName === "yarn") {
        cmd = "yarn add";
    }
    else if (options.packagerName === "npm") {
        cmd = "npm install";
    }
    else {
        // neither expo nor a packagerName was provided, so let's detect one
        return addCmd(pkg, __assign(__assign({}, options), { packagerName: detectPackager() }));
    }
    return "".concat(cmd, " ").concat(pkg).concat(options.dev ? " --save-dev" : "").concat(silent);
}
/**
 *
 * Returns a string command to remove a package with a packager of your choice (or auto-detects).
 *
 * For example, `yarn remove ramda` or `npm uninstall ramda`.
 *
 */
function removeCmd(pkg, options) {
    if (options === void 0) { options = packageInstallOptions; }
    var silent = options.silent ? " --silent" : "";
    var cmd;
    if (options.packagerName === "pnpm") {
        cmd = "pnpm uninstall";
    }
    else if (options.packagerName === "yarn") {
        cmd = "yarn remove";
    }
    else if (options.packagerName === "npm") {
        cmd = "npm uninstall";
    }
    else {
        // neither expo nor a packagerName was provided, so let's detect one
        return removeCmd(pkg, __assign(__assign({}, options), { packagerName: detectPackager() }));
    }
    return "".concat(cmd, " ").concat(pkg).concat(options.dev ? " --save-dev" : "").concat(silent);
}
/**
 *
 * Returns a string command to run a generic install with a packager of your choice (or auto-detects).
 *
 * For example, `yarn install` or `npm install`.
 *
 */
function installCmd(options) {
    var silent = options.silent ? " --silent" : "";
    if (options.packagerName === "pnpm") {
        return "pnpm install".concat(silent);
    }
    else if (options.packagerName === "yarn") {
        return "yarn install".concat(silent);
    }
    else if (options.packagerName === "npm") {
        return "npm install".concat(silent);
    }
    else {
        return installCmd(__assign(__assign({}, options), { packagerName: detectPackager() }));
    }
}
function list(options) {
    if (options === void 0) { options = packageListOptions; }
    if (options.packagerName === "pnpm") {
        // TODO: pnpm list?
        throw new Error("pnpm list is not supported yet");
    }
    else if (options.packagerName === "yarn" ||
        (options.packagerName === undefined && yarnAvailable())) {
        return [
            "yarn".concat(options.global ? " global" : "", " list"),
            function (output) {
                // Parse yarn's human-readable output
                return output
                    .split("\n")
                    .reduce(function (acc, line) {
                    var match = line.match(/info "([^@]+)@([^"]+)" has binaries/);
                    return match ? __spreadArray(__spreadArray([], acc, true), [[match[1], match[2]]], false) : acc;
                }, []);
            },
        ];
    }
    else {
        return [
            "npm list".concat(options.global ? " --global" : "", " --depth=0 --json"),
            function (output) {
                // npm returns a single JSON blob with a "dependencies" key
                // however, sometimes npm can emit warning messages prepended to json output
                var json = JSON.parse(output.replace(/npm WARN.+/g, ""));
                return Object.keys(json.dependencies || []).map(function (key) { return [
                    key,
                    json.dependencies[key].version,
                ]; });
            },
        ];
    }
}
exports.list = list;
/**
 * Returns a string command to run a script via a packager of your choice.
 */
function runCmd(command, options) {
    var silent = options.silent ? " --silent" : "";
    if (options.packagerName === "pnpm") {
        return "pnpm run ".concat(command).concat(silent);
    }
    else if (options.packagerName === "yarn") {
        return "yarn ".concat(command).concat(silent);
    }
    else {
        // defaults to npm run
        return "npm run ".concat(command).concat(silent);
    }
}
exports.packager = {
    run: function (command, options) {
        if (options === void 0) { options = packageInstallOptions; }
        return __awaiter(void 0, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, (0, spawn_1.spawnProgress)("".concat(runCmd(command, options)), {
                        onProgress: options.onProgress,
                    })];
            });
        });
    },
    add: function (pkg, options) {
        if (options === void 0) { options = packageInstallOptions; }
        return __awaiter(void 0, void 0, void 0, function () {
            var cmd;
            return __generator(this, function (_a) {
                cmd = addCmd(pkg, options);
                return [2 /*return*/, (0, spawn_1.spawnProgress)(cmd, { onProgress: options.onProgress })];
            });
        });
    },
    remove: function (pkg, options) {
        if (options === void 0) { options = packageInstallOptions; }
        return __awaiter(void 0, void 0, void 0, function () {
            var cmd;
            return __generator(this, function (_a) {
                cmd = removeCmd(pkg, options);
                return [2 /*return*/, (0, spawn_1.spawnProgress)(cmd, { onProgress: options.onProgress })];
            });
        });
    },
    install: function (options) {
        if (options === void 0) { options = packageInstallOptions; }
        return __awaiter(void 0, void 0, void 0, function () {
            var cmd;
            return __generator(this, function (_a) {
                cmd = installCmd(options);
                return [2 /*return*/, (0, spawn_1.spawnProgress)(cmd, { onProgress: options.onProgress })];
            });
        });
    },
    list: function (options) {
        if (options === void 0) { options = packageListOptions; }
        return __awaiter(void 0, void 0, void 0, function () {
            var _a, cmd, parseFn, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = list(options), cmd = _a[0], parseFn = _a[1];
                        _b = parseFn;
                        return [4 /*yield*/, (0, spawn_1.spawnProgress)(cmd, {})];
                    case 1: return [2 /*return*/, _b.apply(void 0, [_c.sent()])];
                }
            });
        });
    },
    has: function (packageManager) {
        if (packageManager === "yarn")
            return yarnAvailable();
        if (packageManager === "pnpm")
            return pnpmAvailable();
        return true;
    },
    detectPackager: detectPackager,
    runCmd: runCmd,
    addCmd: addCmd,
    installCmd: installCmd,
    availablePackagers: availablePackagers,
};
//# sourceMappingURL=packager.js.map