"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const error_1 = require("@pnpm/error");
const fs = require("mz/fs");
const path = require("path");
const ssri = require("ssri");
const createDownloader_1 = require("./createDownloader");
function default_1(fetchFromRegistry, getCredentials, opts) {
    const download = createDownloader_1.default(fetchFromRegistry, {
        retry: opts.retry,
    });
    return {
        tarball: fetchFromTarball.bind(null, {
            download,
            getCredentialsByURI: getCredentials,
            offline: opts.offline,
        }),
    };
}
exports.default = default_1;
function fetchFromTarball(ctx, cafs, resolution, opts) {
    if (resolution.tarball.startsWith('file:')) {
        const tarball = resolvePath(opts.lockfileDir, resolution.tarball.slice(5));
        return fetchFromLocalTarball(cafs, tarball, {
            integrity: resolution.integrity,
            manifest: opts.manifest,
        });
    }
    if (ctx.offline) {
        throw new error_1.default('NO_OFFLINE_TARBALL', `A package is missing from the store but cannot download it in offline mode. The missing package may be downloaded from ${resolution.tarball}.`);
    }
    const auth = resolution.registry ? ctx.getCredentialsByURI(resolution.registry) : undefined;
    return ctx.download(resolution.tarball, {
        auth,
        cafs,
        integrity: resolution.integrity,
        manifest: opts.manifest,
        onProgress: opts.onProgress,
        onStart: opts.onStart,
        registry: resolution.registry,
    });
}
const isAbsolutePath = /^[/]|^[A-Za-z]:/;
function resolvePath(where, spec) {
    if (isAbsolutePath.test(spec))
        return spec;
    return path.resolve(where, spec);
}
async function fetchFromLocalTarball(cafs, tarball, opts) {
    try {
        const tarballStream = fs.createReadStream(tarball);
        const [fetchResult] = (await Promise.all([
            cafs.addFilesFromTarball(tarballStream, opts.manifest),
            opts.integrity && ssri.checkStream(tarballStream, opts.integrity),
        ]));
        return { filesIndex: fetchResult };
    }
    catch (err) {
        err.attempts = 1;
        err.resource = tarball;
        throw err;
    }
}
//# sourceMappingURL=index.js.map