"use strict";
const crypto = require('crypto');
const decompress = require('decompress-maybe');
const tar = require('tar-fs');
function remote(stream, dest, opts) {
    opts = opts || {};
    return new Promise((resolve, reject) => {
        const actualShasum = crypto.createHash('sha1');
        local(stream
            .on('response', start)
            .on('data', (_) => { actualShasum.update(_); })
            .on('error', reject), dest).then(finish).catch(reject);
        // without pausing, gunzip/tar-fs would miss the beginning of the stream
        if (stream.resume)
            stream.resume();
        function start(res) {
            if (res.statusCode !== 200) {
                return reject(new Error(`Invalid response: ${res.statusCode}`));
            }
            if (opts.onStart)
                opts.onStart();
            if (opts.onProgress && ('content-length' in res.headers)) {
                const onProgress = opts.onProgress;
                let downloaded = 0;
                let size = +res.headers['content-length'];
                res.on('data', (chunk) => {
                    downloaded += chunk.length;
                    onProgress(downloaded, size);
                });
            }
        }
        function finish() {
            const digest = actualShasum.digest('hex');
            if (opts.shasum && digest !== opts.shasum) {
                reject(new Error(`Incorrect shasum (expected ${opts.shasum}, got ${digest})`));
                return;
            }
            resolve();
        }
    });
}
exports.remote = remote;
function local(stream, dest) {
    return new Promise((resolve, reject) => {
        stream
            .pipe(decompress()).on('error', reject)
            .pipe(tar.extract(dest, { strip: 1 })).on('error', reject)
            .on('finish', resolve);
    });
}
exports.local = local;
//# sourceMappingURL=index.js.map