"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.PacoteService = void 0;
const pacote = require("pacote");
const tar = require("tar");
const path = require("path");
const stream_1 = require("stream");
const _ = require("lodash");
const decorators_1 = require("../common/decorators");
const yok_1 = require("../common/yok");
class PacoteService {
    constructor($fs, $injector, $logger, $npmConfigService, $proxyService) {
        this.$fs = $fs;
        this.$injector = $injector;
        this.$logger = $logger;
        this.$npmConfigService = $npmConfigService;
        this.$proxyService = $proxyService;
    }
    get $packageManager() {
        return this.$injector.resolve("packageManager");
    }
    manifest(packageName, options) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$logger.trace(`Calling pacoteService.manifest for packageName: '${packageName}' and options: `, options);
            const manifestOptions = yield this.getPacoteBaseOptions();
            if (options) {
                _.extend(manifestOptions, options);
            }
            packageName = this.getRealPackageName(packageName);
            this.$logger.trace(`Calling pacote.manifest for packageName: ${packageName} and manifestOptions:`, manifestOptions);
            const result = yield pacote.manifest(packageName, manifestOptions);
            this.$logger.trace("pacote.manifest result:", result);
            return result;
        });
    }
    extractPackage(packageName, destinationDirectory, options) {
        return __awaiter(this, void 0, void 0, function* () {
            this.$logger.trace(`Calling pacoteService.extractPackage for packageName: '${packageName}', destinationDir: '${destinationDirectory}' and options: ${options}`);
            const extractOptions = { strip: 1, C: destinationDirectory };
            if (options) {
                _.extend(extractOptions, options);
            }
            packageName = this.getRealPackageName(packageName);
            const pacoteOptions = yield this.getPacoteBaseOptions();
            return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
                this.$logger.trace(`Calling pacoteService.extractPackage for packageName: '${packageName}', destinationDir: '${destinationDirectory}' and options: ${options}`);
                const source = yield pacote
                    .tarball(packageName, pacoteOptions)
                    .catch((err) => {
                    this.$logger.trace(`Error in source while trying to extract stream from ${packageName}. Error is ${err}`);
                    reject(err);
                });
                this.$logger.trace(`Creating extract tar stream with options: ${JSON.stringify(extractOptions, null, 2)}`);
                const destination = tar.x(extractOptions);
                const sourceStream = new stream_1.PassThrough();
                sourceStream.end(source);
                sourceStream.pipe(destination);
                destination.on("error", (err) => {
                    this.$logger.trace(`Error in destination while trying to extract stream from ${packageName}. Error is ${err}`);
                    reject(err);
                });
                destination.on("finish", () => {
                    this.$logger.trace(`Successfully extracted '${packageName}' to ${destinationDirectory}`);
                    resolve();
                });
            }));
        });
    }
    getPacoteBaseOptions() {
        return __awaiter(this, void 0, void 0, function* () {
            const cachePath = yield this.$packageManager.getCachePath();
            const npmConfig = this.$npmConfigService.getConfig();
            const pacoteOptions = _.extend(npmConfig, { cache: cachePath });
            const proxySettings = yield this.$proxyService.getCache();
            if (proxySettings) {
                _.extend(pacoteOptions, proxySettings);
            }
            return pacoteOptions;
        });
    }
    getRealPackageName(packageName) {
        if (this.$fs.exists(packageName)) {
            this.$logger.trace(`Will resolve the full path to package ${packageName}.`);
            packageName = path.resolve(packageName);
        }
        return packageName;
    }
}
__decorate([
    (0, decorators_1.cache)()
], PacoteService.prototype, "$packageManager", null);
exports.PacoteService = PacoteService;
yok_1.injector.register("pacoteService", PacoteService);
