var stream=require("stream");if(!stream.Readable){var stream=require("readable-stream")}var fs=require("graceful-fs");var Q=require("q");var path=require("path");var zlib=require("zlib");var touch=Q.denodeify(require("touch"));var mkpath=Q.denodeify(require("mkpath"));var writeFile=Q.denodeify(fs.writeFile);var inflateRaw=Q.denodeify(zlib.inflateRaw);var symlink=Q.denodeify(fs.symlink);var stat=Q.denodeify(fs.stat);var cache={};var mkdir=function(a){a=path.normalize(path.resolve(process.cwd(),a)+path.sep);if(!cache[a]){var b;if(fs.existsSync(a)){b=new Q()}else{b=mkdir(path.dirname(a))}cache[a]=b.then(function(){return mkpath(a)})}return cache[a]};var extractors={folder:function(b,a){return mkdir(a).then(function(){return{folder:b.path}})},store:function(c,a,d){var e;if(c.uncompressedSize===0){e=touch.bind(null,a)}else{if(c.uncompressedSize<=d.chunkSize){e=function(){return d.getBuffer(c._offset,c._offset+c.uncompressedSize).then(writeFile.bind(null,a))}}else{var b=new stream.Readable();b.wrap(fs.createReadStream(d.filename,{start:c._offset,end:c._offset+c.uncompressedSize-1}));e=pipePromise.bind(null,b,a)}}return mkdir(path.dirname(a)).then(e).then(function(){return{stored:c.path}})},deflate:function(b,a,c){return mkdir(path.dirname(a)).then(function(){if(b._maxSize<=c.chunkSize){return c.getBuffer(b._offset,b._offset+b._maxSize).then(inflateRaw).then(function(f){return writeFile(a,f)})}else{var d=new stream.Readable();d.wrap(fs.createReadStream(c.filename,{start:b._offset}));var e=d.pipe(zlib.createInflateRaw({highWaterMark:32*1024}));return pipePromise(e,a)}}).then(function(){return{deflated:b.path}})},symlink:function(b,a,d,e){var c=path.dirname(a);return mkdir(c).then(function(){return getLinkLocation(b,a,d,e)}).then(function(f){return symlink(path.resolve(c,f),a).then(function(){return{symlink:b.path,linkTo:f}})})},copy:function(b,a,e,f){var d;var c=path.dirname(a);return mkdir(c).then(function(){return getLinkLocation(b,a,e,f)}).then(function(g){return stat(path.resolve(c,g)).then(function(i){if(i.isFile()){d="File";var h=new stream.Readable();h.wrap(fs.createReadStream(path.resolve(c,g)));return pipePromise(h,a)}else{if(i.isDirectory()){d="Directory";return mkdir(a)}else{throw new Error("Could not follow symlink to unknown file type")}}}).then(function(){return{copy:b.path,original:g,type:d}})})}};var getLinkLocation=function(b,a,d,e){var c=path.dirname(a);return d.getBuffer(b._offset,b._offset+b.uncompressedSize).then(function(g){var h=g.toString();var f=path.resolve(c,h);if(path.relative(e,f).slice(0,2)===".."){throw new Error("Symlink links outside archive")}return h})};var pipePromise=function(e,a){var d=Q.defer();var c=fs.createWriteStream(a);var b=function(f){d.reject(f)};e.on("error",b);c.on("error",b);e.on("end",function(){c.end(function(){d.resolve()})});e.pipe(c,{end:false});return d.promise};module.exports=extractors;