"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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 });
exports.BunPackageManager = void 0;
const path = require("path");
const base_package_manager_1 = require("./base-package-manager");
const decorators_1 = require("./common/decorators");
const constants_1 = require("./constants");
const _ = require("lodash");
const yok_1 = require("./common/yok");
class BunPackageManager extends base_package_manager_1.BasePackageManager {
    constructor($childProcess, $errors, $fs, $hostInfo, $logger, $httpClient, $pacoteService) {
        super($childProcess, $fs, $hostInfo, $pacoteService, "bun");
        this.$errors = $errors;
        this.$logger = $logger;
        this.$httpClient = $httpClient;
    }
    install(packageName, pathToSave, config) {
        return __awaiter(this, void 0, void 0, function* () {
            if (config.disableNpmInstall) {
                return;
            }
            if (config.ignoreScripts) {
                config["ignore-scripts"] = true;
            }
            const packageJsonPath = path.join(pathToSave, "package.json");
            const jsonContentBefore = this.$fs.readJson(packageJsonPath);
            const flags = this.getFlagsString(config, true);
            // TODO: Confirm desired behavior. The npm version uses --legacy-peer-deps
            // by default, we could use `--no-peer` for Bun if similar is needed; the
            // pnpm version uses `--shamefully-hoist`, but Bun has no similar flag.
            let params = ["install", "--legacy-peer-deps"];
            const isInstallingAllDependencies = packageName === pathToSave;
            if (!isInstallingAllDependencies) {
                params.push(packageName);
            }
            params = params.concat(flags);
            const cwd = pathToSave;
            try {
                const result = yield this.processPackageManagerInstall(packageName, params, { cwd, isInstallingAllDependencies });
                return result;
            }
            catch (err) {
                // Revert package.json contents to preserve valid state
                this.$fs.writeJson(packageJsonPath, jsonContentBefore);
                throw err;
            }
        });
    }
    uninstall(packageName, config, cwd) {
        return __awaiter(this, void 0, void 0, function* () {
            const flags = this.getFlagsString(config, false);
            return this.$childProcess.exec(`bun remove ${packageName} ${flags}`, {
                cwd,
            });
        });
    }
    // Bun does not have a `view` command; use npm.
    view(packageName, config) {
        return __awaiter(this, void 0, void 0, function* () {
            const wrappedConfig = _.extend({}, config, { json: true }); // always require view response as JSON
            const flags = this.getFlagsString(wrappedConfig, false);
            let viewResult;
            try {
                viewResult = yield this.$childProcess.exec(`npm view ${packageName} ${flags}`);
            }
            catch (e) {
                this.$errors.fail(e.message);
            }
            try {
                return JSON.parse(viewResult);
            }
            catch (err) {
                return null;
            }
        });
    }
    // Bun does not have a `search` command; use npm.
    search(filter, config) {
        return __awaiter(this, void 0, void 0, function* () {
            const flags = this.getFlagsString(config, false);
            return this.$childProcess.exec(`npm search ${filter.join(" ")} ${flags}`);
        });
    }
    searchNpms(keyword) {
        return __awaiter(this, void 0, void 0, function* () {
            // Bugs with npms.io:
            // 1. API returns no results when a valid package name contains @ or /
            //    even if using encodeURIComponent().
            // 2. npms.io's API no longer returns updated results; see
            //    https://github.com/npms-io/npms-api/issues/112. Better to switch to
            //    https://registry.npmjs.org/<query>
            const httpRequestResult = yield this.$httpClient.httpRequest(`https://api.npms.io/v2/search?q=keywords:${keyword}`);
            const result = JSON.parse(httpRequestResult.body);
            return result;
        });
    }
    // Bun does not have a command analogous to `npm config get registry`; Bun
    // uses `bunfig.toml` to define custom registries.
    // - TODO: read `bunfig.toml`, if it exists, and return the registry URL.
    getRegistryPackageData(packageName) {
        return __awaiter(this, void 0, void 0, function* () {
            const registry = yield this.$childProcess.exec(`npm config get registry`);
            const url = registry.trim() + packageName;
            this.$logger.trace(`Trying to get data from npm registry for package ${packageName}, url is: ${url}`);
            const responseData = (yield this.$httpClient.httpRequest(url)).body;
            this.$logger.trace(`Successfully received data from npm registry for package ${packageName}. Response data is: ${responseData}`);
            const jsonData = JSON.parse(responseData);
            this.$logger.trace(`Successfully parsed data from npm registry for package ${packageName}.`);
            return jsonData;
        });
    }
    getCachePath() {
        return __awaiter(this, void 0, void 0, function* () {
            const cachePath = yield this.$childProcess.exec(`bun pm cache`);
            return path.join(cachePath.trim(), constants_1.CACACHE_DIRECTORY_NAME);
        });
    }
}
__decorate([
    (0, decorators_1.exported)("bun")
], BunPackageManager.prototype, "install", null);
__decorate([
    (0, decorators_1.exported)("bun")
], BunPackageManager.prototype, "uninstall", null);
__decorate([
    (0, decorators_1.exported)("bun")
], BunPackageManager.prototype, "view", null);
__decorate([
    (0, decorators_1.exported)("bun")
], BunPackageManager.prototype, "search", null);
__decorate([
    (0, decorators_1.cache)()
], BunPackageManager.prototype, "getCachePath", null);
exports.BunPackageManager = BunPackageManager;
yok_1.injector.register("bun", BunPackageManager);
//# sourceMappingURL=bun-package-manager.js.map