UNPKG

tar-transform

Version:

extract, transform and re-pack tarball entries in form of stream

114 lines (111 loc) 3.38 kB
import { pack as pack$1 } from 'tar-stream'; import { Duplex } from 'stream'; import { createGzip } from 'zlib'; const TAR_PACK_PRIVATE_PROP_KEY = Symbol("tarPackPrivateProp"); function initTarPackReadable(gzipOption, pack) { if (gzipOption) { const gz = createGzip(gzipOption === true ? undefined : gzipOption); pack.pipe(gz); return gz; } else { return pack; } } function initTarPackPrivateProp(options) { const gzipOption = options && options.gzip; const pack = pack$1(); return { pack, readable: initTarPackReadable(gzipOption, pack), setup: false, }; } function packEntry(pack, chunk, callback) { const { headers, stream, content } = chunk; if (stream !== null && stream !== undefined) { stream.pipe(pack.entry(headers, callback)); } else if ((content !== null && content !== undefined) || (headers.type === "directory" && content === undefined)) { if (stream !== null && stream !== undefined) { throw new Error("chunk passed to TarPack.prototype._transform is invalid: both stream and content are provided"); } pack.entry(headers, content, callback); } else { throw new Error("chunk passed to TarPack.prototype._transform is invalid: neither stream nor content is provided"); } } function packEntries(pack, chunks, callback) { let promise = null; for (const chunk of chunks) { const getPromise = () => new Promise((resolve, reject) => { packEntry(pack, chunk, err => { if (err) reject(err); else resolve(); }); }); if (!promise) { promise = getPromise(); } else { promise = promise.then(getPromise); } } if (promise) { return promise .then(() => { callback(); }) .catch(err => { callback(err); }); } else { callback(); } } class TarPack extends Duplex { constructor(options) { super({ readableObjectMode: false, writableObjectMode: true }); this[TAR_PACK_PRIVATE_PROP_KEY] = initTarPackPrivateProp(options); } _write(chunk, encoding, callback) { const { pack } = this[TAR_PACK_PRIVATE_PROP_KEY]; packEntry(pack, chunk, callback); } _writev(chunks, callback) { const { pack } = this[TAR_PACK_PRIVATE_PROP_KEY]; packEntries(pack, chunks.map(c => c.chunk), callback); } _read(size) { const { readable, setup } = this[TAR_PACK_PRIVATE_PROP_KEY]; if (!setup) { readable .on("readable", () => { let chunk; while (null !== (chunk = readable.read(size))) { if (!this.push(chunk)) break; } }) .on("end", () => { // EOF this.push(null); }); this[TAR_PACK_PRIVATE_PROP_KEY].setup = true; } } _final(callback) { this[TAR_PACK_PRIVATE_PROP_KEY].pack.finalize(); callback(); } } function pack(...args) { return new TarPack(...args); } export { TarPack, pack }; //# sourceMappingURL=pack.js.map