"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = require("ramda");
const mkdirp = require("mkdirp-promise");
const path = require("path");
const createWriteStreamAtomic = require("fs-write-stream-atomic");
const ssri = require("ssri");
const unpackStream = require("unpack-stream");
const npmGetCredentialsByURI = require("npm/lib/config/get-credentials-by-uri");
const urlLib = require("url");
const normalizeRegistryUrl = require("normalize-registry-url");
const PQueue = require("p-queue");
exports.default = (client, opts) => {
    opts.rawNpmConfig['registry'] = normalizeRegistryUrl(opts.rawNpmConfig['registry'] || opts.registry);
    const getCredentialsByURI = npmGetCredentialsByURI.bind({
        get(key) {
            return opts.rawNpmConfig[key];
        }
    });
    const requestsQueue = new PQueue({
        concurrency: opts.networkConcurrency,
    });
    function getJSON(url, registry, priority) {
        return __awaiter(this, void 0, void 0, function* () {
            return requestsQueue.add(() => new Promise((resolve, reject) => {
                const getOpts = {
                    auth: getCredentialsByURI(registry),
                    fullMetadata: false,
                };
                client.get(url, getOpts, (err, data, raw, res) => {
                    if (err)
                        return reject(err);
                    resolve(data);
                });
            }), { priority });
        });
    }
    function download(url, saveto, opts) {
        return requestsQueue.add(() => __awaiter(this, void 0, void 0, function* () {
            yield mkdirp(path.dirname(saveto));
            const auth = opts.registry && getCredentialsByURI(opts.registry);
            // If a tarball is hosted on a different place than the manifest, only send
            // credentials on `alwaysAuth`
            const shouldAuth = auth && (auth.alwaysAuth ||
                !opts.registry ||
                urlLib.parse(url).host === urlLib.parse(opts.registry).host);
            return new Promise((resolve, reject) => {
                client.fetch(url, { auth: shouldAuth && auth }, (err, res) => __awaiter(this, void 0, void 0, function* () {
                    if (err)
                        return reject(err);
                    if (res.statusCode !== 200) {
                        return reject(new Error(`Invalid response: ${res.statusCode}`));
                    }
                    if (opts.onStart)
                        opts.onStart();
                    if (opts.onProgress && res.headers['content-length']) {
                        const onProgress = opts.onProgress;
                        let downloaded = 0;
                        let size = +res.headers['content-length'];
                        res.on('data', (chunk) => {
                            downloaded += chunk.length;
                            onProgress(downloaded, size);
                        });
                    }
                    const writeStream = createWriteStreamAtomic(saveto);
                    const stream = res
                        .on('error', reject)
                        .pipe(writeStream)
                        .on('error', reject);
                    Promise.all([
                        opts.integrity && ssri.checkStream(res, opts.integrity),
                        unpackStream.local(res, opts.unpackTo, {
                            generateIntegrity: opts.generatePackageIntegrity,
                        })
                    ])
                        .then(vals => resolve(vals[1]))
                        .catch(reject);
                }));
            });
        }), { priority: 1000 }); // tarballs are requested first because they are bigger than metadata
    }
    return {
        getJSON: R.memoize(getJSON),
        download,
    };
};
//# sourceMappingURL=got.js.map