tar-transform
Version:
extract, transform and re-pack tarball entries in form of stream
119 lines (114 loc) • 3.47 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
var tar = require('tar-stream');
var stream = require('stream');
var zlib = require('zlib');
const TAR_PACK_PRIVATE_PROP_KEY = Symbol("tarPackPrivateProp");
function initTarPackReadable(gzipOption, pack) {
if (gzipOption) {
const gz = zlib.createGzip(gzipOption === true ? undefined : gzipOption);
pack.pipe(gz);
return gz;
}
else {
return pack;
}
}
function initTarPackPrivateProp(options) {
const gzipOption = options && options.gzip;
const pack = tar.pack();
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 stream.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);
}
exports.TarPack = TarPack;
exports.pack = pack;
//# sourceMappingURL=pack.js.map
;